blob: 32bf80c765b7049e29f333e82e8a85734cdba0ad [file] [log] [blame]
Bram Moolenaard799daa2022-06-20 11:17:32 +01001" Vim filetype plugin autoload file
2" Language: man
lifecrisis17befac2023-08-20 18:41:25 +00003" Maintainer: Jason Franklin <jason@oneway.dev>
Bram Moolenaard799daa2022-06-20 11:17:32 +01004" Maintainer: SungHyun Nam <goweol@gmail.com>
5" Autoload Split: Bram Moolenaar
Christian Brabandtf942db22024-01-17 21:50:16 +01006" Last Change: 2024 Jan 17 (make it work on AIX, see #13847)
Ivan Shapovalov84ca1382024-07-06 16:56:02 +02007" 2024 Jul 06 (honor command modifiers, #15117)
David Mandelbergb34ce3e2025-03-05 20:38:20 +01008" 2025 Mar 05 (add :keepjumps, #16791)
David Mandelbergc2623822025-03-10 21:26:50 +01009" 2025 Mar 09 (improve :Man completion for man-db, #16843)
Bram Moolenaard799daa2022-06-20 11:17:32 +010010
11let s:cpo_save = &cpo
12set cpo-=C
13
14let s:man_tag_depth = 0
15
16let s:man_sect_arg = ""
17let s:man_find_arg = "-w"
18try
Christian Brabandtf942db22024-01-17 21:50:16 +010019 if !has("win32") && $OSTYPE !~ 'cygwin\|linux'
20 " cache the value
21 let uname_s = system('uname -s')
22
23 if uname_s =~ "SunOS" && system('uname -r') =~ "^5"
24 " Special Case for Man on SunOS
25 let s:man_sect_arg = "-s"
26 let s:man_find_arg = "-l"
27 elseif uname_s =~? 'AIX'
28 " Special Case for Man on AIX
29 let s:man_sect_arg = ""
30 let s:man_find_arg = ""
31 endif
Bram Moolenaard799daa2022-06-20 11:17:32 +010032 endif
33catch /E145:/
34 " Ignore the error in restricted mode
35endtry
36
Christian Brabandtf942db22024-01-17 21:50:16 +010037unlet! uname_s
38
David Mandelbergc2623822025-03-10 21:26:50 +010039let s:man_db_pages_by_section = v:null
40func! s:ManDbPagesBySection() abort
41 if s:man_db_pages_by_section isnot v:null
42 return s:man_db_pages_by_section
43 endif
44 let s:man_db_pages_by_section = {}
45 let list_command = 'apropos --long .'
46 let unparsed_lines = []
47 for line in systemlist(list_command)
48 " Typical lines:
49 " vim (1) - Vi IMproved, a programmer's text editor
50 "
51 " Unusual lines:
52 " pgm_read_ T _ (3avr) - (unknown subject)
53 "
54 " Code that shows the line's format:
55 " https://gitlab.com/man-db/man-db/-/blob/2607d203472efb036d888e9e7997724a41a53876/src/whatis.c#L409
56 let match = matchlist(line, '^\(.\{-1,}\) (\(\S\+\)) ')
57 if empty(match)
58 call add(unparsed_lines, line)
59 continue
60 endif
61 let [page, section] = match[1:2]
62 if !has_key(s:man_db_pages_by_section, section)
63 let s:man_db_pages_by_section[section] = []
64 endif
65 call add(s:man_db_pages_by_section[section], page)
66 endfor
67 if !empty(unparsed_lines)
68 echomsg 'Unable to parse ' .. string(len(unparsed_lines)) .. ' lines ' ..
69 \ 'from the output of `' .. list_command .. '`. Example lines:'
70 for line in unparsed_lines[:9]
71 echomsg line
72 endfor
73 endif
74 return s:man_db_pages_by_section
75endfunc
76
77func! dist#man#Reload() abort
78 if g:ft_man_implementation ==# 'man-db'
79 let s:man_db_pages_by_section = v:null
80 call s:ManDbPagesBySection()
81 endif
82endfunc
83
84func! s:StartsWithCaseInsensitive(haystack, needle) abort
85 if empty(a:needle)
86 return v:true
87 endif
88 return a:haystack[:len(a:needle)-1] ==? a:needle
89endfunc
90
91func! dist#man#ManDbComplete(arg_lead, cmd_line, cursor_pos) abort
92 let args = split(trim(a:cmd_line[: a:cursor_pos - 1], '', 1), '', v:true)
93 let pages_by_section = s:ManDbPagesBySection()
94 if len(args) > 2
95 " Page in the section args[1]. At least on Debian testing as of
96 " 2025-03-06, man seems to match sections case-insensitively and match any
97 " prefix of the section. E.g., `man 3 sigprocmask` and `man 3PoSi
98 " sigprocmask` with both load sigprocmask(3posix) even though the 3 in the
99 " first command is also the name of a different section.
100 let results = []
101 for [section, pages] in items(pages_by_section)
102 if s:StartsWithCaseInsensitive(section, args[1])
103 call extend(results, pages)
104 endif
105 endfor
106 else
107 " Could be a section, or a page in any section. Add space after sections
108 " since there has to be a second argument in that case.
109 let results = flattennew(values(pages_by_section), 1)
110 for section in keys(pages_by_section)
111 call add(results, section .. ' ')
112 endfor
113 endif
114 call sort(results)
115 call uniq(results)
116 call filter(results,
117 \ {_, val -> s:StartsWithCaseInsensitive(val, a:arg_lead)})
118 return results
119endfunc
120
goweol8cfe52e2023-08-18 06:13:29 +0900121func s:ParseIntoPageAndSection()
122 " Accommodate a reference that terminates in a hyphen.
123 "
124 " See init_charset_table() at
125 " https://git.savannah.gnu.org/cgit/groff.git/tree/src/roff/troff/input.cpp?h=1.22.4#n6794
126 "
127 " See can_break_after() at
128 " https://git.savannah.gnu.org/cgit/groff.git/tree/src/roff/troff/charinfo.h?h=1.22.4#n140
129 "
130 " Assumptions and limitations:
131 " 1) Manual-page references (in consequence of command-related filenames)
132 " do not contain non-ASCII HYPHENs (0x2010), any terminating HYPHEN
133 " must have been introduced to mark division of a word at the end of
134 " a line and can be discarded; whereas similar references may contain
135 " ASCII HYPHEN-MINUSes (0x002d) and any terminating HYPHEN-MINUS forms
136 " a compound word in addition to marking word division.
137 " 2) Well-formed manual-page references always have a section suffix, e.g.
138 " "git-commit(1)", therefore suspended hyphenated compounds are not
139 " determined, e.g. [V] (With cursor at _git-merge-_ below...)
140 " ".................... git-merge- and git-merge-base. (See git-cherry-
141 " pick(1) and git-cherry(1).)" (... look up "git-merge-pick(1)".)
142 "
143 " Note that EM DASH (0x2014), a third stooge from init_charset_table(),
144 " neither connects nor divides parts of a word.
145 let str = expand("<cWORD>")
146
147 if str =~ '\%u2010$' " HYPHEN (-1).
148 let str = strpart(str, 0, strridx(str, "\u2010"))
149
150 " Append the leftmost WORD (or an empty string) from the line below.
151 let str .= get(split(get(getbufline(bufnr('%'), line('.') + 1), 0, '')), 0, '')
152 elseif str =~ '-$' " HYPHEN-MINUS.
153 " Append the leftmost WORD (or an empty string) from the line below.
154 let str .= get(split(get(getbufline(bufnr('%'), line('.') + 1), 0, '')), 0, '')
155 endif
156
157 " According to man(1), section name formats vary (MANSECT):
158 " 1 n l 8 3 2 3posix 3pm 3perl 3am 5 4 9 6 7
159 let parts = matchlist(str, '\(\k\+\)(\(\k\+\))')
160 return (len(parts) > 2)
161 \ ? {'page': parts[1], 'section': parts[2]}
162 \ : {'page': matchstr(str, '\k\+'), 'section': ''}
163endfunc
164
Bram Moolenaard799daa2022-06-20 11:17:32 +0100165func dist#man#PreGetPage(cnt)
166 if a:cnt == 0
goweol8cfe52e2023-08-18 06:13:29 +0900167 let what = s:ParseIntoPageAndSection()
168 let sect = what.section
169 let page = what.page
Bram Moolenaard799daa2022-06-20 11:17:32 +0100170 else
goweol8cfe52e2023-08-18 06:13:29 +0900171 let what = s:ParseIntoPageAndSection()
Bram Moolenaard799daa2022-06-20 11:17:32 +0100172 let sect = a:cnt
goweol8cfe52e2023-08-18 06:13:29 +0900173 let page = what.page
Bram Moolenaard799daa2022-06-20 11:17:32 +0100174 endif
goweol8cfe52e2023-08-18 06:13:29 +0900175
Bram Moolenaard799daa2022-06-20 11:17:32 +0100176 call dist#man#GetPage('', sect, page)
177endfunc
178
179func s:GetCmdArg(sect, page)
Bram Moolenaard799daa2022-06-20 11:17:32 +0100180 if empty(a:sect)
181 return shellescape(a:page)
182 endif
183
184 return s:man_sect_arg . ' ' . shellescape(a:sect) . ' ' . shellescape(a:page)
185endfunc
186
187func s:FindPage(sect, page)
188 let l:cmd = printf('man %s %s', s:man_find_arg, s:GetCmdArg(a:sect, a:page))
189 call system(l:cmd)
190
191 if v:shell_error
192 return 0
193 endif
194
195 return 1
196endfunc
197
198func dist#man#GetPage(cmdmods, ...)
199 if a:0 >= 2
200 let sect = a:1
201 let page = a:2
202 elseif a:0 >= 1
203 let sect = ""
204 let page = a:1
205 else
206 return
207 endif
208
goweol8cfe52e2023-08-18 06:13:29 +0900209 " To support: nmap K :Man <cWORD><CR>
210 if page ==? '<cword>'
211 let what = s:ParseIntoPageAndSection()
212 let sect = what.section
213 let page = what.page
Bram Moolenaard799daa2022-06-20 11:17:32 +0100214 endif
215
216 if !exists('g:ft_man_no_sect_fallback') || (g:ft_man_no_sect_fallback == 0)
217 if sect != "" && s:FindPage(sect, page) == 0
218 let sect = ""
219 endif
220 endif
221 if s:FindPage(sect, page) == 0
222 let msg = 'man.vim: no manual entry for "' . page . '"'
223 if !empty(sect)
224 let msg .= ' in section ' . sect
225 endif
226 echomsg msg
227 return
228 endif
229 exec "let s:man_tag_buf_".s:man_tag_depth." = ".bufnr("%")
230 exec "let s:man_tag_lin_".s:man_tag_depth." = ".line(".")
231 exec "let s:man_tag_col_".s:man_tag_depth." = ".col(".")
232 let s:man_tag_depth = s:man_tag_depth + 1
233
234 let open_cmd = 'edit'
235
236 " Use an existing "man" window if it exists, otherwise open a new one.
237 if &filetype != "man"
238 let thiswin = winnr()
239 exe "norm! \<C-W>b"
240 if winnr() > 1
241 exe "norm! " . thiswin . "\<C-W>w"
242 while 1
243 if &filetype == "man"
244 break
245 endif
246 exe "norm! \<C-W>w"
247 if thiswin == winnr()
248 break
249 endif
250 endwhile
251 endif
252 if &filetype != "man"
Ivan Shapovalov84ca1382024-07-06 16:56:02 +0200253 if a:cmdmods =~ '\<\(tab\|vertical\|horizontal\)\>'
254 let open_cmd = a:cmdmods . ' split'
255 elseif exists("g:ft_man_open_mode")
Bram Moolenaard799daa2022-06-20 11:17:32 +0100256 if g:ft_man_open_mode == 'vert'
257 let open_cmd = 'vsplit'
258 elseif g:ft_man_open_mode == 'tab'
259 let open_cmd = 'tabedit'
260 else
261 let open_cmd = 'split'
262 endif
263 else
Ivan Shapovalov84ca1382024-07-06 16:56:02 +0200264 let open_cmd = 'split'
Bram Moolenaard799daa2022-06-20 11:17:32 +0100265 endif
266 endif
267 endif
268
269 silent execute open_cmd . " $HOME/" . page . '.' . sect . '~'
270
271 " Avoid warning for editing the dummy file twice
272 setl buftype=nofile noswapfile
273
274 setl fdc=0 ma nofen nonu nornu
David Mandelbergb34ce3e2025-03-05 20:38:20 +0100275 keepjumps %delete _
Bram Moolenaard799daa2022-06-20 11:17:32 +0100276 let unsetwidth = 0
277 if empty($MANWIDTH)
278 let $MANWIDTH = winwidth(0)
279 let unsetwidth = 1
280 endif
281
282 " Ensure Vim is not recursively invoked (man-db does this) when doing ctrl-[
283 " on a man page reference by unsetting MANPAGER.
284 " Some versions of env(1) do not support the '-u' option, and in such case
285 " we set MANPAGER=cat.
286 if !exists('s:env_has_u')
287 call system('env -u x true')
288 let s:env_has_u = (v:shell_error == 0)
289 endif
290 let env_cmd = s:env_has_u ? 'env -u MANPAGER' : 'env MANPAGER=cat'
291 let env_cmd .= ' GROFF_NO_SGR=1'
lifecrisis17befac2023-08-20 18:41:25 +0000292 let man_cmd = env_cmd . ' man ' . s:GetCmdArg(sect, page)
293
Bram Moolenaard799daa2022-06-20 11:17:32 +0100294 silent exec "r !" . man_cmd
295
lifecrisis17befac2023-08-20 18:41:25 +0000296 " Emulate piping the buffer through the "col -b" command.
297 " Ref: https://github.com/vim/vim/issues/12301
Yee Cheng Chin249a2082023-09-16 18:09:47 +0200298 exe 'silent! keepjumps keeppatterns %s/\v(.)\b\ze\1?//e' .. (&gdefault ? '' : 'g')
lifecrisis17befac2023-08-20 18:41:25 +0000299
Bram Moolenaard799daa2022-06-20 11:17:32 +0100300 if unsetwidth
301 let $MANWIDTH = ''
302 endif
303 " Remove blank lines from top and bottom.
304 while line('$') > 1 && getline(1) =~ '^\s*$'
David Mandelbergb34ce3e2025-03-05 20:38:20 +0100305 keepjumps 1delete _
Bram Moolenaard799daa2022-06-20 11:17:32 +0100306 endwhile
307 while line('$') > 1 && getline('$') =~ '^\s*$'
David Mandelbergb34ce3e2025-03-05 20:38:20 +0100308 keepjumps $delete _
Bram Moolenaard799daa2022-06-20 11:17:32 +0100309 endwhile
310 1
311 setl ft=man nomod
312 setl bufhidden=hide
313 setl nobuflisted
314 setl noma
315endfunc
316
317func dist#man#PopPage()
318 if s:man_tag_depth > 0
319 let s:man_tag_depth = s:man_tag_depth - 1
320 exec "let s:man_tag_buf=s:man_tag_buf_".s:man_tag_depth
321 exec "let s:man_tag_lin=s:man_tag_lin_".s:man_tag_depth
322 exec "let s:man_tag_col=s:man_tag_col_".s:man_tag_depth
goweol6e5ab2b2023-08-18 06:12:42 +0900323
Bram Moolenaard799daa2022-06-20 11:17:32 +0100324 exec s:man_tag_buf."b"
goweol6e5ab2b2023-08-18 06:12:42 +0900325 call cursor(s:man_tag_lin, s:man_tag_col)
326
Bram Moolenaard799daa2022-06-20 11:17:32 +0100327 exec "unlet s:man_tag_buf_".s:man_tag_depth
328 exec "unlet s:man_tag_lin_".s:man_tag_depth
329 exec "unlet s:man_tag_col_".s:man_tag_depth
330 unlet s:man_tag_buf s:man_tag_lin s:man_tag_col
331 endif
332endfunc
333
334let &cpo = s:cpo_save
335unlet s:cpo_save
336
337" vim: set sw=2 ts=8 noet: