robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1local api , fn =vim . api , vim . fn 2 3local M ={} 4 5--- Run a system command and timeout after 10 seconds. 6--- @param cmd string[] 7--- @param silent boolean? 8--- @param env? table<string,string|number> 9--- @return string 10local function system ( cmd , silent , env ) 11if fn . executable ( assert ( cmd [ 1 ])) == 0 then 12error ( string . format ( 'executable not found: "%s"' , cmd [ 1 ]), 0 ) 13end 14 15local r =vim . system ( cmd , { env =env , timeout =10000 } ): wait () 16 17if not silent then 18if r . code ~= 0 then 19local cmd_str =table . concat ( cmd , ' ' ) 20error ( string . format ( "command error '%s': %s" , cmd_str , r . stderr )) 21end 22assert ( r . stdout ~= '' ) 23end 24 25return assert ( r . stdout ) 26end 27 28--- @enum Man.Attribute 29local Attrs ={ 30None =0 , 31Bold =1 , 32Underline =2 , 33Italic =3 , 34} 35 36--- @param line string 37--- @param row integer 38--- @param hls {attr:Man.Attribute,row:integer,start:integer,final:integer}[] 39--- @return string 40local function render_line ( line , row , hls ) 41--- @type string[] 42local chars ={} 43local prev_char ='' 44local overstrike , escape , osc8 =false , false , false 45 46local attr =Attrs . None 47local byte =0 -- byte offset 48 49local hls_start =# hls + 1 50 51--- @param code integer 52local function add_attr_hl ( code ) 53local continue_hl =true 54if code == 0 then 55attr =Attrs . None 56continue_hl =false 57elseif code == 1 then 58attr =Attrs . Bold 59elseif code == 22 then 60attr =Attrs . Bold 61continue_hl =false 62elseif code == 3 then 63attr =Attrs . Italic 64elseif code == 23 then 65attr =Attrs . Italic 66continue_hl =false 67elseif code == 4 then 68attr =Attrs . Underline 69elseif code == 24 then 70attr =Attrs . Underline 71continue_hl =false 72else 73attr =Attrs . None 74return 75end 76 77if continue_hl then 78hls [ # hls + 1 ] ={ attr =attr , row =row , start =byte , final =- 1 } 79else 80for _ , a in pairs ( attr == Attrs . None and Attrs or { attr } ) do 81for i =hls_start , # hls do 82if hls [ i ]. attr == a and hls [ i ]. final == - 1 then 83hls [ i ]. final =byte 84end 85end 86end 87end 88end 89 90-- Break input into UTF8 code points. ASCII code points (from 0x00 to 0x7f) 91-- can be represented in one byte. Any code point above that is represented by 92-- a leading byte (0xc0 and above) and continuation bytes (0x80 to 0xbf, or 93-- decimal 128 to 191). 94for char in line : gmatch ( '[^\128-\191][\128-\191]*' ) do 95if overstrike then 96local last_hl =hls [ # hls ] 97if char == prev_char then 98if char == '_' and attr == Attrs . Italic and last_hl and last_hl . final == byte then 99-- This underscore is in the middle of an italic word 100attr =Attrs . Italic 101else 102attr =Attrs . Bold 103end 104elseif prev_char == '_' then 105-- Even though underline is strictly what this should be. <bs>_ was used by nroff to 106-- indicate italics which wasn't possible on old typewriters so underline was used. Modern 107-- terminals now support italics so lets use that now. 108-- See: 109-- - https://unix.stackexchange.com/questions/274658/purpose-of-ascii-text-with-overstriking-file-format/274795#274795 110-- - https://cmd.inp.nsk.su/old/cmd2/manuals/unix/UNIX_Unleashed/ch08.htm 111-- attr = Attrs.Underline 112attr =Attrs . Italic 113elseif prev_char == '+' and char == 'o' then 114-- bullet (overstrike text '+^Ho') 115attr =Attrs . Bold 116char ='·' 117elseif prev_char == '·' and char == 'o' then 118-- bullet (additional handling for '+^H+^Ho^Ho') 119attr =Attrs . Bold 120char ='·' 121else 122-- use plain char 123attr =Attrs . None 124end 125 126-- Grow the previous highlight group if possible. `hls` spans the buffer, 127-- so only grow a group that is on the current row. 128if last_hl and last_hl . row == row and last_hl . attr == attr and last_hl . final == byte then 129last_hl . final =byte + # char 130else 131hls [ # hls + 1 ] ={ attr =attr , row =row , start =byte , final =byte + # char } 132end 133 134overstrike =false 135prev_char ='' 136byte =byte + # char 137chars [ # chars + 1 ] =char 138elseif osc8 then 139-- eat characters until String Terminator or bell 140if ( prev_char == '\027' and char == '\\' ) or char == '\a' then 141osc8 =false 142end 143prev_char =char 144elseif escape then 145-- Use prev_char to store the escape sequence 146prev_char =prev_char .. char 147-- We only want to match against SGR sequences, which consist of ESC 148-- followed by '[', then a series of parameter and intermediate bytes in 149-- the range 0x20 - 0x3f, then 'm'. (See ECMA-48, sections 5.4 & 8.3.117) 150--- @type string? 151local sgr =prev_char : match ( '^%[([\032-\063]*)m$' ) 152-- Ignore escape sequences with : characters, as specified by ITU's T.416 153-- Open Document Architecture and interchange format. 154if sgr and not sgr : find ( ':' ) then 155local match --- @type string? 156while sgr and # sgr > 0 do 157-- Match against SGR parameters, which may be separated by ';' 158--- @type string?, string? 159match , sgr =sgr : match ( '^(%d*);?(.*)' ) 160-- Both captures match even when empty, so this pattern cannot fail. 161add_attr_hl ( vim . _assert_integer ( match )) 162end 163escape =false 164elseif prev_char == ']8;' then 165osc8 =true 166escape =false 167elseif not prev_char : match ( '^[][][\032-\063]*$' ) then 168-- Stop looking if this isn't a partial CSI or OSC sequence 169escape =false 170end 171elseif char == '\027' then 172escape =true 173prev_char ='' 174elseif char == '\b' then 175overstrike =true 176prev_char =chars [ # chars ] 177byte =byte - # prev_char 178chars [ # chars ] =nil 179else 180byte =byte + # char 181chars [ # chars + 1 ] =char 182end 183end 184 185return table . concat ( chars , '' ) 186end 187 188local HlGroups ={ 189[ Attrs . Bold ] ='manBold' , 190[ Attrs . Underline ] ='manUnderline' , 191[ Attrs . Italic ] ='manItalic' , 192} 193 194local function highlight_man_page () 195local mod =vim . bo . modifiable 196vim . bo . modifiable =true 197 198local lines =api . nvim_buf_get_lines ( 0 , 0 , - 1 , false ) 199 200--- @type {attr:Man.Attribute,row:integer,start:integer,final:integer}[] 201local hls ={} 202 203for i , line in ipairs ( lines ) do 204lines [ i ] =render_line ( line , i - 1 , hls ) 205end 206 207api . nvim_buf_set_lines ( 0 , 0 , - 1 , false , lines ) 208 209for _ , hl in ipairs ( hls ) do 210if hl . attr ~= Attrs . None then 211--- @diagnostic disable-next-line: deprecated 212api . nvim_buf_add_highlight ( 0 , - 1 , HlGroups [ hl . attr ], hl . row , hl . start , hl . final ) 213end 214end 215 216vim . bo . modifiable =mod 217end 218 219--- @param name? string 220--- @param sect? string 221local function get_path ( name , sect ) 222name =name or '' 223sect =sect or '' 224-- We can avoid relying on -S or -s here since they are very 225-- inconsistently supported. Instead, call -w with a section and a name. 226local cmd =sect == '' and { 'man' , '-w' , name } or { 'man' , '-w' , sect , name } 227 228local lines =system ( cmd , true ) 229local results =vim . split ( lines , '\n' , { trimempty =true } ) 230 231return M . _match_manpage_path ( results , name , sect ) 232end 233 234--- Given an array of paths returned by man -w, 235--- find the correct path for the given name and section. 236--- @param paths? string[] 237--- @param name? string 238--- @param sect? string 239function M . _match_manpage_path ( paths , name , sect ) 240paths =paths or {} 241name =name or '' 242sect =sect or '' 243-- Some man implementations (OpenBSD) return all available paths from the 244-- search command. Previously, this function would simply select the first one. 245-- 246-- However, some searches will report matches that are incorrect: 247-- man -w strlen may return string.3 followed by strlen.3, and therefore 248-- selecting the first would get us the wrong page. Thus, we must find the 249-- first matching one. 250-- 251-- There's yet another special case here. Consider the following: 252-- If you run man -w strlen and string.3 comes up first, this is a problem. We 253-- should search for a matching named one in the results list. 254-- However, if you search for man -w clock_gettime, you will *only* get 255-- clock_getres.2, which is the right page. Searching the results for 256-- clock_gettime will no longer work. In this case, we should just use the 257-- first one that was found in the correct section. 258local first_path =paths [ 1 ] 259if not first_path then 260return 261end 262 263-- `man -w /some/path` echoes the input for any existent file. Accept only 264-- paths that look like a man page (`.../man1/bash.1`). #30873 265if sect == '' and # paths == 1 and first_path == name then 266local tail =vim . fs . basename ( name ) 267local parent =vim . fs . basename ( vim . fs . dirname ( name )) 268if not ( parent : find ( '^man' ) and tail : find ( '%.%d' )) then 269return 270end 271return name 272end 273 274-- find any that match the specified name 275--- @type string[] 276--- @param v string 277local namematches =vim . tbl_filter ( function ( v ) 278local tail =vim . fs . basename ( v ) 279return tail : find ( name , 1 , true ) ~= nil 280end , paths ) 281local sectmatches ={} --- @type string[] 282 283if # namematches > 0 and sect ~= '' then 284--- @param v string 285sectmatches =vim . tbl_filter ( function ( v ) 286-- On some systems, there are multiple extensions, e.g. strlen.3.gz 287-- We must test all of the extensions to make sure we get the correct match. 288-- Limit to 3 tests to avoid the risk of getting stuck. 289local root =v 290for _ =1 , 3 do 291local extension =fn . fnamemodify ( root , ':e' ) 292if extension == sect then 293return true 294elseif extension == '' then 295return false 296end 297root =fn . fnamemodify ( root , ':r' ) 298end 299return false 300end , namematches ) 301end 302 303return ( sectmatches [ 1 ] or namematches [ 1 ] or first_path ): gsub ( '\n+$' , '' ) 304end 305 306--- Attempt to extract the name and sect out of 'name(sect)' 307--- otherwise just return the largest string of valid characters in ref 308--- @param ref string 309--- @return string? name 310--- @return string? sect 311--- @return string? err 312local function parse_ref ( ref ) 313if ref == '' or ref : sub ( 1 , 1 ) == '-' then 314return nil , nil , ( 'invalid manpage reference "%s"' ): format ( ref ) 315end 316 317-- match "<name>(<sect>)" 318-- note: name can contain spaces 319local name , sect =ref : match ( '([^()]+)%(([^()]+)%)' ) 320if name and sect then 321-- see ':Man 3X curses' on why tolower. 322-- TODO(nhooyr) Not sure if this is portable across OSs 323-- but I have not seen a single uppercase section. 324return name , sect : lower () 325end 326 327name =ref : match ( '[^()]+' ) 328if not name then 329return nil , nil , ( 'invalid manpage reference "%s"' ): format ( ref ) 330end 331return name 332end 333 334--- Attempts to find the path to a manpage based on the passed section and name. 335--- 336--- 1. If manpage could not be found with the given sect and name, 337--- then try all the sections in b:man_default_sects. 338--- 2. If it still could not be found, then we try again without a section. 339--- 3. If still not found but $MANSECT is set, then we try again with $MANSECT 340--- unset. 341--- 4. If a path still wasn't found, return nil. 342--- @param name string? 343--- @param sect string? 344--- @return string? path 345function M . _find_path ( name , sect ) 346if sect and sect ~= '' then 347local ret =get_path ( name , sect ) 348if ret then 349return ret 350end 351end 352 353if vim . b . man_default_sects ~= nil then 354for sec in vim . gsplit ( vim . b . man_default_sects , ',' , { trimempty =true } ) do 355local ret =get_path ( name , sec ) 356if ret then 357return ret 358end 359end 360end 361 362-- if none of the above worked, we will try with no section 363local ret =get_path ( name ) 364if ret then 365return ret 366end 367 368-- if that still didn't work, we will check for $MANSECT and try again with it 369-- unset 370if vim . env . MANSECT then 371--- @type string 372local mansect =vim . env . MANSECT 373vim . env . MANSECT =nil 374local res =get_path ( name ) 375vim . env . MANSECT =mansect 376if res then 377return res 378end 379end 380 381-- finally, if that didn't work, there is no hope 382return nil 383end 384 385--- Extracts the name/section from the 'path/name.sect', because sometimes the 386--- actual section is more specific than what we provided to `man` 387--- (try `:Man 3 App::CLI`). Also on linux, name seems to be case-insensitive. 388--- So for `:Man PRIntf`, we still want the name of the buffer to be 'printf'. 389--- @param path string 390--- @return string? name 391--- @return string? sect 392local function parse_path ( path ) 393local tail =vim . fs . basename ( path ) 394if 395path : match ( '%.[glx]z$' ) 396or path : match ( '%.bz2$' ) 397or path : match ( '%.lzma$' ) 398or path : match ( '%.Z$' ) 399then 400tail =fn . fnamemodify ( tail , ':r' ) 401end 402return tail : match ( '^(.+)%.([^.]+)$' ) 403end 404 405--- @return boolean 406local function find_man () 407if vim . bo . filetype == 'man' then 408return true 409end 410 411local win =1 412while win <= fn . winnr ( '$' ) do 413local buf =fn . winbufnr ( win ) 414if vim . bo [ buf ]. filetype == 'man' then 415vim . cmd ( win .. 'wincmd w' ) 416return true 417end 418win =win + 1 419end 420return false 421end 422 423local function set_options () 424vim . bo . swapfile =false 425vim . bo . buftype ='nofile' 426vim . bo . bufhidden ='hide' 427vim . bo . modified =false 428vim . bo . readonly =true 429vim . bo . modifiable =false 430vim . bo . filetype ='man' 431end 432 433--- Always use -l if possible. #6683 434--- @type boolean? 435local localfile_arg 436 437--- @return integer 438local function get_manwidth () 439-- Disable hard-wrap by using a big $MANWIDTH (max 1000 on some systems #9065). 440-- Soft-wrap: ftplugin/man.lua sets wrap/breakindent/…. 441-- Hard-wrap: driven by `man`. 442local manwidth --- @type integer 443if ( vim . g . man_hardwrap or 1 ) ~= 1 then 444manwidth =999 445elseif vim . env . MANWIDTH then 446local env_manwidth =vim . _tointeger ( vim . env . MANWIDTH ) or 0 447manwidth =math . min ( env_manwidth , api . nvim_win_get_width ( 0 ) - vim . o . wrapmargin ) 448else 449manwidth =api . nvim_win_get_width ( 0 ) - vim . o . wrapmargin 450end 451return manwidth 452end 453 454--- @param path string 455--- @param silent boolean? 456--- @param manwidth integer? 457--- @return string 458local function get_page ( path , silent , manwidth ) 459manwidth =manwidth or get_manwidth () 460 461if localfile_arg == nil then 462local mpath =get_path ( 'man' ) 463-- Check for -l support. 464localfile_arg =( mpath and system ( { 'man' , '-l' , mpath } , true , { MANPAGER ='cat' } ) or '' ) 465~= '' 466end 467 468local cmd =localfile_arg and { 'man' , '-l' , path } or { 'man' , path } 469 470-- Force MANPAGER=cat to ensure Vim is not recursively invoked (by man-db). 471-- http://comments.gmane.org/gmane.editors.vim.devel/29085 472-- Set MAN_KEEP_FORMATTING so Debian man doesn't discard backspaces. 473return system ( cmd , silent , { 474MANPAGER ='cat' , 475MANWIDTH =manwidth , 476MAN_KEEP_FORMATTING =1 , 477} ) 478end 479 480--- @param path string 481--- @param psect string 482local function format_candidate ( path , psect ) 483if vim . endswith ( path , '.pdf' ) or vim . endswith ( path , '.in' ) then 484-- invalid extensions 485return '' 486end 487local name , sect =parse_path ( path ) 488if not name or not sect then 489return '' 490end 491if sect == psect then 492return name 493elseif sect : match ( psect .. '.+$' ) then -- invalid extensions 494-- We include the section if the user provided section is a prefix 495-- of the actual section. 496return ( '%s(%s)' ): format ( name , sect ) 497end 498return '' 499end 500 501--- @param name string 502--- @param sect? string 503--- @return string[] paths 504--- @return string? err 505local function get_paths ( name , sect ) 506-- Try several sources for getting the list man directories: 507-- 1. `manpath -q` 508-- 2. `man -w` (works on most systems) 509-- 3. $MANPATH 510-- 511-- Note we prefer `manpath -q` because `man -w`: 512-- - does not work on MacOS 14 and later. 513-- - only returns '/usr/bin/man' on MacOS 13 and earlier. 514--- @type string? 515local mandirs_raw =vim . npcall ( system , { 'manpath' , '-q' } ) 516or vim . npcall ( system , { 'man' , '-w' } ) 517or vim . env . MANPATH 518 519if not mandirs_raw then 520-- Fall back to direct lookup ("man -w [sect] name"). NetBSD man lacks "-w". #25919 521local ok , path =pcall ( M . _find_path , name , sect ) 522if ok and path then 523return { path } 524end 525return {} , "Could not determine man directories from: 'man -w', 'manpath' or $MANPATH" 526end 527 528local mandirs =table . concat ( vim . split ( mandirs_raw , '[:\n]' , { trimempty =true } ), ',' ) 529 530sect =sect or '' 531 532--- @type string[] 533local paths =fn . globpath ( mandirs , 'man[^\\/]*/' .. name .. '*.' .. sect .. '*' , false , true ) 534 535-- Prioritize the result from find_path as it obeys b:man_default_sects. 536local first =M . _find_path ( name , sect ) 537if first then 538--- @param v string 539paths =vim . tbl_filter ( function ( v ) 540return v ~= first 541end , paths ) 542table . insert ( paths , 1 , first ) 543end 544 545return paths 546end 547 548--- @param arg_lead string 549--- @param cmd_line string 550--- @return string? sect 551--- @return string? psect 552--- @return string? name 553local function parse_cmdline ( arg_lead , cmd_line ) 554local args =vim . split ( cmd_line , '%s+' , { trimempty =true } ) 555local cmd_offset =fn . index ( args , 'Man' ) 556if cmd_offset > 0 then 557-- Prune all arguments up to :Man itself. Otherwise modifier commands like 558-- :tab, :vertical, etc. would lead to a wrong length. 559args =vim . list_slice ( args , cmd_offset + 1 ) 560end 561 562if # args > 3 then 563return 564end 565 566local arg =args [ 2 ] 567if not arg then 568-- returning full completion is laggy. Require some arg_lead to complete 569-- return '', '', '' 570return 571end 572 573if arg_lead : match ( '^[^()]+%([^()]*$' ) then 574-- cursor (|) is at ':Man printf(|' or ':Man 1 printf(|' 575-- The latter is allowed because of ':Man pri<TAB>'. 576-- It will offer 'priclass.d(1m)' even though section is specified as 1. 577local tmp =vim . split ( arg_lead , '(' , { plain =true } ) 578local name =tmp [ 1 ] 579-- See extract_sect_and_name_ref on why :lower() 580local sect =( tmp [ 2 ] or '' ): lower () 581return sect , '' , name 582end 583 584if not arg : match ( '^[^()]+$' ) then 585-- cursor (|) is at ':Man 3() |' or ':Man (3|' or ':Man 3() pri|' 586-- or ':Man 3() pri |' 587return 588end 589 590if # args == 2 then 591--- @type string, string 592local name , sect 593if arg_lead == '' then 594-- cursor (|) is at ':Man 1 |' 595name ='' 596sect =args [ 1 ]: lower () 597else 598-- cursor (|) is at ':Man pri|' 599if arg_lead : match ( '/' ) then 600-- if the name is a path, complete files 601-- TODO(nhooyr) why does this complete the last one automatically 602return fn . glob ( arg_lead .. '*' , false , true ) 603end 604name =arg_lead 605sect ='' 606end 607return sect , sect , name 608end 609 610if not arg_lead : match ( '[^()]+$' ) then 611-- cursor (|) is at ':Man 3 printf |' or ':Man 3 (pr)i|' 612return 613end 614 615-- cursor (|) is at ':Man 3 pri|' 616local name , sect =arg_lead , arg : lower () 617return sect , sect , name 618end 619 620--- @param arg_lead string 621--- @param cmd_line string 622function M . man_complete ( arg_lead , cmd_line ) 623local sect , psect , name =parse_cmdline ( arg_lead , cmd_line ) 624if not ( sect and psect and name ) then 625return {} 626end 627 628local ok , pages =pcall ( get_paths , name , sect ) 629if not ok then 630return nil 631end 632 633-- We check for duplicates in case the same manpage in different languages 634-- was found. 635local pages_fmt ={} --- @type string[] 636local pages_fmt_keys ={} --- @type table<string,true> 637for _ , v in ipairs ( pages ) do 638local x =format_candidate ( v , psect ) 639local xl =x : lower () -- ignore case when searching avoiding duplicates 640if not pages_fmt_keys [ xl ] then 641pages_fmt [ # pages_fmt + 1 ] =x 642pages_fmt_keys [ xl ] =true 643end 644end 645table . sort ( pages_fmt ) 646 647return pages_fmt 648end 649 650--- @param pattern string 651--- @return {name:string,filename:string,cmd:string}[] 652function M . goto_tag ( pattern , _ , _ ) 653local name , sect , err =parse_ref ( pattern ) 654if err then 655error ( err ) 656end 657 658local paths , err2 =get_paths ( assert ( name ), sect ) 659if err2 then 660error ( err2 ) 661end 662 663--- @type table[] 664local ret ={} 665 666for _ , path in ipairs ( paths ) do 667local pname , psect =parse_path ( path ) 668if pname and psect then 669ret [ # ret + 1 ] ={ 670name =pname , 671filename =( 'man://%s(%s)' ): format ( pname , psect ), 672cmd ='1' , 673} 674end 675end 676 677return ret 678end 679 680--- Called when Nvim is invoked as $MANPAGER. 681function M . init_pager () 682if fn . getline ( 1 ): match ( '^%s*$' ) then 683api . nvim_buf_set_lines ( 0 , 0 , 1 , false , {} ) 684else 685vim . cmd ( 'keepjumps 1' ) 686end 687highlight_man_page () 688-- Guess the ref from the heading (which is usually uppercase, so we cannot 689-- know the correct casing, cf. `man glDrawArraysInstanced`). 690--- @type string 691local ref =( fn . getline ( 1 ): match ( '^[^)]+%)' ) or '' ): gsub ( ' ' , '_' ) 692local ok , _ , sect =pcall ( parse_ref , ref ) 693vim . b . man_sect =ok and ( sect or '' ) or '' 694 695local man_bufname ='man://' .. fn . fnameescape ( ref ): lower () 696 697-- Raw manpage into (:Man!) overlooks `match('man://')` condition, 698-- so if the buffer already exists, create new with a non existing name. 699if fn . bufexists ( man_bufname ) == 1 then 700local new_bufname =man_bufname 701for i =1 , 100 do 702if fn . bufexists ( new_bufname ) == 0 then 703break 704end 705new_bufname =( '%s?new=%s' ): format ( man_bufname , i ) 706end 707vim . cmd . file ( { new_bufname , mods ={ silent =true } } ) 708elseif not fn . bufname ( '%' ): match ( 'man://' ) then -- Avoid duplicate buffers, E95. 709vim . cmd . file ( { man_bufname , mods ={ silent =true } } ) 710end 711 712set_options () 713vim . bo . bufhidden ='unload' 714end 715 716--- Combine the name and sect into a manpage reference so that all 717--- verification/extraction can be kept in a single function. 718--- @param args string[] 719--- @return string? ref 720local function ref_from_args ( args ) 721if # args <= 1 then 722return args [ 1 ] 723elseif args [ 1 ]: match ( '^%d$' ) or args [ 1 ]: match ( '^%d%a' ) or args [ 1 ]: match ( '^%a$' ) then 724-- NB: Valid sections are not only digits, but also: 725-- - <digit><word> (see POSIX mans), 726-- - and even <letter> and <word> (see, for example, by tcl/tk) 727-- NB2: don't optimize to :match("^%d"), as it will match manpages like 728-- 441toppm and others whose name starts with digit 729local sect =args [ 1 ] 730table . remove ( args , 1 ) 731local name =table . concat ( args , ' ' ) 732return ( '%s(%s)' ): format ( name , sect ) 733end 734 735return table . concat ( args , ' ' ) 736end 737 738--- @param count integer 739--- @param smods vim.api.keyset.cmd_mods 740--- @param args string[] 741--- @return string? err 742function M . open_page ( count , smods , args ) 743local ref =ref_from_args ( args ) 744if not ref then 745ref =vim . bo . filetype == 'man' and fn . expand ( '<cWORD>' ) or fn . expand ( '<cword>' ) 746if ref == '' then 747return 'no identifier under cursor' 748end 749end 750 751local name , sect , err =parse_ref ( ref ) 752if err then 753return err 754end 755assert ( name ) 756 757if count >= 0 then 758sect =tostring ( count ) 759end 760 761-- Try both spaces and underscores, use the first that exists. 762local path =M . _find_path ( name , sect ) 763if not path then 764--- Replace spaces in a man page name with underscores 765--- intended for PostgreSQL, which has man pages like 'CREATE_TABLE(7)'; 766--- while editing SQL source code, it's nice to visually select 'CREATE TABLE' 767--- and hit 'K', which requires this transformation 768path =M . _find_path ( name : gsub ( '%s' , '_' ), sect ) 769if not path then 770return 'no manual entry for ' .. name 771end 772end 773 774name , sect =parse_path ( path ) 775if not name or not sect then 776return 'no manual entry for ' .. ( name or path ) 777end 778local buf =api . nvim_get_current_buf () 779local save_tfu =vim . bo [ buf ]. tagfunc 780vim . bo [ buf ]. tagfunc =M . goto_tag 781 782local target =( '%s(%s)' ): format ( name , sect ) 783 784local ok , ret =pcall ( function () 785smods . silent =true 786smods . keepalt =true 787if smods . hide or ( smods . tab == - 1 and find_man ()) then 788vim . cmd . tag ( { target , mods =smods } ) 789else 790vim . cmd . stag ( { target , mods =smods } ) 791end 792end ) 793 794if api . nvim_buf_is_valid ( buf ) then 795vim . bo [ buf ]. tagfunc =save_tfu 796end 797 798if not ok then 799error ( ret ) 800end 801set_options () 802 803vim . b . man_sect =sect 804end 805 806--- Called when a man:// buffer is opened. 807--- @param ref string 808--- @return string? err 809function M . read_page ( ref ) 810local name , sect , err =parse_ref ( ref ) 811if err then 812return err 813end 814 815local path =M . _find_path ( name , sect ) 816if not path then 817return 'no manual entry for ' .. name 818end 819 820local _ , page_sect =parse_path ( path ) 821local manwidth =get_manwidth () 822local page =get_page ( path , nil , manwidth ) 823 824vim . b . manwidth =manwidth 825vim . b . man_sect =page_sect 826vim . bo . modifiable =true 827vim . bo . readonly =false 828vim . bo . swapfile =false 829 830api . nvim_buf_set_lines ( 0 , 0 , - 1 , false , vim . split ( page , '\n' )) 831 832while fn . getline ( 1 ): match ( '^%s*$' ) do 833api . nvim_buf_set_lines ( 0 , 0 , 1 , false , {} ) 834end 835-- XXX: nroff justifies text by filling it with whitespace. That interacts 836-- badly with our use of $MANWIDTH=999. Hack around this by using a fixed 837-- size for those whitespace regions. 838-- Use try/catch to avoid setting v:errmsg. 839vim . cmd ( [[ 840try 841keeppatterns keepjumps %s/\s\{199,}/\=repeat(' ', 10)/g 842catch 843endtry 844]] ) 845vim . cmd ( '1' ) -- Move cursor to first line 846highlight_man_page () 847set_options () 848end 849 850--- @return string? err 851function M . refresh_page () 852if vim . bo . filetype ~= 'man' then 853return 854end 855 856local ref =api . nvim_buf_get_name ( 0 ): match ( 'man://(.*)' ) 857if not ref or vim . b . manwidth == nil or vim . b . manwidth == get_manwidth () then 858return 859end 860 861return M . read_page ( ref ) 862end 863 864function M . show_toc () 865local bufnr =api . nvim_get_current_buf () 866local bufname =api . nvim_buf_get_name ( bufnr ) 867local info =fn . getloclist ( 0 , { winid =1 } ) 868if info ~= '' and vim . w [ info . winid ]. qf_toc == bufname then 869vim . cmd . lopen () 870return 871end 872 873--- @type {bufnr:integer, lnum:integer, text:string}[] 874local toc ={} 875 876local lnum =2 877local last_line =fn . line ( '$' ) - 1 878while lnum > 0 and lnum < last_line do 879local text =fn . getline ( lnum ) 880if text : match ( '^%s+[-+]%S' ) or text : match ( '^ %S' ) or text : match ( '^%S' ) then 881toc [ # toc + 1 ] ={ 882bufnr =bufnr , 883lnum =lnum , 884text =text : gsub ( '^%s+' , '' ): gsub ( '%s+$' , '' ), 885} 886end 887lnum =fn . nextnonblank ( lnum + 1 ) 888end 889 890fn . setloclist ( 0 , toc , ' ' ) 891fn . setloclist ( 0 , {} , 'a' , { title ='Table of contents' } ) 892vim . cmd . lopen () 893vim . w . qf_toc =bufname 894-- reload syntax file after setting qf_toc variable 895vim . bo . filetype ='qf' 896end 897 898return M