robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
25.9 KiB898 linesraw
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)
11  if fn.executable(assert(cmd[1])) == 0 then
12    error(string.format('executable not found: "%s"', cmd[1]), 0)
13  end
14
15  local r = vim.system(cmd, { env = env, timeout = 10000 }):wait()
16
17  if not silent then
18    if r.code ~= 0 then
19      local cmd_str = table.concat(cmd, ' ')
20      error(string.format("command error '%s': %s", cmd_str, r.stderr))
21    end
22    assert(r.stdout ~= '')
23  end
24
25  return assert(r.stdout)
26end
27
28--- @enum Man.Attribute
29local Attrs = {
30  None = 0,
31  Bold = 1,
32  Underline = 2,
33  Italic = 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[]
42  local chars = {}
43  local prev_char = ''
44  local overstrike, escape, osc8 = false, false, false
45
46  local attr = Attrs.None
47  local byte = 0 -- byte offset
48
49  local hls_start = #hls + 1
50
51  --- @param code integer
52  local function add_attr_hl(code)
53    local continue_hl = true
54    if code == 0 then
55      attr = Attrs.None
56      continue_hl = false
57    elseif code == 1 then
58      attr = Attrs.Bold
59    elseif code == 22 then
60      attr = Attrs.Bold
61      continue_hl = false
62    elseif code == 3 then
63      attr = Attrs.Italic
64    elseif code == 23 then
65      attr = Attrs.Italic
66      continue_hl = false
67    elseif code == 4 then
68      attr = Attrs.Underline
69    elseif code == 24 then
70      attr = Attrs.Underline
71      continue_hl = false
72    else
73      attr = Attrs.None
74      return
75    end
76
77    if continue_hl then
78      hls[#hls + 1] = { attr = attr, row = row, start = byte, final = -1 }
79    else
80      for _, a in pairs(attr == Attrs.None and Attrs or { attr }) do
81        for i = hls_start, #hls do
82          if hls[i].attr == a and hls[i].final == -1 then
83            hls[i].final = byte
84          end
85        end
86      end
87    end
88  end
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).
94  for char in line:gmatch('[^\128-\191][\128-\191]*') do
95    if overstrike then
96      local last_hl = hls[#hls]
97      if char == prev_char then
98        if 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
100          attr = Attrs.Italic
101        else
102          attr = Attrs.Bold
103        end
104      elseif 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
112        attr = Attrs.Italic
113      elseif prev_char == '+' and char == 'o' then
114        -- bullet (overstrike text '+^Ho')
115        attr = Attrs.Bold
116        char = '·'
117      elseif prev_char == '·' and char == 'o' then
118        -- bullet (additional handling for '+^H+^Ho^Ho')
119        attr = Attrs.Bold
120        char = '·'
121      else
122        -- use plain char
123        attr = Attrs.None
124      end
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.
128      if last_hl and last_hl.row == row and last_hl.attr == attr and last_hl.final == byte then
129        last_hl.final = byte + #char
130      else
131        hls[#hls + 1] = { attr = attr, row = row, start = byte, final = byte + #char }
132      end
133
134      overstrike = false
135      prev_char = ''
136      byte = byte + #char
137      chars[#chars + 1] = char
138    elseif osc8 then
139      -- eat characters until String Terminator or bell
140      if (prev_char == '\027' and char == '\\') or char == '\a' then
141        osc8 = false
142      end
143      prev_char = char
144    elseif escape then
145      -- Use prev_char to store the escape sequence
146      prev_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?
151      local 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.
154      if sgr and not sgr:find(':') then
155        local match --- @type string?
156        while sgr and #sgr > 0 do
157          -- Match against SGR parameters, which may be separated by ';'
158          --- @type string?, string?
159          match, sgr = sgr:match('^(%d*);?(.*)')
160          -- Both captures match even when empty, so this pattern cannot fail.
161          add_attr_hl(vim._assert_integer(match))
162        end
163        escape = false
164      elseif prev_char == ']8;' then
165        osc8 = true
166        escape = false
167      elseif not prev_char:match('^[][][\032-\063]*$') then
168        -- Stop looking if this isn't a partial CSI or OSC sequence
169        escape = false
170      end
171    elseif char == '\027' then
172      escape = true
173      prev_char = ''
174    elseif char == '\b' then
175      overstrike = true
176      prev_char = chars[#chars]
177      byte = byte - #prev_char
178      chars[#chars] = nil
179    else
180      byte = byte + #char
181      chars[#chars + 1] = char
182    end
183  end
184
185  return 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()
195  local mod = vim.bo.modifiable
196  vim.bo.modifiable = true
197
198  local lines = api.nvim_buf_get_lines(0, 0, -1, false)
199
200  --- @type {attr:Man.Attribute,row:integer,start:integer,final:integer}[]
201  local hls = {}
202
203  for i, line in ipairs(lines) do
204    lines[i] = render_line(line, i - 1, hls)
205  end
206
207  api.nvim_buf_set_lines(0, 0, -1, false, lines)
208
209  for _, hl in ipairs(hls) do
210    if hl.attr ~= Attrs.None then
211      --- @diagnostic disable-next-line: deprecated
212      api.nvim_buf_add_highlight(0, -1, HlGroups[hl.attr], hl.row, hl.start, hl.final)
213    end
214  end
215
216  vim.bo.modifiable = mod
217end
218
219--- @param name? string
220--- @param sect? string
221local function get_path(name, sect)
222  name = name or ''
223  sect = 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.
226  local cmd = sect == '' and { 'man', '-w', name } or { 'man', '-w', sect, name }
227
228  local lines = system(cmd, true)
229  local results = vim.split(lines, '\n', { trimempty = true })
230
231  return 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)
240  paths = paths or {}
241  name = name or ''
242  sect = 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.
258  local first_path = paths[1]
259  if not first_path then
260    return
261  end
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
265  if sect == '' and #paths == 1 and first_path == name then
266    local tail = vim.fs.basename(name)
267    local parent = vim.fs.basename(vim.fs.dirname(name))
268    if not (parent:find('^man') and tail:find('%.%d')) then
269      return
270    end
271    return name
272  end
273
274  -- find any that match the specified name
275  --- @type string[]
276  --- @param v string
277  local namematches = vim.tbl_filter(function(v)
278    local tail = vim.fs.basename(v)
279    return tail:find(name, 1, true) ~= nil
280  end, paths)
281  local sectmatches = {} --- @type string[]
282
283  if #namematches > 0 and sect ~= '' then
284    --- @param v string
285    sectmatches = 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.
289      local root = v
290      for _ = 1, 3 do
291        local extension = fn.fnamemodify(root, ':e')
292        if extension == sect then
293          return true
294        elseif extension == '' then
295          return false
296        end
297        root = fn.fnamemodify(root, ':r')
298      end
299      return false
300    end, namematches)
301  end
302
303  return (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)
313  if ref == '' or ref:sub(1, 1) == '-' then
314    return nil, nil, ('invalid manpage reference "%s"'):format(ref)
315  end
316
317  -- match "<name>(<sect>)"
318  -- note: name can contain spaces
319  local name, sect = ref:match('([^()]+)%(([^()]+)%)')
320  if 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.
324    return name, sect:lower()
325  end
326
327  name = ref:match('[^()]+')
328  if not name then
329    return nil, nil, ('invalid manpage reference "%s"'):format(ref)
330  end
331  return 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)
346  if sect and sect ~= '' then
347    local ret = get_path(name, sect)
348    if ret then
349      return ret
350    end
351  end
352
353  if vim.b.man_default_sects ~= nil then
354    for sec in vim.gsplit(vim.b.man_default_sects, ',', { trimempty = true }) do
355      local ret = get_path(name, sec)
356      if ret then
357        return ret
358      end
359    end
360  end
361
362  -- if none of the above worked, we will try with no section
363  local ret = get_path(name)
364  if ret then
365    return ret
366  end
367
368  -- if that still didn't work, we will check for $MANSECT and try again with it
369  -- unset
370  if vim.env.MANSECT then
371    --- @type string
372    local mansect = vim.env.MANSECT
373    vim.env.MANSECT = nil
374    local res = get_path(name)
375    vim.env.MANSECT = mansect
376    if res then
377      return res
378    end
379  end
380
381  -- finally, if that didn't work, there is no hope
382  return 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)
393  local tail = vim.fs.basename(path)
394  if
395    path:match('%.[glx]z$')
396    or path:match('%.bz2$')
397    or path:match('%.lzma$')
398    or path:match('%.Z$')
399  then
400    tail = fn.fnamemodify(tail, ':r')
401  end
402  return tail:match('^(.+)%.([^.]+)$')
403end
404
405--- @return boolean
406local function find_man()
407  if vim.bo.filetype == 'man' then
408    return true
409  end
410
411  local win = 1
412  while win <= fn.winnr('$') do
413    local buf = fn.winbufnr(win)
414    if vim.bo[buf].filetype == 'man' then
415      vim.cmd(win .. 'wincmd w')
416      return true
417    end
418    win = win + 1
419  end
420  return false
421end
422
423local function set_options()
424  vim.bo.swapfile = false
425  vim.bo.buftype = 'nofile'
426  vim.bo.bufhidden = 'hide'
427  vim.bo.modified = false
428  vim.bo.readonly = true
429  vim.bo.modifiable = false
430  vim.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`.
442  local manwidth --- @type integer
443  if (vim.g.man_hardwrap or 1) ~= 1 then
444    manwidth = 999
445  elseif vim.env.MANWIDTH then
446    local env_manwidth = vim._tointeger(vim.env.MANWIDTH) or 0
447    manwidth = math.min(env_manwidth, api.nvim_win_get_width(0) - vim.o.wrapmargin)
448  else
449    manwidth = api.nvim_win_get_width(0) - vim.o.wrapmargin
450  end
451  return 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)
459  manwidth = manwidth or get_manwidth()
460
461  if localfile_arg == nil then
462    local mpath = get_path('man')
463    -- Check for -l support.
464    localfile_arg = (mpath and system({ 'man', '-l', mpath }, true, { MANPAGER = 'cat' }) or '')
465      ~= ''
466  end
467
468  local 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.
473  return system(cmd, silent, {
474    MANPAGER = 'cat',
475    MANWIDTH = manwidth,
476    MAN_KEEP_FORMATTING = 1,
477  })
478end
479
480--- @param path string
481--- @param psect string
482local function format_candidate(path, psect)
483  if vim.endswith(path, '.pdf') or vim.endswith(path, '.in') then
484    -- invalid extensions
485    return ''
486  end
487  local name, sect = parse_path(path)
488  if not name or not sect then
489    return ''
490  end
491  if sect == psect then
492    return name
493  elseif sect:match(psect .. '.+$') then -- invalid extensions
494    -- We include the section if the user provided section is a prefix
495    -- of the actual section.
496    return ('%s(%s)'):format(name, sect)
497  end
498  return ''
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?
515  local mandirs_raw = vim.npcall(system, { 'manpath', '-q' })
516    or vim.npcall(system, { 'man', '-w' })
517    or vim.env.MANPATH
518
519  if not mandirs_raw then
520    -- Fall back to direct lookup ("man -w [sect] name"). NetBSD man lacks "-w". #25919
521    local ok, path = pcall(M._find_path, name, sect)
522    if ok and path then
523      return { path }
524    end
525    return {}, "Could not determine man directories from: 'man -w', 'manpath' or $MANPATH"
526  end
527
528  local mandirs = table.concat(vim.split(mandirs_raw, '[:\n]', { trimempty = true }), ',')
529
530  sect = sect or ''
531
532  --- @type string[]
533  local paths = fn.globpath(mandirs, 'man[^\\/]*/' .. name .. '*.' .. sect .. '*', false, true)
534
535  -- Prioritize the result from find_path as it obeys b:man_default_sects.
536  local first = M._find_path(name, sect)
537  if first then
538    --- @param v string
539    paths = vim.tbl_filter(function(v)
540      return v ~= first
541    end, paths)
542    table.insert(paths, 1, first)
543  end
544
545  return 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)
554  local args = vim.split(cmd_line, '%s+', { trimempty = true })
555  local cmd_offset = fn.index(args, 'Man')
556  if 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.
559    args = vim.list_slice(args, cmd_offset + 1)
560  end
561
562  if #args > 3 then
563    return
564  end
565
566  local arg = args[2]
567  if not arg then
568    -- returning full completion is laggy. Require some arg_lead to complete
569    -- return '', '', ''
570    return
571  end
572
573  if 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.
577    local tmp = vim.split(arg_lead, '(', { plain = true })
578    local name = tmp[1]
579    -- See extract_sect_and_name_ref on why :lower()
580    local sect = (tmp[2] or ''):lower()
581    return sect, '', name
582  end
583
584  if not arg:match('^[^()]+$') then
585    -- cursor (|) is at ':Man 3() |' or ':Man (3|' or ':Man 3() pri|'
586    -- or ':Man 3() pri |'
587    return
588  end
589
590  if #args == 2 then
591    --- @type string, string
592    local name, sect
593    if arg_lead == '' then
594      -- cursor (|) is at ':Man 1 |'
595      name = ''
596      sect = args[1]:lower()
597    else
598      -- cursor (|) is at ':Man pri|'
599      if arg_lead:match('/') then
600        -- if the name is a path, complete files
601        -- TODO(nhooyr) why does this complete the last one automatically
602        return fn.glob(arg_lead .. '*', false, true)
603      end
604      name = arg_lead
605      sect = ''
606    end
607    return sect, sect, name
608  end
609
610  if not arg_lead:match('[^()]+$') then
611    -- cursor (|) is at ':Man 3 printf |' or ':Man 3 (pr)i|'
612    return
613  end
614
615  -- cursor (|) is at ':Man 3 pri|'
616  local name, sect = arg_lead, arg:lower()
617  return sect, sect, name
618end
619
620--- @param arg_lead string
621--- @param cmd_line string
622function M.man_complete(arg_lead, cmd_line)
623  local sect, psect, name = parse_cmdline(arg_lead, cmd_line)
624  if not (sect and psect and name) then
625    return {}
626  end
627
628  local ok, pages = pcall(get_paths, name, sect)
629  if not ok then
630    return nil
631  end
632
633  -- We check for duplicates in case the same manpage in different languages
634  -- was found.
635  local pages_fmt = {} --- @type string[]
636  local pages_fmt_keys = {} --- @type table<string,true>
637  for _, v in ipairs(pages) do
638    local x = format_candidate(v, psect)
639    local xl = x:lower() -- ignore case when searching avoiding duplicates
640    if not pages_fmt_keys[xl] then
641      pages_fmt[#pages_fmt + 1] = x
642      pages_fmt_keys[xl] = true
643    end
644  end
645  table.sort(pages_fmt)
646
647  return pages_fmt
648end
649
650--- @param pattern string
651--- @return {name:string,filename:string,cmd:string}[]
652function M.goto_tag(pattern, _, _)
653  local name, sect, err = parse_ref(pattern)
654  if err then
655    error(err)
656  end
657
658  local paths, err2 = get_paths(assert(name), sect)
659  if err2 then
660    error(err2)
661  end
662
663  --- @type table[]
664  local ret = {}
665
666  for _, path in ipairs(paths) do
667    local pname, psect = parse_path(path)
668    if pname and psect then
669      ret[#ret + 1] = {
670        name = pname,
671        filename = ('man://%s(%s)'):format(pname, psect),
672        cmd = '1',
673      }
674    end
675  end
676
677  return ret
678end
679
680--- Called when Nvim is invoked as $MANPAGER.
681function M.init_pager()
682  if fn.getline(1):match('^%s*$') then
683    api.nvim_buf_set_lines(0, 0, 1, false, {})
684  else
685    vim.cmd('keepjumps 1')
686  end
687  highlight_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
691  local ref = (fn.getline(1):match('^[^)]+%)') or ''):gsub(' ', '_')
692  local ok, _, sect = pcall(parse_ref, ref)
693  vim.b.man_sect = ok and (sect or '') or ''
694
695  local 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.
699  if fn.bufexists(man_bufname) == 1 then
700    local new_bufname = man_bufname
701    for i = 1, 100 do
702      if fn.bufexists(new_bufname) == 0 then
703        break
704      end
705      new_bufname = ('%s?new=%s'):format(man_bufname, i)
706    end
707    vim.cmd.file({ new_bufname, mods = { silent = true } })
708  elseif not fn.bufname('%'):match('man://') then -- Avoid duplicate buffers, E95.
709    vim.cmd.file({ man_bufname, mods = { silent = true } })
710  end
711
712  set_options()
713  vim.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)
721  if #args <= 1 then
722    return args[1]
723  elseif 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
729    local sect = args[1]
730    table.remove(args, 1)
731    local name = table.concat(args, ' ')
732    return ('%s(%s)'):format(name, sect)
733  end
734
735  return 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)
743  local ref = ref_from_args(args)
744  if not ref then
745    ref = vim.bo.filetype == 'man' and fn.expand('<cWORD>') or fn.expand('<cword>')
746    if ref == '' then
747      return 'no identifier under cursor'
748    end
749  end
750
751  local name, sect, err = parse_ref(ref)
752  if err then
753    return err
754  end
755  assert(name)
756
757  if count >= 0 then
758    sect = tostring(count)
759  end
760
761  -- Try both spaces and underscores, use the first that exists.
762  local path = M._find_path(name, sect)
763  if 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
768    path = M._find_path(name:gsub('%s', '_'), sect)
769    if not path then
770      return 'no manual entry for ' .. name
771    end
772  end
773
774  name, sect = parse_path(path)
775  if not name or not sect then
776    return 'no manual entry for ' .. (name or path)
777  end
778  local buf = api.nvim_get_current_buf()
779  local save_tfu = vim.bo[buf].tagfunc
780  vim.bo[buf].tagfunc = M.goto_tag
781
782  local target = ('%s(%s)'):format(name, sect)
783
784  local ok, ret = pcall(function()
785    smods.silent = true
786    smods.keepalt = true
787    if smods.hide or (smods.tab == -1 and find_man()) then
788      vim.cmd.tag({ target, mods = smods })
789    else
790      vim.cmd.stag({ target, mods = smods })
791    end
792  end)
793
794  if api.nvim_buf_is_valid(buf) then
795    vim.bo[buf].tagfunc = save_tfu
796  end
797
798  if not ok then
799    error(ret)
800  end
801  set_options()
802
803  vim.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)
810  local name, sect, err = parse_ref(ref)
811  if err then
812    return err
813  end
814
815  local path = M._find_path(name, sect)
816  if not path then
817    return 'no manual entry for ' .. name
818  end
819
820  local _, page_sect = parse_path(path)
821  local manwidth = get_manwidth()
822  local page = get_page(path, nil, manwidth)
823
824  vim.b.manwidth = manwidth
825  vim.b.man_sect = page_sect
826  vim.bo.modifiable = true
827  vim.bo.readonly = false
828  vim.bo.swapfile = false
829
830  api.nvim_buf_set_lines(0, 0, -1, false, vim.split(page, '\n'))
831
832  while fn.getline(1):match('^%s*$') do
833    api.nvim_buf_set_lines(0, 0, 1, false, {})
834  end
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.
839  vim.cmd([[
840    try
841      keeppatterns keepjumps %s/\s\{199,}/\=repeat(' ', 10)/g
842    catch
843    endtry
844  ]])
845  vim.cmd('1') -- Move cursor to first line
846  highlight_man_page()
847  set_options()
848end
849
850--- @return string? err
851function M.refresh_page()
852  if vim.bo.filetype ~= 'man' then
853    return
854  end
855
856  local ref = api.nvim_buf_get_name(0):match('man://(.*)')
857  if not ref or vim.b.manwidth == nil or vim.b.manwidth == get_manwidth() then
858    return
859  end
860
861  return M.read_page(ref)
862end
863
864function M.show_toc()
865  local bufnr = api.nvim_get_current_buf()
866  local bufname = api.nvim_buf_get_name(bufnr)
867  local info = fn.getloclist(0, { winid = 1 })
868  if info ~= '' and vim.w[info.winid].qf_toc == bufname then
869    vim.cmd.lopen()
870    return
871  end
872
873  --- @type {bufnr:integer, lnum:integer, text:string}[]
874  local toc = {}
875
876  local lnum = 2
877  local last_line = fn.line('$') - 1
878  while lnum > 0 and lnum < last_line do
879    local text = fn.getline(lnum)
880    if text:match('^%s+[-+]%S') or text:match('^   %S') or text:match('^%S') then
881      toc[#toc + 1] = {
882        bufnr = bufnr,
883        lnum = lnum,
884        text = text:gsub('^%s+', ''):gsub('%s+$', ''),
885      }
886    end
887    lnum = fn.nextnonblank(lnum + 1)
888  end
889
890  fn.setloclist(0, toc, ' ')
891  fn.setloclist(0, {}, 'a', { title = 'Table of contents' })
892  vim.cmd.lopen()
893  vim.w.qf_toc = bufname
894  -- reload syntax file after setting qf_toc variable
895  vim.bo.filetype = 'qf'
896end
897
898return M