robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
18.3 KiB580 linesraw
1--- @brief
2---
3--- vim.health is a minimal framework to help users troubleshoot configuration and any other
4--- environment conditions that a plugin might care about. Nvim ships with healthchecks for
5--- configuration, performance, python support, ruby support, clipboard support, and more.
6---
7--- To run all healthchecks, use:
8--- ```vim
9--- :checkhealth
10--- ```
11--- Plugin authors are encouraged to write new healthchecks. |health-dev|
12---
13---<pre>help
14--- COMMANDS                                *health-commands*
15---
16---                                                              *:che* *:checkhealth*
17--- :che[ckhealth]  Run all healthchecks.
18---                                         *E5009*
19---                 Nvim depends on |$VIMRUNTIME|, 'runtimepath' and 'packpath' to
20---                 find the standard "runtime files" for syntax highlighting,
21---                 filetype-specific behavior, and standard plugins (including
22---                 :checkhealth).  If the runtime files cannot be found then
23---                 those features will not work.
24---
25--- :che[ckhealth] {plugins}
26---                 Run healthcheck(s) for one or more plugins. E.g. to run only
27---                 the standard Nvim healthcheck: >vim
28---                         :checkhealth vim.health
29--- <
30---                 To run the healthchecks for the "foo" and "bar" plugins
31---                 (assuming they are on 'runtimepath' and they have implemented
32---                 the Lua `require("foo.health").check()` interface): >vim
33---                         :checkhealth foo bar
34--- <
35---                 To run healthchecks for Lua submodules, use dot notation or
36---                 "*" to refer to all submodules. For example Nvim provides
37---                 `vim.lsp` and `vim.treesitter`:  >vim
38---                         :checkhealth vim.lsp vim.treesitter
39---                         :checkhealth vim*
40--- <
41---
42--- USAGE                                                        *health-usage*
43---
44--- Local mappings in the healthcheck buffer:
45---
46--- q               Closes the window.
47---
48--- Global configuration:
49---                                                              *g:health*
50--- g:health  Dictionary with the following optional keys:
51---           - `style` (`'float'|nil`) Set to "float" to display :checkhealth in
52---           a floating window instead of the default behavior.
53---
54---           Example: >lua
55---             vim.g.health = { style = 'float' }
56---
57---</pre>
58---
59--- Local configuration:
60---
61--- Checkhealth sets its buffer filetype to "checkhealth". You can customize the buffer by handling
62--- the |FileType| event. For example if you don't want emojis in the health report:
63--- ```vim
64--- autocmd FileType checkhealth :set modifiable | silent! %s/\v( ?[^\x00-\x7F])//g
65--- ```
66--- Sometimes you might need to suppress filetype warnings if you have specified them dynamically.
67--- For example with the yaml.ansible filetype:
68--- ```vim
69--- autocmd FileType checkhealth :set modifiable | silent! g/Unknown filetype 'yaml\.ansible'/d
70--- ```
71---<pre>help
72--- --------------------------------------------------------------------------------
73--- Create a healthcheck                                    *health-dev*
74---</pre>
75---
76--- Healthchecks are functions that check the user environment, configuration, or any other
77--- prerequisites that a plugin cares about. Nvim ships with healthchecks in:
78--- - $VIMRUNTIME/autoload/health/
79--- - $VIMRUNTIME/lua/vim/lsp/health.lua
80--- - $VIMRUNTIME/lua/vim/treesitter/health.lua
81--- - and more...
82---
83--- To add a new healthcheck for your own plugin, simply create a "health.lua" module on
84--- 'runtimepath' that returns a table with a "check()" function. Then |:checkhealth| will
85--- automatically find and invoke the function.
86---
87--- For example if your plugin is named "foo", define your healthcheck module at
88--- one of these locations (on 'runtimepath'):
89--- - lua/foo/health/init.lua
90--- - lua/foo/health.lua
91---
92--- If your plugin also provides a submodule named "bar" for which you want a separate healthcheck,
93--- define the healthcheck at one of these locations:
94--- - lua/foo/bar/health/init.lua
95--- - lua/foo/bar/health.lua
96---
97--- All such health modules must return a Lua table containing a `check()` function.
98---
99--- Copy this sample code into `lua/foo/health.lua`, replacing "foo" in the path with your plugin
100--- name:
101---
102--- ```lua
103--- local M = {}
104---
105--- M.check = function()
106---   vim.health.start("foo report")
107---   -- make sure setup function parameters are ok
108---   if check_setup() then
109---     vim.health.ok("Setup is correct")
110---   else
111---     vim.health.error("Setup is incorrect")
112---   end
113---   -- do some more checking
114---   -- ...
115--- end
116---
117--- return M
118--- ```
119
120local M = {}
121local async = require('vim.async') --- @type vim.async._core
122
123local s_output = {} ---@type string[]
124local check_summary = { warn = 0, error = 0 }
125
126--- From a path return a list [{name}, {func}, {type}] representing a healthcheck
127--- @param path string
128--- @return [string, string, 'l'|'v']
129local function filepath_to_healthcheck(path)
130  path = vim.fs.abspath(vim.fs.normalize(path))
131  local name --- @type string
132  local func --- @type string
133  local filetype --- @type 'l'|'v'
134  if path:find('vim$') then
135    name = vim.fs.basename(path):gsub('%.vim$', '')
136    func = 'health#' .. name .. '#check'
137    filetype = 'v'
138  else
139    local rtp_lua = vim
140      .iter(vim.api.nvim_get_runtime_file('lua/', true))
141      :map(function(dir)
142        return vim.fs.abspath(vim.fs.normalize(dir))
143      end)
144      :find(function(dir)
145        return vim.fs.relpath(dir, path)
146      end)
147    -- The healthcheck path came from nvim_get_runtime_file(), so a runtime directory must match.
148    assert(rtp_lua)
149    -- "/path/to/rtp/lua/foo/bar/health.lua" => "foo/bar/health.lua"
150    -- "/another/rtp/lua/baz/health/init.lua" => "baz/health/init.lua"
151    local subpath = path:gsub('^' .. vim.pesc(rtp_lua), ''):gsub('^/+', '')
152    if vim.fs.basename(subpath) == 'health.lua' then
153      -- */health.lua
154      name = vim.fs.dirname(subpath)
155    else
156      -- */health/init.lua
157      name = vim.fs.dirname(vim.fs.dirname(subpath))
158    end
159    name = name:gsub('/', '.')
160
161    func = 'require("' .. name .. '.health").check()'
162    filetype = 'l'
163  end
164  return { name, func, filetype }
165end
166
167--- @param plugin_names string
168--- @return [string, string, 'l'|'v'|''][] { {name, func, type}, ... } representing healthchecks
169local function get_healthcheck_list(plugin_names)
170  local healthchecks = {} --- @type [string, string, 'l'|'v'|''][]
171  local plugin_names_list = vim.split(plugin_names, ' ')
172  for _, p in pairs(plugin_names_list) do
173    -- support vim/lsp/health{/init/}.lua as :checkhealth vim.lsp
174
175    p = p:gsub('%.', '/')
176    p = p:gsub('*', '**')
177
178    local paths = vim.api.nvim_get_runtime_file('autoload/health/' .. p .. '.vim', true)
179    vim.list_extend(
180      paths,
181      vim.api.nvim_get_runtime_file('lua/**/' .. p .. '/health/init.lua', true)
182    )
183    vim.list_extend(paths, vim.api.nvim_get_runtime_file('lua/**/' .. p .. '/health.lua', true))
184
185    if vim.tbl_count(paths) == 0 then
186      healthchecks[#healthchecks + 1] = { p, '', '' } -- healthcheck not found
187    else
188      local unique_paths = {} --- @type table<string, boolean>
189      for _, v in pairs(paths) do
190        unique_paths[v] = true
191      end
192      paths = {}
193      for k, _ in pairs(unique_paths) do
194        paths[#paths + 1] = k
195      end
196
197      for _, v in ipairs(paths) do
198        healthchecks[#healthchecks + 1] = filepath_to_healthcheck(v)
199      end
200    end
201  end
202  return healthchecks
203end
204
205--- @param plugin_names string
206--- @return table<string, [string, 'l'|'v'|'']> {name: [func, type], ..} representing healthchecks
207local function get_healthcheck(plugin_names)
208  local health_list = get_healthcheck_list(plugin_names)
209  local healthchecks = {} --- @type table<string, [string, 'l'|'v'|'']>
210  for _, c in pairs(health_list) do
211    if c[1] ~= 'vim' then
212      healthchecks[c[1]] = { c[2], c[3] }
213    end
214  end
215
216  return healthchecks
217end
218
219--- Indents lines *except* line 1 of a multiline string.
220---
221--- @param s string
222--- @param columns integer
223--- @return string
224local function indent_after_line1(s, columns)
225  return (vim.text.indent(columns, s):gsub('^%s+', ''))
226end
227
228--- Changes ':h clipboard' to ':help |clipboard|'.
229---
230--- @param s string
231--- @return string
232local function help_to_link(s)
233  return vim.fn.substitute(s, [[\v:h%[elp] ([^|][^"\r\n ]+)]], [[:help |\1|]], [[g]])
234end
235
236--- Format a message for a specific report item.
237---
238--- @param status string
239--- @param msg string
240--- @param ... string|string[] Optional advice
241--- @return string
242local function format_report_message(status, msg, ...)
243  local output = '- ' .. status
244  if status ~= '' then
245    output = output .. ' '
246  end
247
248  output = output .. indent_after_line1(msg, 2)
249
250  local varargs = ...
251
252  -- Optional parameters
253  if varargs then
254    if type(varargs) == 'string' then
255      varargs = { varargs }
256    end
257
258    output = output .. '\n  - ADVICE:'
259
260    -- Report each suggestion
261    for _, v in ipairs(varargs) do
262      if v then
263        output = output .. '\n    - ' .. indent_after_line1(v, 6) --- @type string
264      end
265    end
266  end
267
268  return help_to_link(output)
269end
270
271--- @param output string
272local function collect_output(output)
273  vim.list_extend(s_output, vim.split(output, '\n'))
274end
275
276--- Starts a new report. Most plugins should call this only once, but if
277--- you want different sections to appear in your report, call this once
278--- per section.
279---
280--- @param name string
281function M.start(name)
282  local input = string.format('\n%s ~', name)
283  collect_output(input)
284end
285
286--- Reports an informational message.
287---
288--- @param msg string
289function M.info(msg)
290  local input = format_report_message('', msg)
291  collect_output(input)
292end
293
294--- Reports a "success" message.
295---
296--- @param msg string
297function M.ok(msg)
298  local input = format_report_message('✅ OK', msg)
299  collect_output(input)
300end
301
302--- Reports a warning.
303---
304--- @param msg string
305--- @param ... string|string[] Optional advice
306function M.warn(msg, ...)
307  local input = format_report_message('⚠️ WARNING', msg, ...)
308  collect_output(input)
309  check_summary['warn'] = check_summary['warn'] + 1
310end
311
312--- Reports an error.
313---
314--- @param msg string
315--- @param ... string|string[] Optional advice
316function M.error(msg, ...)
317  local input = format_report_message('❌ ERROR', msg, ...)
318  collect_output(input)
319  check_summary['error'] = check_summary['error'] + 1
320end
321
322---@param path string
323---@return string
324local path2name = function(path)
325  if vim.fs.ext(path) == 'lua' then
326    -- Lua: transform "../lua/vim/lsp/health.lua" into "vim.lsp"
327
328    -- Get full path, make sure all slashes are '/'
329    path = vim.fs.normalize(path)
330
331    -- Remove everything up to the last /lua/ folder
332    path = path:gsub('^.*/lua/', '')
333
334    -- Remove the filename (health.lua) or (health/init.lua)
335    path = vim.fs.dirname(path:gsub('/init%.lua$', ''))
336
337    -- Change slashes to dots
338    path = path:gsub('/', '.')
339
340    return path
341  else
342    -- Vim: transform "../autoload/health/provider.vim" into "provider"
343    return vim.fn.fnamemodify(path, ':t:r')
344  end
345end
346
347local PATTERNS = { '/autoload/health/*.vim', '/lua/**/**/health.lua', '/lua/**/**/health/init.lua' }
348--- :checkhealth completion function used by cmdexpand.c get_healthcheck_names()
349M._complete = function()
350  ---@type table<string,boolean>
351  local unique = vim
352    .iter(vim.tbl_map(function(pattern)
353      return vim.tbl_map(path2name, vim.api.nvim_get_runtime_file(pattern, true))
354    end, PATTERNS))
355    :flatten()
356    :fold({}, function(t, name)
357      t[name] = true -- Remove duplicates
358      return t
359    end)
360  -- vim.health is this file, which is not a healthcheck
361  unique['vim'] = nil
362  local rv = vim.tbl_keys(unique)
363  table.sort(rv)
364  return rv
365end
366
367--- Gets the results heading for the current report section.
368---
369---@return string
370local function get_summary()
371  local s = ''
372  local errors = check_summary['error']
373  local warns = check_summary['warn']
374
375  s = s .. (warns > 0 and (' %2d ⚠️'):format(warns) or '')
376  s = s .. (errors > 0 and (' %2d ❌'):format(errors) or '')
377  if errors == 0 and warns == 0 then
378    s = s .. '✅'
379  end
380
381  return s
382end
383
384---Emit progress messages
385---@param len integer
386---@return fun(status: 'success'|'running', idx: integer?, fmt: string, ...: any): nil
387local function progress_report(len)
388  local progress = { kind = 'progress', source = 'vim.health', title = 'checkhealth' }
389
390  return function(status, idx, fmt, ...)
391    progress.status = status
392    local progress_percent = idx and math.floor(idx / len * 100) or nil
393    progress.percent = status == 'success' and nil or progress_percent
394    progress.id = vim.api.nvim_echo({ { fmt:format(...) } }, false, progress)
395    vim.cmd.redraw()
396  end
397end
398
399--- Runs the specified healthchecks, or all discovered healthchecks if eap.args is empty.
400---
401--- Specified healthchecks are given as plugin names, split on whitespace. For example using
402--- `:checkhealth vim.* nvim` will check `vim.lsp`, `vim.treesitter` and `nvim` modules.
403---
404--- @param eap vim._core.ExCmdArgs
405function M._check(eap)
406  local plugin_names = eap.args
407  local smods = eap.smods
408  local healthchecks = plugin_names == '' and get_healthcheck('*') or get_healthcheck(plugin_names)
409
410  local emptybuf = vim.fn.bufnr('$') == 1 and vim.fn.getline(1) == '' and 1 == vim.fn.line('$')
411
412  local bufnr ---@type integer
413  if vim.tbl_get(vim.g, 'health', 'style') == 'float' then
414    local available_lines = vim.o.lines - 12
415    local max_height = math.min(math.floor(vim.o.lines * 0.8), available_lines)
416    local max_width = 80
417    local float_winid
418    bufnr, float_winid = vim.lsp.util.open_floating_preview({}, '', {
419      height = max_height,
420      width = max_width,
421      offset_x = math.floor((vim.o.columns - max_width) / 2),
422      offset_y = math.floor((available_lines - max_height) / 2),
423      relative = 'editor',
424      close_events = {},
425    })
426    vim.api.nvim_set_current_win(float_winid)
427    vim.wo[float_winid].list = false
428  else
429    bufnr = vim.api.nvim_create_buf(true, true)
430    -- When no command modifiers are used:
431    -- - If the current buffer is empty, open healthcheck directly.
432    -- - If not specified otherwise open healthcheck in a tab.
433    local has_mods = smods.tab > 0 or smods.split ~= '' or smods.horizontal or smods.vertical
434    if has_mods then
435      vim.cmd.sbuffer { bufnr, mods = smods }
436    elseif emptybuf then
437      vim.cmd.buffer(bufnr)
438    else
439      vim.cmd.sbuffer { bufnr, mods = { tab = vim.api.nvim_tabpage_get_number(0) } }
440    end
441  end
442  vim.bo[bufnr].modifiable = true
443
444  if vim.fn.bufexists('health://') == 1 then
445    vim.cmd.bwipe('health://')
446  end
447  vim.cmd.file('health://')
448
449  -- This should only happen when doing `:checkhealth vim`
450  if next(healthchecks) == nil then
451    vim.fn.setline(1, 'ERROR: No healthchecks found.')
452    return
453  end
454
455  -- Show nvim-owned first (`vim.*`, `runtime/lua/vim/**/health.lua`).
456  local names = vim.tbl_keys(healthchecks) --- @type string[]
457  table.sort(names, function(a, b)
458    local a_nvim = vim.startswith(a, 'vim.')
459    local b_nvim = vim.startswith(b, 'vim.')
460    if a_nvim ~= b_nvim then
461      return a_nvim
462    end
463    return a < b
464  end)
465
466  local task --- @type vim.async.Task<nil>
467
468  -- Quit with 'q' inside healthcheck buffers.
469  vim._with({ buf = bufnr }, function()
470    if
471      vim.tbl_get(vim.g, 'health', 'style') == 'float'
472      or vim.fn.maparg('q', 'n', false, false) == ''
473    then
474      vim.keymap.set('n', 'q', function()
475        task:close()
476        if not pcall(vim.cmd.close) then
477          vim.cmd.bdelete()
478        end
479      end, { buf = bufnr, silent = true, noremap = true, nowait = true })
480    end
481  end)
482
483  task = async.run('checkhealth', function()
484    local total_checks = #names
485    local progress_msg = progress_report(total_checks)
486    local check_idx = 1
487    for _, name in ipairs(names) do
488      local value = healthchecks[name]
489      progress_msg('running', check_idx, 'checking %s', name)
490      local func = value[1]
491      local type = value[2]
492      s_output = {}
493      check_summary = { warn = 0, error = 0 }
494
495      if func == '' then
496        M.error('No healthcheck found for "' .. name .. '" plugin.')
497      end
498      if type == 'v' then
499        vim.fn.call(func, {})
500      else
501        local f = assert(loadstring(func))
502        --- @diagnostic disable-next-line: assign-type-mismatch
503        local ok, output = async.pawait(async.run(name, f)) ---@type boolean, string
504        async.await(vim.schedule)
505        if not ok then
506          M.error(
507            string.format(
508              'Failed to run healthcheck for "%s" plugin. Exception:\n%s\n',
509              name,
510              output
511            )
512          )
513        end
514      end
515      -- in the event the healthcheck doesn't return anything
516      -- (the plugin author should avoid this possibility)
517      if next(s_output) == nil then
518        s_output = {}
519        M.error('The healthcheck report for "' .. name .. '" plugin is empty.')
520      end
521
522      local report = get_summary()
523      local replen = vim.fn.strwidth(report)
524      local header = {
525        string.rep('=', 78),
526        -- Example: `foo.health: [ …] 1 ⚠️  5 ❌`
527        ('%s: %s%s'):format(name, (' '):rep(76 - name:len() - replen), report),
528        '',
529      }
530
531      -- remove empty line after header from report_start
532      if s_output[1] == '' then
533        local tmp = {} ---@type string[]
534        for i = 2, #s_output do
535          tmp[#tmp + 1] = s_output[i]
536        end
537        s_output = {}
538        for _, v in ipairs(tmp) do
539          s_output[#s_output + 1] = v
540        end
541      end
542      s_output[#s_output + 1] = ''
543      s_output = vim.list_extend(header, s_output)
544
545      if not vim.api.nvim_buf_is_valid(bufnr) then
546        return
547      end
548      vim.api.nvim_buf_set_lines(bufnr, check_idx == 1 and 0 or -1, -1, true, s_output)
549
550      check_idx = check_idx + 1
551    end
552
553    progress_msg('success', nil, 'checks done')
554
555    if not vim.api.nvim_buf_is_valid(bufnr) then
556      return
557    end
558    -- Once we're done writing checks, set nomodifiable.
559    vim.bo[bufnr].modifiable = false
560    vim._with({ buf = bufnr }, function()
561      vim.cmd.setfiletype('checkhealth')
562    end)
563  end)
564
565  local cancel_autocmd = vim.api.nvim_create_autocmd('BufUnload', {
566    buffer = bufnr,
567    once = true,
568    callback = function()
569      task:close()
570    end,
571  })
572  task:on_complete(function(err)
573    pcall(vim.api.nvim_del_autocmd, cancel_autocmd)
574    if err and err ~= 'closed' then
575      error(task:traceback(err), 0)
576    end
577  end)
578end
579
580return M