local api, fn = vim.api, vim.fn
local M = {}
local function system(cmd, silent, env)
if fn.executable(cmd[1]) == 0 then
error(string.format('executable not found: "%s"', cmd[1]), 0)
end
local r = vim.system(cmd, { env = env, timeout = 10000 }):wait()
if not silent then
if r.code ~= 0 then
local cmd_str = table.concat(cmd, ' ')
error(string.format("command error '%s': %s", cmd_str, r.stderr))
end
assert(r.stdout ~= '')
end
return assert(r.stdout)
end
local Attrs = {
None = 0,
Bold = 1,
Underline = 2,
Italic = 3,
}
local function render_line(line, row, hls)
local chars = {}
local prev_char = ''
local overstrike, escape, osc8 = false, false, false
local attr = Attrs.None
local byte = 0
local hls_start = #hls + 1
local function add_attr_hl(code)
local continue_hl = true
if code == 0 then
attr = Attrs.None
continue_hl = false
elseif code == 1 then
attr = Attrs.Bold
elseif code == 22 then
attr = Attrs.Bold
continue_hl = false
elseif code == 3 then
attr = Attrs.Italic
elseif code == 23 then
attr = Attrs.Italic
continue_hl = false
elseif code == 4 then
attr = Attrs.Underline
elseif code == 24 then
attr = Attrs.Underline
continue_hl = false
else
attr = Attrs.None
return
end
if continue_hl then
hls[#hls + 1] = { attr = attr, row = row, start = byte, final = -1 }
else
for _, a in pairs(attr == Attrs.None and Attrs or { attr }) do
for i = hls_start, #hls do
if hls[i].attr == a and hls[i].final == -1 then
hls[i].final = byte
end
end
end
end
end
for char in line:gmatch('[^\128-\191][\128-\191]*') do
if overstrike then
local last_hl = hls[#hls]
if char == prev_char then
if char == '_' and attr == Attrs.Italic and last_hl and last_hl.final == byte then
attr = Attrs.Italic
else
attr = Attrs.Bold
end
elseif prev_char == '_' then
attr = Attrs.Italic
elseif prev_char == '+' and char == 'o' then
attr = Attrs.Bold
char = '·'
elseif prev_char == '·' and char == 'o' then
attr = Attrs.Bold
char = '·'
else
attr = Attrs.None
end
if last_hl and last_hl.attr == attr and last_hl.final == byte then
last_hl.final = byte + #char
else
hls[#hls + 1] = { attr = attr, row = row, start = byte, final = byte + #char }
end
overstrike = false
prev_char = ''
byte = byte + #char
chars[#chars + 1] = char
elseif osc8 then
if (prev_char == '\027' and char == '\\') or char == '\a' then
osc8 = false
end
prev_char = char
elseif escape then
prev_char = prev_char .. char
local sgr = prev_char:match('^%[([\032-\063]*)m$')
if sgr and not sgr:find(':') then
local match
while sgr and #sgr > 0 do
match, sgr = sgr:match('^(%d*);?(.*)')
add_attr_hl(match + 0)
end
escape = false
elseif prev_char == ']8;' then
osc8 = true
escape = false
elseif not prev_char:match('^[][][\032-\063]*$') then
escape = false
end
elseif char == '\027' then
escape = true
prev_char = ''
elseif char == '\b' then
overstrike = true
prev_char = chars[#chars]
byte = byte - #prev_char
chars[#chars] = nil
else
byte = byte + #char
chars[#chars + 1] = char
end
end
return table.concat(chars, '')
end
local HlGroups = {
[Attrs.Bold] = 'manBold',
[Attrs.Underline] = 'manUnderline',
[Attrs.Italic] = 'manItalic',
}
local function highlight_man_page()
local mod = vim.bo.modifiable
vim.bo.modifiable = true
local lines = api.nvim_buf_get_lines(0, 0, -1, false)
local hls = {}
for i, line in ipairs(lines) do
lines[i] = render_line(line, i - 1, hls)
end
api.nvim_buf_set_lines(0, 0, -1, false, lines)
for _, hl in ipairs(hls) do
if hl.attr ~= Attrs.None then
api.nvim_buf_add_highlight(0, -1, HlGroups[hl.attr], hl.row, hl.start, hl.final)
end
end
vim.bo.modifiable = mod
end
local function get_path(name, sect)
name = name or ''
sect = sect or ''
local cmd
if sect == '' then
cmd = { 'man', '-w', name }
else
cmd = { 'man', '-w', sect, name }
end
local lines = system(cmd, true)
local results = vim.split(lines, '\n', { trimempty = true })
if #results == 0 then
return
end
if sect == '' and #results == 1 and results[1] == name then
return
end
local namematches = vim.tbl_filter(function(v)
local tail = fn.fnamemodify(v, ':t')
return tail:find(name, 1, true) ~= nil
end, results) or {}
local sectmatches = {}
if #namematches > 0 and sect ~= '' then
sectmatches = vim.tbl_filter(function(v)
return fn.fnamemodify(v, ':e') == sect
end, namematches)
end
return (sectmatches[1] or namematches[1] or results[1]):gsub('\n+$', '')
end
local function parse_ref(ref)
if ref == '' or ref:sub(1, 1) == '-' then
return nil, nil, ('invalid manpage reference "%s"'):format(ref)
end
local name, sect = ref:match('([^()]+)%(([^()]+)%)')
if name then
return name, sect:lower()
end
name = ref:match('[^()]+')
if not name then
return nil, nil, ('invalid manpage reference "%s"'):format(ref)
end
return name
end
function M._find_path(name, sect)
if sect and sect ~= '' then
local ret = get_path(name, sect)
if ret then
return ret
end
end
if vim.b.man_default_sects ~= nil then
for sec in vim.gsplit(vim.b.man_default_sects, ',', { trimempty = true }) do
local ret = get_path(name, sec)
if ret then
return ret
end
end
end
local ret = get_path(name)
if ret then
return ret
end
if vim.env.MANSECT then
local mansect = vim.env.MANSECT
vim.env.MANSECT = nil
local res = get_path(name)
vim.env.MANSECT = mansect
if res then
return res
end
end
return nil
end
local function parse_path(path)
local tail = fn.fnamemodify(path, ':t')
if
path:match('%.[glx]z$')
or path:match('%.bz2$')
or path:match('%.lzma$')
or path:match('%.Z$')
then
tail = fn.fnamemodify(tail, ':r')
end
return tail:match('^(.+)%.([^.]+)$')
end
local function find_man()
if vim.bo.filetype == 'man' then
return true
end
local win = 1
while win <= fn.winnr('$') do
local buf = fn.winbufnr(win)
if vim.bo[buf].filetype == 'man' then
vim.cmd(win .. 'wincmd w')
return true
end
win = win + 1
end
return false
end
local function set_options()
vim.bo.swapfile = false
vim.bo.buftype = 'nofile'
vim.bo.bufhidden = 'unload'
vim.bo.modified = false
vim.bo.readonly = true
vim.bo.modifiable = false
vim.bo.filetype = 'man'
end
local localfile_arg
local function get_page(path, silent)
local manwidth
if (vim.g.man_hardwrap or 1) ~= 1 then
manwidth = 999
elseif vim.env.MANWIDTH then
vim.env.MANWIDTH = tonumber(vim.env.MANWIDTH) or 0
manwidth = math.min(vim.env.MANWIDTH, api.nvim_win_get_width(0) - vim.o.wrapmargin)
else
manwidth = api.nvim_win_get_width(0) - vim.o.wrapmargin
end
if localfile_arg == nil then
local mpath = get_path('man')
localfile_arg = (mpath and system({ 'man', '-l', mpath }, true, { MANPAGER = 'cat' }) or '')
~= ''
end
local cmd = localfile_arg and { 'man', '-l', path } or { 'man', path }
return system(cmd, silent, {
MANPAGER = 'cat',
MANWIDTH = manwidth,
MAN_KEEP_FORMATTING = 1,
})
end
local function format_candidate(path, psect)
if vim.endswith(path, '.pdf') or vim.endswith(path, '.in') then
return ''
end
local name, sect = parse_path(path)
if sect == psect then
return name
elseif sect:match(psect .. '.+$') then
return ('%s(%s)'):format(name, sect)
end
return ''
end
local function get_paths(name, sect)
local mandirs_raw = vim.F.npcall(system, { 'manpath', '-q' })
or vim.F.npcall(system, { 'man', '-w' })
or vim.env.MANPATH
if not mandirs_raw then
return {}, "Could not determine man directories from: 'man -w', 'manpath' or $MANPATH"
end
local mandirs = table.concat(vim.split(mandirs_raw, '[:\n]', { trimempty = true }), ',')
sect = sect or ''
local paths = fn.globpath(mandirs, 'man[^\\/]*/' .. name .. '*.' .. sect .. '*', false, true)
local first = M._find_path(name, sect)
if first then
paths = vim.tbl_filter(function(v)
return v ~= first
end, paths)
table.insert(paths, 1, first)
end
return paths
end
local function parse_cmdline(arg_lead, cmd_line)
local args = vim.split(cmd_line, '%s+', { trimempty = true })
local cmd_offset = fn.index(args, 'Man')
if cmd_offset > 0 then
args = vim.list_slice(args, cmd_offset + 1)
end
if #args > 3 then
return
end
if #args == 1 then
return
end
if arg_lead:match('^[^()]+%([^()]*$') then
local tmp = vim.split(arg_lead, '(', { plain = true })
local name = tmp[1]
local sect = (tmp[2] or ''):lower()
return sect, '', name
end
if not args[2]:match('^[^()]+$') then
return
end
if #args == 2 then
local name, sect
if arg_lead == '' then
name = ''
sect = args[1]:lower()
else
if arg_lead:match('/') then
return fn.glob(arg_lead .. '*', false, true)
end
name = arg_lead
sect = ''
end
return sect, sect, name
end
if not arg_lead:match('[^()]+$') then
return
end
local name, sect = arg_lead, args[2]:lower()
return sect, sect, name
end
function M.man_complete(arg_lead, cmd_line)
local sect, psect, name = parse_cmdline(arg_lead, cmd_line)
if not (sect and psect and name) then
return {}
end
local ok, pages = pcall(get_paths, name, sect)
if not ok then
return nil
end
local pages_fmt = {}
local pages_fmt_keys = {}
for _, v in ipairs(pages) do
local x = format_candidate(v, psect)
local xl = x:lower()
if not pages_fmt_keys[xl] then
pages_fmt[#pages_fmt + 1] = x
pages_fmt_keys[xl] = true
end
end
table.sort(pages_fmt)
return pages_fmt
end
function M.goto_tag(pattern, _, _)
local name, sect, err = parse_ref(pattern)
if err then
error(err)
end
local paths, err2 = get_paths(assert(name), sect)
if err2 then
error(err2)
end
local ret = {}
for _, path in ipairs(paths) do
local pname, psect = parse_path(path)
ret[#ret + 1] = {
name = pname,
filename = ('man://%s(%s)'):format(pname, psect),
cmd = '1',
}
end
return ret
end
function M.init_pager()
if fn.getline(1):match('^%s*$') then
api.nvim_buf_set_lines(0, 0, 1, false, {})
else
vim.cmd('keepjumps 1')
end
highlight_man_page()
local ref = (fn.getline(1):match('^[^)]+%)') or ''):gsub(' ', '_')
local _, sect, err = pcall(parse_ref, ref)
vim.b.man_sect = err ~= nil and sect or ''
local man_bufname = 'man://' .. fn.fnameescape(ref):lower()
if fn.bufexists(man_bufname) == 1 then
local new_bufname = man_bufname
for i = 1, 100 do
if fn.bufexists(new_bufname) == 0 then
break
end
new_bufname = ('%s?new=%s'):format(man_bufname, i)
end
vim.cmd.file({ new_bufname, mods = { silent = true } })
elseif not fn.bufname('%'):match('man://') then
vim.cmd.file({ man_bufname, mods = { silent = true } })
end
set_options()
end
local function ref_from_args(args)
if #args <= 1 then
return args[1]
elseif args[1]:match('^%d$') or args[1]:match('^%d%a') or args[1]:match('^%a$') then
local sect = args[1]
table.remove(args, 1)
local name = table.concat(args, ' ')
return ('%s(%s)'):format(name, sect)
end
return table.concat(args, ' ')
end
function M.open_page(count, smods, args)
local ref = ref_from_args(args)
if not ref then
ref = vim.bo.filetype == 'man' and fn.expand('<cWORD>') or fn.expand('<cword>')
if ref == '' then
return 'no identifier under cursor'
end
end
local name, sect, err = parse_ref(ref)
if err then
return err
end
assert(name)
if count >= 0 then
sect = tostring(count)
end
local path = M._find_path(name, sect)
if not path then
path = M._find_path(name:gsub('%s', '_'), sect)
if not path then
return 'no manual entry for ' .. name
end
end
name, sect = parse_path(path)
local buf = api.nvim_get_current_buf()
local save_tfu = vim.bo[buf].tagfunc
vim.bo[buf].tagfunc = "v:lua.require'man'.goto_tag"
local target = ('%s(%s)'):format(name, sect)
local ok, ret = pcall(function()
smods.silent = true
smods.keepalt = true
if smods.hide or (smods.tab == -1 and find_man()) then
vim.cmd.tag({ target, mods = smods })
else
vim.cmd.stag({ target, mods = smods })
end
end)
if api.nvim_buf_is_valid(buf) then
vim.bo[buf].tagfunc = save_tfu
end
if not ok then
error(ret)
end
set_options()
vim.b.man_sect = sect
end
function M.read_page(ref)
local name, sect, err = parse_ref(ref)
if err then
return err
end
local path = M._find_path(name, sect)
if not path then
return 'no manual entry for ' .. name
end
local _, sect1 = parse_path(path)
local page = get_page(path)
vim.b.man_sect = sect1
vim.bo.modifiable = true
vim.bo.readonly = false
vim.bo.swapfile = false
api.nvim_buf_set_lines(0, 0, -1, false, vim.split(page, '\n'))
while fn.getline(1):match('^%s*$') do
api.nvim_buf_set_lines(0, 0, 1, false, {})
end
vim.cmd([[
try
keeppatterns keepjumps %s/\s\{199,}/\=repeat(' ', 10)/g
catch
endtry
]])
vim.cmd('1')
highlight_man_page()
set_options()
end
function M.show_toc()
local bufnr = api.nvim_get_current_buf()
local bufname = api.nvim_buf_get_name(bufnr)
local info = fn.getloclist(0, { winid = 1 })
if info ~= '' and vim.w[info.winid].qf_toc == bufname then
vim.cmd.lopen()
return
end
local toc = {}
local lnum = 2
local last_line = fn.line('$') - 1
while lnum and lnum < last_line do
local text = fn.getline(lnum)
if text:match('^%s+[-+]%S') or text:match('^ %S') or text:match('^%S') then
toc[#toc + 1] = {
bufnr = bufnr,
lnum = lnum,
text = text:gsub('^%s+', ''):gsub('%s+$', ''),
}
end
lnum = fn.nextnonblank(lnum + 1)
end
fn.setloclist(0, toc, ' ')
fn.setloclist(0, {}, 'a', { title = 'Table of contents' })
vim.cmd.lopen()
vim.w.qf_toc = bufname
vim.bo.filetype = 'qf'
end
return M