gen_help_html.lua 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492
  1. --- Converts Nvim :help files to HTML. Validates |tag| links and document syntax (parser errors).
  2. --
  3. -- USAGE (For CI/local testing purposes): Simply `make lintdoc` or `scripts/lintdoc.lua`, which
  4. -- basically does the following:
  5. -- 1. :helptags ALL
  6. -- 2. nvim -V1 -es +"lua require('scripts.gen_help_html').run_validate()" +q
  7. -- 3. nvim -V1 -es +"lua require('scripts.gen_help_html').test_gen()" +q
  8. --
  9. -- USAGE (GENERATE HTML):
  10. -- 1. `:helptags ALL` first; this script depends on vim.fn.taglist().
  11. -- 2. nvim -V1 -es --clean +"lua require('scripts.gen_help_html').gen('./runtime/doc', 'target/dir/')" +q
  12. -- - Read the docstring at gen().
  13. -- 3. cd target/dir/ && jekyll serve --host 0.0.0.0
  14. -- 4. Visit http://localhost:4000/…/help.txt.html
  15. --
  16. -- USAGE (VALIDATE):
  17. -- 1. nvim -V1 -es +"lua require('scripts.gen_help_html').validate('./runtime/doc')" +q
  18. -- - validate() is 10x faster than gen(), so it is used in CI.
  19. --
  20. -- SELF-TEST MODE:
  21. -- 1. nvim -V1 -es +"lua require('scripts.gen_help_html')._test()" +q
  22. --
  23. -- NOTES:
  24. -- * This script is used by the automation repo: https://github.com/neovim/doc
  25. -- * :helptags checks for duplicate tags, whereas this script checks _links_ (to tags).
  26. -- * gen() and validate() are the primary (programmatic) entrypoints. validate() only exists
  27. -- because gen() is too slow (~1 min) to run in per-commit CI.
  28. -- * visit_node() is the core function used by gen() to traverse the document tree and produce HTML.
  29. -- * visit_validate() is the core function used by validate().
  30. -- * Files in `new_layout` will be generated with a "flow" layout instead of preformatted/fixed-width layout.
  31. local tagmap = nil ---@type table<string, string>
  32. local helpfiles = nil ---@type string[]
  33. local invalid_links = {} ---@type table<string, any>
  34. local invalid_urls = {} ---@type table<string, any>
  35. local invalid_spelling = {} ---@type table<string, table<string, string>>
  36. local spell_dict = {
  37. Neovim = 'Nvim',
  38. NeoVim = 'Nvim',
  39. neovim = 'Nvim',
  40. lua = 'Lua',
  41. VimL = 'Vimscript',
  42. vimL = 'Vimscript',
  43. viml = 'Vimscript',
  44. ['tree-sitter'] = 'treesitter',
  45. ['Tree-sitter'] = 'Treesitter',
  46. }
  47. --- specify the list of keywords to ignore (i.e. allow), or true to disable spell check completely.
  48. --- @type table<string, true|string[]>
  49. local spell_ignore_files = {
  50. ['credits.txt'] = { 'Neovim' },
  51. ['news.txt'] = { 'tree-sitter' }, -- in news, may refer to the upstream "tree-sitter" library
  52. ['news-0.10.txt'] = { 'tree-sitter' },
  53. }
  54. local language = nil
  55. local M = {}
  56. -- These files are generated with "flow" layout (non fixed-width, wrapped text paragraphs).
  57. -- All other files are "legacy" files which require fixed-width layout.
  58. local new_layout = {
  59. ['api.txt'] = true,
  60. ['lsp.txt'] = true,
  61. ['channel.txt'] = true,
  62. ['deprecated.txt'] = true,
  63. ['develop.txt'] = true,
  64. ['dev_style.txt'] = true,
  65. ['dev_theme.txt'] = true,
  66. ['dev_tools.txt'] = true,
  67. ['dev_vimpatch.txt'] = true,
  68. ['editorconfig.txt'] = true,
  69. ['faq.txt'] = true,
  70. ['gui.txt'] = true,
  71. ['intro.txt'] = true,
  72. ['lua.txt'] = true,
  73. ['luaref.txt'] = true,
  74. ['news.txt'] = true,
  75. ['news-0.9.txt'] = true,
  76. ['news-0.10.txt'] = true,
  77. ['nvim.txt'] = true,
  78. ['provider.txt'] = true,
  79. ['tui.txt'] = true,
  80. ['ui.txt'] = true,
  81. ['vim_diff.txt'] = true,
  82. }
  83. -- Map of new:old pages, to redirect renamed pages.
  84. local redirects = {
  85. ['credits'] = 'backers',
  86. ['tui'] = 'term',
  87. ['terminal'] = 'nvim_terminal_emulator',
  88. }
  89. -- TODO: These known invalid |links| require an update to the relevant docs.
  90. local exclude_invalid = {
  91. ["'string'"] = 'eval.txt',
  92. Query = 'treesitter.txt',
  93. matchit = 'vim_diff.txt',
  94. ['set!'] = 'treesitter.txt',
  95. }
  96. -- False-positive "invalid URLs".
  97. local exclude_invalid_urls = {
  98. ['http://'] = 'usr_23.txt',
  99. ['http://.'] = 'usr_23.txt',
  100. ['http://aspell.net/man-html/Affix-Compression.html'] = 'spell.txt',
  101. ['http://aspell.net/man-html/Phonetic-Code.html'] = 'spell.txt',
  102. ['http://canna.sourceforge.jp/'] = 'mbyte.txt',
  103. ['http://gnuada.sourceforge.net'] = 'ft_ada.txt',
  104. ['http://lua-users.org/wiki/StringLibraryTutorial'] = 'lua.txt',
  105. ['http://michael.toren.net/code/'] = 'pi_tar.txt',
  106. ['http://papp.plan9.de'] = 'syntax.txt',
  107. ['http://wiki.services.openoffice.org/wiki/Dictionaries'] = 'spell.txt',
  108. ['http://www.adapower.com'] = 'ft_ada.txt',
  109. ['http://www.jclark.com/'] = 'quickfix.txt',
  110. ['http://oldblog.antirez.com/post/redis-and-scripting.html'] = 'faq.txt',
  111. }
  112. -- Deprecated, brain-damaged files that I don't care about.
  113. local ignore_errors = {
  114. ['pi_netrw.txt'] = true,
  115. ['credits.txt'] = true,
  116. }
  117. local function tofile(fname, text)
  118. local f = io.open(fname, 'w')
  119. if not f then
  120. error(('failed to write: %s'):format(f))
  121. else
  122. f:write(text)
  123. f:close()
  124. end
  125. end
  126. ---@type fun(s: string): string
  127. local function html_esc(s)
  128. return (s:gsub('&', '&amp;'):gsub('<', '&lt;'):gsub('>', '&gt;'))
  129. end
  130. local function url_encode(s)
  131. -- Credit: tpope / vim-unimpaired
  132. -- NOTE: these chars intentionally *not* escaped: ' ( )
  133. return vim.fn.substitute(
  134. vim.fn.iconv(s, 'latin1', 'utf-8'),
  135. [=[[^A-Za-z0-9()'_.~-]]=],
  136. [=[\="%".printf("%02X",char2nr(submatch(0)))]=],
  137. 'g'
  138. )
  139. end
  140. local function expandtabs(s)
  141. return s:gsub('\t', (' '):rep(8)) --[[ @as string ]]
  142. end
  143. local function to_titlecase(s)
  144. local text = ''
  145. for w in vim.gsplit(s, '[ \t]+') do
  146. text = ('%s %s%s'):format(text, vim.fn.toupper(w:sub(1, 1)), w:sub(2))
  147. end
  148. return text
  149. end
  150. local function to_heading_tag(text)
  151. -- Prepend "_" to avoid conflicts with actual :help tags.
  152. return text and string.format('_%s', vim.fn.tolower((text:gsub('%s+', '-')))) or 'unknown'
  153. end
  154. local function basename_noext(f)
  155. return vim.fs.basename(f:gsub('%.txt', ''))
  156. end
  157. local function is_blank(s)
  158. return not not s:find([[^[\t ]*$]])
  159. end
  160. ---@type fun(s: string, dir?:0|1|2): string
  161. local function trim(s, dir)
  162. return vim.fn.trim(s, '\r\t\n ', dir or 0)
  163. end
  164. --- Removes common punctuation from URLs.
  165. ---
  166. --- TODO: fix this in the parser instead... https://github.com/neovim/tree-sitter-vimdoc
  167. ---
  168. --- @param url string
  169. --- @return string, string (fixed_url, removed_chars) where `removed_chars` is in the order found in the input.
  170. local function fix_url(url)
  171. local removed_chars = ''
  172. local fixed_url = url
  173. -- Remove up to one of each char from end of the URL, in this order.
  174. for _, c in ipairs({ '.', ')' }) do
  175. if fixed_url:sub(-1) == c then
  176. removed_chars = c .. removed_chars
  177. fixed_url = fixed_url:sub(1, -2)
  178. end
  179. end
  180. return fixed_url, removed_chars
  181. end
  182. --- Checks if a given line is a "noise" line that doesn't look good in HTML form.
  183. local function is_noise(line, noise_lines)
  184. if
  185. -- First line is always noise.
  186. (noise_lines ~= nil and vim.tbl_count(noise_lines) == 0)
  187. or line:find('Type .*gO.* to see the table of contents')
  188. -- Title line of traditional :help pages.
  189. -- Example: "NVIM REFERENCE MANUAL by ..."
  190. or line:find([[^%s*N?VIM[ \t]*REFERENCE[ \t]*MANUAL]])
  191. -- First line of traditional :help pages.
  192. -- Example: "*api.txt* Nvim"
  193. or line:find('%s*%*?[a-zA-Z]+%.txt%*?%s+N?[vV]im%s*$')
  194. -- modeline
  195. -- Example: "vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl:"
  196. or line:find('^%s*vim?%:.*ft=help')
  197. or line:find('^%s*vim?%:.*filetype=help')
  198. or line:find('[*>]local%-additions[*<]')
  199. then
  200. -- table.insert(stats.noise_lines, getbuflinestr(root, opt.buf, 0))
  201. table.insert(noise_lines or {}, line)
  202. return true
  203. end
  204. return false
  205. end
  206. --- Creates a github issue URL at neovim/tree-sitter-vimdoc with prefilled content.
  207. --- @return string
  208. local function get_bug_url_vimdoc(fname, to_fname, sample_text)
  209. local this_url = string.format('https://neovim.io/doc/user/%s', vim.fs.basename(to_fname))
  210. local bug_url = (
  211. 'https://github.com/neovim/tree-sitter-vimdoc/issues/new?labels=bug&title=parse+error%3A+'
  212. .. vim.fs.basename(fname)
  213. .. '+&body=Found+%60tree-sitter-vimdoc%60+parse+error+at%3A+'
  214. .. this_url
  215. .. '%0D%0DContext%3A%0D%0D%60%60%60%0D'
  216. .. url_encode(sample_text)
  217. .. '%0D%60%60%60'
  218. )
  219. return bug_url
  220. end
  221. --- Creates a github issue URL at neovim/neovim with prefilled content.
  222. --- @return string
  223. local function get_bug_url_nvim(fname, to_fname, sample_text, token_name)
  224. local this_url = string.format('https://neovim.io/doc/user/%s', vim.fs.basename(to_fname))
  225. local bug_url = (
  226. 'https://github.com/neovim/neovim/issues/new?labels=bug&title=user+docs+HTML%3A+'
  227. .. vim.fs.basename(fname)
  228. .. '+&body=%60gen_help_html.lua%60+problem+at%3A+'
  229. .. this_url
  230. .. '%0D'
  231. .. (token_name and '+unhandled+token%3A+%60' .. token_name .. '%60' or '')
  232. .. '%0DContext%3A%0D%0D%60%60%60%0D'
  233. .. url_encode(sample_text)
  234. .. '%0D%60%60%60'
  235. )
  236. return bug_url
  237. end
  238. --- Gets a "foo.html" name from a "foo.txt" helpfile name.
  239. local function get_helppage(f)
  240. if not f then
  241. return nil
  242. end
  243. -- Special case: help.txt is the "main landing page" of :help files, not index.txt.
  244. if f == 'index.txt' then
  245. return 'vimindex.html'
  246. elseif f == 'help.txt' then
  247. return 'index.html'
  248. end
  249. return (f:gsub('%.txt$', '')) .. '.html'
  250. end
  251. --- Counts leading spaces (tab=8) to decide the indent size of multiline text.
  252. ---
  253. --- Blank lines (empty or whitespace-only) are ignored.
  254. local function get_indent(s)
  255. local min_indent = nil
  256. for line in vim.gsplit(s, '\n') do
  257. if line and not is_blank(line) then
  258. local ws = expandtabs(line:match('^%s+') or '')
  259. min_indent = (not min_indent or ws:len() < min_indent) and ws:len() or min_indent
  260. end
  261. end
  262. return min_indent or 0
  263. end
  264. --- Removes the common indent level, after expanding tabs to 8 spaces.
  265. local function trim_indent(s)
  266. local indent_size = get_indent(s)
  267. local trimmed = ''
  268. for line in vim.gsplit(s, '\n') do
  269. line = expandtabs(line)
  270. trimmed = ('%s%s\n'):format(trimmed, line:sub(indent_size + 1))
  271. end
  272. return trimmed:sub(1, -2)
  273. end
  274. --- Gets raw buffer text in the node's range (+/- an offset), as a newline-delimited string.
  275. ---@param node TSNode
  276. ---@param bufnr integer
  277. ---@param offset integer
  278. local function getbuflinestr(node, bufnr, offset)
  279. local line1, _, line2, _ = node:range()
  280. line1 = line1 - offset
  281. line2 = line2 + offset
  282. local lines = vim.fn.getbufline(bufnr, line1 + 1, line2 + 1)
  283. return table.concat(lines, '\n')
  284. end
  285. --- Gets the whitespace just before `node` from the raw buffer text.
  286. --- Needed for preformatted `old` lines.
  287. ---@param node TSNode
  288. ---@param bufnr integer
  289. ---@return string
  290. local function getws(node, bufnr)
  291. local line1, c1, line2, _ = node:range()
  292. ---@type string
  293. local raw = vim.fn.getbufline(bufnr, line1 + 1, line2 + 1)[1]
  294. local text_before = raw:sub(1, c1)
  295. local leading_ws = text_before:match('%s+$') or ''
  296. return leading_ws
  297. end
  298. local function get_tagname(node, bufnr)
  299. local text = vim.treesitter.get_node_text(node, bufnr)
  300. local tag = (node:type() == 'optionlink' or node:parent():type() == 'optionlink')
  301. and ("'%s'"):format(text)
  302. or text
  303. local helpfile = vim.fs.basename(tagmap[tag]) or nil -- "api.txt"
  304. local helppage = get_helppage(helpfile) -- "api.html"
  305. return helppage, tag
  306. end
  307. --- Returns true if the given invalid tagname is a false positive.
  308. local function ignore_invalid(s)
  309. return not not (
  310. exclude_invalid[s]
  311. -- Strings like |~/====| appear in various places and the parser thinks they are links, but they
  312. -- are just table borders.
  313. or s:find('===')
  314. or s:find('%-%-%-')
  315. )
  316. end
  317. local function ignore_parse_error(fname, s)
  318. if ignore_errors[vim.fs.basename(fname)] then
  319. return true
  320. end
  321. -- Ignore parse errors for unclosed tag.
  322. -- This is common in vimdocs and is treated as plaintext by :help.
  323. return s:find("^[`'|*]")
  324. end
  325. ---@param node TSNode
  326. local function has_ancestor(node, ancestor_name)
  327. local p = node ---@type TSNode?
  328. while p do
  329. p = p:parent()
  330. if not p or p:type() == 'help_file' then
  331. break
  332. elseif p:type() == ancestor_name then
  333. return true
  334. end
  335. end
  336. return false
  337. end
  338. --- Gets the first matching child node matching `name`.
  339. ---@param node TSNode
  340. local function first(node, name)
  341. for c, _ in node:iter_children() do
  342. if c:named() and c:type() == name then
  343. return c
  344. end
  345. end
  346. return nil
  347. end
  348. local function validate_link(node, bufnr, fname)
  349. local helppage, tagname = get_tagname(node:child(1), bufnr)
  350. local ignored = false
  351. if not tagmap[tagname] then
  352. ignored = has_ancestor(node, 'column_heading') or node:has_error() or ignore_invalid(tagname)
  353. if not ignored then
  354. invalid_links[tagname] = vim.fs.basename(fname)
  355. end
  356. end
  357. return helppage, tagname, ignored
  358. end
  359. --- TODO: port the logic from scripts/check_urls.vim
  360. local function validate_url(text, fname)
  361. local ignored = false
  362. if ignore_errors[vim.fs.basename(fname)] then
  363. ignored = true
  364. elseif text:find('http%:') and not exclude_invalid_urls[text] then
  365. invalid_urls[text] = vim.fs.basename(fname)
  366. end
  367. return ignored
  368. end
  369. --- Traverses the tree at `root` and checks that |tag| links point to valid helptags.
  370. ---@param root TSNode
  371. ---@param level integer
  372. ---@param lang_tree TSTree
  373. ---@param opt table
  374. ---@param stats table
  375. local function visit_validate(root, level, lang_tree, opt, stats)
  376. level = level or 0
  377. local node_name = (root.named and root:named()) and root:type() or nil
  378. -- Parent kind (string).
  379. local parent = root:parent() and root:parent():type() or nil
  380. local toplevel = level < 1
  381. local function node_text(node)
  382. return vim.treesitter.get_node_text(node or root, opt.buf)
  383. end
  384. local text = trim(node_text())
  385. if root:child_count() > 0 then
  386. for node, _ in root:iter_children() do
  387. if node:named() then
  388. visit_validate(node, level + 1, lang_tree, opt, stats)
  389. end
  390. end
  391. end
  392. if node_name == 'ERROR' then
  393. if ignore_parse_error(opt.fname, text) then
  394. return
  395. end
  396. -- Store the raw text to give context to the error report.
  397. local sample_text = not toplevel and getbuflinestr(root, opt.buf, 0) or '[top level!]'
  398. -- Flatten the sample text to a single, truncated line.
  399. sample_text = vim.trim(sample_text):gsub('[\t\n]', ' '):sub(1, 80)
  400. table.insert(stats.parse_errors, sample_text)
  401. elseif
  402. (node_name == 'word' or node_name == 'uppercase_name')
  403. and (not vim.tbl_contains({ 'codespan', 'taglink', 'tag' }, parent))
  404. then
  405. local text_nopunct = vim.fn.trim(text, '.,', 0) -- Ignore some punctuation.
  406. local fname_basename = assert(vim.fs.basename(opt.fname))
  407. if spell_dict[text_nopunct] then
  408. local should_ignore = (
  409. spell_ignore_files[fname_basename] == true
  410. or vim.tbl_contains(
  411. (spell_ignore_files[fname_basename] or {}) --[[ @as string[] ]],
  412. text_nopunct
  413. )
  414. )
  415. if not should_ignore then
  416. invalid_spelling[text_nopunct] = invalid_spelling[text_nopunct] or {}
  417. invalid_spelling[text_nopunct][fname_basename] = node_text(root:parent())
  418. end
  419. end
  420. elseif node_name == 'url' then
  421. local fixed_url, _ = fix_url(trim(text))
  422. validate_url(fixed_url, opt.fname)
  423. elseif node_name == 'taglink' or node_name == 'optionlink' then
  424. local _, _, _ = validate_link(root, opt.buf, opt.fname)
  425. end
  426. end
  427. -- Fix tab alignment issues caused by concealed characters like |, `, * in tags
  428. -- and code blocks.
  429. ---@param text string
  430. ---@param next_node_text string
  431. local function fix_tab_after_conceal(text, next_node_text)
  432. -- Vim tabs take into account the two concealed characters even though they
  433. -- are invisible, so we need to add back in the two spaces if this is
  434. -- followed by a tab to make the tab alignment to match Vim's behavior.
  435. if string.sub(next_node_text, 1, 1) == '\t' then
  436. text = text .. ' '
  437. end
  438. return text
  439. end
  440. ---@class (exact) nvim.gen_help_html.heading
  441. ---@field name string
  442. ---@field subheadings nvim.gen_help_html.heading[]
  443. ---@field tag string
  444. -- Generates HTML from node `root` recursively.
  445. ---@param root TSNode
  446. ---@param level integer
  447. ---@param lang_tree TSTree
  448. ---@param headings nvim.gen_help_html.heading[]
  449. ---@param opt table
  450. ---@param stats table
  451. local function visit_node(root, level, lang_tree, headings, opt, stats)
  452. level = level or 0
  453. local node_name = (root.named and root:named()) and root:type() or nil
  454. -- Previous sibling kind (string).
  455. local prev = root:prev_sibling()
  456. and (root:prev_sibling().named and root:prev_sibling():named())
  457. and root:prev_sibling():type()
  458. or nil
  459. -- Next sibling kind (string).
  460. local next_ = root:next_sibling()
  461. and (root:next_sibling().named and root:next_sibling():named())
  462. and root:next_sibling():type()
  463. or nil
  464. -- Parent kind (string).
  465. local parent = root:parent() and root:parent():type() or nil
  466. -- Gets leading whitespace of `node`.
  467. local function ws(node)
  468. node = node or root
  469. local ws_ = getws(node, opt.buf)
  470. -- XXX: first node of a (line) includes whitespace, even after
  471. -- https://github.com/neovim/tree-sitter-vimdoc/pull/31 ?
  472. if ws_ == '' then
  473. ws_ = vim.treesitter.get_node_text(node, opt.buf):match('^%s+') or ''
  474. end
  475. return ws_
  476. end
  477. local function node_text(node, ws_)
  478. node = node or root
  479. ws_ = (ws_ == nil or ws_ == true) and getws(node, opt.buf) or ''
  480. return string.format('%s%s', ws_, vim.treesitter.get_node_text(node, opt.buf))
  481. end
  482. local text = ''
  483. local trimmed ---@type string
  484. if root:named_child_count() == 0 or node_name == 'ERROR' then
  485. text = node_text()
  486. trimmed = html_esc(trim(text))
  487. text = html_esc(text)
  488. else
  489. -- Process children and join them with whitespace.
  490. for node, _ in root:iter_children() do
  491. if node:named() then
  492. local r = visit_node(node, level + 1, lang_tree, headings, opt, stats)
  493. text = string.format('%s%s', text, r)
  494. end
  495. end
  496. trimmed = trim(text)
  497. end
  498. if node_name == 'help_file' then -- root node
  499. return text
  500. elseif node_name == 'url' then
  501. local fixed_url, removed_chars = fix_url(trimmed)
  502. return ('%s<a href="%s">%s</a>%s'):format(ws(), fixed_url, fixed_url, removed_chars)
  503. elseif node_name == 'word' or node_name == 'uppercase_name' then
  504. return text
  505. elseif node_name == 'note' then
  506. return ('<b>%s</b>'):format(text)
  507. elseif node_name == 'h1' or node_name == 'h2' or node_name == 'h3' then
  508. if is_noise(text, stats.noise_lines) then
  509. return '' -- Discard common "noise" lines.
  510. end
  511. -- Remove tags from ToC text.
  512. local heading_node = first(root, 'heading')
  513. local hname = trim(node_text(heading_node):gsub('%*.*%*', ''))
  514. if not heading_node or hname == '' then
  515. return '' -- Spurious "===" or "---" in the help doc.
  516. end
  517. -- Generate an anchor id from the heading text.
  518. local tagname = to_heading_tag(hname)
  519. if node_name == 'h1' or #headings == 0 then
  520. ---@type nvim.gen_help_html.heading
  521. local heading = { name = hname, subheadings = {}, tag = tagname }
  522. headings[#headings + 1] = heading
  523. else
  524. table.insert(
  525. headings[#headings].subheadings,
  526. { name = hname, subheadings = {}, tag = tagname }
  527. )
  528. end
  529. local el = node_name == 'h1' and 'h2' or 'h3'
  530. return ('<%s id="%s" class="help-heading">%s</%s>\n'):format(el, tagname, trimmed, el)
  531. elseif node_name == 'heading' then
  532. return trimmed
  533. elseif node_name == 'column_heading' or node_name == 'column_name' then
  534. if root:has_error() then
  535. return text
  536. end
  537. return ('<div class="help-column_heading">%s</div>'):format(text)
  538. elseif node_name == 'block' then
  539. if is_blank(text) then
  540. return ''
  541. end
  542. if opt.old then
  543. -- XXX: Treat "old" docs as preformatted: they use indentation for layout.
  544. -- Trim trailing newlines to avoid too much whitespace between divs.
  545. return ('<div class="old-help-para">%s</div>\n'):format(trim(text, 2))
  546. end
  547. return string.format('<div class="help-para">\n%s\n</div>\n', text)
  548. elseif node_name == 'line' then
  549. if
  550. (parent ~= 'codeblock' or parent ~= 'code')
  551. and (is_blank(text) or is_noise(text, stats.noise_lines))
  552. then
  553. return '' -- Discard common "noise" lines.
  554. end
  555. -- XXX: Avoid newlines (too much whitespace) after block elements in old (preformatted) layout.
  556. local div = opt.old
  557. and root:child(0)
  558. and vim.list_contains({ 'column_heading', 'h1', 'h2', 'h3' }, root:child(0):type())
  559. return string.format('%s%s', div and trim(text) or text, div and '' or '\n')
  560. elseif node_name == 'line_li' then
  561. local sib = root:prev_sibling()
  562. local prev_li = sib and sib:type() == 'line_li'
  563. if not prev_li then
  564. opt.indent = 1
  565. else
  566. -- The previous listitem _sibling_ is _logically_ the _parent_ if it is indented less.
  567. local parent_indent = get_indent(node_text(sib))
  568. local this_indent = get_indent(node_text())
  569. if this_indent > parent_indent then
  570. opt.indent = opt.indent + 1
  571. elseif this_indent < parent_indent then
  572. opt.indent = math.max(1, opt.indent - 1)
  573. end
  574. end
  575. local margin = opt.indent == 1 and '' or ('margin-left: %drem;'):format((1.5 * opt.indent))
  576. return string.format('<div class="help-li" style="%s">%s</div>', margin, text)
  577. elseif node_name == 'taglink' or node_name == 'optionlink' then
  578. local helppage, tagname, ignored = validate_link(root, opt.buf, opt.fname)
  579. if ignored then
  580. return text
  581. end
  582. local s = ('%s<a href="%s#%s">%s</a>'):format(
  583. ws(),
  584. helppage,
  585. url_encode(tagname),
  586. html_esc(tagname)
  587. )
  588. if opt.old and node_name == 'taglink' then
  589. s = fix_tab_after_conceal(s, node_text(root:next_sibling()))
  590. end
  591. return s
  592. elseif vim.list_contains({ 'codespan', 'keycode' }, node_name) then
  593. if root:has_error() then
  594. return text
  595. end
  596. local s = ('%s<code>%s</code>'):format(ws(), trimmed)
  597. if opt.old and node_name == 'codespan' then
  598. s = fix_tab_after_conceal(s, node_text(root:next_sibling()))
  599. end
  600. return s
  601. elseif node_name == 'argument' then
  602. return ('%s<code>{%s}</code>'):format(ws(), text)
  603. elseif node_name == 'codeblock' then
  604. return text
  605. elseif node_name == 'language' then
  606. language = node_text(root)
  607. return ''
  608. elseif node_name == 'code' then -- Highlighted codeblock (child).
  609. if is_blank(text) then
  610. return ''
  611. end
  612. local code ---@type string
  613. if language then
  614. code = ('<pre><code class="language-%s">%s</code></pre>'):format(
  615. language,
  616. trim(trim_indent(text), 2)
  617. )
  618. language = nil
  619. else
  620. code = ('<pre>%s</pre>'):format(trim(trim_indent(text), 2))
  621. end
  622. return code
  623. elseif node_name == 'tag' then -- anchor, h4 pseudo-heading
  624. if root:has_error() then
  625. return text
  626. end
  627. local in_heading = vim.list_contains({ 'h1', 'h2', 'h3' }, parent)
  628. local h4 = not in_heading and not next_ and get_indent(node_text()) > 8 -- h4 pseudo-heading
  629. local cssclass = h4 and 'help-tag-right' or 'help-tag'
  630. local tagname = node_text(root:child(1), false)
  631. if vim.tbl_count(stats.first_tags) < 2 then
  632. -- Force the first 2 tags in the doc to be anchored at the main heading.
  633. table.insert(stats.first_tags, tagname)
  634. return ''
  635. end
  636. local el = 'span'
  637. local encoded_tagname = url_encode(tagname)
  638. local s = ('%s<%s id="%s" class="%s"><a href="#%s">%s</a></%s>'):format(
  639. ws(),
  640. el,
  641. encoded_tagname,
  642. cssclass,
  643. encoded_tagname,
  644. trimmed,
  645. el
  646. )
  647. if opt.old then
  648. s = fix_tab_after_conceal(s, node_text(root:next_sibling()))
  649. end
  650. if in_heading and prev ~= 'tag' then
  651. -- Start the <span> container for tags in a heading.
  652. -- This makes "justify-content:space-between" right-align the tags.
  653. -- <h2>foo bar<span>tag1 tag2</span></h2>
  654. return string.format('<span class="help-heading-tags">%s', s)
  655. elseif in_heading and next_ == nil then
  656. -- End the <span> container for tags in a heading.
  657. return string.format('%s</span>', s)
  658. end
  659. return s .. (h4 and '<br>' or '') -- HACK: <br> avoids h4 pseudo-heading mushing with text.
  660. elseif node_name == 'delimiter' or node_name == 'modeline' then
  661. return ''
  662. elseif node_name == 'ERROR' then
  663. if ignore_parse_error(opt.fname, trimmed) then
  664. return text
  665. end
  666. -- Store the raw text to give context to the bug report.
  667. local sample_text = level > 0 and getbuflinestr(root, opt.buf, 3) or '[top level!]'
  668. table.insert(stats.parse_errors, sample_text)
  669. return ('<a class="parse-error" target="_blank" title="Report bug... (parse error)" href="%s">%s</a>'):format(
  670. get_bug_url_vimdoc(opt.fname, opt.to_fname, sample_text),
  671. trimmed
  672. )
  673. else -- Unknown token.
  674. local sample_text = level > 0 and getbuflinestr(root, opt.buf, 3) or '[top level!]'
  675. return ('<a class="unknown-token" target="_blank" title="Report bug... (unhandled token "%s")" href="%s">%s</a>'):format(
  676. node_name,
  677. get_bug_url_nvim(opt.fname, opt.to_fname, sample_text, node_name),
  678. trimmed
  679. ),
  680. ('unknown-token:"%s"'):format(node_name)
  681. end
  682. end
  683. --- @param dir string e.g. '$VIMRUNTIME/doc'
  684. --- @param include string[]|nil
  685. --- @return string[]
  686. local function get_helpfiles(dir, include)
  687. local rv = {}
  688. for f, type in vim.fs.dir(dir) do
  689. if
  690. vim.endswith(f, '.txt')
  691. and type == 'file'
  692. and (not include or vim.list_contains(include, f))
  693. then
  694. local fullpath = vim.fn.fnamemodify(('%s/%s'):format(dir, f), ':p')
  695. table.insert(rv, fullpath)
  696. end
  697. end
  698. return rv
  699. end
  700. --- Populates the helptags map.
  701. local function get_helptags(help_dir)
  702. local m = {}
  703. -- Load a random help file to convince taglist() to do its job.
  704. vim.cmd(string.format('split %s/api.txt', help_dir))
  705. vim.cmd('lcd %:p:h')
  706. for _, item in ipairs(vim.fn.taglist('.*')) do
  707. if vim.endswith(item.filename, '.txt') then
  708. m[item.name] = item.filename
  709. end
  710. end
  711. vim.cmd('q!')
  712. return m
  713. end
  714. --- Use the vimdoc parser defined in the build, not whatever happens to be installed on the system.
  715. local function ensure_runtimepath()
  716. if not vim.o.runtimepath:find('build/lib/nvim/') then
  717. vim.cmd [[set runtimepath^=./build/lib/nvim/]]
  718. end
  719. end
  720. --- Opens `fname` (or `text`, if given) in a buffer and gets a treesitter parser for the buffer contents.
  721. ---
  722. --- @param fname string :help file to parse
  723. --- @param text string? :help file contents
  724. --- @param parser_path string? path to non-default vimdoc.so
  725. --- @return vim.treesitter.LanguageTree, integer (lang_tree, bufnr)
  726. local function parse_buf(fname, text, parser_path)
  727. local buf ---@type integer
  728. if text then
  729. vim.cmd('split new') -- Text contents.
  730. vim.api.nvim_put(vim.split(text, '\n'), '', false, false)
  731. vim.cmd('setfiletype help')
  732. -- vim.treesitter.language.add('vimdoc')
  733. buf = vim.api.nvim_get_current_buf()
  734. elseif type(fname) == 'string' then
  735. vim.cmd('split ' .. vim.fn.fnameescape(fname)) -- Filename.
  736. buf = vim.api.nvim_get_current_buf()
  737. else
  738. -- Left for debugging
  739. ---@diagnostic disable-next-line: no-unknown
  740. buf = fname
  741. vim.cmd('sbuffer ' .. tostring(fname)) -- Buffer number.
  742. end
  743. if parser_path then
  744. vim.treesitter.language.add('vimdoc', { path = parser_path })
  745. end
  746. local lang_tree = assert(vim.treesitter.get_parser(buf, nil, { error = false }))
  747. return lang_tree, buf
  748. end
  749. --- Validates one :help file `fname`:
  750. --- - checks that |tag| links point to valid helptags.
  751. --- - recursively counts parse errors ("ERROR" nodes)
  752. ---
  753. --- @param fname string help file to validate
  754. --- @param parser_path string? path to non-default vimdoc.so
  755. --- @return { invalid_links: number, parse_errors: string[] }
  756. local function validate_one(fname, parser_path)
  757. local stats = {
  758. parse_errors = {},
  759. }
  760. local lang_tree, buf = parse_buf(fname, nil, parser_path)
  761. for _, tree in ipairs(lang_tree:trees()) do
  762. visit_validate(tree:root(), 0, tree, { buf = buf, fname = fname }, stats)
  763. end
  764. lang_tree:destroy()
  765. vim.cmd.close()
  766. return stats
  767. end
  768. --- Generates HTML from one :help file `fname` and writes the result to `to_fname`.
  769. ---
  770. --- @param fname string Source :help file.
  771. --- @param text string|nil Source :help file contents, or nil to read `fname`.
  772. --- @param to_fname string Destination .html file
  773. --- @param old boolean Preformat paragraphs (for old :help files which are full of arbitrary whitespace)
  774. --- @param parser_path string? path to non-default vimdoc.so
  775. ---
  776. --- @return string html
  777. --- @return table stats
  778. local function gen_one(fname, text, to_fname, old, commit, parser_path)
  779. local stats = {
  780. noise_lines = {},
  781. parse_errors = {},
  782. first_tags = {}, -- Track the first few tags in doc.
  783. }
  784. local lang_tree, buf = parse_buf(fname, text, parser_path)
  785. ---@type nvim.gen_help_html.heading[]
  786. local headings = {} -- Headings (for ToC). 2-dimensional: h1 contains h2/h3.
  787. local title = to_titlecase(basename_noext(fname))
  788. local html = ([[
  789. <!DOCTYPE html>
  790. <html>
  791. <head>
  792. <meta charset="utf-8">
  793. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  794. <meta name="viewport" content="width=device-width, initial-scale=1">
  795. <meta name="description" content="Neovim user documentation">
  796. <!-- algolia docsearch https://docsearch.algolia.com/docs/docsearch-v3/ -->
  797. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@docsearch/css@3" />
  798. <link rel="preconnect" href="https://X185E15FPG-dsn.algolia.net" crossorigin />
  799. <link href="/css/bootstrap.min.css" rel="stylesheet">
  800. <link href="/css/main.css" rel="stylesheet">
  801. <link href="help.css" rel="stylesheet">
  802. <link href="/highlight/styles/neovim.min.css" rel="stylesheet">
  803. <script src="/highlight/highlight.min.js"></script>
  804. <script>hljs.highlightAll();</script>
  805. <title>%s - Neovim docs</title>
  806. </head>
  807. <body>
  808. ]]):format(title)
  809. local logo_svg = [[
  810. <svg xmlns="http://www.w3.org/2000/svg" role="img" width="173" height="50" viewBox="0 0 742 214" aria-label="Neovim">
  811. <title>Neovim</title>
  812. <defs>
  813. <linearGradient x1="50%" y1="0%" x2="50%" y2="100%" id="a">
  814. <stop stop-color="#16B0ED" stop-opacity=".8" offset="0%" />
  815. <stop stop-color="#0F59B2" stop-opacity=".837" offset="100%" />
  816. </linearGradient>
  817. <linearGradient x1="50%" y1="0%" x2="50%" y2="100%" id="b">
  818. <stop stop-color="#7DB643" offset="0%" />
  819. <stop stop-color="#367533" offset="100%" />
  820. </linearGradient>
  821. <linearGradient x1="50%" y1="0%" x2="50%" y2="100%" id="c">
  822. <stop stop-color="#88C649" stop-opacity=".8" offset="0%" />
  823. <stop stop-color="#439240" stop-opacity=".84" offset="100%" />
  824. </linearGradient>
  825. </defs>
  826. <g fill="none" fill-rule="evenodd">
  827. <path
  828. d="M.027 45.459L45.224-.173v212.171L.027 166.894V45.459z"
  829. fill="url(#a)"
  830. transform="translate(1 1)"
  831. />
  832. <path
  833. d="M129.337 45.89L175.152-.149l-.928 212.146-45.197-45.104.31-121.005z"
  834. fill="url(#b)"
  835. transform="matrix(-1 0 0 1 305 1)"
  836. />
  837. <path
  838. d="M45.194-.137L162.7 179.173l-32.882 32.881L12.25 33.141 45.194-.137z"
  839. fill="url(#c)"
  840. transform="translate(1 1)"
  841. />
  842. <path
  843. d="M46.234 84.032l-.063 7.063-36.28-53.563 3.36-3.422 32.983 49.922z"
  844. fill-opacity=".13"
  845. fill="#000"
  846. />
  847. <g fill="#444">
  848. <path
  849. d="M227 154V64.44h4.655c1.55 0 2.445.75 2.685 2.25l.806 13.502c4.058-5.16 8.786-9.316 14.188-12.466 5.4-3.15 11.413-4.726 18.037-4.726 4.893 0 9.205.781 12.935 2.34 3.729 1.561 6.817 3.811 9.264 6.751 2.448 2.942 4.297 6.48 5.55 10.621 1.253 4.14 1.88 8.821 1.88 14.042V154h-8.504V96.754c0-8.402-1.91-14.987-5.729-19.757-3.82-4.771-9.667-7.156-17.544-7.156-5.851 0-11.28 1.516-16.292 4.545-5.013 3.032-9.489 7.187-13.427 12.467V154H227zM350.624 63c5.066 0 9.755.868 14.069 2.605 4.312 1.738 8.052 4.268 11.219 7.592s5.638 7.412 7.419 12.264C385.11 90.313 386 95.883 386 102.17c0 1.318-.195 2.216-.588 2.696-.393.48-1.01.719-1.851.719h-64.966v1.70c0 6.708.784 12.609 2.353 17.7 1.567 5.09 3.8 9.357 6.695 12.802 2.895 3.445 6.393 6.034 10.495 7.771 4.1 1.738 8.686 2.606 13.752 2.606 4.524 0 8.446-.494 11.762-1.483 3.317-.988 6.108-2.097 8.37-3.324 2.261-1.227 4.056-2.336 5.383-3.324 1.326-.988 2.292-1.482 2.895-1.482.784 0 1.388.3 1.81.898l2.352 2.875c-1.448 1.797-3.362 3.475-5.745 5.031-2.383 1.558-5.038 2.891-7.962 3.998-2.926 1.109-6.062 1.991-9.41 2.65a52.21 52.21 0 01-10.088.989c-6.152 0-11.762-1.064-16.828-3.19-5.067-2.125-9.415-5.225-13.043-9.298-3.63-4.074-6.435-9.06-8.415-14.96C310.99 121.655 310 114.9 310 107.294c0-6.408.92-12.323 2.76-17.744 1.84-5.421 4.493-10.093 7.961-14.016 3.467-3.922 7.72-6.991 12.758-9.209C338.513 64.11 344.229 63 350.624 63zm.573 6c-4.696 0-8.904.702-12.623 2.105-3.721 1.404-6.936 3.421-9.65 6.053-2.713 2.631-4.908 5.79-6.586 9.474S319.55 94.439 319 99h60c0-4.679-.672-8.874-2.013-12.588-1.343-3.712-3.232-6.856-5.67-9.43-2.44-2.571-5.367-4.545-8.782-5.92-3.413-1.374-7.192-2.062-11.338-2.062zM435.546 63c6.526 0 12.368 1.093 17.524 3.28 5.154 2.186 9.5 5.286 13.04 9.298 3.538 4.013 6.238 8.85 8.099 14.51 1.861 5.66 2.791 11.994 2.791 19.002 0 7.008-.932 13.327-2.791 18.957-1.861 5.631-4.561 10.452-8.099 14.465-3.54 4.012-7.886 7.097-13.04 9.254-5.156 2.156-10.998 3.234-17.524 3.234-6.529 0-12.369-1.078-17.525-3.234-5.155-2.157-9.517-5.242-13.085-9.254-3.57-4.013-6.285-8.836-8.145-14.465-1.861-5.63-2.791-11.95-2.791-18.957 0-7.008.93-13.342 2.791-19.002 1.861-5.66 4.576-10.496 8.145-14.51 3.568-4.012 7.93-7.112 13.085-9.299C423.177 64.094 429.017 63 435.546 63zm-.501 86c5.341 0 10.006-.918 13.997-2.757 3.99-1.838 7.32-4.474 9.992-7.909 2.67-3.435 4.664-7.576 5.986-12.428 1.317-4.85 1.98-10.288 1.98-16.316 0-5.965-.66-11.389-1.98-16.27-1.322-4.88-3.316-9.053-5.986-12.519-2.67-3.463-6-6.13-9.992-7.999-3.991-1.867-8.657-2.802-13.997-2.802s-10.008.935-13.997 2.802c-3.991 1.87-7.322 4.536-9.992 8-2.671 3.465-4.68 7.637-6.03 12.518-1.35 4.881-2.026 10.305-2.026 16.27 0 6.026.675 11.465 2.025 16.316 1.35 4.852 3.36 8.993 6.031 12.428 2.67 3.435 6 6.07 9.992 7.91 3.99 1.838 8.656 2.756 13.997 2.756z"
  850. fill="currentColor"
  851. />
  852. <path
  853. d="M530.57 152h-20.05L474 60h18.35c1.61 0 2.967.39 4.072 1.166 1.103.778 1.865 1.763 2.283 2.959l17.722 49.138a92.762 92.762 0 012.551 8.429c.686 2.751 1.298 5.5 1.835 8.25.537-2.75 1.148-5.499 1.835-8.25a77.713 77.713 0 012.64-8.429l18.171-49.138c.417-1.196 1.164-2.181 2.238-2.96 1.074-.776 2.356-1.165 3.849-1.165H567l-36.43 92zM572 61h23v92h-23zM610 153V60.443h13.624c2.887 0 4.78 1.354 5.682 4.06l1.443 6.856a52.7 52.7 0 015.097-4.962 32.732 32.732 0 015.683-3.879 30.731 30.731 0 016.496-2.57c2.314-.632 4.855-.948 7.624-.948 5.832 0 10.63 1.579 14.39 4.736 3.758 3.157 6.57 7.352 8.434 12.585 1.444-3.068 3.248-5.698 5.413-7.894 2.165-2.194 4.541-3.984 7.127-5.367a32.848 32.848 0 018.254-3.068 39.597 39.597 0 018.796-.992c5.111 0 9.653.783 13.622 2.345 3.97 1.565 7.307 3.849 10.014 6.857 2.706 3.007 4.766 6.675 6.18 11.005C739.29 83.537 740 88.5 740 94.092V153h-22.284V94.092c0-5.894-1.294-10.329-3.878-13.306-2.587-2.977-6.376-4.465-11.368-4.465-2.286 0-4.404.391-6.358 1.172a15.189 15.189 0 00-5.144 3.383c-1.473 1.474-2.631 3.324-3.474 5.548-.842 2.225-1.263 4.781-1.263 7.668V153h-22.37V94.092c0-6.194-1.249-10.704-3.744-13.532-2.497-2.825-6.18-4.24-11.051-4.24-3.19 0-6.18.798-8.976 2.391-2.799 1.593-5.399 3.775-7.804 6.54V153H610zM572 30h23v19h-23z"
  854. fill="currentColor"
  855. fill-opacity=".8"
  856. />
  857. </g>
  858. </g>
  859. </svg>
  860. ]]
  861. local main = ''
  862. for _, tree in ipairs(lang_tree:trees()) do
  863. main = main
  864. .. (
  865. visit_node(
  866. tree:root(),
  867. 0,
  868. tree,
  869. headings,
  870. { buf = buf, old = old, fname = fname, to_fname = to_fname, indent = 1 },
  871. stats
  872. )
  873. )
  874. end
  875. main = ([[
  876. <header class="container">
  877. <nav class="navbar navbar-expand-lg">
  878. <div class="container-fluid">
  879. <a href="/" class="navbar-brand" aria-label="logo">
  880. <!--TODO: use <img src="….svg"> here instead. Need one that has green lettering instead of gray. -->
  881. %s
  882. <!--<img src="https://neovim.io/logos/neovim-logo.svg" width="173" height="50" alt="Neovim" />-->
  883. </a>
  884. <div id="docsearch"></div> <!-- algolia docsearch https://docsearch.algolia.com/docs/docsearch-v3/ -->
  885. </div>
  886. </nav>
  887. </header>
  888. <div class="container golden-grid help-body">
  889. <div class="col-wide">
  890. <a name="%s" href="#%s"><h1 id="%s">%s</h1></a>
  891. <p>
  892. <i>
  893. Nvim <code>:help</code> pages, <a href="https://github.com/neovim/neovim/blob/master/scripts/gen_help_html.lua">generated</a>
  894. from <a href="https://github.com/neovim/neovim/blob/master/runtime/doc/%s">source</a>
  895. using the <a href="https://github.com/neovim/tree-sitter-vimdoc">tree-sitter-vimdoc</a> parser.
  896. </i>
  897. </p>
  898. <hr/>
  899. %s
  900. </div>
  901. ]]):format(
  902. logo_svg,
  903. stats.first_tags[1] or '',
  904. stats.first_tags[2] or '',
  905. stats.first_tags[2] or '',
  906. title,
  907. vim.fs.basename(fname),
  908. main
  909. )
  910. ---@type string
  911. local toc = [[
  912. <div class="col-narrow toc">
  913. <div><a href="index.html">Main</a></div>
  914. <div><a href="vimindex.html">Commands index</a></div>
  915. <div><a href="quickref.html">Quick reference</a></div>
  916. <hr/>
  917. ]]
  918. local n = 0 -- Count of all headings + subheadings.
  919. for _, h1 in ipairs(headings) do
  920. n = n + 1 + #h1.subheadings
  921. end
  922. for _, h1 in ipairs(headings) do
  923. ---@type string
  924. toc = toc .. ('<div class="help-toc-h1"><a href="#%s">%s</a>\n'):format(h1.tag, h1.name)
  925. if n < 30 or #headings < 10 then -- Show subheadings only if there aren't too many.
  926. for _, h2 in ipairs(h1.subheadings) do
  927. toc = toc
  928. .. ('<div class="help-toc-h2"><a href="#%s">%s</a></div>\n'):format(h2.tag, h2.name)
  929. end
  930. end
  931. toc = toc .. '</div>'
  932. end
  933. toc = toc .. '</div>\n'
  934. local bug_url = get_bug_url_nvim(fname, to_fname, 'TODO', nil)
  935. local bug_link = string.format('(<a href="%s" target="_blank">report docs bug...</a>)', bug_url)
  936. local footer = ([[
  937. <footer>
  938. <div class="container flex">
  939. <div class="generator-stats">
  940. Generated at %s from <code><a href="https://github.com/neovim/neovim/commit/%s">%s</a></code>
  941. </div>
  942. <div class="generator-stats">
  943. parse_errors: %d %s | <span title="%s">noise_lines: %d</span>
  944. </div>
  945. <div>
  946. <!-- algolia docsearch https://docsearch.algolia.com/docs/docsearch-v3/ -->
  947. <script src="https://cdn.jsdelivr.net/npm/@docsearch/js@3"></script>
  948. <script type="module">
  949. docsearch({
  950. container: '#docsearch',
  951. appId: 'X185E15FPG',
  952. apiKey: 'b5e6b2f9c636b2b471303205e59832ed',
  953. indexName: 'nvim',
  954. });
  955. </script>
  956. </footer>
  957. ]]):format(
  958. os.date('%Y-%m-%d %H:%M'),
  959. commit,
  960. commit:sub(1, 7),
  961. #stats.parse_errors,
  962. bug_link,
  963. html_esc(table.concat(stats.noise_lines, '\n')),
  964. #stats.noise_lines
  965. )
  966. html = ('%s%s%s</div>\n%s</body>\n</html>\n'):format(html, main, toc, footer)
  967. vim.cmd('q!')
  968. lang_tree:destroy()
  969. return html, stats
  970. end
  971. local function gen_css(fname)
  972. local css = [[
  973. :root {
  974. --code-color: #004b4b;
  975. --tag-color: #095943;
  976. }
  977. @media (prefers-color-scheme: dark) {
  978. :root {
  979. --code-color: #00c243;
  980. --tag-color: #00b7b7;
  981. }
  982. }
  983. @media (min-width: 40em) {
  984. .toc {
  985. position: fixed;
  986. left: 67%;
  987. }
  988. .golden-grid {
  989. display: grid;
  990. grid-template-columns: 65% auto;
  991. grid-gap: 1em;
  992. }
  993. }
  994. @media (max-width: 40em) {
  995. .golden-grid {
  996. /* Disable grid for narrow viewport (mobile phone). */
  997. display: block;
  998. }
  999. }
  1000. .toc {
  1001. /* max-width: 12rem; */
  1002. height: 85%; /* Scroll if there are too many items. https://github.com/neovim/neovim.github.io/issues/297 */
  1003. overflow: auto; /* Scroll if there are too many items. https://github.com/neovim/neovim.github.io/issues/297 */
  1004. }
  1005. .toc > div {
  1006. text-overflow: ellipsis;
  1007. overflow: hidden;
  1008. white-space: nowrap;
  1009. }
  1010. html {
  1011. scroll-behavior: auto;
  1012. }
  1013. body {
  1014. font-size: 18px;
  1015. line-height: 1.5;
  1016. }
  1017. h1, h2, h3, h4, h5 {
  1018. font-family: sans-serif;
  1019. border-bottom: 1px solid var(--tag-color); /*rgba(0, 0, 0, .9);*/
  1020. }
  1021. h3, h4, h5 {
  1022. border-bottom-style: dashed;
  1023. }
  1024. .help-column_heading {
  1025. color: var(--code-color);
  1026. }
  1027. .help-body {
  1028. padding-bottom: 2em;
  1029. }
  1030. .help-line {
  1031. /* font-family: ui-monospace,SFMono-Regular,SF Mono,Menlo,Consolas,Liberation Mono,monospace; */
  1032. }
  1033. .help-li {
  1034. white-space: normal;
  1035. display: list-item;
  1036. margin-left: 1.5rem; /* padding-left: 1rem; */
  1037. }
  1038. .help-para {
  1039. padding-top: 10px;
  1040. padding-bottom: 10px;
  1041. }
  1042. .old-help-para {
  1043. padding-top: 10px;
  1044. padding-bottom: 10px;
  1045. /* Tabs are used for alignment in old docs, so we must match Vim's 8-char expectation. */
  1046. tab-size: 8;
  1047. white-space: pre-wrap;
  1048. font-size: 16px;
  1049. font-family: ui-monospace,SFMono-Regular,SF Mono,Menlo,Consolas,Liberation Mono,monospace;
  1050. word-wrap: break-word;
  1051. }
  1052. .old-help-para pre, .old-help-para pre:hover {
  1053. /* Text following <pre> is already visually separated by the linebreak. */
  1054. margin-bottom: 0;
  1055. /* Long lines that exceed the textwidth should not be wrapped (no "pre-wrap").
  1056. Since text may overflow horizontally, we make the contents to be scrollable
  1057. (only if necessary) to prevent overlapping with the navigation bar at the right. */
  1058. white-space: pre;
  1059. overflow-x: auto;
  1060. }
  1061. /* TODO: should this rule be deleted? help tags are rendered as <code> or <span>, not <a> */
  1062. a.help-tag, a.help-tag:focus, a.help-tag:hover {
  1063. color: inherit;
  1064. text-decoration: none;
  1065. }
  1066. .help-tag {
  1067. color: var(--tag-color);
  1068. }
  1069. /* Tag pseudo-header common in :help docs. */
  1070. .help-tag-right {
  1071. color: var(--tag-color);
  1072. margin-left: auto;
  1073. margin-right: 0;
  1074. float: right;
  1075. display: block;
  1076. }
  1077. .help-tag a,
  1078. .help-tag-right a {
  1079. color: inherit;
  1080. }
  1081. .help-tag a:not(:hover),
  1082. .help-tag-right a:not(:hover) {
  1083. text-decoration: none;
  1084. }
  1085. h1 .help-tag, h2 .help-tag, h3 .help-tag {
  1086. font-size: smaller;
  1087. }
  1088. .help-heading {
  1089. white-space: normal;
  1090. display: flex;
  1091. flex-flow: row wrap;
  1092. justify-content: space-between;
  1093. gap: 0 15px;
  1094. }
  1095. /* The (right-aligned) "tags" part of a section heading. */
  1096. .help-heading-tags {
  1097. margin-right: 10px;
  1098. }
  1099. .help-toc-h1 {
  1100. }
  1101. .help-toc-h2 {
  1102. margin-left: 1em;
  1103. }
  1104. .parse-error {
  1105. background-color: red;
  1106. }
  1107. .unknown-token {
  1108. color: black;
  1109. background-color: yellow;
  1110. }
  1111. code {
  1112. color: var(--code-color);
  1113. font-size: 16px;
  1114. }
  1115. pre {
  1116. /* Tabs are used in codeblocks only for indentation, not alignment, so we can aggressively shrink them. */
  1117. tab-size: 2;
  1118. white-space: pre-wrap;
  1119. line-height: 1.3; /* Important for ascii art. */
  1120. overflow: visible;
  1121. /* font-family: ui-monospace,SFMono-Regular,SF Mono,Menlo,Consolas,Liberation Mono,monospace; */
  1122. font-size: 16px;
  1123. margin-top: 10px;
  1124. }
  1125. pre:last-child {
  1126. margin-bottom: 0;
  1127. }
  1128. pre:hover {
  1129. overflow: visible;
  1130. }
  1131. .generator-stats {
  1132. color: gray;
  1133. font-size: smaller;
  1134. }
  1135. ]]
  1136. tofile(fname, css)
  1137. end
  1138. -- Testing
  1139. local function ok(cond, expected, actual, message)
  1140. assert(
  1141. (not expected and not actual) or (expected and actual),
  1142. 'if "expected" is given, "actual" is also required'
  1143. )
  1144. if expected then
  1145. assert(
  1146. cond,
  1147. ('%sexpected %s, got: %s'):format(
  1148. message and (message .. '\n') or '',
  1149. vim.inspect(expected),
  1150. vim.inspect(actual)
  1151. )
  1152. )
  1153. return cond
  1154. else
  1155. return assert(cond)
  1156. end
  1157. end
  1158. local function eq(expected, actual, message)
  1159. return ok(vim.deep_equal(expected, actual), expected, actual, message)
  1160. end
  1161. function M._test()
  1162. tagmap = get_helptags('$VIMRUNTIME/doc')
  1163. helpfiles = get_helpfiles(vim.fs.normalize('$VIMRUNTIME/doc'))
  1164. ok(vim.tbl_count(tagmap) > 3000, '>3000', vim.tbl_count(tagmap))
  1165. ok(
  1166. vim.endswith(tagmap['vim.diagnostic.set()'], 'diagnostic.txt'),
  1167. tagmap['vim.diagnostic.set()'],
  1168. 'diagnostic.txt'
  1169. )
  1170. ok(vim.endswith(tagmap['%:s'], 'cmdline.txt'), tagmap['%:s'], 'cmdline.txt')
  1171. ok(is_noise([[vim:tw=78:isk=!-~,^*,^\|,^\":ts=8:noet:ft=help:norl:]]))
  1172. ok(is_noise([[ NVIM REFERENCE MANUAL by Thiago de Arruda ]]))
  1173. ok(not is_noise([[vim:tw=78]]))
  1174. eq(0, get_indent('a'))
  1175. eq(1, get_indent(' a'))
  1176. eq(2, get_indent(' a\n b\n c\n'))
  1177. eq(5, get_indent(' a\n \n b\n c\n d\n e\n'))
  1178. eq(
  1179. 'a\n \n b\n c\n d\n e\n',
  1180. trim_indent(' a\n \n b\n c\n d\n e\n')
  1181. )
  1182. local fixed_url, removed_chars = fix_url('https://example.com).')
  1183. eq('https://example.com', fixed_url)
  1184. eq(').', removed_chars)
  1185. fixed_url, removed_chars = fix_url('https://example.com.)')
  1186. eq('https://example.com.', fixed_url)
  1187. eq(')', removed_chars)
  1188. fixed_url, removed_chars = fix_url('https://example.com.')
  1189. eq('https://example.com', fixed_url)
  1190. eq('.', removed_chars)
  1191. fixed_url, removed_chars = fix_url('https://example.com)')
  1192. eq('https://example.com', fixed_url)
  1193. eq(')', removed_chars)
  1194. fixed_url, removed_chars = fix_url('https://example.com')
  1195. eq('https://example.com', fixed_url)
  1196. eq('', removed_chars)
  1197. print('all tests passed.\n')
  1198. end
  1199. --- @class nvim.gen_help_html.gen_result
  1200. --- @field helpfiles string[] list of generated HTML files, from the source docs {include}
  1201. --- @field err_count integer number of parse errors in :help docs
  1202. --- @field invalid_links table<string, any>
  1203. --- Generates HTML from :help docs located in `help_dir` and writes the result in `to_dir`.
  1204. ---
  1205. --- Example:
  1206. ---
  1207. --- gen('$VIMRUNTIME/doc', '/path/to/neovim.github.io/_site/doc/', {'api.txt', 'autocmd.txt', 'channel.txt'}, nil)
  1208. ---
  1209. --- @param help_dir string Source directory containing the :help files. Must run `make helptags` first.
  1210. --- @param to_dir string Target directory where the .html files will be written.
  1211. --- @param include string[]|nil Process only these filenames. Example: {'api.txt', 'autocmd.txt', 'channel.txt'}
  1212. ---
  1213. --- @return nvim.gen_help_html.gen_result result
  1214. function M.gen(help_dir, to_dir, include, commit, parser_path)
  1215. vim.validate('help_dir', help_dir, function(d)
  1216. return vim.fn.isdirectory(vim.fs.normalize(d)) == 1
  1217. end, 'valid directory')
  1218. vim.validate('to_dir', to_dir, 'string')
  1219. vim.validate('include', include, 'table', true)
  1220. vim.validate('commit', commit, 'string', true)
  1221. vim.validate('parser_path', parser_path, function(f)
  1222. return vim.fn.filereadable(vim.fs.normalize(f)) == 1
  1223. end, true, 'valid vimdoc.{so,dll} filepath')
  1224. local err_count = 0
  1225. local redirects_count = 0
  1226. ensure_runtimepath()
  1227. tagmap = get_helptags(vim.fs.normalize(help_dir))
  1228. helpfiles = get_helpfiles(help_dir, include)
  1229. to_dir = vim.fs.normalize(to_dir)
  1230. parser_path = parser_path and vim.fs.normalize(parser_path) or nil
  1231. print(('output dir: %s\n\n'):format(to_dir))
  1232. vim.fn.mkdir(to_dir, 'p')
  1233. gen_css(('%s/help.css'):format(to_dir))
  1234. for _, f in ipairs(helpfiles) do
  1235. -- "foo.txt"
  1236. local helpfile = vim.fs.basename(f)
  1237. -- "to/dir/foo.html"
  1238. local to_fname = ('%s/%s'):format(to_dir, get_helppage(helpfile))
  1239. local html, stats =
  1240. gen_one(f, nil, to_fname, not new_layout[helpfile], commit or '?', parser_path)
  1241. tofile(to_fname, html)
  1242. print(
  1243. ('generated (%-2s errors): %-15s => %s'):format(
  1244. #stats.parse_errors,
  1245. helpfile,
  1246. vim.fs.basename(to_fname)
  1247. )
  1248. )
  1249. -- Generate redirect pages for renamed help files.
  1250. local helpfile_tag = (helpfile:gsub('%.txt$', ''))
  1251. local redirect_from = redirects[helpfile_tag]
  1252. if redirect_from then
  1253. local redirect_text = ([[
  1254. *%s* Nvim
  1255. This document moved to: |%s|
  1256. ==============================================================================
  1257. This document moved to: |%s|
  1258. This document moved to: |%s|
  1259. ==============================================================================
  1260. vim:tw=78:ts=8:ft=help:norl:
  1261. ]]):format(
  1262. redirect_from,
  1263. helpfile_tag,
  1264. helpfile_tag,
  1265. helpfile_tag,
  1266. helpfile_tag,
  1267. helpfile_tag
  1268. )
  1269. local redirect_to = ('%s/%s'):format(to_dir, get_helppage(redirect_from))
  1270. local redirect_html, _ =
  1271. gen_one(redirect_from, redirect_text, redirect_to, false, commit or '?', parser_path)
  1272. assert(redirect_html:find(helpfile_tag))
  1273. tofile(redirect_to, redirect_html)
  1274. print(
  1275. ('generated (redirect) : %-15s => %s'):format(
  1276. redirect_from .. '.txt',
  1277. vim.fs.basename(to_fname)
  1278. )
  1279. )
  1280. redirects_count = redirects_count + 1
  1281. end
  1282. err_count = err_count + #stats.parse_errors
  1283. end
  1284. print(('\ngenerated %d html pages'):format(#helpfiles + redirects_count))
  1285. print(('total errors: %d'):format(err_count))
  1286. print(('invalid tags: %s'):format(vim.inspect(invalid_links)))
  1287. assert(#(include or {}) > 0 or redirects_count == vim.tbl_count(redirects)) -- sanity check
  1288. print(('redirects: %d'):format(redirects_count))
  1289. print('\n')
  1290. --- @type nvim.gen_help_html.gen_result
  1291. return {
  1292. helpfiles = helpfiles,
  1293. err_count = err_count,
  1294. invalid_links = invalid_links,
  1295. }
  1296. end
  1297. --- @class nvim.gen_help_html.validate_result
  1298. --- @field helpfiles integer number of generated helpfiles
  1299. --- @field err_count integer number of parse errors
  1300. --- @field parse_errors table<string, string[]>
  1301. --- @field invalid_links table<string, any> invalid tags in :help docs
  1302. --- @field invalid_urls table<string, any> invalid URLs in :help docs
  1303. --- @field invalid_spelling table<string, table<string, string>> invalid spelling in :help docs
  1304. --- Validates all :help files found in `help_dir`:
  1305. --- - checks that |tag| links point to valid helptags.
  1306. --- - recursively counts parse errors ("ERROR" nodes)
  1307. ---
  1308. --- This is 10x faster than gen(), for use in CI.
  1309. ---
  1310. --- @return nvim.gen_help_html.validate_result result
  1311. function M.validate(help_dir, include, parser_path)
  1312. vim.validate('help_dir', help_dir, function(d)
  1313. return vim.fn.isdirectory(vim.fs.normalize(d)) == 1
  1314. end, 'valid directory')
  1315. vim.validate('include', include, 'table', true)
  1316. vim.validate('parser_path', parser_path, function(f)
  1317. return vim.fn.filereadable(vim.fs.normalize(f)) == 1
  1318. end, true, 'valid vimdoc.{so,dll} filepath')
  1319. local err_count = 0 ---@type integer
  1320. local files_to_errors = {} ---@type table<string, string[]>
  1321. ensure_runtimepath()
  1322. tagmap = get_helptags(vim.fs.normalize(help_dir))
  1323. helpfiles = get_helpfiles(help_dir, include)
  1324. parser_path = parser_path and vim.fs.normalize(parser_path) or nil
  1325. for _, f in ipairs(helpfiles) do
  1326. local helpfile = vim.fs.basename(f)
  1327. local rv = validate_one(f, parser_path)
  1328. print(('validated (%-4s errors): %s'):format(#rv.parse_errors, helpfile))
  1329. if #rv.parse_errors > 0 then
  1330. files_to_errors[helpfile] = rv.parse_errors
  1331. vim.print(('%s'):format(vim.iter(rv.parse_errors):fold('', function(s, v)
  1332. return s .. '\n ' .. v
  1333. end)))
  1334. end
  1335. err_count = err_count + #rv.parse_errors
  1336. end
  1337. ---@type nvim.gen_help_html.validate_result
  1338. return {
  1339. helpfiles = #helpfiles,
  1340. err_count = err_count,
  1341. parse_errors = files_to_errors,
  1342. invalid_links = invalid_links,
  1343. invalid_urls = invalid_urls,
  1344. invalid_spelling = invalid_spelling,
  1345. }
  1346. end
  1347. --- Validates vimdoc files on $VIMRUNTIME. and print human-readable error messages if fails.
  1348. ---
  1349. --- If this fails, try these steps (in order):
  1350. --- 1. Fix/cleanup the :help docs.
  1351. --- 2. Fix the parser: https://github.com/neovim/tree-sitter-vimdoc
  1352. --- 3. File a parser bug, and adjust the tolerance of this test in the meantime.
  1353. ---
  1354. --- @param help_dir? string e.g. '$VIMRUNTIME/doc' or './runtime/doc'
  1355. function M.run_validate(help_dir)
  1356. help_dir = vim.fs.normalize(help_dir or '$VIMRUNTIME/doc')
  1357. print('doc path = ' .. vim.uv.fs_realpath(help_dir))
  1358. local rv = M.validate(help_dir)
  1359. -- Check that we actually found helpfiles.
  1360. ok(rv.helpfiles > 100, '>100 :help files', rv.helpfiles)
  1361. eq({}, rv.parse_errors, 'no parse errors')
  1362. eq(0, rv.err_count, 'no parse errors')
  1363. eq({}, rv.invalid_links, 'invalid tags in :help docs')
  1364. eq({}, rv.invalid_urls, 'invalid URLs in :help docs')
  1365. eq(
  1366. {},
  1367. rv.invalid_spelling,
  1368. 'invalid spelling in :help docs (see spell_dict in scripts/gen_help_html.lua)'
  1369. )
  1370. end
  1371. --- Test-generates HTML from docs.
  1372. ---
  1373. --- 1. Test that gen_help_html.lua actually works.
  1374. --- 2. Test that parse errors did not increase wildly. Because we explicitly test only a few
  1375. --- :help files, we can be precise about the tolerances here.
  1376. --- @param help_dir? string e.g. '$VIMRUNTIME/doc' or './runtime/doc'
  1377. function M.test_gen(help_dir)
  1378. local tmpdir = vim.fs.dirname(vim.fn.tempname())
  1379. help_dir = vim.fs.normalize(help_dir or '$VIMRUNTIME/doc')
  1380. print('doc path = ' .. vim.uv.fs_realpath(help_dir))
  1381. -- Because gen() is slow (~30s), this test is limited to a few files.
  1382. local input = { 'help.txt', 'index.txt', 'nvim.txt' }
  1383. local rv = M.gen(help_dir, tmpdir, input)
  1384. eq(#input, #rv.helpfiles)
  1385. eq(0, rv.err_count, 'parse errors in :help docs')
  1386. eq({}, rv.invalid_links, 'invalid tags in :help docs')
  1387. end
  1388. return M