man.lua 23 KB

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