gen_vimdoc.lua 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  1. #!/usr/bin/env -S nvim -l
  2. --- Generates Nvim :help docs from Lua/C docstrings
  3. ---
  4. --- The generated :help text for each function is formatted as follows:
  5. --- - Max width of 78 columns (`TEXT_WIDTH`).
  6. --- - Indent with spaces (not tabs).
  7. --- - Indent of 4 columns for body text (`INDENTATION`).
  8. --- - Function signature and helptag (right-aligned) on the same line.
  9. --- - Signature and helptag must have a minimum of 8 spaces between them.
  10. --- - If the signature is too long, it is placed on the line after the helptag.
  11. --- Signature wraps with subsequent lines indented to the open parenthesis.
  12. --- - Subsection bodies are indented an additional 4 spaces.
  13. --- - Body consists of function description, parameters, return description, and
  14. --- C declaration (`INCLUDE_C_DECL`).
  15. --- - Parameters are omitted for the `void` and `Error *` types, or if the
  16. --- parameter is marked as [out].
  17. --- - Each function documentation is separated by a single line.
  18. local luacats_parser = require('scripts.luacats_parser')
  19. local cdoc_parser = require('scripts.cdoc_parser')
  20. local util = require('scripts.util')
  21. local fmt = string.format
  22. local wrap = util.wrap
  23. local md_to_vimdoc = util.md_to_vimdoc
  24. local TEXT_WIDTH = 78
  25. local INDENTATION = 4
  26. --- @class (exact) nvim.gen_vimdoc.Config
  27. ---
  28. --- Generated documentation target, e.g. api.txt
  29. --- @field filename string
  30. ---
  31. --- @field section_order string[]
  32. ---
  33. --- List of files/directories for doxygen to read, relative to `base_dir`.
  34. --- @field files string[]
  35. ---
  36. --- @field exclude_types? true
  37. ---
  38. --- Section name overrides. Key: filename (e.g., vim.c)
  39. --- @field section_name? table<string,string>
  40. ---
  41. --- @field fn_name_pat? string
  42. ---
  43. --- @field fn_xform? fun(fun: nvim.luacats.parser.fun)
  44. ---
  45. --- For generated section names.
  46. --- @field section_fmt fun(name: string): string
  47. ---
  48. --- @field helptag_fmt fun(name: string): string|string[]
  49. ---
  50. --- Per-function helptag.
  51. --- @field fn_helptag_fmt? fun(fun: nvim.luacats.parser.fun): string
  52. ---
  53. --- @field append_only? string[]
  54. local function contains(t, xs)
  55. return vim.tbl_contains(xs, t)
  56. end
  57. --- @type {level:integer, prerelease:boolean}?
  58. local nvim_api_info_
  59. --- @return {level: integer, prerelease:boolean}
  60. local function nvim_api_info()
  61. if not nvim_api_info_ then
  62. --- @type integer?, boolean?
  63. local level, prerelease
  64. for l in io.lines('CMakeLists.txt') do
  65. --- @cast l string
  66. if level and prerelease then
  67. break
  68. end
  69. local m1 = l:match('^set%(NVIM_API_LEVEL%s+(%d+)%)')
  70. if m1 then
  71. level = tonumber(m1) --[[@as integer]]
  72. end
  73. local m2 = l:match('^set%(NVIM_API_PRERELEASE%s+(%w+)%)')
  74. if m2 then
  75. prerelease = m2 == 'true'
  76. end
  77. end
  78. nvim_api_info_ = { level = level, prerelease = prerelease }
  79. end
  80. return nvim_api_info_
  81. end
  82. --- @param fun nvim.luacats.parser.fun
  83. --- @return string
  84. local function fn_helptag_fmt_common(fun)
  85. local fn_sfx = fun.table and '' or '()'
  86. if fun.classvar then
  87. return fmt('%s:%s%s', fun.classvar, fun.name, fn_sfx)
  88. end
  89. if fun.module then
  90. return fmt('%s.%s%s', fun.module, fun.name, fn_sfx)
  91. end
  92. return fun.name .. fn_sfx
  93. end
  94. --- @type table<string,nvim.gen_vimdoc.Config>
  95. local config = {
  96. api = {
  97. filename = 'api.txt',
  98. section_order = {
  99. 'vim.c',
  100. 'vimscript.c',
  101. 'command.c',
  102. 'options.c',
  103. 'buffer.c',
  104. 'extmark.c',
  105. 'window.c',
  106. 'win_config.c',
  107. 'tabpage.c',
  108. 'autocmd.c',
  109. 'ui.c',
  110. },
  111. exclude_types = true,
  112. fn_name_pat = 'nvim_.*',
  113. files = { 'src/nvim/api' },
  114. section_name = {
  115. ['vim.c'] = 'Global',
  116. },
  117. section_fmt = function(name)
  118. return name .. ' Functions'
  119. end,
  120. helptag_fmt = function(name)
  121. return fmt('api-%s', name:lower())
  122. end,
  123. },
  124. lua = {
  125. filename = 'lua.txt',
  126. section_order = {
  127. 'hl.lua',
  128. 'diff.lua',
  129. 'mpack.lua',
  130. 'json.lua',
  131. 'base64.lua',
  132. 'spell.lua',
  133. 'builtin.lua',
  134. '_options.lua',
  135. '_editor.lua',
  136. '_inspector.lua',
  137. 'shared.lua',
  138. 'loader.lua',
  139. 'uri.lua',
  140. 'ui.lua',
  141. 'filetype.lua',
  142. 'keymap.lua',
  143. 'fs.lua',
  144. 'glob.lua',
  145. 'lpeg.lua',
  146. 're.lua',
  147. 'regex.lua',
  148. 'secure.lua',
  149. 'version.lua',
  150. 'iter.lua',
  151. 'snippet.lua',
  152. 'text.lua',
  153. 'tohtml.lua',
  154. },
  155. files = {
  156. 'runtime/lua/vim/iter.lua',
  157. 'runtime/lua/vim/_editor.lua',
  158. 'runtime/lua/vim/_options.lua',
  159. 'runtime/lua/vim/shared.lua',
  160. 'runtime/lua/vim/loader.lua',
  161. 'runtime/lua/vim/uri.lua',
  162. 'runtime/lua/vim/ui.lua',
  163. 'runtime/lua/vim/filetype.lua',
  164. 'runtime/lua/vim/keymap.lua',
  165. 'runtime/lua/vim/fs.lua',
  166. 'runtime/lua/vim/hl.lua',
  167. 'runtime/lua/vim/secure.lua',
  168. 'runtime/lua/vim/version.lua',
  169. 'runtime/lua/vim/_inspector.lua',
  170. 'runtime/lua/vim/snippet.lua',
  171. 'runtime/lua/vim/text.lua',
  172. 'runtime/lua/vim/glob.lua',
  173. 'runtime/lua/vim/_meta/builtin.lua',
  174. 'runtime/lua/vim/_meta/diff.lua',
  175. 'runtime/lua/vim/_meta/mpack.lua',
  176. 'runtime/lua/vim/_meta/json.lua',
  177. 'runtime/lua/vim/_meta/base64.lua',
  178. 'runtime/lua/vim/_meta/regex.lua',
  179. 'runtime/lua/vim/_meta/lpeg.lua',
  180. 'runtime/lua/vim/_meta/re.lua',
  181. 'runtime/lua/vim/_meta/spell.lua',
  182. 'runtime/lua/tohtml.lua',
  183. },
  184. fn_xform = function(fun)
  185. if contains(fun.module, { 'vim.uri', 'vim.shared', 'vim._editor' }) then
  186. fun.module = 'vim'
  187. end
  188. if fun.module == 'vim' and contains(fun.name, { 'cmd', 'inspect' }) then
  189. fun.table = nil
  190. end
  191. if fun.classvar or vim.startswith(fun.name, 'vim.') or fun.module == 'vim.iter' then
  192. return
  193. end
  194. fun.name = fmt('%s.%s', fun.module, fun.name)
  195. end,
  196. section_name = {
  197. ['_inspector.lua'] = 'inspector',
  198. },
  199. section_fmt = function(name)
  200. name = name:lower()
  201. if name == '_editor' then
  202. return 'Lua module: vim'
  203. elseif name == '_options' then
  204. return 'LUA-VIMSCRIPT BRIDGE'
  205. elseif name == 'builtin' then
  206. return 'VIM'
  207. end
  208. if
  209. contains(name, {
  210. 'hl',
  211. 'mpack',
  212. 'json',
  213. 'base64',
  214. 'diff',
  215. 'spell',
  216. 'regex',
  217. 'lpeg',
  218. 're',
  219. })
  220. then
  221. return 'VIM.' .. name:upper()
  222. end
  223. if name == 'tohtml' then
  224. return 'Lua module: tohtml'
  225. end
  226. return 'Lua module: vim.' .. name
  227. end,
  228. helptag_fmt = function(name)
  229. if name == '_editor' then
  230. return 'lua-vim'
  231. elseif name == '_options' then
  232. return 'lua-vimscript'
  233. elseif name == 'tohtml' then
  234. return 'tohtml'
  235. end
  236. return 'vim.' .. name:lower()
  237. end,
  238. fn_helptag_fmt = function(fun)
  239. local name = fun.name
  240. if vim.startswith(name, 'vim.') then
  241. local fn_sfx = fun.table and '' or '()'
  242. return name .. fn_sfx
  243. elseif fun.classvar == 'Option' then
  244. return fmt('vim.opt:%s()', name)
  245. end
  246. return fn_helptag_fmt_common(fun)
  247. end,
  248. append_only = {
  249. 'shared.lua',
  250. },
  251. },
  252. lsp = {
  253. filename = 'lsp.txt',
  254. section_order = {
  255. 'lsp.lua',
  256. 'client.lua',
  257. 'buf.lua',
  258. 'diagnostic.lua',
  259. 'codelens.lua',
  260. 'completion.lua',
  261. 'inlay_hint.lua',
  262. 'tagfunc.lua',
  263. 'semantic_tokens.lua',
  264. 'handlers.lua',
  265. 'util.lua',
  266. 'log.lua',
  267. 'rpc.lua',
  268. 'protocol.lua',
  269. },
  270. files = {
  271. 'runtime/lua/vim/lsp',
  272. 'runtime/lua/vim/lsp.lua',
  273. },
  274. fn_xform = function(fun)
  275. fun.name = fun.name:gsub('result%.', '')
  276. if fun.module == 'vim.lsp.protocol' then
  277. fun.classvar = nil
  278. end
  279. end,
  280. section_fmt = function(name)
  281. if name:lower() == 'lsp' then
  282. return 'Lua module: vim.lsp'
  283. end
  284. return 'Lua module: vim.lsp.' .. name:lower()
  285. end,
  286. helptag_fmt = function(name)
  287. if name:lower() == 'lsp' then
  288. return 'lsp-core'
  289. end
  290. return fmt('lsp-%s', name:lower())
  291. end,
  292. },
  293. diagnostic = {
  294. filename = 'diagnostic.txt',
  295. section_order = {
  296. 'diagnostic.lua',
  297. },
  298. files = { 'runtime/lua/vim/diagnostic.lua' },
  299. section_fmt = function()
  300. return 'Lua module: vim.diagnostic'
  301. end,
  302. helptag_fmt = function()
  303. return 'diagnostic-api'
  304. end,
  305. },
  306. treesitter = {
  307. filename = 'treesitter.txt',
  308. section_order = {
  309. 'tstree.lua',
  310. 'tsnode.lua',
  311. 'treesitter.lua',
  312. 'language.lua',
  313. 'query.lua',
  314. 'highlighter.lua',
  315. 'languagetree.lua',
  316. 'dev.lua',
  317. },
  318. files = {
  319. 'runtime/lua/vim/treesitter/_meta/',
  320. 'runtime/lua/vim/treesitter.lua',
  321. 'runtime/lua/vim/treesitter/',
  322. },
  323. section_fmt = function(name)
  324. if name:lower() == 'treesitter' then
  325. return 'Lua module: vim.treesitter'
  326. elseif name:lower() == 'tstree' then
  327. return 'TREESITTER TREES'
  328. elseif name:lower() == 'tsnode' then
  329. return 'TREESITTER NODES'
  330. end
  331. return 'Lua module: vim.treesitter.' .. name:lower()
  332. end,
  333. helptag_fmt = function(name)
  334. if name:lower() == 'treesitter' then
  335. return 'lua-treesitter-core'
  336. elseif name:lower() == 'tstree' then
  337. return { 'treesitter-tree', 'TSTree' }
  338. elseif name:lower() == 'tsnode' then
  339. return { 'treesitter-node', 'TSNode' }
  340. end
  341. return 'lua-treesitter-' .. name:lower()
  342. end,
  343. },
  344. editorconfig = {
  345. filename = 'editorconfig.txt',
  346. files = {
  347. 'runtime/lua/editorconfig.lua',
  348. },
  349. section_order = {
  350. 'editorconfig.lua',
  351. },
  352. section_fmt = function(_name)
  353. return 'EditorConfig integration'
  354. end,
  355. helptag_fmt = function(name)
  356. return name:lower()
  357. end,
  358. fn_xform = function(fun)
  359. fun.table = true
  360. fun.name = vim.split(fun.name, '.', { plain = true })[2]
  361. end,
  362. },
  363. health = {
  364. filename = 'health.txt',
  365. files = {
  366. 'runtime/lua/vim/health.lua',
  367. },
  368. section_order = {
  369. 'health.lua',
  370. },
  371. section_fmt = function(_name)
  372. return 'Checkhealth'
  373. end,
  374. helptag_fmt = function()
  375. return { 'vim.health', 'health' }
  376. end,
  377. },
  378. }
  379. --- @param ty string
  380. --- @param generics table<string,string>
  381. --- @return string
  382. local function replace_generics(ty, generics)
  383. if ty:sub(-2) == '[]' then
  384. local ty0 = ty:sub(1, -3)
  385. if generics[ty0] then
  386. return generics[ty0] .. '[]'
  387. end
  388. elseif ty:sub(-1) == '?' then
  389. local ty0 = ty:sub(1, -2)
  390. if generics[ty0] then
  391. return generics[ty0] .. '?'
  392. end
  393. end
  394. return generics[ty] or ty
  395. end
  396. --- @param name string
  397. local function fmt_field_name(name)
  398. local name0, opt = name:match('^([^?]*)(%??)$')
  399. return fmt('{%s}%s', name0, opt)
  400. end
  401. --- @param ty string
  402. --- @param generics? table<string,string>
  403. --- @param default? string
  404. local function render_type(ty, generics, default)
  405. if generics then
  406. ty = replace_generics(ty, generics)
  407. end
  408. ty = ty:gsub('%s*|%s*nil', '?')
  409. ty = ty:gsub('nil%s*|%s*(.*)', '%1?')
  410. ty = ty:gsub('%s*|%s*', '|')
  411. if default then
  412. return fmt('(`%s`, default: %s)', ty, default)
  413. end
  414. return fmt('(`%s`)', ty)
  415. end
  416. --- @param p nvim.luacats.parser.param|nvim.luacats.parser.field
  417. local function should_render_field_or_param(p)
  418. return not p.nodoc
  419. and not p.access
  420. and not contains(p.name, { '_', 'self' })
  421. and not vim.startswith(p.name, '_')
  422. end
  423. --- @param desc? string
  424. --- @return string?, string?
  425. local function get_default(desc)
  426. if not desc then
  427. return
  428. end
  429. local default = desc:match('\n%s*%([dD]efault: ([^)]+)%)')
  430. if default then
  431. desc = desc:gsub('\n%s*%([dD]efault: [^)]+%)', '')
  432. end
  433. return desc, default
  434. end
  435. --- @param ty string
  436. --- @param classes? table<string,nvim.luacats.parser.class>
  437. --- @return nvim.luacats.parser.class?
  438. local function get_class(ty, classes)
  439. if not classes then
  440. return
  441. end
  442. local cty = ty:gsub('%s*|%s*nil', '?'):gsub('?$', ''):gsub('%[%]$', '')
  443. return classes[cty]
  444. end
  445. --- @param obj nvim.luacats.parser.param|nvim.luacats.parser.return|nvim.luacats.parser.field
  446. --- @param classes? table<string,nvim.luacats.parser.class>
  447. local function inline_type(obj, classes)
  448. local ty = obj.type
  449. if not ty then
  450. return
  451. end
  452. local cls = get_class(ty, classes)
  453. if not cls or cls.nodoc then
  454. return
  455. end
  456. if not cls.inlinedoc then
  457. -- Not inlining so just add a: "See |tag|."
  458. local tag = fmt('|%s|', cls.name)
  459. if obj.desc and obj.desc:find(tag) then
  460. -- Tag already there
  461. return
  462. end
  463. -- TODO(lewis6991): Aim to remove this. Need this to prevent dead
  464. -- references to types defined in runtime/lua/vim/lsp/_meta/protocol.lua
  465. if not vim.startswith(cls.name, 'vim.') then
  466. return
  467. end
  468. obj.desc = obj.desc or ''
  469. local period = (obj.desc == '' or vim.endswith(obj.desc, '.')) and '' or '.'
  470. obj.desc = obj.desc .. fmt('%s See %s.', period, tag)
  471. return
  472. end
  473. local ty_isopt = (ty:match('%?$') or ty:match('%s*|%s*nil')) ~= nil
  474. local ty_islist = (ty:match('%[%]$')) ~= nil
  475. ty = ty_isopt and 'table?' or ty_islist and 'table[]' or 'table'
  476. local desc = obj.desc or ''
  477. if cls.desc then
  478. desc = desc .. cls.desc
  479. elseif desc == '' then
  480. if ty_islist then
  481. desc = desc .. 'A list of objects with the following fields:'
  482. else
  483. desc = desc .. 'A table with the following fields:'
  484. end
  485. end
  486. local desc_append = {}
  487. for _, f in ipairs(cls.fields) do
  488. if not f.access then
  489. local fdesc, default = get_default(f.desc)
  490. local fty = render_type(f.type, nil, default)
  491. local fnm = fmt_field_name(f.name)
  492. table.insert(desc_append, table.concat({ '-', fnm, fty, fdesc }, ' '))
  493. end
  494. end
  495. desc = desc .. '\n' .. table.concat(desc_append, '\n')
  496. obj.type = ty
  497. obj.desc = desc
  498. end
  499. --- @param xs (nvim.luacats.parser.param|nvim.luacats.parser.field)[]
  500. --- @param generics? table<string,string>
  501. --- @param classes? table<string,nvim.luacats.parser.class>
  502. --- @param exclude_types? true
  503. --- @param cfg nvim.gen_vimdoc.Config
  504. local function render_fields_or_params(xs, generics, classes, exclude_types, cfg)
  505. local ret = {} --- @type string[]
  506. xs = vim.tbl_filter(should_render_field_or_param, xs)
  507. local indent = 0
  508. for _, p in ipairs(xs) do
  509. if p.type or p.desc then
  510. indent = math.max(indent, #p.name + 3)
  511. end
  512. if exclude_types then
  513. p.type = nil
  514. end
  515. end
  516. for _, p in ipairs(xs) do
  517. local pdesc, default = get_default(p.desc)
  518. p.desc = pdesc
  519. inline_type(p, classes)
  520. local nm, ty = p.name, p.type
  521. local desc = p.classvar and string.format('See |%s|.', cfg.fn_helptag_fmt(p)) or p.desc
  522. local fnm = p.kind == 'operator' and fmt('op(%s)', nm) or fmt_field_name(nm)
  523. local pnm = fmt(' • %-' .. indent .. 's', fnm)
  524. if ty then
  525. local pty = render_type(ty, generics, default)
  526. if desc then
  527. table.insert(ret, pnm)
  528. if #pty > TEXT_WIDTH - indent then
  529. vim.list_extend(ret, { ' ', pty, '\n' })
  530. table.insert(ret, md_to_vimdoc(desc, 9 + indent, 9 + indent, TEXT_WIDTH, true))
  531. else
  532. desc = fmt('%s %s', pty, desc)
  533. table.insert(ret, md_to_vimdoc(desc, 1, 9 + indent, TEXT_WIDTH, true))
  534. end
  535. else
  536. table.insert(ret, fmt('%s %s\n', pnm, pty))
  537. end
  538. else
  539. if desc then
  540. table.insert(ret, pnm)
  541. table.insert(ret, md_to_vimdoc(desc, 1, 9 + indent, TEXT_WIDTH, true))
  542. end
  543. end
  544. end
  545. return table.concat(ret)
  546. end
  547. --- @param class nvim.luacats.parser.class
  548. --- @param classes table<string,nvim.luacats.parser.class>
  549. --- @param cfg nvim.gen_vimdoc.Config
  550. local function render_class(class, classes, cfg)
  551. if class.access or class.nodoc or class.inlinedoc then
  552. return
  553. end
  554. local ret = {} --- @type string[]
  555. table.insert(ret, fmt('*%s*\n', class.name))
  556. if class.parent then
  557. local txt = fmt('Extends: |%s|', class.parent)
  558. table.insert(ret, md_to_vimdoc(txt, INDENTATION, INDENTATION, TEXT_WIDTH))
  559. table.insert(ret, '\n')
  560. end
  561. if class.desc then
  562. table.insert(ret, md_to_vimdoc(class.desc, INDENTATION, INDENTATION, TEXT_WIDTH))
  563. end
  564. local fields_txt = render_fields_or_params(class.fields, nil, classes, nil, cfg)
  565. if not fields_txt:match('^%s*$') then
  566. table.insert(ret, '\n Fields: ~\n')
  567. table.insert(ret, fields_txt)
  568. end
  569. table.insert(ret, '\n')
  570. return table.concat(ret)
  571. end
  572. --- @param classes table<string,nvim.luacats.parser.class>
  573. --- @param cfg nvim.gen_vimdoc.Config
  574. local function render_classes(classes, cfg)
  575. local ret = {} --- @type string[]
  576. for _, class in vim.spairs(classes) do
  577. ret[#ret + 1] = render_class(class, classes, cfg)
  578. end
  579. return table.concat(ret)
  580. end
  581. --- @param fun nvim.luacats.parser.fun
  582. --- @param cfg nvim.gen_vimdoc.Config
  583. local function render_fun_header(fun, cfg)
  584. local ret = {} --- @type string[]
  585. local args = {} --- @type string[]
  586. for _, p in ipairs(fun.params or {}) do
  587. if p.name ~= 'self' then
  588. args[#args + 1] = fmt_field_name(p.name)
  589. end
  590. end
  591. local nm = fun.name
  592. if fun.classvar then
  593. nm = fmt('%s:%s', fun.classvar, nm)
  594. end
  595. if nm == 'vim.bo' then
  596. nm = 'vim.bo[{bufnr}]'
  597. end
  598. if nm == 'vim.wo' then
  599. nm = 'vim.wo[{winid}][{bufnr}]'
  600. end
  601. local proto = fun.table and nm or nm .. '(' .. table.concat(args, ', ') .. ')'
  602. local tag = '*' .. cfg.fn_helptag_fmt(fun) .. '*'
  603. if #proto + #tag > TEXT_WIDTH - 8 then
  604. table.insert(ret, fmt('%78s\n', tag))
  605. local name, pargs = proto:match('([^(]+%()(.*)')
  606. table.insert(ret, name)
  607. table.insert(ret, wrap(pargs, 0, #name, TEXT_WIDTH))
  608. else
  609. local pad = TEXT_WIDTH - #proto - #tag
  610. table.insert(ret, proto .. string.rep(' ', pad) .. tag)
  611. end
  612. return table.concat(ret)
  613. end
  614. --- @param returns nvim.luacats.parser.return[]
  615. --- @param generics? table<string,string>
  616. --- @param classes? table<string,nvim.luacats.parser.class>
  617. --- @param exclude_types boolean
  618. local function render_returns(returns, generics, classes, exclude_types)
  619. local ret = {} --- @type string[]
  620. returns = vim.deepcopy(returns)
  621. if exclude_types then
  622. for _, r in ipairs(returns) do
  623. r.type = nil
  624. end
  625. end
  626. if #returns > 1 then
  627. table.insert(ret, ' Return (multiple): ~\n')
  628. elseif #returns == 1 and next(returns[1]) then
  629. table.insert(ret, ' Return: ~\n')
  630. end
  631. for _, p in ipairs(returns) do
  632. inline_type(p, classes)
  633. local rnm, ty, desc = p.name, p.type, p.desc
  634. local blk = {} --- @type string[]
  635. if ty then
  636. blk[#blk + 1] = render_type(ty, generics)
  637. end
  638. blk[#blk + 1] = rnm
  639. blk[#blk + 1] = desc
  640. table.insert(ret, md_to_vimdoc(table.concat(blk, ' '), 8, 8, TEXT_WIDTH, true))
  641. end
  642. return table.concat(ret)
  643. end
  644. --- @param fun nvim.luacats.parser.fun
  645. --- @param classes table<string,nvim.luacats.parser.class>
  646. --- @param cfg nvim.gen_vimdoc.Config
  647. local function render_fun(fun, classes, cfg)
  648. if fun.access or fun.deprecated or fun.nodoc then
  649. return
  650. end
  651. if cfg.fn_name_pat and not fun.name:match(cfg.fn_name_pat) then
  652. return
  653. end
  654. if vim.startswith(fun.name, '_') or fun.name:find('[:.]_') then
  655. return
  656. end
  657. local ret = {} --- @type string[]
  658. table.insert(ret, render_fun_header(fun, cfg))
  659. table.insert(ret, '\n')
  660. if fun.since then
  661. local since = assert(tonumber(fun.since), 'invalid @since on ' .. fun.name)
  662. local info = nvim_api_info()
  663. if since == 0 or (info.prerelease and since == info.level) then
  664. -- Experimental = (since==0 or current prerelease)
  665. local s = 'WARNING: This feature is experimental/unstable.'
  666. table.insert(ret, md_to_vimdoc(s, INDENTATION, INDENTATION, TEXT_WIDTH))
  667. table.insert(ret, '\n')
  668. else
  669. local v = assert(util.version_level[since], 'invalid @since on ' .. fun.name)
  670. fun.attrs = fun.attrs or {}
  671. table.insert(fun.attrs, ('Since: %s'):format(v))
  672. end
  673. end
  674. if fun.desc then
  675. table.insert(ret, md_to_vimdoc(fun.desc, INDENTATION, INDENTATION, TEXT_WIDTH))
  676. end
  677. if fun.notes then
  678. table.insert(ret, '\n Note: ~\n')
  679. for _, p in ipairs(fun.notes) do
  680. table.insert(ret, ' • ' .. md_to_vimdoc(p.desc, 0, 8, TEXT_WIDTH, true))
  681. end
  682. end
  683. if fun.attrs then
  684. table.insert(ret, '\n Attributes: ~\n')
  685. for _, attr in ipairs(fun.attrs) do
  686. local attr_str = ({
  687. textlock = 'not allowed when |textlock| is active or in the |cmdwin|',
  688. textlock_allow_cmdwin = 'not allowed when |textlock| is active',
  689. fast = '|api-fast|',
  690. remote_only = '|RPC| only',
  691. lua_only = 'Lua |vim.api| only',
  692. })[attr] or attr
  693. table.insert(ret, fmt(' %s\n', attr_str))
  694. end
  695. end
  696. if fun.params and #fun.params > 0 then
  697. local param_txt =
  698. render_fields_or_params(fun.params, fun.generics, classes, cfg.exclude_types, cfg)
  699. if not param_txt:match('^%s*$') then
  700. table.insert(ret, '\n Parameters: ~\n')
  701. ret[#ret + 1] = param_txt
  702. end
  703. end
  704. if fun.returns then
  705. local txt = render_returns(fun.returns, fun.generics, classes, cfg.exclude_types)
  706. if not txt:match('^%s*$') then
  707. table.insert(ret, '\n')
  708. ret[#ret + 1] = txt
  709. end
  710. end
  711. if fun.see then
  712. table.insert(ret, '\n See also: ~\n')
  713. for _, p in ipairs(fun.see) do
  714. table.insert(ret, ' • ' .. md_to_vimdoc(p.desc, 0, 8, TEXT_WIDTH, true))
  715. end
  716. end
  717. table.insert(ret, '\n')
  718. return table.concat(ret)
  719. end
  720. --- @param funs nvim.luacats.parser.fun[]
  721. --- @param classes table<string,nvim.luacats.parser.class>
  722. --- @param cfg nvim.gen_vimdoc.Config
  723. local function render_funs(funs, classes, cfg)
  724. local ret = {} --- @type string[]
  725. for _, f in ipairs(funs) do
  726. if cfg.fn_xform then
  727. cfg.fn_xform(f)
  728. end
  729. ret[#ret + 1] = render_fun(f, classes, cfg)
  730. end
  731. -- Sort via prototype. Experimental API functions ("nvim__") sort last.
  732. table.sort(ret, function(a, b)
  733. local a1 = ('\n' .. a):match('\n[a-zA-Z_][^\n]+\n')
  734. local b1 = ('\n' .. b):match('\n[a-zA-Z_][^\n]+\n')
  735. local a1__ = a1:find('^%s*nvim__') and 1 or 0
  736. local b1__ = b1:find('^%s*nvim__') and 1 or 0
  737. if a1__ ~= b1__ then
  738. return a1__ < b1__
  739. end
  740. return a1:lower() < b1:lower()
  741. end)
  742. return table.concat(ret)
  743. end
  744. --- @return string
  745. local function get_script_path()
  746. local str = debug.getinfo(2, 'S').source:sub(2)
  747. return str:match('(.*[/\\])') or './'
  748. end
  749. local script_path = get_script_path()
  750. local base_dir = vim.fs.dirname(vim.fs.dirname(script_path))
  751. local function delete_lines_below(doc_file, tokenstr)
  752. local lines = {} --- @type string[]
  753. local found = false
  754. for line in io.lines(doc_file) do
  755. if line:find(vim.pesc(tokenstr)) then
  756. found = true
  757. break
  758. end
  759. lines[#lines + 1] = line
  760. end
  761. if not found then
  762. error(fmt('not found: %s in %s', tokenstr, doc_file))
  763. end
  764. lines[#lines] = nil
  765. local fp = assert(io.open(doc_file, 'w'))
  766. fp:write(table.concat(lines, '\n'))
  767. fp:write('\n')
  768. fp:close()
  769. end
  770. --- @param x string
  771. local function mktitle(x)
  772. if x == 'ui' then
  773. return 'UI'
  774. end
  775. return x:sub(1, 1):upper() .. x:sub(2)
  776. end
  777. --- @class nvim.gen_vimdoc.Section
  778. --- @field name string
  779. --- @field title string
  780. --- @field help_tag string
  781. --- @field funs_txt string
  782. --- @field doc? string[]
  783. --- @param filename string
  784. --- @param cfg nvim.gen_vimdoc.Config
  785. --- @param section_docs table<string,nvim.gen_vimdoc.Section>
  786. --- @param funs_txt string
  787. --- @return nvim.gen_vimdoc.Section?
  788. local function make_section(filename, cfg, section_docs, funs_txt)
  789. -- filename: e.g., 'autocmd.c'
  790. -- name: e.g. 'autocmd'
  791. local name = filename:match('(.*)%.[a-z]+')
  792. -- Formatted (this is what's going to be written in the vimdoc)
  793. -- e.g., "Autocmd Functions"
  794. local sectname = cfg.section_name and cfg.section_name[filename] or mktitle(name)
  795. -- section tag: e.g., "*api-autocmd*"
  796. local help_labels = cfg.helptag_fmt(sectname)
  797. if type(help_labels) == 'table' then
  798. help_labels = table.concat(help_labels, '* *')
  799. end
  800. local help_tags = '*' .. help_labels .. '*'
  801. if funs_txt == '' and #section_docs == 0 then
  802. return
  803. end
  804. return {
  805. name = sectname,
  806. title = cfg.section_fmt(sectname),
  807. help_tag = help_tags,
  808. funs_txt = funs_txt,
  809. doc = section_docs,
  810. }
  811. end
  812. --- @param section nvim.gen_vimdoc.Section
  813. --- @param add_header? boolean
  814. local function render_section(section, add_header)
  815. local doc = {} --- @type string[]
  816. if add_header ~= false then
  817. vim.list_extend(doc, {
  818. string.rep('=', TEXT_WIDTH),
  819. '\n',
  820. section.title,
  821. fmt('%' .. (TEXT_WIDTH - section.title:len()) .. 's', section.help_tag),
  822. })
  823. end
  824. local sdoc = '\n\n' .. table.concat(section.doc or {}, '\n')
  825. if sdoc:find('[^%s]') then
  826. doc[#doc + 1] = sdoc
  827. end
  828. if section.funs_txt then
  829. table.insert(doc, '\n\n')
  830. table.insert(doc, section.funs_txt)
  831. end
  832. return table.concat(doc)
  833. end
  834. local parsers = {
  835. lua = luacats_parser.parse,
  836. c = cdoc_parser.parse,
  837. h = cdoc_parser.parse,
  838. }
  839. --- @param files string[]
  840. local function expand_files(files)
  841. for k, f in pairs(files) do
  842. if vim.fn.isdirectory(f) == 1 then
  843. table.remove(files, k)
  844. for path, ty in vim.fs.dir(f) do
  845. if ty == 'file' then
  846. table.insert(files, vim.fs.joinpath(f, path))
  847. end
  848. end
  849. end
  850. end
  851. end
  852. --- @param cfg nvim.gen_vimdoc.Config
  853. local function gen_target(cfg)
  854. cfg.fn_helptag_fmt = cfg.fn_helptag_fmt or fn_helptag_fmt_common
  855. print('Target:', cfg.filename)
  856. local sections = {} --- @type table<string,nvim.gen_vimdoc.Section>
  857. expand_files(cfg.files)
  858. --- @type table<string,[table<string,nvim.luacats.parser.class>, nvim.luacats.parser.fun[], string[]]>
  859. local file_results = {}
  860. --- @type table<string,nvim.luacats.parser.class>
  861. local all_classes = {}
  862. --- First pass so we can collect all classes
  863. for _, f in vim.spairs(cfg.files) do
  864. local ext = assert(f:match('%.([^.]+)$')) --[[@as 'h'|'c'|'lua']]
  865. local parser = assert(parsers[ext])
  866. local classes, funs, briefs = parser(f)
  867. file_results[f] = { classes, funs, briefs }
  868. all_classes = vim.tbl_extend('error', all_classes, classes)
  869. end
  870. for f, r in vim.spairs(file_results) do
  871. local classes, funs, briefs = r[1], r[2], r[3]
  872. local briefs_txt = {} --- @type string[]
  873. for _, b in ipairs(briefs) do
  874. briefs_txt[#briefs_txt + 1] = md_to_vimdoc(b, 0, 0, TEXT_WIDTH)
  875. end
  876. print(' Processing file:', f)
  877. local funs_txt = render_funs(funs, all_classes, cfg)
  878. if next(classes) then
  879. local classes_txt = render_classes(classes, cfg)
  880. if vim.trim(classes_txt) ~= '' then
  881. funs_txt = classes_txt .. '\n' .. funs_txt
  882. end
  883. end
  884. -- FIXME: Using f_base will confuse `_meta/protocol.lua` with `protocol.lua`
  885. local f_base = vim.fs.basename(f)
  886. sections[f_base] = make_section(f_base, cfg, briefs_txt, funs_txt)
  887. end
  888. local first_section_tag = sections[cfg.section_order[1]].help_tag
  889. local docs = {} --- @type string[]
  890. for _, f in ipairs(cfg.section_order) do
  891. local section = sections[f]
  892. if section then
  893. print(string.format(" Rendering section: '%s'", section.title))
  894. local add_sep_and_header = not vim.tbl_contains(cfg.append_only or {}, f)
  895. docs[#docs + 1] = render_section(section, add_sep_and_header)
  896. end
  897. end
  898. table.insert(
  899. docs,
  900. fmt(' vim:tw=78:ts=8:sw=%d:sts=%d:et:ft=help:norl:\n', INDENTATION, INDENTATION)
  901. )
  902. local doc_file = vim.fs.joinpath(base_dir, 'runtime', 'doc', cfg.filename)
  903. if vim.uv.fs_stat(doc_file) then
  904. delete_lines_below(doc_file, first_section_tag)
  905. end
  906. local fp = assert(io.open(doc_file, 'a'))
  907. fp:write(table.concat(docs, '\n'))
  908. fp:close()
  909. end
  910. local function run()
  911. for _, cfg in vim.spairs(config) do
  912. gen_target(cfg)
  913. end
  914. end
  915. run()