robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
30.5 KiB1149 linesraw
1#!/usr/bin/env -S nvim -l
2
3-- Generator for various vimdoc and Lua type files
4
5local util = require('gen.util')
6local lint = require('gen.lint')
7local api_type = require('gen.api_types')
8local fmt = string.format
9
10local DEP_API_METADATA = arg[1]
11local TAGS_FILE = arg[2]
12local TEXT_WIDTH = 78
13
14--- @class vim.api.metadata
15--- @field name string
16--- @field parameters [string,string][]
17--- @field return_type string
18--- @field deprecated_since integer
19--- @field eval boolean
20--- @field fast boolean
21--- @field handler_id integer
22--- @field impl_name string
23--- @field lua boolean
24--- @field method boolean
25--- @field remote boolean
26--- @field since integer
27
28local LUA_API_RETURN_OVERRIDES = {
29  nvim_parse_cmd = 'vim.api.keyset.cmd_ret',
30  nvim_win_get_config = 'vim.api.keyset.win_config_ret',
31}
32
33local LUA_META_HEADER = {
34  '--- @meta _',
35  '--',
36  '-- DO NOT EDIT. GENERATED BY: src/gen/gen_eval_files.lua',
37  '--',
38  "error('Cannot require a meta file')",
39}
40
41local LUA_API_META_HEADER = vim.list_extend(vim.deepcopy(LUA_META_HEADER), {
42  '',
43  '--- This file embeds vimdoc as the function descriptions',
44  '--- so ignore any doc related errors.',
45  '--- @diagnostic disable: undefined-doc-name,luadoc-miss-symbol',
46  '',
47  'vim.api = {}',
48})
49
50local LUA_OPTION_META_HEADER = vim.list_extend(vim.deepcopy(LUA_META_HEADER), {
51  '',
52  '---@class vim.bo',
53  '---@field [integer] vim.bo',
54  'vim.bo = vim.bo',
55  '',
56  '---@class vim.wo',
57  '---@field [integer] vim.wo',
58  'vim.wo = vim.wo',
59})
60
61local LUA_VVAR_META_HEADER = vim.list_extend(vim.deepcopy(LUA_META_HEADER), {
62  '',
63  '--- @class vim.v',
64  'vim.v = ...',
65})
66
67local LUA_KEYWORDS = {
68  ['and'] = true,
69  ['end'] = true,
70  ['function'] = true,
71  ['or'] = true,
72  ['if'] = true,
73  ['while'] = true,
74  ['repeat'] = true,
75  ['true'] = true,
76  ['false'] = true,
77}
78
79local OPTION_TYPES = {
80  boolean = 'boolean',
81  number = 'integer',
82  string = 'string',
83}
84
85--- @param s string
86--- @return string
87local function luaescape(s)
88  if LUA_KEYWORDS[s] then
89    return s .. '_'
90  end
91  return s
92end
93
94--- @param x string
95--- @param sep? string
96--- @return string[]
97local function split(x, sep)
98  return vim.split(x, sep or '\n', { plain = true })
99end
100
101--- @param f string
102--- @param params [string,string,string?][]|true
103--- @return string
104local function render_fun_sig(f, params)
105  local param_str --- @type string
106  if params == true then
107    param_str = '...'
108  else
109    param_str = table.concat(
110      vim.tbl_map(
111        --- @param v [string,string,string?]
112        --- @return string
113        function(v)
114          return luaescape(v[1])
115        end,
116        params
117      ),
118      ', '
119    )
120  end
121
122  if LUA_KEYWORDS[f] then
123    return fmt("vim.fn['%s'] = function(%s) end", f, param_str)
124  else
125    return fmt('function vim.fn.%s(%s) end', f, param_str)
126  end
127end
128
129--- Uniquify names
130--- @param params [string,string,string?][]
131--- @return [string,string,string?][]
132local function process_params(params)
133  local seen = {} --- @type table<string,true>
134  local sfx = 1
135
136  for _, p in ipairs(params) do
137    if seen[p[1]] then
138      p[1] = p[1] .. sfx
139      sfx = sfx + 1
140    else
141      seen[p[1]] = true
142    end
143  end
144
145  return params
146end
147
148--- @return table<string, vim.EvalFn>
149local function get_api_meta()
150  local ret = {} --- @type table<string, vim.EvalFn>
151
152  local cdoc_parser = require('gen.cdoc_parser')
153
154  local f = 'src/nvim/api'
155
156  local function include(fun)
157    if not vim.startswith(fun.name, 'nvim_') then
158      return false
159    end
160    if vim.tbl_contains(fun.attrs or {}, 'lua_only') then
161      return true
162    end
163    if vim.tbl_contains(fun.attrs or {}, 'remote_only') then
164      return false
165    end
166    return true
167  end
168
169  --- @type table<string,nvim.cdoc.parser.fun>
170  local functions = {}
171  for path, ty in vim.fs.dir(f) do
172    if ty == 'file' and (vim.endswith(path, '.c') or vim.endswith(path, '.h')) then
173      local filename = vim.fs.joinpath(f, path)
174      local _, funs = cdoc_parser.parse(filename)
175      for _, fn in ipairs(funs) do
176        if include(fn) then
177          functions[fn.name] = fn
178        end
179      end
180    end
181  end
182
183  for _, fun in pairs(functions) do
184    local deprecated = fun.deprecated_since ~= nil
185
186    local notes = {} --- @type string[]
187    for _, note in ipairs(fun.notes or {}) do
188      notes[#notes + 1] = note.desc
189    end
190
191    local sees = {} --- @type string[]
192    for _, see in ipairs(fun.see or {}) do
193      sees[#sees + 1] = see.desc
194    end
195
196    local params = {} --- @type [string,string,string?][]
197    for _, p in ipairs(fun.params) do
198      params[#params + 1] = {
199        p.name,
200        p.type,
201        not deprecated and p.desc or nil,
202      }
203    end
204
205    local r = {
206      signature = 'NA',
207      name = fun.name,
208      params = params,
209      notes = notes,
210      see = sees,
211      returns = fun.returns[1].type,
212      deprecated = deprecated,
213    }
214
215    if not deprecated then
216      r.desc = fun.desc
217      r.returns_desc = fun.returns[1].desc
218    end
219
220    ret[fun.name] = r
221  end
222  return ret
223end
224
225--- Convert vimdoc references to markdown literals
226--- Convert vimdoc codeblocks to markdown codeblocks
227---
228--- Ensure code blocks have one empty line before the start fence and after the closing fence.
229---
230--- @param x string
231--- @param special string?
232---                | 'see-api-meta' Normalize `@see` for API meta docstrings.
233--- @return string
234local function norm_text(x, special)
235  if special == 'see-api-meta' then
236    -- Try to guess a symbol that actually works in @see.
237    -- "nvim_xx()" => "vim.api.nvim_xx"
238    x = x:gsub([=[%|?(nvim_[^.()| ]+)%(?%)?%|?]=], 'vim.api.%1')
239    -- TODO: Remove backticks when LuaLS resolves: https://github.com/LuaLS/lua-language-server/issues/2889
240    -- "|foo|" => "`:help foo`"
241    x = x:gsub([=[|([^%s|]+)|]=], '`:help %1`')
242  end
243
244  return (
245    x:gsub('|([^%s|]+)|', '`%1`')
246      :gsub('\n*>lua', '\n\n```lua')
247      :gsub('\n*>vim', '\n\n```vim')
248      :gsub('\n+<$', '\n```')
249      :gsub('\n+<\n+', '\n```\n\n')
250      :gsub('%s+>\n+', '\n```\n')
251      :gsub('\n+<%s+\n?', '\n```\n')
252  )
253end
254
255--- @param items string[]
256--- @param conjunction string
257--- @return string
258--- Example: "foo, bar, or baz"
259local function join_with_conjunction(items, conjunction)
260  if #items == 0 then
261    return ''
262  elseif #items == 1 then
263    return items[1]
264  elseif #items == 2 then
265    return items[1] .. ' ' .. conjunction .. ' ' .. items[2]
266  end
267
268  local parts = {} --- @type string[]
269  for i = 1, #items - 1 do
270    parts[#parts + 1] = items[i]
271  end
272  return table.concat(parts, ', ') .. ', ' .. conjunction .. ' ' .. items[#items]
273end
274
275--- @param fun vim.EvalFn
276--- @return string?
277--- Example: "Lua: Prefer |math.abs()|."
278local function see_lua_text(fun)
279  if not fun.see_lua or fun.see_lua == false then
280    return
281  end
282
283  return 'Lua: Prefer ' .. join_with_conjunction(fun.see_lua, 'or') .. '.'
284end
285
286local VIMDOC_PARAGRAPH_PREFIX = '\t\t'
287local VIMDOC_PARAGRAPH_INDENT = 16 -- Two tabs in rendered vimdoc.
288
289--- @param text string
290--- @return string
291--- Example: "\t\tLua: Prefer |math.abs()|."
292local function tab_indent_vimdoc(text)
293  return VIMDOC_PARAGRAPH_PREFIX
294    .. util
295      .md_to_vimdoc(text, 0, 0, TEXT_WIDTH - VIMDOC_PARAGRAPH_INDENT)
296      :gsub('\n', '\n' .. VIMDOC_PARAGRAPH_PREFIX)
297end
298
299--- @param fun vim.EvalFn
300--- @param write fun(line: string)
301--- Example first line: "--- Lua: Prefer |math.abs()|."
302local function render_eval_see_lua_meta(fun, write)
303  local text = see_lua_text(fun)
304  if not text then
305    return
306  end
307
308  write('--- ' .. text)
309  write('---')
310end
311
312--- @param fun vim.EvalFn
313--- @param write fun(line: string)
314--- Example first line: "\t\tLua: Prefer |math.abs()|."
315local function render_eval_see_lua_doc(fun, write)
316  local text = see_lua_text(fun)
317  if not text then
318    return
319  end
320
321  write(tab_indent_vimdoc(text))
322  write('')
323end
324
325--- Generates LuaLS docstring for an API function.
326--- @param _f string
327--- @param fun vim.EvalFn
328--- @param write fun(line: string)
329local function render_api_meta(_f, fun, write)
330  write('')
331
332  if fun.deprecated then
333    write('--- @deprecated')
334  end
335
336  local internal = vim.startswith(fun.name, 'nvim__')
337  if internal or (fun.since and tonumber(fun.since) == 0) then
338    write('--- WARNING: This feature is experimental/unstable.')
339    write('---')
340  end
341
342  local desc = fun.desc
343  if desc then
344    write(util.prefix_lines('--- ', norm_text(desc)))
345  end
346
347  -- LuaLS doesn't support @note. Render @note items as a markdown list.
348  if fun.notes and #fun.notes > 0 then
349    write('--- Note:')
350    write(util.prefix_lines('--- ', table.concat(fun.notes, '\n')))
351    write('---')
352  end
353
354  for _, see in ipairs(fun.see or {}) do
355    write(util.prefix_lines('--- @see ', norm_text(see, 'see-api-meta')))
356  end
357
358  local param_names = {} --- @type string[]
359  local params = process_params(fun.params)
360  for _, p in ipairs(params) do
361    local pname, ptype, pdesc = luaescape(p[1]), p[2], p[3]
362    param_names[#param_names + 1] = pname
363    if pdesc then
364      local s = '--- @param ' .. pname .. ' ' .. ptype .. ' '
365      local pdesc_a = split(vim.trim(norm_text(pdesc)))
366      write(s .. pdesc_a[1])
367      for i = 2, #pdesc_a do
368        if not pdesc_a[i] then
369          break
370        end
371        write('--- ' .. pdesc_a[i])
372      end
373    else
374      write('--- @param ' .. pname .. ' ' .. ptype)
375    end
376  end
377
378  if fun.returns ~= 'nil' then
379    local ret_desc = fun.returns_desc and ' # ' .. fun.returns_desc or ''
380    local ret = LUA_API_RETURN_OVERRIDES[fun.name] or fun.returns
381    write(util.prefix_lines('--- ', '@return ' .. ret .. ret_desc))
382  end
383  local param_str = table.concat(param_names, ', ')
384
385  write(fmt('function vim.api.%s(%s) end', fun.name, param_str))
386end
387
388--- @return table<string, vim.EvalFn>
389local function get_api_keysets_meta()
390  local mpack_f = assert(io.open(DEP_API_METADATA, 'rb'))
391  local metadata = assert(vim.mpack.decode(mpack_f:read('*all')))
392
393  local ret = {} --- @type table<string, vim.EvalFn>
394
395  --- @type {name: string, keys: string[], types: table<string,string>}[]
396  local keysets = metadata.keysets
397  local event_type = 'vim.api.keyset.events|vim.api.keyset.events[]'
398
399  lint.lint_names('src/nvim/api/keysets_defs.h', nil, keysets)
400
401  for _, k in ipairs(keysets) do
402    util.sort_by_key(k.keys)
403    local params = {}
404    for _, key in ipairs(k.keys) do
405      local pty = k.types[key] or 'any'
406      table.insert(params, {
407        key .. '?',
408        k.name:find('autocmd') and key == 'event' and event_type or api_type(pty),
409      })
410    end
411    ret[k.name] = {
412      signature = 'NA',
413      name = k.name,
414      params = params,
415    }
416  end
417
418  return ret
419end
420
421--- Generates LuaLS docstring for an API keyset.
422--- @param _f string
423--- @param fun vim.EvalFn
424--- @param write fun(line: string)
425local function render_api_keyset_meta(_f, fun, write)
426  if string.sub(fun.name, 1, 1) == '_' then
427    return -- not exported
428  elseif fun.name == 'create_autocmd' then
429    local events = vim.deepcopy(require('nvim.auevents'))
430    for event in pairs(events.aliases) do
431      events.events[event] = true
432    end
433    write('')
434    write('--- @alias vim.api.keyset.events')
435    for event in vim.spairs(events.events) do
436      write(("--- |'%s'"):format(event))
437    end
438  end
439  write('')
440  write('--- @class vim.api.keyset.' .. fun.name)
441  for _, p in ipairs(fun.params) do
442    write('--- @field ' .. p[1] .. ' ' .. p[2])
443  end
444end
445
446--- @return table<string, vim.EvalFn>
447local function get_eval_meta()
448  return require('nvim.eval').funcs
449end
450
451--- Group suffix variants for Lua metadata; Vimdoc keeps separate entries.
452--- @return table<string, vim.EvalFn[]>
453local function get_eval_lua_meta()
454  local ret = {} --- @type table<string, vim.EvalFn[]>
455  -- Sorting puts the base declaration before its __N variants.
456  for name, fun in vim.spairs(get_eval_meta()) do
457    if fun.lua ~= false then
458      local base = name:match('^(.-)__%d+$') or name
459      ret[base] = ret[base] or {}
460      table.insert(ret[base], fun)
461    end
462  end
463  return ret
464end
465
466--- Generates LuaLS docstring for a Vimscript "eval" function.
467--- @param f string
468--- @param funs vim.EvalFn[]
469--- @param write fun(line: string)
470local function render_eval_meta(f, funs, write)
471  local fun = assert(funs[1])
472
473  local funname = fun.name or f
474  local params = process_params(fun.params)
475
476  write('')
477  if fun.deprecated then
478    write('--- @deprecated')
479  end
480
481  -- Combine descriptions into one docstring: the base first, then its __N variants.
482  for _, variant in ipairs(funs) do
483    render_eval_see_lua_meta(variant, write)
484
485    local desc = variant.desc --[[@as string?]]
486
487    if desc then
488      desc = desc:gsub('\n%s*\n%s*$', '\n')
489      for _, l in ipairs(split(desc)) do
490        l = l:gsub('^      ', ''):gsub('\t', '  '):gsub('@', '\\@')
491        write('--- ' .. l)
492      end
493    end
494  end
495
496  for _, text in
497    ipairs(vim.fn.reverse(fun.generics or {} --[[@as string[] ]]))
498  do
499    write(fmt('--- @generic %s', text))
500  end
501
502  -- E.g. sign_undefine__1 becomes @overload fun(list?: string[]): (integer[]).
503  for i, overload in ipairs(funs) do
504    if i > 1 then
505      local overload_params = {} --- @type string[]
506      local req_args = type(overload.args) == 'table' and overload.args[1] or overload.args or 0
507      for j, param in ipairs(process_params(overload.params)) do
508        local pname, ptype = luaescape(param[1]), param[2]
509        local optional = (pname ~= '...' and j > req_args) and '?' or ''
510        overload_params[#overload_params + 1] = fmt('%s%s: %s', pname, optional, ptype)
511      end
512      local generics = overload.generics and ('<' .. table.concat(overload.generics, ', ') .. '>')
513        or ''
514      -- Group the return list so a type like (0|-1)[] remains one array return.
515      local ret = overload.returns == false and '' or ': (' .. (overload.returns or 'any') .. ')'
516      write(fmt('--- @overload fun%s(%s)%s', generics, table.concat(overload_params, ', '), ret))
517    end
518  end
519
520  local req_args = type(fun.args) == 'table' and fun.args[1] or fun.args or 0
521
522  for i, param in ipairs(params) do
523    local pname, ptype = luaescape(param[1]), param[2]
524    local optional = (pname ~= '...' and i > req_args) and '?' or ''
525    write(fmt('--- @param %s%s %s', pname, optional, ptype))
526  end
527
528  if fun.returns ~= false then
529    local ret_desc = fun.returns_desc and ' # ' .. fun.returns_desc or ''
530    write('--- @return ' .. (fun.returns or 'any') .. ret_desc)
531  end
532
533  write(render_fun_sig(funname, params))
534end
535
536--- Generates vimdoc heading for a Vimscript "eval" function signature.
537--- @param name string
538--- @param name_tag boolean
539--- @param fun vim.EvalFn
540--- @param write fun(line: string)
541local function render_sig_and_tag(name, name_tag, fun, write)
542  if not fun.signature then
543    return
544  end
545
546  local tags = name_tag and { '*' .. name .. '()*' } or {}
547
548  if fun.tags then
549    for _, t in ipairs(fun.tags) do
550      tags[#tags + 1] = '*' .. t .. '*'
551    end
552  end
553
554  if #tags == 0 then
555    write(fun.signature)
556    return
557  end
558
559  local tag = table.concat(tags, ' ')
560  local siglen = #fun.signature
561  local conceal_offset = 2 * (#tags - 1)
562  local tag_pad_len = math.max(1, 80 - #tag + conceal_offset)
563
564  if siglen + #tag > 80 then
565    write(string.rep(' ', tag_pad_len) .. tag)
566    write(fun.signature)
567  else
568    write(fmt('%s%s%s', fun.signature, string.rep(' ', tag_pad_len - siglen), tag))
569  end
570end
571
572--- Generates vimdoc for a Vimscript "eval" function.
573--- @param f string
574--- @param fun vim.EvalFn
575--- @param write fun(line: string)
576local function render_eval_doc(f, fun, write)
577  if fun.deprecated or not fun.signature then
578    return
579  end
580
581  render_sig_and_tag(fun.name or f, not f:find('__%d+$'), fun, write)
582
583  render_eval_see_lua_doc(fun, write)
584
585  if not fun.desc then
586    return
587  end
588
589  local params = process_params(fun.params)
590  local req_args = type(fun.args) == 'table' and fun.args[1] or fun.args or 0
591
592  local desc_l = split(vim.trim(fun.desc))
593  for _, l in ipairs(desc_l) do
594    l = l:gsub('^      ', '')
595    if vim.startswith(l, '<') and not l:match('^<[^ \t]+>') then
596      write('<\t\t' .. l:sub(2))
597    elseif l:match('^>[a-z0-9]*$') then
598      write(l)
599    else
600      write('\t\t' .. l)
601    end
602  end
603
604  if #desc_l > 0 and not desc_l[#desc_l]:match('^<?$') then
605    write('')
606  end
607
608  if fun.fast then
609    write(util.md_to_vimdoc('Attributes: ~', 16, 16, TEXT_WIDTH))
610    write(util.md_to_vimdoc('|api-fast|', 18, 18, TEXT_WIDTH))
611    write('')
612  end
613
614  if #params > 0 then
615    write(util.md_to_vimdoc('Parameters: ~', 16, 16, TEXT_WIDTH))
616    for i, param in ipairs(params) do
617      local pname, ptype = param[1], param[2]
618      local optional = (pname ~= '...' and i > req_args) and '?' or ''
619      local s = fmt('- %-14s (`%s%s`)', fmt('{%s}', pname), ptype, optional)
620      write(util.md_to_vimdoc(s, 16, 18, TEXT_WIDTH))
621    end
622    write('')
623  end
624
625  if fun.returns ~= false then
626    write(util.md_to_vimdoc('Return: ~', 16, 16, TEXT_WIDTH))
627    local ret = fmt('(`%s`)', (fun.returns or 'any'))
628    ret = ret .. (fun.returns_desc and ' ' .. fun.returns_desc or '')
629    ret = util.md_to_vimdoc(ret, 18, 18, TEXT_WIDTH)
630    write(ret)
631    write('')
632  end
633end
634
635--- @param d vim.option_defaults
636--- @param vimdoc? boolean
637--- @return string
638local function render_option_default(d, vimdoc)
639  local dt --- @type integer|boolean|string|fun(): string
640  if d.if_false ~= nil then
641    dt = d.if_false
642  else
643    dt = d.if_true
644  end
645
646  if vimdoc then
647    if d.doc then
648      return d.doc
649    end
650    if type(dt) == 'boolean' then
651      return dt and 'on' or 'off'
652    end
653  end
654
655  if dt == '' or dt == nil or type(dt) == 'function' then
656    dt = d.meta
657  end
658
659  local v --- @type string
660  if not vimdoc then
661    v = vim.inspect(dt) --[[@as string]]
662  else
663    v = type(dt) == 'string' and '"' .. dt .. '"' or tostring(dt)
664  end
665
666  --- @type table<string, string|false>
667  local envvars = {
668    TMPDIR = false,
669    VIMRUNTIME = false,
670    XDG_CONFIG_HOME = vim.env.HOME .. '/.local/config',
671    XDG_DATA_HOME = vim.env.HOME .. '/.local/share',
672    XDG_STATE_HOME = vim.env.HOME .. '/.local/state',
673  }
674
675  for name, default in pairs(envvars) do
676    local value = vim.env[name] or default
677    if value then
678      v = v:gsub(vim.pesc(value), '$' .. name)
679    end
680  end
681
682  return v
683end
684
685--- @param _f string
686--- @param opt vim.option_meta
687--- @param write fun(line: string)
688local function render_option_meta(_f, opt, write)
689  write('')
690  for _, l in ipairs(split(norm_text(opt.desc))) do
691    write('--- ' .. l)
692  end
693
694  -- A non-list string option with a fixed value set (e.g. 'ambiwidth', 'tagcase') documents its
695  -- exact value union; everything else uses its Lua type.
696  local values = {} --- @type string[]
697  if opt.type == 'string' and not opt.list and opt.schema then
698    for _, v in ipairs(require('nvim.options').schema_values(opt.schema)) do
699      values[#values + 1] = fmt("'%s'", v)
700    end
701  end
702  if opt.type == 'func' or opt.type == 'expr' then
703    -- "Callback" option ('operatorfunc', 'foldexpr', …).
704    write('--- @type string|function')
705  elseif #values > 0 then
706    write('--- @type ' .. table.concat(values, '|'))
707  else
708    write('--- @type ' .. OPTION_TYPES[opt.type])
709  end
710
711  write(
712    'vim.o.'
713      .. opt.full_name
714      .. ' = '
715      .. render_option_default(opt.defaults --[[@as vim.option_defaults]])
716  )
717  if opt.abbreviation then
718    write('vim.o.' .. opt.abbreviation .. ' = vim.o.' .. opt.full_name)
719  end
720
721  for _, s in pairs {
722    { 'wo', 'win' },
723    { 'bo', 'buf' },
724    { 'go', 'global' },
725  } do
726    local id, scope = s[1], s[2]
727    if vim.list_contains(opt.scope, scope) or (id == 'go' and #opt.scope > 1) then
728      local pfx = 'vim.' .. id .. '.'
729      write(pfx .. opt.full_name .. ' = vim.o.' .. opt.full_name)
730      if opt.abbreviation then
731        write(pfx .. opt.abbreviation .. ' = ' .. pfx .. opt.full_name)
732      end
733    end
734  end
735end
736
737--- @param _f string
738--- @param opt vim.option_meta
739--- @param write fun(line: string)
740local function render_vvar_meta(_f, opt, write)
741  write('')
742
743  local desc = split(norm_text(opt.desc))
744  while desc[#desc]:match('^%s*$') do
745    desc[#desc] = nil
746  end
747
748  for _, l in ipairs(desc) do
749    write('--- ' .. l)
750  end
751
752  write('--- @type ' .. (opt.type or 'any'))
753
754  if LUA_KEYWORDS[opt.full_name] then
755    write("vim.v['" .. opt.full_name .. "'] = ...")
756  else
757    write('vim.v.' .. opt.full_name .. ' = ...')
758  end
759end
760
761--- Generates vimdoc for option scope flags.
762--- @param o vim.option_meta
763--- @return string
764local function option_scope_doc(o)
765  local m = {
766    global = 'global',
767    buf = 'local to buffer',
768    win = 'local to window',
769    tab = 'local to tabpage',
770  }
771
772  local r --- @type string
773  if #o.scope == 1 then
774    r = m[o.scope[1]]
775  else
776    assert(o.scope[1] == 'global')
777    r = 'global or ' .. m[o.scope[2]] .. (o.scope[2] ~= 'tab' and ' |global-local|' or '')
778  end
779
780  if
781    vim.list_contains({
782      'bufhidden',
783      'buftype',
784      'filetype',
785      'modified',
786      'previewwindow',
787      'readonly',
788      'scroll',
789      'syntax',
790      'winfixheight',
791      'winfixwidth',
792      'winpinned',
793    }, o.full_name)
794  then
795    r = r .. '  |local-noglobal|'
796  end
797
798  return r
799end
800
801--- Generates vimdoc for option "attributes" (e.g. modeline restriction).
802-- @param o vim.option_meta
803-- @return string?
804local function option_attrs_doc(o)
805  local attrs = {} --- @type string[]
806  if o.secure then
807    attrs[#attrs + 1] = 'Disallowed in |modeline|. |no-modeline-option|'
808  end
809  if #attrs == 0 then
810    return nil
811  end
812  return table.concat(attrs, '\n\t\t\t')
813end
814
815--- @param x string
816local function dedent(x)
817  return (vim.text.indent(0, (x:gsub('\n%s-([\n]?)$', '\n%1'))))
818end
819
820--- @return table<string,vim.option_meta>
821local function get_option_meta()
822  local opts = require('nvim.options').options
823  local optinfo = vim.api.nvim_get_all_options_info()
824  local ret = {} --- @type table<string,vim.option_meta>
825  for _, o in ipairs(opts) do
826    local is_window_option = #o.scope == 1 and o.scope[1] == 'win'
827    local is_option_hidden = o.immutable and not o.varname and not is_window_option
828    if not is_option_hidden and o.desc then
829      if o.full_name == 'cmdheight' then
830        table.insert(o.scope, 'tab')
831      end
832      local r = vim.deepcopy(o) --[[@as vim.option_meta]]
833      r.desc = o.desc:gsub('^        ', ''):gsub('\n        ', '\n')
834      if o.full_name == 'eventignorewin' then
835        local events = require('nvim.auevents').events
836        local tags_file = assert(io.open(TAGS_FILE))
837        local tags_text = tags_file:read('*a')
838        tags_file:close()
839        local map_fn = function(event_name, is_window_local)
840          if is_window_local then
841            return nil -- Don't include in the list of events outside window context.
842          end
843          local tag_pat = fmt('\n%s\t([^\t]+)\t', event_name)
844          local link_text = fmt('|%s|', event_name)
845          local tags_match = tags_text:match(tag_pat) --- @type string?
846          return tags_match and tags_match ~= 'deprecated.txt' and link_text or nil
847        end
848        local extra_desc = vim.iter(vim.spairs(events)):map(map_fn):join(',\n\t')
849        r.desc = r.desc:gsub('<PLACEHOLDER>', extra_desc)
850      end
851      r.defaults = r.defaults or {}
852      if r.defaults.meta == nil then
853        r.defaults.meta = optinfo[o.full_name].default
854      end
855      ret[o.full_name] = r
856    end
857  end
858  return ret
859end
860
861--- @return table<string,vim.option_meta>
862local function get_vvar_meta()
863  local info = require('nvim.vvars').vars
864  local ret = {} --- @type table<string,vim.option_meta>
865  for name, o in pairs(info) do
866    o.desc = dedent(o.desc)
867    o.full_name = name
868    ret[name] = o
869  end
870  return ret
871end
872
873--- @param opt vim.option_meta
874--- @return string[]
875local function build_option_tags(opt)
876  --- @type string[]
877  local tags = { opt.full_name }
878
879  tags[#tags + 1] = opt.abbreviation
880  if opt.type == 'boolean' then
881    for i = 1, #tags do
882      tags[#tags + 1] = 'no' .. tags[i]
883    end
884  end
885
886  for i, t in ipairs(tags) do
887    tags[i] = "'" .. t .. "'"
888  end
889
890  for _, t in ipairs(opt.tags or {}) do
891    tags[#tags + 1] = t
892  end
893
894  for i, t in ipairs(tags) do
895    tags[i] = '*' .. t .. '*'
896  end
897
898  return tags
899end
900
901--- @param _f string
902--- @param opt vim.option_meta
903--- @param write fun(line: string)
904local function render_option_doc(_f, opt, write)
905  local tags = build_option_tags(opt)
906  local tag_str = table.concat(tags, ' ')
907  local conceal_offset = 2 * (#tags - 1)
908  local tag_pad = string.rep('\t', math.ceil((64 - #tag_str + conceal_offset) / 8))
909  -- local pad = string.rep(' ', 80 - #tag_str + conceal_offset)
910  write(tag_pad .. tag_str)
911
912  local name_str --- @type string
913  if opt.abbreviation then
914    name_str = fmt("'%s' '%s'", opt.full_name, opt.abbreviation)
915  else
916    name_str = fmt("'%s'", opt.full_name)
917  end
918
919  -- Callback (func/expr) options are labeled "string" in the help, their ":set" form.
920  local otype = (opt.type == 'func' or opt.type == 'expr') and 'string' or opt.type
921  if opt.defaults.doc or opt.defaults.if_true ~= nil or opt.defaults.meta ~= nil then
922    local v = render_option_default(opt.defaults --[[@as vim.option_defaults]], true)
923    local pad = string.rep('\t', math.max(1, math.ceil((24 - #name_str) / 8)))
924    if opt.defaults.doc then
925      local deflen = #fmt('%s%s%s (', name_str, pad, otype)
926      --- @type string
927      v = v:gsub('\n', '\n' .. string.rep(' ', deflen - 2))
928    end
929    write(fmt('%s%s%s\t(default %s)', name_str, pad, otype, v))
930  else
931    write(fmt('%s\t%s', name_str, otype))
932  end
933
934  write('\t\t\t' .. option_scope_doc(opt))
935  local attrs = option_attrs_doc(opt)
936  if attrs then
937    write('\t\t\t' .. attrs)
938  end
939  for _, l in ipairs(split(opt.desc)) do
940    if l == '<' or l:match('^<%s') then
941      write(l)
942    else
943      write('\t' .. l:gsub('\\<', '<'))
944    end
945  end
946end
947
948--- @param _f string
949--- @param vvar vim.option_meta
950--- @param write fun(line: string)
951local function render_vvar_doc(_f, vvar, write)
952  local name = vvar.full_name
953
954  local tags = { 'v:' .. name, name .. '-variable' }
955  if vvar.tags then
956    vim.list_extend(tags, vvar.tags)
957  end
958
959  for i, t in ipairs(tags) do
960    tags[i] = '*' .. t .. '*'
961  end
962
963  local tag_str = table.concat(tags, ' ')
964  local conceal_offset = 2 * (#tags - 1)
965
966  local tag_pad = string.rep('\t', math.ceil((64 - #tag_str + conceal_offset) / 8))
967  write(tag_pad .. tag_str)
968
969  local desc = split(vvar.desc)
970
971  if (#desc == 1 or #desc == 2 and desc[2]:match('^%s*$')) and #name < 10 then
972    -- single line
973    write('v:' .. name .. '\t' .. desc[1]:gsub('^%s*', ''))
974    write('')
975  else
976    write('v:' .. name)
977    for _, l in ipairs(desc) do
978      if l == '<' or l:match('^<%s') then
979        write(l)
980      else
981        write('\t\t' .. l:gsub('\\<', '<'))
982      end
983    end
984  end
985end
986
987--- @class nvim.gen_eval_files.elem
988--- @field path string
989--- @field from? string Skip lines in path until this pattern is reached.
990--- @field funcs fun(): table<string, table>
991--- @field render fun(f:string,obj:table,write:fun(line:string))
992--- @field header? string[]
993--- @field footer? string[]
994
995--- @type nvim.gen_eval_files.elem[]
996local CONFIG = {
997  {
998    path = 'runtime/lua/vim/_meta/vimfn.gen.lua',
999    header = LUA_META_HEADER,
1000    funcs = get_eval_lua_meta,
1001    render = render_eval_meta,
1002  },
1003  {
1004    path = 'runtime/lua/vim/_meta/api.gen.lua',
1005    header = LUA_API_META_HEADER,
1006    funcs = get_api_meta,
1007    render = render_api_meta,
1008  },
1009  {
1010    path = 'runtime/lua/vim/_meta/api_keysets.gen.lua',
1011    header = LUA_META_HEADER,
1012    funcs = get_api_keysets_meta,
1013    render = render_api_keyset_meta,
1014  },
1015  {
1016    path = 'runtime/doc/vimfn.txt',
1017    funcs = get_eval_meta,
1018    render = render_eval_doc,
1019    header = {
1020      '*vimfn.txt*	Nvim',
1021      '',
1022      '',
1023      '\t\t  NVIM REFERENCE MANUAL',
1024      '',
1025      '',
1026      'Vimscript functions\t\t\t*vimscript-functions* *builtin.txt*',
1027      '',
1028      'For functions grouped by what they are used for see |function-list|.',
1029      '',
1030      '\t\t\t\t      Type |gO| to see the table of contents.',
1031      '==============================================================================',
1032      '1. Details					*vimscript-functions-details*',
1033      '',
1034    },
1035    footer = {
1036      '==============================================================================',
1037      '2. Matching a pattern in a String			*string-match*',
1038      '',
1039      'This is common between several functions. A regexp pattern as explained at',
1040      '|pattern| is normally used to find a match in the buffer lines.  When a',
1041      'pattern is used to find a match in a String, almost everything works in the',
1042      'same way.  The difference is that a String is handled like it is one line.',
1043      'When it contains a "\\n" character, this is not seen as a line break for the',
1044      'pattern.  It can be matched with a "\\n" in the pattern, or with ".".  Example:',
1045      '>vim',
1046      '\tlet a = "aaaa\\nxxxx"',
1047      '\techo matchstr(a, "..\\n..")',
1048      '\t" aa',
1049      '\t" xx',
1050      '\techo matchstr(a, "a.x")',
1051      '\t" a',
1052      '\t" x',
1053      '',
1054      'Don\'t forget that "^" will only match at the first character of the String and',
1055      '"$" at the last character of the string.  They don\'t match after or before a',
1056      '"\\n".',
1057      '',
1058      ' vim:tw=78:ts=8:noet:ft=help:norl:',
1059    },
1060  },
1061  {
1062    path = 'runtime/lua/vim/_meta/options.gen.lua',
1063    header = LUA_OPTION_META_HEADER,
1064    funcs = get_option_meta,
1065    render = render_option_meta,
1066  },
1067  {
1068    path = 'runtime/doc/options.txt',
1069    header = { '' },
1070    from = 'A jump table for the options with a short description can be found at |Q_op|.',
1071    footer = {
1072      ' vim:tw=78:ts=8:noet:ft=help:norl:',
1073    },
1074    funcs = get_option_meta,
1075    render = render_option_doc,
1076  },
1077  {
1078    path = 'runtime/lua/vim/_meta/vvars.gen.lua',
1079    header = LUA_VVAR_META_HEADER,
1080    funcs = get_vvar_meta,
1081    render = render_vvar_meta,
1082  },
1083  {
1084    path = 'runtime/doc/vvars.txt',
1085    header = { '' },
1086    from = 'Type |gO| to see the table of contents.',
1087    footer = {
1088      ' vim:tw=78:ts=8:noet:ft=help:norl:',
1089    },
1090    funcs = get_vvar_meta,
1091    render = render_vvar_doc,
1092  },
1093}
1094
1095--- @param elem nvim.gen_eval_files.elem
1096local function render(elem)
1097  print('Rendering ' .. elem.path)
1098  local from_lines = {} --- @type string[]
1099  local from = elem.from
1100  if from then
1101    for line in io.lines(elem.path) do
1102      from_lines[#from_lines + 1] = line
1103      if line:match(from) then
1104        break
1105      end
1106    end
1107  end
1108
1109  local o = assert(io.open(elem.path, 'w'))
1110
1111  --- @param l string
1112  local function write(l)
1113    local l1 = l:gsub('%s+$', '')
1114    o:write(l1)
1115    o:write('\n')
1116  end
1117
1118  for _, l in ipairs(from_lines) do
1119    write(l)
1120  end
1121
1122  for _, l in ipairs(elem.header or {}) do
1123    write(l)
1124  end
1125
1126  local funcs = elem.funcs()
1127
1128  --- @type string[]
1129  local fnames = vim.tbl_keys(funcs)
1130  table.sort(fnames)
1131
1132  for _, f in ipairs(fnames) do
1133    elem.render(f, funcs[f], write)
1134  end
1135
1136  for _, l in ipairs(elem.footer or {}) do
1137    write(l)
1138  end
1139
1140  o:close()
1141end
1142
1143local function main()
1144  for _, c in ipairs(CONFIG) do
1145    render(c)
1146  end
1147end
1148
1149main()