man.lua 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  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. if hl.attr ~= Attrs.None then
  184. --- @diagnostic disable-next-line: deprecated
  185. api.nvim_buf_add_highlight(0, -1, HlGroups[hl.attr], hl.row, hl.start, hl.final)
  186. end
  187. end
  188. vim.bo.modifiable = mod
  189. end
  190. --- @param name? string
  191. --- @param sect? string
  192. local function get_path(name, sect)
  193. name = name or ''
  194. sect = sect or ''
  195. -- Some man implementations (OpenBSD) return all available paths from the
  196. -- search command. Previously, this function would simply select the first one.
  197. --
  198. -- However, some searches will report matches that are incorrect:
  199. -- man -w strlen may return string.3 followed by strlen.3, and therefore
  200. -- selecting the first would get us the wrong page. Thus, we must find the
  201. -- first matching one.
  202. --
  203. -- There's yet another special case here. Consider the following:
  204. -- If you run man -w strlen and string.3 comes up first, this is a problem. We
  205. -- should search for a matching named one in the results list.
  206. -- However, if you search for man -w clock_gettime, you will *only* get
  207. -- clock_getres.2, which is the right page. Searching the results for
  208. -- clock_gettime will no longer work. In this case, we should just use the
  209. -- first one that was found in the correct section.
  210. --
  211. -- Finally, we can avoid relying on -S or -s here since they are very
  212. -- inconsistently supported. Instead, call -w with a section and a name.
  213. local cmd --- @type string[]
  214. if sect == '' then
  215. cmd = { 'man', '-w', name }
  216. else
  217. cmd = { 'man', '-w', sect, name }
  218. end
  219. local lines = system(cmd, true)
  220. local results = vim.split(lines, '\n', { trimempty = true })
  221. if #results == 0 then
  222. return
  223. end
  224. -- `man -w /some/path` will return `/some/path` for any existent file, which
  225. -- stops us from actually determining if a path has a corresponding man file.
  226. -- Since `:Man /some/path/to/man/file` isn't supported anyway, we should just
  227. -- error out here if we detect this is the case.
  228. if sect == '' and #results == 1 and results[1] == name then
  229. return
  230. end
  231. -- find any that match the specified name
  232. --- @param v string
  233. local namematches = vim.tbl_filter(function(v)
  234. local tail = fn.fnamemodify(v, ':t')
  235. return tail:find(name, 1, true) ~= nil
  236. end, results) or {}
  237. local sectmatches = {}
  238. if #namematches > 0 and sect ~= '' then
  239. --- @param v string
  240. sectmatches = vim.tbl_filter(function(v)
  241. return fn.fnamemodify(v, ':e') == sect
  242. end, namematches)
  243. end
  244. return (sectmatches[1] or namematches[1] or results[1]):gsub('\n+$', '')
  245. end
  246. --- Attempt to extract the name and sect out of 'name(sect)'
  247. --- otherwise just return the largest string of valid characters in ref
  248. --- @param ref string
  249. --- @return string? name
  250. --- @return string? sect
  251. --- @return string? err
  252. local function parse_ref(ref)
  253. if ref == '' or ref:sub(1, 1) == '-' then
  254. return nil, nil, ('invalid manpage reference "%s"'):format(ref)
  255. end
  256. -- match "<name>(<sect>)"
  257. -- note: name can contain spaces
  258. local name, sect = ref:match('([^()]+)%(([^()]+)%)')
  259. if name then
  260. -- see ':Man 3X curses' on why tolower.
  261. -- TODO(nhooyr) Not sure if this is portable across OSs
  262. -- but I have not seen a single uppercase section.
  263. return name, sect:lower()
  264. end
  265. name = ref:match('[^()]+')
  266. if not name then
  267. return nil, nil, ('invalid manpage reference "%s"'):format(ref)
  268. end
  269. return name
  270. end
  271. --- Attempts to find the path to a manpage based on the passed section and name.
  272. ---
  273. --- 1. If manpage could not be found with the given sect and name,
  274. --- then try all the sections in b:man_default_sects.
  275. --- 2. If it still could not be found, then we try again without a section.
  276. --- 3. If still not found but $MANSECT is set, then we try again with $MANSECT
  277. --- unset.
  278. --- 4. If a path still wasn't found, return nil.
  279. --- @param name string?
  280. --- @param sect string?
  281. --- @return string? path
  282. function M._find_path(name, sect)
  283. if sect and sect ~= '' then
  284. local ret = get_path(name, sect)
  285. if ret then
  286. return ret
  287. end
  288. end
  289. if vim.b.man_default_sects ~= nil then
  290. for sec in vim.gsplit(vim.b.man_default_sects, ',', { trimempty = true }) do
  291. local ret = get_path(name, sec)
  292. if ret then
  293. return ret
  294. end
  295. end
  296. end
  297. -- if none of the above worked, we will try with no section
  298. local ret = get_path(name)
  299. if ret then
  300. return ret
  301. end
  302. -- if that still didn't work, we will check for $MANSECT and try again with it
  303. -- unset
  304. if vim.env.MANSECT then
  305. --- @type string
  306. local mansect = vim.env.MANSECT
  307. vim.env.MANSECT = nil
  308. local res = get_path(name)
  309. vim.env.MANSECT = mansect
  310. if res then
  311. return res
  312. end
  313. end
  314. -- finally, if that didn't work, there is no hope
  315. return nil
  316. end
  317. --- Extracts the name/section from the 'path/name.sect', because sometimes the
  318. --- actual section is more specific than what we provided to `man`
  319. --- (try `:Man 3 App::CLI`). Also on linux, name seems to be case-insensitive.
  320. --- So for `:Man PRIntf`, we still want the name of the buffer to be 'printf'.
  321. --- @param path string
  322. --- @return string name
  323. --- @return string sect
  324. local function parse_path(path)
  325. local tail = fn.fnamemodify(path, ':t')
  326. if
  327. path:match('%.[glx]z$')
  328. or path:match('%.bz2$')
  329. or path:match('%.lzma$')
  330. or path:match('%.Z$')
  331. then
  332. tail = fn.fnamemodify(tail, ':r')
  333. end
  334. return tail:match('^(.+)%.([^.]+)$')
  335. end
  336. --- @return boolean
  337. local function find_man()
  338. if vim.bo.filetype == 'man' then
  339. return true
  340. end
  341. local win = 1
  342. while win <= fn.winnr('$') do
  343. local buf = fn.winbufnr(win)
  344. if vim.bo[buf].filetype == 'man' then
  345. vim.cmd(win .. 'wincmd w')
  346. return true
  347. end
  348. win = win + 1
  349. end
  350. return false
  351. end
  352. local function set_options()
  353. vim.bo.swapfile = false
  354. vim.bo.buftype = 'nofile'
  355. vim.bo.bufhidden = 'unload'
  356. vim.bo.modified = false
  357. vim.bo.readonly = true
  358. vim.bo.modifiable = false
  359. vim.bo.filetype = 'man'
  360. end
  361. --- Always use -l if possible. #6683
  362. --- @type boolean?
  363. local localfile_arg
  364. --- @param path string
  365. --- @param silent boolean?
  366. --- @return string
  367. local function get_page(path, silent)
  368. -- Disable hard-wrap by using a big $MANWIDTH (max 1000 on some systems #9065).
  369. -- Soft-wrap: ftplugin/man.lua sets wrap/breakindent/….
  370. -- Hard-wrap: driven by `man`.
  371. local manwidth --- @type integer|string
  372. if (vim.g.man_hardwrap or 1) ~= 1 then
  373. manwidth = 999
  374. elseif vim.env.MANWIDTH then
  375. manwidth = vim.env.MANWIDTH --- @type string|integer
  376. else
  377. manwidth = api.nvim_win_get_width(0) - vim.o.wrapmargin
  378. end
  379. if localfile_arg == nil then
  380. local mpath = get_path('man')
  381. -- Check for -l support.
  382. localfile_arg = (mpath and system({ 'man', '-l', mpath }, true) or '') ~= ''
  383. end
  384. local cmd = localfile_arg and { 'man', '-l', path } or { 'man', path }
  385. -- Force MANPAGER=cat to ensure Vim is not recursively invoked (by man-db).
  386. -- http://comments.gmane.org/gmane.editors.vim.devel/29085
  387. -- Set MAN_KEEP_FORMATTING so Debian man doesn't discard backspaces.
  388. return system(cmd, silent, {
  389. MANPAGER = 'cat',
  390. MANWIDTH = manwidth,
  391. MAN_KEEP_FORMATTING = 1,
  392. })
  393. end
  394. --- @param path string
  395. --- @param psect string
  396. local function format_candidate(path, psect)
  397. if vim.endswith(path, '.pdf') or vim.endswith(path, '.in') then
  398. -- invalid extensions
  399. return ''
  400. end
  401. local name, sect = parse_path(path)
  402. if sect == psect then
  403. return name
  404. elseif sect:match(psect .. '.+$') then -- invalid extensions
  405. -- We include the section if the user provided section is a prefix
  406. -- of the actual section.
  407. return ('%s(%s)'):format(name, sect)
  408. end
  409. return ''
  410. end
  411. --- @param name string
  412. --- @param sect? string
  413. --- @return string[] paths
  414. --- @return string? err
  415. local function get_paths(name, sect)
  416. -- Try several sources for getting the list man directories:
  417. -- 1. `manpath -q`
  418. -- 2. `man -w` (works on most systems)
  419. -- 3. $MANPATH
  420. --
  421. -- Note we prefer `manpath -q` because `man -w`:
  422. -- - does not work on MacOS 14 and later.
  423. -- - only returns '/usr/bin/man' on MacOS 13 and earlier.
  424. --- @type string?
  425. local mandirs_raw = vim.F.npcall(system, { 'manpath', '-q' })
  426. or vim.F.npcall(system, { 'man', '-w' })
  427. or vim.env.MANPATH
  428. if not mandirs_raw then
  429. return {}, "Could not determine man directories from: 'man -w', 'manpath' or $MANPATH"
  430. end
  431. local mandirs = table.concat(vim.split(mandirs_raw, '[:\n]', { trimempty = true }), ',')
  432. sect = sect or ''
  433. --- @type string[]
  434. local paths = fn.globpath(mandirs, 'man[^\\/]*/' .. name .. '*.' .. sect .. '*', false, true)
  435. -- Prioritize the result from find_path as it obeys b:man_default_sects.
  436. local first = M._find_path(name, sect)
  437. if first then
  438. --- @param v string
  439. paths = vim.tbl_filter(function(v)
  440. return v ~= first
  441. end, paths)
  442. table.insert(paths, 1, first)
  443. end
  444. return paths
  445. end
  446. --- @param arg_lead string
  447. --- @param cmd_line string
  448. --- @return string? sect
  449. --- @return string? psect
  450. --- @return string? name
  451. local function parse_cmdline(arg_lead, cmd_line)
  452. local args = vim.split(cmd_line, '%s+', { trimempty = true })
  453. local cmd_offset = fn.index(args, 'Man')
  454. if cmd_offset > 0 then
  455. -- Prune all arguments up to :Man itself. Otherwise modifier commands like
  456. -- :tab, :vertical, etc. would lead to a wrong length.
  457. args = vim.list_slice(args, cmd_offset + 1)
  458. end
  459. if #args > 3 then
  460. return
  461. end
  462. if #args == 1 then
  463. -- returning full completion is laggy. Require some arg_lead to complete
  464. -- return '', '', ''
  465. return
  466. end
  467. if arg_lead:match('^[^()]+%([^()]*$') then
  468. -- cursor (|) is at ':Man printf(|' or ':Man 1 printf(|'
  469. -- The later is is allowed because of ':Man pri<TAB>'.
  470. -- It will offer 'priclass.d(1m)' even though section is specified as 1.
  471. local tmp = vim.split(arg_lead, '(', { plain = true })
  472. local name = tmp[1]
  473. -- See extract_sect_and_name_ref on why :lower()
  474. local sect = (tmp[2] or ''):lower()
  475. return sect, '', name
  476. end
  477. if not args[2]:match('^[^()]+$') then
  478. -- cursor (|) is at ':Man 3() |' or ':Man (3|' or ':Man 3() pri|'
  479. -- or ':Man 3() pri |'
  480. return
  481. end
  482. if #args == 2 then
  483. --- @type string, string
  484. local name, sect
  485. if arg_lead == '' then
  486. -- cursor (|) is at ':Man 1 |'
  487. name = ''
  488. sect = args[1]:lower()
  489. else
  490. -- cursor (|) is at ':Man pri|'
  491. if arg_lead:match('/') then
  492. -- if the name is a path, complete files
  493. -- TODO(nhooyr) why does this complete the last one automatically
  494. return fn.glob(arg_lead .. '*', false, true)
  495. end
  496. name = arg_lead
  497. sect = ''
  498. end
  499. return sect, sect, name
  500. end
  501. if not arg_lead:match('[^()]+$') then
  502. -- cursor (|) is at ':Man 3 printf |' or ':Man 3 (pr)i|'
  503. return
  504. end
  505. -- cursor (|) is at ':Man 3 pri|'
  506. local name, sect = arg_lead, args[2]:lower()
  507. return sect, sect, name
  508. end
  509. --- @param arg_lead string
  510. --- @param cmd_line string
  511. function M.man_complete(arg_lead, cmd_line)
  512. local sect, psect, name = parse_cmdline(arg_lead, cmd_line)
  513. if not (sect and psect and name) then
  514. return {}
  515. end
  516. local pages = get_paths(name, sect)
  517. -- We check for duplicates in case the same manpage in different languages
  518. -- was found.
  519. local pages_fmt = {} --- @type string[]
  520. local pages_fmt_keys = {} --- @type table<string,true>
  521. for _, v in ipairs(pages) do
  522. local x = format_candidate(v, psect)
  523. local xl = x:lower() -- ignore case when searching avoiding duplicates
  524. if not pages_fmt_keys[xl] then
  525. pages_fmt[#pages_fmt + 1] = x
  526. pages_fmt_keys[xl] = true
  527. end
  528. end
  529. table.sort(pages_fmt)
  530. return pages_fmt
  531. end
  532. --- @param pattern string
  533. --- @return {name:string,filename:string,cmd:string}[]
  534. function M.goto_tag(pattern, _, _)
  535. local name, sect, err = parse_ref(pattern)
  536. if err then
  537. error(err)
  538. end
  539. local paths, err2 = get_paths(assert(name), sect)
  540. if err2 then
  541. error(err2)
  542. end
  543. --- @type table[]
  544. local ret = {}
  545. for _, path in ipairs(paths) do
  546. local pname, psect = parse_path(path)
  547. ret[#ret + 1] = {
  548. name = pname,
  549. filename = ('man://%s(%s)'):format(pname, psect),
  550. cmd = '1',
  551. }
  552. end
  553. return ret
  554. end
  555. --- Called when Nvim is invoked as $MANPAGER.
  556. function M.init_pager()
  557. if fn.getline(1):match('^%s*$') then
  558. api.nvim_buf_set_lines(0, 0, 1, false, {})
  559. else
  560. vim.cmd('keepjumps 1')
  561. end
  562. highlight_man_page()
  563. -- Guess the ref from the heading (which is usually uppercase, so we cannot
  564. -- know the correct casing, cf. `man glDrawArraysInstanced`).
  565. --- @type string
  566. local ref = (fn.getline(1):match('^[^)]+%)') or ''):gsub(' ', '_')
  567. local _, sect, err = pcall(parse_ref, ref)
  568. vim.b.man_sect = err ~= nil and sect or ''
  569. if not fn.bufname('%'):match('man://') then -- Avoid duplicate buffers, E95.
  570. vim.cmd.file({ 'man://' .. fn.fnameescape(ref):lower(), mods = { silent = true } })
  571. end
  572. set_options()
  573. end
  574. --- Combine the name and sect into a manpage reference so that all
  575. --- verification/extraction can be kept in a single function.
  576. --- @param args string[]
  577. --- @return string? ref
  578. local function ref_from_args(args)
  579. if #args <= 1 then
  580. return args[1]
  581. elseif args[1]:match('^%d$') or args[1]:match('^%d%a') or args[1]:match('^%a$') then
  582. -- NB: Valid sections are not only digits, but also:
  583. -- - <digit><word> (see POSIX mans),
  584. -- - and even <letter> and <word> (see, for example, by tcl/tk)
  585. -- NB2: don't optimize to :match("^%d"), as it will match manpages like
  586. -- 441toppm and others whose name starts with digit
  587. local sect = args[1]
  588. table.remove(args, 1)
  589. local name = table.concat(args, ' ')
  590. return ('%s(%s)'):format(name, sect)
  591. end
  592. return table.concat(args, ' ')
  593. end
  594. --- @param count integer
  595. --- @param args string[]
  596. --- @return string? err
  597. function M.open_page(count, smods, args)
  598. local ref = ref_from_args(args)
  599. if not ref then
  600. ref = vim.bo.filetype == 'man' and fn.expand('<cWORD>') or fn.expand('<cword>')
  601. if ref == '' then
  602. return 'no identifier under cursor'
  603. end
  604. end
  605. local name, sect, err = parse_ref(ref)
  606. if err then
  607. return err
  608. end
  609. assert(name)
  610. if count >= 0 then
  611. sect = tostring(count)
  612. end
  613. -- Try both spaces and underscores, use the first that exists.
  614. local path = M._find_path(name, sect)
  615. if not path then
  616. --- Replace spaces in a man page name with underscores
  617. --- intended for PostgreSQL, which has man pages like 'CREATE_TABLE(7)';
  618. --- while editing SQL source code, it's nice to visually select 'CREATE TABLE'
  619. --- and hit 'K', which requires this transformation
  620. path = M._find_path(name:gsub('%s', '_'), sect)
  621. if not path then
  622. return 'no manual entry for ' .. name
  623. end
  624. end
  625. name, sect = parse_path(path)
  626. local buf = api.nvim_get_current_buf()
  627. local save_tfu = vim.bo[buf].tagfunc
  628. vim.bo[buf].tagfunc = "v:lua.require'man'.goto_tag"
  629. local target = ('%s(%s)'):format(name, sect)
  630. local ok, ret = pcall(function()
  631. smods.silent = true
  632. smods.keepalt = true
  633. if smods.hide or (smods.tab == -1 and find_man()) then
  634. vim.cmd.tag({ target, mods = smods })
  635. else
  636. vim.cmd.stag({ target, mods = smods })
  637. end
  638. end)
  639. if api.nvim_buf_is_valid(buf) then
  640. vim.bo[buf].tagfunc = save_tfu
  641. end
  642. if not ok then
  643. error(ret)
  644. end
  645. set_options()
  646. vim.b.man_sect = sect
  647. end
  648. --- Called when a man:// buffer is opened.
  649. --- @return string? err
  650. function M.read_page(ref)
  651. local name, sect, err = parse_ref(ref)
  652. if err then
  653. return err
  654. end
  655. local path = M._find_path(name, sect)
  656. if not path then
  657. return 'no manual entry for ' .. name
  658. end
  659. local _, sect1 = parse_path(path)
  660. local page = get_page(path)
  661. vim.b.man_sect = sect1
  662. vim.bo.modifiable = true
  663. vim.bo.readonly = false
  664. vim.bo.swapfile = false
  665. api.nvim_buf_set_lines(0, 0, -1, false, vim.split(page, '\n'))
  666. while fn.getline(1):match('^%s*$') do
  667. api.nvim_buf_set_lines(0, 0, 1, false, {})
  668. end
  669. -- XXX: nroff justifies text by filling it with whitespace. That interacts
  670. -- badly with our use of $MANWIDTH=999. Hack around this by using a fixed
  671. -- size for those whitespace regions.
  672. -- Use try/catch to avoid setting v:errmsg.
  673. vim.cmd([[
  674. try
  675. keeppatterns keepjumps %s/\s\{199,}/\=repeat(' ', 10)/g
  676. catch
  677. endtry
  678. ]])
  679. vim.cmd('1') -- Move cursor to first line
  680. highlight_man_page()
  681. set_options()
  682. end
  683. function M.show_toc()
  684. local bufnr = api.nvim_get_current_buf()
  685. local bufname = api.nvim_buf_get_name(bufnr)
  686. local info = fn.getloclist(0, { winid = 1 })
  687. if info ~= '' and vim.w[info.winid].qf_toc == bufname then
  688. vim.cmd.lopen()
  689. return
  690. end
  691. --- @type {bufnr:integer, lnum:integer, text:string}[]
  692. local toc = {}
  693. local lnum = 2
  694. local last_line = fn.line('$') - 1
  695. while lnum and lnum < last_line do
  696. local text = fn.getline(lnum)
  697. if text:match('^%s+[-+]%S') or text:match('^ %S') or text:match('^%S') then
  698. toc[#toc + 1] = {
  699. bufnr = bufnr,
  700. lnum = lnum,
  701. text = text:gsub('^%s+', ''):gsub('%s+$', ''),
  702. }
  703. end
  704. lnum = fn.nextnonblank(lnum + 1)
  705. end
  706. fn.setloclist(0, toc, ' ')
  707. fn.setloclist(0, {}, 'a', { title = 'Table of contents' })
  708. vim.cmd.lopen()
  709. vim.w.qf_toc = bufname
  710. end
  711. return M