1" Maintainer: Anmol Sethi <hi@nhooyr.io>
2
3if exists('s:loaded_man')
4  finish
5endif
6let s:loaded_man = 1
7
8let s:find_arg = '-w'
9let s:localfile_arg = v:true  " Always use -l if possible. #6683
10let s:section_arg = '-S'
11
12function! man#init() abort
13  try
14    " Check for -l support.
15    call s:get_page(s:get_path('', 'man'))
16  catch /command error .*/
17    let s:localfile_arg = v:false
18  endtry
19endfunction
20
21function! man#open_page(count, mods, ...) abort
22  if a:0 > 2
23    call s:error('too many arguments')
24    return
25  elseif a:0 == 0
26    let ref = &filetype ==# 'man' ? expand('<cWORD>') : expand('<cword>')
27    if empty(ref)
28      call s:error('no identifier under cursor')
29      return
30    endif
31  elseif a:0 ==# 1
32    let ref = a:1
33  else
34    " Combine the name and sect into a manpage reference so that all
35    " verification/extraction can be kept in a single function.
36    " If a:2 is a reference as well, that is fine because it is the only
37    " reference that will match.
38    let ref = a:2.'('.a:1.')'
39  endif
40  try
41    let [sect, name] = s:extract_sect_and_name_ref(ref)
42    if a:count >= 0
43      let sect = string(a:count)
44    endif
45    let path = s:verify_exists(sect, name)
46    let [sect, name] = s:extract_sect_and_name_path(path)
47  catch
48    call s:error(v:exception)
49    return
50  endtry
51
52  let [l:buf, l:save_tfu] = [bufnr(), &tagfunc]
53  try
54    setlocal tagfunc=man#goto_tag
55    let l:target = l:name . '(' . l:sect . ')'
56    if a:mods !~# 'tab' && s:find_man()
57      execute 'silent keepalt tag' l:target
58    else
59      execute 'silent keepalt' a:mods 'stag' l:target
60    endif
61    call s:set_options(v:false)
62  finally
63    call setbufvar(l:buf, '&tagfunc', l:save_tfu)
64  endtry
65
66  let b:man_sect = sect
67endfunction
68
69" Called when a man:// buffer is opened.
70function! man#read_page(ref) abort
71  try
72    let [sect, name] = s:extract_sect_and_name_ref(a:ref)
73    let path = s:verify_exists(sect, name)
74    let [sect, name] = s:extract_sect_and_name_path(path)
75    let page = s:get_page(path)
76  catch
77    call s:error(v:exception)
78    return
79  endtry
80  let b:man_sect = sect
81  call s:put_page(page)
82endfunction
83
84" Handler for s:system() function.
85function! s:system_handler(jobid, data, event) dict abort
86  if a:event is# 'stdout' || a:event is# 'stderr'
87    let self[a:event] .= join(a:data, "\n")
88  else
89    let self.exit_code = a:data
90  endif
91endfunction
92
93" Run a system command and timeout after 30 seconds.
94function! s:system(cmd, ...) abort
95  let opts = {
96        \ 'stdout': '',
97        \ 'stderr': '',
98        \ 'exit_code': 0,
99        \ 'on_stdout': function('s:system_handler'),
100        \ 'on_stderr': function('s:system_handler'),
101        \ 'on_exit': function('s:system_handler'),
102        \ }
103  let jobid = jobstart(a:cmd, opts)
104
105  if jobid < 1
106    throw printf('command error %d: %s', jobid, join(a:cmd))
107  endif
108
109  let res = jobwait([jobid], 30000)
110  if res[0] == -1
111    try
112      call jobstop(jobid)
113      throw printf('command timed out: %s', join(a:cmd))
114    catch /^Vim(call):E900:/
115    endtry
116  elseif res[0] == -2
117    throw printf('command interrupted: %s', join(a:cmd))
118  endif
119  if opts.exit_code != 0
120    throw printf("command error (%d) %s: %s", jobid, join(a:cmd), substitute(opts.stderr, '\_s\+$', '', &gdefault ? '' : 'g'))
121  endif
122
123  return opts.stdout
124endfunction
125
126function! s:set_options(pager) abort
127  setlocal filetype=man
128  setlocal noswapfile buftype=nofile bufhidden=hide
129  setlocal nomodified readonly nomodifiable
130  if a:pager
131    nnoremap <silent> <buffer> <nowait> q :lclose<CR>:q<CR>
132  endif
133endfunction
134
135function! s:get_page(path) abort
136  " Disable hard-wrap by using a big $MANWIDTH (max 1000 on some systems #9065).
137  " Soft-wrap: ftplugin/man.vim sets wrap/breakindent/….
138  " Hard-wrap: driven by `man`.
139  let manwidth = !get(g:, 'man_hardwrap', 1) ? 999 : (empty($MANWIDTH) ? winwidth(0) : $MANWIDTH)
140  " Force MANPAGER=cat to ensure Vim is not recursively invoked (by man-db).
141  " http://comments.gmane.org/gmane.editors.vim.devel/29085
142  " Set MAN_KEEP_FORMATTING so Debian man doesn't discard backspaces.
143  let cmd = ['env', 'MANPAGER=cat', 'MANWIDTH='.manwidth, 'MAN_KEEP_FORMATTING=1', 'man']
144  return s:system(cmd + (s:localfile_arg ? ['-l', a:path] : [a:path]))
145endfunction
146
147function! s:put_page(page) abort
148  setlocal modifiable noreadonly noswapfile
149  silent keepjumps %delete _
150  silent put =a:page
151  while getline(1) =~# '^\s*$'
152    silent keepjumps 1delete _
153  endwhile
154  " XXX: nroff justifies text by filling it with whitespace.  That interacts
155  " badly with our use of $MANWIDTH=999.  Hack around this by using a fixed
156  " size for those whitespace regions.
157  silent! keeppatterns keepjumps %s/\s\{199,}/\=repeat(' ', 10)/g
158  1
159  lua require("man").highlight_man_page()
160  call s:set_options(v:false)
161endfunction
162
163function! man#show_toc() abort
164  let bufname = bufname('%')
165  let info = getloclist(0, {'winid': 1})
166  if !empty(info) && getwinvar(info.winid, 'qf_toc') ==# bufname
167    lopen
168    return
169  endif
170
171  let toc = []
172  let lnum = 2
173  let last_line = line('$') - 1
174  while lnum && lnum < last_line
175    let text = getline(lnum)
176    if text =~# '^\%( \{3\}\)\=\S.*$'
177      call add(toc, {'bufnr': bufnr('%'), 'lnum': lnum, 'text': text})
178    endif
179    let lnum = nextnonblank(lnum + 1)
180  endwhile
181
182  call setloclist(0, toc, ' ')
183  call setloclist(0, [], 'a', {'title': 'Man TOC'})
184  lopen
185  let w:qf_toc = bufname
186endfunction
187
188" attempt to extract the name and sect out of 'name(sect)'
189" otherwise just return the largest string of valid characters in ref
190function! s:extract_sect_and_name_ref(ref) abort
191  if a:ref[0] ==# '-' " try ':Man -pandoc' with this disabled.
192    throw 'manpage name cannot start with ''-'''
193  endif
194  let ref = matchstr(a:ref, '[^()]\+([^()]\+)')
195  if empty(ref)
196    let name = matchstr(a:ref, '[^()]\+')
197    if empty(name)
198      throw 'manpage reference cannot contain only parentheses'
199    endif
200    return ['', s:spaces_to_underscores(name)]
201  endif
202  let left = split(ref, '(')
203  " see ':Man 3X curses' on why tolower.
204  " TODO(nhooyr) Not sure if this is portable across OSs
205  " but I have not seen a single uppercase section.
206  return [tolower(split(left[1], ')')[0]), s:spaces_to_underscores(left[0])]
207endfunction
208
209" replace spaces in a man page name with underscores
210" intended for PostgreSQL, which has man pages like 'CREATE_TABLE(7)';
211" while editing SQL source code, it's nice to visually select 'CREATE TABLE'
212" and hit 'K', which requires this transformation
213function! s:spaces_to_underscores(str)
214  return substitute(a:str, ' ', '_', 'g')
215endfunction
216
217function! s:get_path(sect, name) abort
218  " Some man implementations (OpenBSD) return all available paths from the
219  " search command, so we get() the first one. #8341
220  if empty(a:sect)
221    return substitute(get(split(s:system(['man', s:find_arg, a:name])), 0, ''), '\n\+$', '', '')
222  endif
223  " '-s' flag handles:
224  "   - tokens like 'printf(echo)'
225  "   - sections starting with '-'
226  "   - 3pcap section (found on macOS)
227  "   - commas between sections (for section priority)
228  return substitute(get(split(s:system(['man', s:find_arg, s:section_arg, a:sect, a:name])), 0, ''), '\n\+$', '', '')
229endfunction
230
231" s:verify_exists attempts to find the path to a manpage
232" based on the passed section and name.
233"
234" 1. If the passed section is empty, b:man_default_sects is used.
235" 2. If manpage could not be found with the given sect and name,
236"    then another attempt is made with b:man_default_sects.
237" 3. If it still could not be found, then we try again without a section.
238" 4. If still not found but $MANSECT is set, then we try again with $MANSECT
239"    unset.
240"
241" This function is careful to avoid duplicating a search if a previous
242" step has already done it. i.e if we use b:man_default_sects in step 1,
243" then we don't do it again in step 2.
244function! s:verify_exists(sect, name) abort
245  let sect = a:sect
246  if empty(sect)
247    let sect = get(b:, 'man_default_sects', '')
248  endif
249
250  try
251    return s:get_path(sect, a:name)
252  catch /^command error (/
253  endtry
254
255  if !empty(get(b:, 'man_default_sects', '')) && sect !=# b:man_default_sects
256    try
257      return s:get_path(b:man_default_sects, a:name)
258    catch /^command error (/
259    endtry
260  endif
261
262  if !empty(sect)
263    try
264      return s:get_path('', a:name)
265    catch /^command error (/
266    endtry
267  endif
268
269  if !empty($MANSECT)
270    try
271      let MANSECT = $MANSECT
272      call setenv('MANSECT', v:null)
273      return s:get_path('', a:name)
274    catch /^command error (/
275    finally
276      call setenv('MANSECT', MANSECT)
277    endtry
278  endif
279
280  throw 'no manual entry for ' . a:name
281endfunction
282
283" Extracts the name/section from the 'path/name.sect', because sometimes the actual section is
284" more specific than what we provided to `man` (try `:Man 3 App::CLI`).
285" Also on linux, name seems to be case-insensitive. So for `:Man PRIntf`, we
286" still want the name of the buffer to be 'printf'.
287function! s:extract_sect_and_name_path(path) abort
288  let tail = fnamemodify(a:path, ':t')
289  if a:path =~# '\.\%([glx]z\|bz2\|lzma\|Z\)$' " valid extensions
290    let tail = fnamemodify(tail, ':r')
291  endif
292  let sect = matchstr(tail, '\.\zs[^.]\+$')
293  let name = matchstr(tail, '^.\+\ze\.')
294  return [sect, name]
295endfunction
296
297function! s:find_man() abort
298  let l:win = 1
299  while l:win <= winnr('$')
300    let l:buf = winbufnr(l:win)
301    if getbufvar(l:buf, '&filetype', '') ==# 'man'
302      execute l:win.'wincmd w'
303      return 1
304    endif
305    let l:win += 1
306  endwhile
307  return 0
308endfunction
309
310function! s:error(msg) abort
311  redraw
312  echohl ErrorMsg
313  echon 'man.vim: ' a:msg
314  echohl None
315endfunction
316
317" see s:extract_sect_and_name_ref on why tolower(sect)
318function! man#complete(arg_lead, cmd_line, cursor_pos) abort
319  let args = split(a:cmd_line)
320  let cmd_offset = index(args, 'Man')
321  if cmd_offset > 0
322    " Prune all arguments up to :Man itself. Otherwise modifier commands like
323    " :tab, :vertical, etc. would lead to a wrong length.
324    let args = args[cmd_offset:]
325  endif
326  let l = len(args)
327  if l > 3
328    return
329  elseif l ==# 1
330    let name = ''
331    let sect = ''
332  elseif a:arg_lead =~# '^[^()]\+([^()]*$'
333    " cursor (|) is at ':Man printf(|' or ':Man 1 printf(|'
334    " The later is is allowed because of ':Man pri<TAB>'.
335    " It will offer 'priclass.d(1m)' even though section is specified as 1.
336    let tmp = split(a:arg_lead, '(')
337    let name = tmp[0]
338    let sect = tolower(get(tmp, 1, ''))
339    return s:complete(sect, '', name)
340  elseif args[1] !~# '^[^()]\+$'
341    " cursor (|) is at ':Man 3() |' or ':Man (3|' or ':Man 3() pri|'
342    " or ':Man 3() pri |'
343    return
344  elseif l ==# 2
345    if empty(a:arg_lead)
346      " cursor (|) is at ':Man 1 |'
347      let name = ''
348      let sect = tolower(args[1])
349    else
350      " cursor (|) is at ':Man pri|'
351      if a:arg_lead =~# '\/'
352        " if the name is a path, complete files
353        " TODO(nhooyr) why does this complete the last one automatically
354        return glob(a:arg_lead.'*', 0, 1)
355      endif
356      let name = a:arg_lead
357      let sect = ''
358    endif
359  elseif a:arg_lead !~# '^[^()]\+$'
360    " cursor (|) is at ':Man 3 printf |' or ':Man 3 (pr)i|'
361    return
362  else
363    " cursor (|) is at ':Man 3 pri|'
364    let name = a:arg_lead
365    let sect = tolower(args[1])
366  endif
367  return s:complete(sect, sect, name)
368endfunction
369
370function! s:get_paths(sect, name, do_fallback) abort
371  " callers must try-catch this, as some `man` implementations don't support `s:find_arg`
372  try
373    let mandirs = join(split(s:system(['man', s:find_arg]), ':\|\n'), ',')
374    let paths = globpath(mandirs, 'man?/'.a:name.'*.'.a:sect.'*', 0, 1)
375    try
376      " Prioritize the result from verify_exists as it obeys b:man_default_sects.
377      let first = s:verify_exists(a:sect, a:name)
378      let paths = filter(paths, 'v:val !=# first')
379      let paths = [first] + paths
380    catch
381    endtry
382    return paths
383  catch
384    if !a:do_fallback
385      throw v:exception
386    endif
387
388    " Fallback to a single path, with the page we're trying to find.
389    try
390      return [s:verify_exists(a:sect, a:name)]
391    catch
392      return []
393    endtry
394  endtry
395endfunction
396
397function! s:complete(sect, psect, name) abort
398  let pages = s:get_paths(a:sect, a:name, v:false)
399  " We remove duplicates in case the same manpage in different languages was found.
400  return uniq(sort(map(pages, 's:format_candidate(v:val, a:psect)'), 'i'))
401endfunction
402
403function! s:format_candidate(path, psect) abort
404  if a:path =~# '\.\%(pdf\|in\)$' " invalid extensions
405    return
406  endif
407  let [sect, name] = s:extract_sect_and_name_path(a:path)
408  if sect ==# a:psect
409    return name
410  elseif sect =~# a:psect.'.\+$'
411    " We include the section if the user provided section is a prefix
412    " of the actual section.
413    return name.'('.sect.')'
414  endif
415endfunction
416
417" Called when Nvim is invoked as $MANPAGER.
418function! man#init_pager() abort
419  " https://github.com/neovim/neovim/issues/6828
420  let og_modifiable = &modifiable
421  setlocal modifiable
422
423  if getline(1) =~# '^\s*$'
424    silent keepjumps 1delete _
425  else
426    keepjumps 1
427  endif
428  lua require("man").highlight_man_page()
429  " Guess the ref from the heading (which is usually uppercase, so we cannot
430  " know the correct casing, cf. `man glDrawArraysInstanced`).
431  let ref = substitute(matchstr(getline(1), '^[^)]\+)'), ' ', '_', 'g')
432  try
433    let b:man_sect = s:extract_sect_and_name_ref(ref)[0]
434  catch
435    let b:man_sect = ''
436  endtry
437  if -1 == match(bufname('%'), 'man:\/\/')  " Avoid duplicate buffers, E95.
438    execute 'silent file man://'.tolower(fnameescape(ref))
439  endif
440
441  call s:set_options(v:true)
442  let &l:modifiable = og_modifiable
443endfunction
444
445function! man#goto_tag(pattern, flags, info) abort
446  let [l:sect, l:name] = s:extract_sect_and_name_ref(a:pattern)
447
448  let l:paths = s:get_paths(l:sect, l:name, v:true)
449  let l:structured = []
450
451  for l:path in l:paths
452    let [l:sect, l:name] = s:extract_sect_and_name_path(l:path)
453    let l:structured += [{
454          \ 'name': l:name,
455          \ 'title': l:name . '(' . l:sect . ')'
456          \ }]
457  endfor
458
459  if &cscopetag
460    " return only a single entry so we work well with :cstag (#11675)
461    let l:structured = l:structured[:0]
462  endif
463
464  return map(l:structured, {
465  \  _, entry -> {
466  \      'name': entry.name,
467  \      'filename': 'man://' . entry.title,
468  \      'cmd': '1'
469  \    }
470  \  })
471endfunction
472
473call man#init()
474