\n%s', text)
end
if opt.old then
-- XXX: Treat "old" docs as preformatted: they use indentation for layout.
-- Trim trailing newlines to avoid too much whitespace between divs.
return ('
%s
\n'):format(trim(text, 2))
end
return string.format('
\n%s\n
\n', text)
elseif node_name == 'line' then
if
(parent ~= 'codeblock' and parent ~= 'code')
and (is_blank(text) or is_noise(text, stats.noise_lines))
then
return '' -- Discard common "noise" lines.
end
if parent == 'codeblock' or parent == 'code' then
return text -- Includes its newline.
end
-- Tags at EOL (not listitem) after Tab/2+ spaces are right-aligned, own div. |help-tag-heading|
local t = #parts + 1 -- First trailing tag.
while t > 1 and assert(root:named_child(t - 2)):type() == 'tag' do
t = t - 1
end
local tags = table.concat(parts, '', t)
local gap = tags:match('^%s*')
local before = table.concat(parts, '', 1, t - 1)
local tagspan = ('
%s'):format(trim(tags))
local is_heading = parent == 'block' and trim(tags) ~= '' and (#gap >= 2 or gap:find('\t'))
if is_heading and opt.old then
return ('%s%s%s\n'):format(before, gap, tagspan) -- Preformatted: the newline ends the line.
elseif is_heading then
return ('
%s%s
\n'):format(before, tagspan)
end
-- XXX: Avoid newlines (too much whitespace) after block elements in old (preformatted) layout.
local div = opt.old
and root:child(0)
and vim.list_contains({ 'column_heading', 'h1', 'h2', 'h3' }, root:child(0):type())
return string.format('%s%s', div and trim(text) or text, div and '' or '\n')
elseif parent == 'line_li' and node_name == 'prefix' then
return ''
elseif node_name == 'line_li' then
local prefix = first(root, 'prefix')
local numli = prefix and trim(node_text(prefix)):match('%d') -- Numbered listitem?
local sib = root:prev_sibling()
local prev_li = sib and sib:type() == 'line_li'
local cssclass = numli and 'help-li-num' or 'help-li'
-- Conjoin list items separated by blank lines (wrapped in separate blocks), unless the block
-- starts with something else (then it's a new list).
if not sib then
local parent_block = root:parent()
local prev_block = parent_block and parent_block:prev_sibling()
local prev_last = prev_block and prev_block:type() == 'block' and last(prev_block)
if prev_last and prev_last:type() == 'line_li' then
prev_li = true
sib = prev_last
end
end
-- Column of the prefix, not `root`: it may start at a codeblock-terminating "<".
local this_w = get_col(assert(prefix), opt.buf)
if not prev_li then
opt.indent = 1
-- Track the indent width for each indent level so that we can dedent
-- to the correct level later.
opt.indent_w = { this_w }
else
opt.indent_w = opt.indent_w or { this_w }
local sib_w = get_col(assert(first(sib, 'prefix')), opt.buf)
-- Unindented listitem is top-level. Check only its first line: other lines in the captured
-- listitem may be at column 0 (e.g. codeblock ">" or "<").
if this_w == 0 then
opt.indent = 1
opt.indent_w = { this_w }
elseif this_w > sib_w then
-- Previous sibling is logically the _parent_ if it is indented less.
opt.indent = opt.indent + 1
opt.indent_w[opt.indent] = this_w
elseif this_w < sib_w then
-- Dedent: pop indent levels deeper than the current item, so we return to the correct
-- ancestor level.
while opt.indent > 1 and (opt.indent_w[opt.indent] or 0) > this_w do
opt.indent_w[opt.indent] = nil
opt.indent = opt.indent - 1
end
opt.indent_w[opt.indent] = this_w
end
end
local margin = opt.indent == 1 and '' or ('margin-left: %drem;'):format((1.5 * opt.indent))
return string.format('
%s
', cssclass, margin, text)
elseif node_name == 'taglink' or node_name == 'optionlink' then
local helppage, tagname, ignored = validate_link(root, opt.buf, opt.fname)
if ignored or not helppage then
return html_esc(node_text(root))
end
return ('%s
%s'):format(
ws(),
helppage,
url_encode(tagname),
html_esc(tagname)
)
elseif vim.list_contains({ 'codespan', 'keycode' }, node_name) then
if root:has_error() then
return text
end
return ('%s
%s'):format(ws(), trimmed)
elseif node_name == 'argument' then
return ('%s
%s'):format(ws(), trim(node_text(root)))
elseif node_name == 'codeblock' then
return text
elseif node_name == 'language' then
language = trim(node_text(root))
return ''
elseif node_name == 'code' then -- Highlighted codeblock (child).
if is_blank(text) then
return ''
end
local code ---@type string
if language then
code = ('
%s
'):format(
language,
trim(trim_indent(text), 2)
)
language = nil
else
code = ('
%s
'):format(trim(trim_indent(text), 2))
end
return code
elseif node_name == 'tag' then -- anchor
if root:has_error() then
return text
end
local in_heading = vim.list_contains({ 'h1', 'h2', 'h3' }, parent)
local tagname = node_text(root:child(1), false)
local el = 'span'
local encoded_tagname = url_encode(tagname)
local s = ('%s<%s id="%s" class="help-tag">
%s%s>'):format(
ws(),
el,
encoded_tagname,
encoded_tagname,
trimmed,
el
)
if in_heading and prev ~= 'tag' then
-- Start the
container for tags in a heading.
-- This makes "justify-content:space-between" right-align the tags.
-- foo bartag1 tag2
return string.format('%s', s)
elseif in_heading and next_ == nil then
-- End the container for tags in a heading.
return string.format('%s', s)
end
return s
elseif node_name == 'delimiter' or node_name == 'modeline' then
return ''
elseif node_name == 'ERROR' then
if ignore_parse_error(opt.fname, trimmed) then
return text
end
-- Store the raw text to give context to the bug report.
local sample_text = level > 0 and getbuflinestr(root, opt.buf, 3) or '[top level!]'
table.insert(stats.parse_errors, sample_text)
return ('%s'):format(
get_bug_url_vimdoc(opt.fname, opt.to_fname, sample_text),
trimmed
)
else -- Unknown token.
local sample_text = level > 0 and getbuflinestr(root, opt.buf, 3) or '[top level!]'
return ('%s'):format(
node_name,
get_bug_url_nvim(opt.fname, opt.to_fname, sample_text, node_name),
trimmed
),
('unknown-token:"%s"'):format(node_name)
end
end
--- @param dir string e.g. '$VIMRUNTIME/doc'
--- @param include string[]|nil
--- @return string[]
local function get_helpfiles(dir, include)
local rv = {}
for f, type in vim.fs.dir(dir) do
if
vim.endswith(f, '.txt')
and type == 'file'
and (not include or vim.list_contains(include, f))
then
local fullpath = vim.fn.fnamemodify(('%s/%s'):format(dir, f), ':p')
table.insert(rv, fullpath)
end
end
return rv
end
--- Populates the helptags map.
--- @param help_dir string
--- @return table
local function _get_helptags(help_dir)
---@type table
local m = {}
-- Load a random help file to convince taglist() to do its job.
vim.cmd(string.format('split %s/api.txt', help_dir))
vim.cmd('lcd %:p:h')
local tags = vim.fn.taglist('.*') --[[ @as {name: string, filename: string}[] ]]
for _, item in ipairs(tags) do
if vim.endswith(item.filename, '.txt') then
m[item.name] = item.filename
end
end
vim.cmd('q!')
return m
end
--- Populates the helptags map.
local function get_helptags(help_dir)
local m = _get_helptags(help_dir)
--- XXX: Append tags from netrw, until we remove it...
local netrwtags = _get_helptags(vim.fs.normalize('$VIMRUNTIME/pack/dist/opt/netrw/doc/'))
m = vim.tbl_extend('keep', m, netrwtags)
return m
end
--- Use the vimdoc parser defined in the build, not whatever happens to be installed on the system.
local function ensure_runtimepath()
if not vim.o.runtimepath:find('build/lib/nvim/') then
vim.cmd [[set runtimepath^=./build/lib/nvim/]]
end
end
--- Opens `fname` (or `text`, if given) in a buffer and gets a treesitter parser for the buffer contents.
---
--- @param fname string :help file to parse
--- @param text string? :help file contents
--- @return vim.treesitter.LanguageTree, integer (lang_tree, bufnr)
local function parse_buf(fname, text)
local buf ---@type integer
if text then
vim.cmd('split new') -- Text contents.
vim.api.nvim_put(vim.split(text, '\n'), '', false, false)
vim.cmd('setfiletype help')
buf = vim.api.nvim_get_current_buf()
elseif type(fname) == 'string' then
vim.cmd('split ' .. vim.fn.fnameescape(fname)) -- Filename.
buf = vim.api.nvim_get_current_buf()
else
-- Left for debugging
---@diagnostic disable-next-line: no-unknown
buf = fname
vim.cmd('sbuffer ' .. tostring(fname)) -- Buffer number.
end
local lang_tree = assert(vim.treesitter.get_parser(buf, nil))
lang_tree:parse()
return lang_tree, buf
end
--- Validates one :help file `fname`:
--- - checks that |tag| links point to valid helptags.
--- - recursively counts parse errors ("ERROR" nodes)
---
--- @param fname string help file to validate
--- @param request_urls boolean? whether to make requests to the URLs
--- @return { invalid_links: number, parse_errors: string[], has_title: boolean }
local function validate_one(fname, request_urls)
local stats = {
parse_errors = {},
}
local lang_tree, buf = parse_buf(fname, nil)
stats.has_title = get_title(lang_tree:trees()[1]:root(), buf) ~= nil
for _, tree in ipairs(lang_tree:trees()) do
visit_validate(tree:root(), 0, tree, {
buf = buf,
fname = fname,
request_urls = request_urls,
}, stats)
end
lang_tree:destroy()
vim.cmd.close()
return stats
end
--- Generates HTML from one :help file `fname`.
---
--- @param fname string Source :help file.
--- @param text string|nil Source :help file contents, or nil to read `fname`.
--- @param to_fname string Destination .html file
--- @param old boolean Preformat paragraphs (for old :help files which are full of arbitrary whitespace)
---
--- @return string html
--- @return table stats
--- @return string main HTML body, without the Hugo front matter.
local function gen_one_html(fname, text, to_fname, old, commit)
local stats = {
noise_lines = {},
parse_errors = {},
}
local lang_tree, buf = parse_buf(fname, text)
---@type nvim.gen_help_html.heading[]
local headings = {} -- Headings (for ToC). 2-dimensional: h1 contains h2/h3.
local title = assert(get_title(lang_tree:trees()[1]:root(), buf), ('%s: no title'):format(fname))
local title_text = get_heading_name(title, buf)
local main = ''
for _, tree in ipairs(lang_tree:trees()) do
main = main
.. (
ts_node_to_html(
tree:root(),
0,
tree,
headings,
{ buf = buf, old = old, fname = fname, to_fname = to_fname, indent = 1, title = title },
stats
)
)
end
-- Title is first, outside of any block. Anchored at the filename tag ("*foo.txt*" on the first
-- line, which is discarded as noise).
main = ('%s
\n%s'):format(
url_encode(vim.fs.basename(fname)),
stats.title_html or html_esc(title_text),
main
)
local frontmatter = vim.json.encode({
title = title_text,
layout = 'single', -- Hugo-specific, to make _index.html the same as the other pages
aliases = { -- Hugo-specific, make /api.html redirect to /api/
vim.fs.joinpath('/doc/user', vim.fs.basename(to_fname)),
},
params = {
basename = vim.fs.basename(fname),
commit = commit,
parseErrors = #stats.parse_errors,
bugUrl = get_bug_url_nvim(fname, to_fname, 'TODO', nil),
noiseLines = html_esc(table.concat(stats.noise_lines, '\n')),
noiseLinesCount = #stats.noise_lines,
headings = headings,
},
}, { indent = ' ', sort_keys = true })
local html = ('%s\n%s'):format(frontmatter, main)
vim.cmd('q!')
lang_tree:destroy()
return html, stats, main
end
--- Generates a JSON map of tags to URL-encoded `filename#anchor` locations.
---
---@param fname string
local function gen_helptags_json(fname)
assert(tagmap, '`tagmap` not generated yet')
local t = {} ---@type table
for tag, f in pairs(tagmap) do
-- "foo.txt"
local helpfile = vim.fs.basename(f)
-- "foo.html"
local htmlpage = assert(get_helppage_html(helpfile))
-- "foo.html#tag"
t[tag] = ('%s#%s'):format(htmlpage, url_encode(tag))
end
tofile(fname, vim.json.encode(t, { indent = ' ', sort_keys = true }))
end
local function gen_helptag_html(fname)
local frontmatter = vim.json.encode({
title = 'Helptag redirect',
layout = 'helptag',
aliases = { vim.fs.basename(fname) },
}, { indent = ' ', sort_keys = true })
tofile(fname, frontmatter)
end
-- Testing
local function ok(cond, expected, actual, message)
assert(
(not expected and not actual) or (expected and actual),
'if "expected" is given, "actual" is also required'
)
if expected then
assert(
cond,
('%sexpected %s, got: %s'):format(
message and (message .. '\n') or '',
vim.inspect(expected),
vim.inspect(actual)
)
)
else
assert(cond)
end
return true
end
local function eq(expected, actual, message)
return ok(vim.deep_equal(expected, actual), expected, actual, message)
end
function M._test()
tagmap = get_helptags('$VIMRUNTIME/doc')
helpfiles = get_helpfiles(vim.fs.normalize('$VIMRUNTIME/doc'))
ok(vim.tbl_count(tagmap) > 3000, '>3000', vim.tbl_count(tagmap))
ok(
vim.endswith(tagmap['vim.diagnostic.set()'], 'diagnostic.txt'),
tagmap['vim.diagnostic.set()'],
'diagnostic.txt'
)
ok(vim.endswith(tagmap['%:s'], 'cmdline.txt'), tagmap['%:s'], 'cmdline.txt')
ok(is_noise([[vim:tw=78:isk=!-~,^*,^\|,^\":ts=8:noet:ft=help:norl:]]))
ok(is_noise([[ NVIM REFERENCE MANUAL by Thiago de Arruda ]]))
ok(is_noise('\t\t VIM USER MANUAL\tby Bram Moolenaar'))
ok(not is_noise([[vim:tw=78]]))
eq(
'a\n \n b\n c\n d\n e\n',
trim_indent(' a\n \n b\n c\n d\n e\n')
)
local fixed_url, removed_chars = fix_url('https://example.com).')
eq('https://example.com', fixed_url)
eq(').', removed_chars)
fixed_url, removed_chars = fix_url('https://example.com.)')
eq('https://example.com.', fixed_url)
eq(')', removed_chars)
fixed_url, removed_chars = fix_url('https://example.com.')
eq('https://example.com', fixed_url)
eq('.', removed_chars)
fixed_url, removed_chars = fix_url('https://example.com)')
eq('https://example.com', fixed_url)
eq(')', removed_chars)
fixed_url, removed_chars = fix_url('https://example.com')
eq('https://example.com', fixed_url)
eq('', removed_chars)
print('all tests passed.\n')
end
--- Generate redirect pages for renamed help files.
--- @param commit string?
--- @param helpfile string Name of the help file being generated
--- @param to_dir string Target directory where the output files will be written.
--- @param to_fname string Name of the already-generated page in the new location
---
--- @return boolean Whether a redirect page has been generated
local function gen_redirect_pages(commit, helpfile, to_dir, to_fname)
local helpfile_tag = (helpfile:gsub('%.txt$', '')):gsub('_', '-') -- "dev_tools.txt" => "dev-tools"
local redirect_from = redirects[helpfile]
if not redirect_from then
return false
end
local redirect_text = vim.text
.indent(
0,
[[
*%s* Nvim
==============================================================================
Document moved
Document moved to: |%s|
==============================================================================
vim:tw=78:ts=8:ft=help:norl:
]]
)
:format(redirect_from, helpfile_tag)
local redirect_to_fname = get_helppage_html(redirect_from, true)
local redirect_to = ('%s/%s'):format(to_dir, redirect_to_fname)
local redirect_html, _ =
gen_one_html(redirect_from, redirect_text, redirect_to, false, commit or '?')
assert(
redirect_html:find(vim.pesc(helpfile_tag)),
('not found in redirect html: %s'):format(helpfile_tag)
)
tofile(redirect_to, redirect_html)
print(('generated (redirect) : %-15s => %s'):format(redirect_from, vim.fs.basename(to_fname)))
return true
end
--- Stylesheet for `output_format=print` (PDF generation via `chrome --headless`).
local print_css = [[
@page { size: A4; margin: 15mm; }
body { font: 10.5pt/1.4 system-ui, sans-serif; }
a { color: inherit; }
.chapter { break-before: page; }
.chapter:first-child { break-before: auto; }
h1, h2, h3, h4 { break-after: avoid; }
.help-heading { display: flex; flex-flow: row wrap; justify-content: space-between; gap: 0 1em; }
pre, code, .old-help-para { font-family: ui-monospace, Menlo, Consolas, monospace; }
pre, .old-help-para { font-size: 9pt; white-space: pre-wrap; tab-size: 8; }
pre { background: #f4f4f4; padding: 0.4em 0.6em; break-inside: avoid; }
.help-para, .old-help-para { margin: 0.6em 0; counter-reset: li; }
.help-li, .help-li-num { display: list-item; margin-left: 1.5em; }
.help-li-num { list-style: none; }
.help-li-num::before { counter-increment: li; content: counter(li) ". "; margin-left: -1em; }
.help-tag, .help-tag-right { color: #0a6b52; }
.help-tag-right { float: right; }
.help-tag-heading { display: flow-root; }
.help-column_heading { font-weight: bold; }
.help-table { border-collapse: collapse; margin: 0.6em 0; break-inside: avoid; }
.help-table th, .help-table td { padding: 0.15em 0.8em; text-align: left; vertical-align: top; border-bottom: 1px solid #ccc; }
.help-table th, .help-table-sep td { border-bottom-color: #888; }
]]
--- Joins page bodies into one standalone HTML page, for printing to PDF.
--- Links to `helpfiles` become in-page links; other links go to neovim.io.
---
--- @param chapters string[] Page bodies.
--- @param helpfiles string[] Source files of `chapters`.
--- @return string
local function gen_print_html(chapters, helpfiles)
local pages = {} ---@type table
for _, f in ipairs(helpfiles) do
pages[(get_helppage_html(vim.fs.basename(f)):gsub('/$', ''))] = true
end
local body = table.concat(chapters, '\n')
body = body:gsub('href="/doc/user/([^"#]*)(#?[^"]*)"', function(page, anchor)
page = page:gsub('/$', '')
if pages[page] and anchor ~= '' then
return ('href="%s"'):format(anchor)
end
return ('href="https://neovim.io/doc/user/%s%s"'):format(
page == '' and '' or page .. '/',
anchor
)
end)
return ('\nNvim\n\n\n%s\n\n'):format(
vim.text.indent(0, print_css),
body
)
end
--- @class nvim.gen_help_html.gen_result
--- @field helpfiles string[] list of generated HTML files, from the source docs {include}
--- @field err_count integer number of parse errors in :help docs
--- @field invalid_links table
--- Generates HTML from :help docs located in `help_dir` and writes the result in `to_dir`.
---
--- Example:
---
--- gen('html', '$VIMRUNTIME/doc', '/path/to/neovim.github.io/_site/doc/', {'api.txt', 'autocmd.txt', 'channel.txt'}, nil)
---
--- @param output_format string "html", or "print" (one standalone `to_dir/print.html` for printing
--- to PDF, with the files in `include` order).
--- @param help_dir string Source directory containing the :help files. Must run `make helptags` first.
--- @param to_dir string Target directory where the output files will be written.
--- @param include string[]|nil Process only these filenames. Example: {'api.txt', 'autocmd.txt', 'channel.txt'}
--- @param commit string?
--- @param parser_path string? path to non-default vimdoc.so/dylib/dll
---
--- @return nvim.gen_help_html.gen_result result
function M.gen(output_format, help_dir, to_dir, include, commit, parser_path)
vim.validate('output_format', output_format, function(s)
return s == 'html' or s == 'print'
end, '"html" or "print"')
vim.validate('help_dir', help_dir, function(d)
return vim.fn.isdirectory(vim.fs.normalize(d)) == 1
end, 'valid directory')
vim.validate('to_dir', to_dir, 'string')
vim.validate('include', include, 'table', true)
vim.validate('commit', commit, 'string', true)
vim.validate('parser_path', parser_path, function(f)
return vim.fn.filereadable(vim.fs.normalize(f)) == 1
end, true, 'valid vimdoc.{so,dll,dylib} filepath')
local err_count = 0
local redirects_count = 0
ensure_runtimepath()
parser_path = parser_path and vim.fs.normalize(parser_path) or nil
if parser_path then
-- XXX: Delete the installed .so files first, else this won't work :(
-- /usr/local/lib/nvim/parser/vimdoc.so
-- ./build/lib/nvim/parser/vimdoc.so
vim.treesitter.language.add('vimdoc', { path = parser_path })
end
tagmap = get_helptags(vim.fs.normalize(help_dir))
helpfiles = get_helpfiles(help_dir, include)
-- Sort-order (matters for output_format=print).
-- Decided by `include`, else: help.txt, user manual, reference, rest alphabetically.
local order = {} ---@type table
local function add(f)
order[f] = order[f] or vim.tbl_count(order)
end
for _, f in ipairs(include or {}) do
add(f)
end
if not include and output_format == 'print' then
add('help.txt')
for _, toc in ipairs({ 'usr_toc.txt', 'help.txt' }) do
local path = ('%s/%s'):format(help_dir, toc)
if vim.fn.filereadable(path) == 1 then
add(toc)
for f in table.concat(vim.fn.readfile(path), '\n'):gmatch('|([%w_.-]+%.txt)|') do
add(f)
end
end
end
end
table.sort(helpfiles, function(a, b)
local fa, fb = vim.fs.basename(a), vim.fs.basename(b)
local oa, ob = order[fa] or math.huge, order[fb] or math.huge
return oa < ob or (oa == ob and fa < fb)
end)
to_dir = vim.fs.normalize(to_dir)
print(('output dir: %s\n\n'):format(to_dir))
vim.fn.mkdir(to_dir, 'p')
if output_format == 'html' then
-- NOTE: Better for Hugo to be in static/, but works fine with contents/ as to_dir
gen_helptags_json(('%s/helptags.json'):format(to_dir))
gen_helptag_html(('%s/helptag.html'):format(to_dir))
end
local chapters = {} ---@type string[] Page bodies, for "print" format.
for _, f in ipairs(helpfiles) do
-- "foo.txt"
local helpfile = vim.fs.basename(f)
-- "to/dir/foo.html"
local to_fname = ('%s/%s'):format(to_dir, get_helppage_html(helpfile, true))
local converted_help, stats, main =
gen_one_html(f, nil, to_fname, not new_layout[helpfile], commit or '?')
if output_format == 'print' then
chapters[#chapters + 1] = (''):format(main)
else
tofile(to_fname, converted_help)
end
print(
('generated (%-2s errors): %-15s => %s'):format(
#stats.parse_errors,
helpfile,
vim.fs.basename(to_fname)
)
)
if output_format == 'html' then
local generated = gen_redirect_pages(commit, helpfile, to_dir, to_fname)
if generated then
redirects_count = redirects_count + 1
end
end
err_count = err_count + #stats.parse_errors
end
if output_format == 'print' then
local to_fname = ('%s/print.html'):format(to_dir)
tofile(to_fname, gen_print_html(chapters, helpfiles))
print(('\nprint: %s'):format(to_fname))
end
print(('\ngenerated %d pages'):format(#helpfiles + redirects_count))
print(('total errors: %d'):format(err_count))
-- Why aren't the netrw tags found in neovim/docs/ CI?
print(('invalid tags: %s'):format(vim.inspect(invalid_links)))
if output_format == 'html' then
eq(redirects_count, include and redirects_count or vim.tbl_count(redirects)) -- sanity check
print(('redirects: %d'):format(redirects_count))
end
print('\n')
--- @type nvim.gen_help_html.gen_result
return {
helpfiles = helpfiles,
err_count = err_count,
invalid_links = invalid_links,
}
end
--- @class nvim.gen_help_html.validate_result
--- @field helpfiles integer number of generated helpfiles
--- @field err_count integer number of parse errors
--- @field parse_errors table
--- @field invalid_links table invalid tags in :help docs
--- @field invalid_urls table invalid URLs in :help docs
--- @field invalid_spelling table> invalid spelling in :help docs
--- @field no_title string[] :help docs without a title (see `get_title`)
--- Validates all :help files found in `help_dir`:
--- - checks that |tag| links point to valid helptags.
--- - recursively counts parse errors ("ERROR" nodes)
--- - checks that each doc (except the user manual) has a title (see `get_title`)
---
--- This is 10x faster than gen(), for use in CI.
---
--- @return nvim.gen_help_html.validate_result result
function M.validate(help_dir, include, parser_path, request_urls)
vim.validate('help_dir', help_dir, function(d)
return vim.fn.isdirectory(vim.fs.normalize(d)) == 1
end, 'valid directory')
vim.validate('include', include, 'table', true)
vim.validate('parser_path', parser_path, function(f)
return vim.fn.filereadable(vim.fs.normalize(f)) == 1
end, true, 'valid vimdoc.{so,dll,dylib} filepath')
local err_count = 0 ---@type integer
local files_to_errors = {} ---@type table
local no_title = {} ---@type string[]
ensure_runtimepath()
parser_path = parser_path and vim.fs.normalize(parser_path) or nil
if parser_path then
-- XXX: Delete the installed .so files first, else this won't work :(
-- /usr/local/lib/nvim/parser/vimdoc.so
-- ./build/lib/nvim/parser/vimdoc.so
vim.treesitter.language.add('vimdoc', { path = parser_path })
end
tagmap = get_helptags(vim.fs.normalize(help_dir))
helpfiles = get_helpfiles(help_dir, include)
for _, f in ipairs(helpfiles) do
local helpfile = vim.fs.basename(f)
local rv = validate_one(f, request_urls)
print(('validated (%-4s errors): %s'):format(#rv.parse_errors, helpfile))
if #rv.parse_errors > 0 then
files_to_errors[helpfile] = rv.parse_errors
vim.print(('%s'):format(vim.iter(rv.parse_errors):fold('', function(s, v)
return s .. '\n ' .. v
end)))
end
err_count = err_count + #rv.parse_errors
if not rv.has_title then
no_title[#no_title + 1] = helpfile
end
end
-- Requests are async, wait for them to finish.
-- TODO(yochem): `:cancel()` tasks after #36146
vim.wait(20000, function()
return pending_urls <= 0
end)
ok(pending_urls <= 0, 'pending url checks', pending_urls)
---@type nvim.gen_help_html.validate_result
return {
helpfiles = #helpfiles,
err_count = err_count,
parse_errors = files_to_errors,
invalid_links = invalid_links,
invalid_urls = invalid_urls,
invalid_spelling = invalid_spelling,
no_title = no_title,
}
end
--- Validates vimdoc files in $VIMRUNTIME, and prints error messages on failure.
---
--- If this fails, try these steps (in order):
--- 1. Fix/cleanup the :help docs.
--- 2. Fix the parser: https://github.com/neovim/tree-sitter-vimdoc
--- 3. File a parser bug, and adjust the tolerance of this test in the meantime.
---
--- @param help_dir? string e.g. '$VIMRUNTIME/doc' or './runtime/doc'
--- @param request_urls? boolean make network requests to check if the URLs are reachable.
function M.run_validate(help_dir, request_urls)
help_dir = vim.fs.normalize(help_dir or '$VIMRUNTIME/doc')
print('doc path = ' .. vim.uv.fs_realpath(help_dir))
local rv = M.validate(help_dir, nil, nil, request_urls)
-- Check that we actually found helpfiles.
ok(rv.helpfiles > 100, '>100 :help files', rv.helpfiles)
eq({}, rv.parse_errors, 'no parse errors')
eq(0, rv.err_count, 'no parse errors')
eq({}, rv.invalid_links, 'invalid tags in :help docs')
eq({}, rv.invalid_urls, 'invalid URLs in :help docs')
eq(
{},
rv.invalid_spelling,
'invalid spelling in :help docs (see spell_dict in src/gen/gen_help_html.lua)'
)
eq({}, rv.no_title, ':help docs without a title (see `get_title` in src/gen/gen_help_html.lua)')
end
--- Test-generates HTML from docs.
---
--- 1. Test that gen_help_html.lua actually works.
--- 2. Test that parse errors did not increase wildly. Because we explicitly test only a few
--- :help files, we can be precise about the tolerances here.
--- @param help_dir? string e.g. '$VIMRUNTIME/doc' or './runtime/doc'
function M.test_gen(help_dir)
local tmpdir = vim.fs.dirname(vim.fn.tempname())
help_dir = vim.fs.normalize(help_dir or '$VIMRUNTIME/doc')
print('doc path = ' .. vim.uv.fs_realpath(help_dir))
-- Because gen() is slow (~30s), this test is limited to a few files.
local input = { 'api.txt', 'index.txt', 'nvim.txt' }
local rv = M.gen('html', help_dir, tmpdir, input)
eq(#input, #rv.helpfiles)
eq(0, rv.err_count, 'parse errors in :help docs')
eq({}, rv.invalid_links, 'invalid tags in :help docs')
end
return M