robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
26.3 KiB858 linesraw
1local nvim_on = require('vim._core.util').nvim_on
2
3local M = {}
4local async = require('vim.async') --- @type vim.async._core
5local health = require('vim.health')
6
7---@async
8---@param cmd string[]
9---@param opts? vim.SystemOpts
10---@return vim.SystemCompleted
11local function run_system(cmd, opts)
12  --- @diagnostic disable-next-line: assign-type-mismatch
13  local result = async.await(3, vim.system, cmd, opts) --- @type vim.SystemCompleted
14  async.await(vim.schedule)
15  return result
16end
17
18---Run a system command and return ok and its stdout and stderr combined.
19---@async
20---@param cmd string[]
21---@param timeout? integer Timeout in ms (default: no timeout).
22---@return boolean
23---@return string
24local function system(cmd, timeout)
25  local result = run_system(cmd, { text = true, timeout = timeout })
26  if not result then -- Workaround https://github.com/neovim/neovim/issues/37922
27    return false, 'command failed'
28  end
29  return result.code == 0, vim.trim(('%s\n%s'):format(result.stdout, result.stderr))
30end
31
32local suggest_faq = 'https://neovim.io/doc/build/#building'
33
34local function check_runtime()
35  health.start('Runtime')
36  -- Files from an old installation.
37  local bad_files = {
38    ['autoload/health/nvim.vim'] = false,
39    ['autoload/health/provider.vim'] = false,
40    ['autoload/man.vim'] = false,
41    ['lua/provider/node/health.lua'] = false,
42    ['lua/provider/perl/health.lua'] = false,
43    ['lua/provider/python/health.lua'] = false,
44    ['lua/provider/ruby/health.lua'] = false,
45    ['lua/vim/_defaults.lua'] = false,
46    ['lua/vim/_editor.lua'] = false,
47    ['lua/vim/_extui.lua'] = false,
48    ['lua/vim/_extui/cmdline.lua'] = false,
49    ['lua/vim/_extui/messages.lua'] = false,
50    ['lua/vim/_extui/shared.lua'] = false,
51    ['lua/vim/_options.lua'] = false,
52    ['lua/vim/_stringbuffer.lua'] = false,
53    ['lua/vim/_system.lua'] = false,
54    ['lua/vim/shared.lua'] = false,
55    ['plugin/health.vim'] = false,
56    ['plugin/man.vim'] = false,
57    ['plugin/nvim/net.lua'] = false,
58    ['plugin/nvim/spellfile.lua'] = false,
59    ['queries/help/highlights.scm'] = false,
60    ['queries/help/injections.scm'] = false,
61    ['scripts.vim'] = false,
62    ['syntax/syncolor.vim'] = false,
63  }
64  local bad_files_msg = ''
65  for k, _ in pairs(bad_files) do
66    local path = ('%s/%s'):format(vim.env.VIMRUNTIME, k)
67    if vim.uv.fs_stat(path) then
68      bad_files[k] = true
69      bad_files_msg = ('%s%s\n'):format(bad_files_msg, path)
70    end
71  end
72
73  local ok = (bad_files_msg == '')
74  local info = ok and health.ok or health.info
75  info(string.format('$VIMRUNTIME: %s', vim.env.VIMRUNTIME))
76  if not ok then
77    health.error(
78      string.format(
79        'Found old files in $VIMRUNTIME (this can cause weird behavior):\n%s',
80        bad_files_msg
81      ),
82      { 'Delete the $VIMRUNTIME directory, then reinstall Nvim.' }
83    )
84  end
85end
86
87local function check_config()
88  health.start('Configuration')
89  local ok = true
90
91  local init_lua = vim.fn.stdpath('config') .. '/init.lua'
92  local init_vim = vim.fn.stdpath('config') .. '/init.vim'
93  local vimrc = vim.env.MYVIMRC and vim.fs.normalize(vim.env.MYVIMRC) or init_lua
94
95  if vim.fn.filereadable(vimrc) == 0 and vim.fn.filereadable(init_vim) == 0 then
96    ok = false
97    local has_vim = vim.fn.filereadable(vim.fs.normalize('~/.vimrc')) == 1
98    health.warn(
99      ('%s user config file: %s'):format(
100        -1 == vim.fn.getfsize(vimrc) and 'Missing' or 'Unreadable',
101        vimrc
102      ),
103      { has_vim and ':help nvim-from-vim' or ':help config' }
104    )
105  end
106
107  -- If $VIM is empty we don't care. Else make sure it is valid.
108  if vim.env.VIM and vim.fn.filereadable(vim.env.VIM .. '/runtime/doc/nvim.txt') == 0 then
109    ok = false
110    health.error('$VIM is invalid: ' .. vim.env.VIM)
111  end
112
113  if vim.env.NVIM_TUI_ENABLE_CURSOR_SHAPE then
114    ok = false
115    health.warn('$NVIM_TUI_ENABLE_CURSOR_SHAPE is ignored in Nvim 0.2+', {
116      "Use the 'guicursor' option to configure cursor shape. :help 'guicursor'",
117      'https://github.com/neovim/neovim/wiki/Following-HEAD#20170402',
118    })
119  end
120
121  if vim.v.ctype == 'C' then
122    ok = false
123    health.error(
124      'Locale does not support UTF-8. Unicode characters may not display correctly.'
125        .. ('\n$LANG=%s $LC_ALL=%s $LC_CTYPE=%s'):format(
126          vim.env.LANG or '',
127          vim.env.LC_ALL or '',
128          vim.env.LC_CTYPE or ''
129        ),
130      {
131        'If using tmux, try the -u option.',
132        'Ensure that your terminal/shell/tmux/etc inherits the environment, or set $LANG explicitly.',
133        'Configure your system locale.',
134      }
135    )
136  end
137
138  if vim.o.paste == 1 then
139    ok = false
140    health.error(
141      "'paste' is enabled. This option is only for pasting text.\nIt should not be set in your config.",
142      {
143        'Remove `set paste` from your init.vim, if applicable.',
144        'Check `:verbose set paste?` to see if a plugin or script set the option.',
145      }
146    )
147  end
148
149  local writeable = true
150  local shadaopt = vim.fn.split(vim.o.shada, ',')
151  local shadafile = (
152    vim.o.shada == '' and vim.o.shada
153    or vim.fn.substitute(vim.fn.matchstr(shadaopt[#shadaopt], '^n.\\+'), '^n', '', '')
154  )
155  shadafile = (
156    vim.o.shadafile == ''
157      and (shadafile == '' and vim.fn.stdpath('state') .. '/shada/main.shada' or vim.fs.normalize(
158        shadafile
159      ))
160    or (vim.o.shadafile == 'NONE' and '' or vim.o.shadafile)
161  )
162  if shadafile ~= '' and vim.fn.glob(shadafile) == '' then
163    -- Since this may be the first time Nvim has been run, try to create a shada file.
164    if not pcall(vim.cmd.wshada) then
165      writeable = false
166    end
167  end
168  if
169    not writeable
170    or (
171      shadafile ~= ''
172      and (vim.fn.filereadable(shadafile) == 0 or vim.fn.filewritable(shadafile) ~= 1)
173    )
174  then
175    ok = false
176    health.error(
177      'shada file is not '
178        .. ((not writeable or vim.fn.filereadable(shadafile) == 1) and 'writeable' or 'readable')
179        .. ':\n'
180        .. shadafile
181    )
182  end
183
184  if ok then
185    health.ok('no issues found')
186  end
187end
188
189-- Note: this is part of check_performance().
190local function check_watchers()
191  local a = vim._watch.active()
192  local total = a.watch + a.watchdirs + a.inotify
193  health.info(
194    ('Filewatchers (vim._watch): %d (watch=%d, watchdirs=%d, inotify=%d)'):format(
195      total,
196      a.watch,
197      a.watchdirs,
198      a.inotify
199    )
200  )
201
202  -- Walk libuv for an independent view. These counts include handles created outside `vim._watch`
203  -- (e.g. plugins calling `vim.uv.new_fs_event()` directly).
204  local libuv = { fs_event = 0, fs_poll = 0, process = 0, timer = 0 }
205  vim.uv.walk(function(handle)
206    if handle:is_closing() then
207      return
208    end
209    local t = handle:get_type()
210    if libuv[t] ~= nil then
211      libuv[t] = libuv[t] + 1
212    end
213  end)
214  health.info(
215    ('libuv handles: fs_event=%d, fs_poll=%d, process=%d, timer=%d'):format(
216      libuv.fs_event,
217      libuv.fs_poll,
218      libuv.process,
219      libuv.timer
220    )
221  )
222end
223
224--- Reads a single integer from a file (e.g. a `/proc/sys` entry).
225---@param path string
226---@return integer?
227local function read_int(path)
228  local ok, lines = pcall(vim.fn.readfile, path, '', 1)
229  local v = ok and lines[1] and tonumber(lines[1])
230  return v or nil
231end
232
233-- Note: this is part of check_performance().
234---@async
235local function check_limits()
236  -- 'ulimit -n' (RLIMIT_NOFILE): each Nvim buffer may hold an open swapfile. Sockets, channels, filewatchers also consume file descriptors.
237  if vim.fn.has('win32') == 0 then
238    local ok, out = system({ 'sh', '-c', 'ulimit -Sn' }) -- Must use a shell.
239    out = vim.trim(out or '')
240    local soft = tonumber(out)
241    local used = require('vim._core.proc').count_open_fds()
242    local used_str = used and (', currently open: %d'):format(used) or ''
243    local raise_advice = {
244      '\'swapfile\' buffers, sockets, channels, and file-watchers consume file descriptors. A low limit causes "(libuv) kqueue(): Too many open files" (EMFILE) errors.',
245      'Increase the limit: add `ulimit -n 8192` to your shell rc. On macOS see also `launchctl limit maxfiles`; on Linux see `/etc/security/limits.conf` and systemd `LimitNOFILE`.',
246    }
247    if out == 'unlimited' then
248      health.ok(('ulimit -n (max open files): unlimited%s'):format(used_str))
249    elseif not ok or soft == nil then
250      health.info(('ulimit -n (max open files): unknown (%s)%s'):format(out, used_str))
251    elseif soft < 1024 then
252      health.warn(('ulimit -n (max open files) is low: %d%s'):format(soft, used_str), raise_advice)
253    elseif used and used > soft * 0.8 then
254      health.warn(
255        ('Open files near the limit: %d of %d (ulimit -n)'):format(used, soft),
256        raise_advice
257      )
258    else
259      health.ok(('ulimit -n (max open files): %d%s'):format(soft, used_str))
260    end
261  end
262
263  -- Linux inotify limits filewatchers (LSP, vim._watch). Exhausting them reports ENOSPC ("no space on device").
264  if vim.uv.os_uname().sysname == 'Linux' then
265    local watches = read_int('/proc/sys/fs/inotify/max_user_watches')
266    local instances = read_int('/proc/sys/fs/inotify/max_user_instances')
267    if watches and watches < 8192 then
268      health.warn(('fs.inotify.max_user_watches is low: %d'):format(watches), {
269        'Filewatchers may fail with ENOSPC. To increase the limit: `sysctl fs.inotify.max_user_watches=524288` (persist in /etc/sysctl.conf).',
270      })
271    end
272    if instances and instances < 128 then
273      health.warn(('fs.inotify.max_user_instances is low: %d'):format(instances), {
274        'To increase the limit: `sysctl fs.inotify.max_user_instances=512` (persist in /etc/sysctl.conf).',
275      })
276    end
277  end
278end
279
280---@async
281local function check_performance()
282  health.start('Performance')
283
284  -- Check buildtype
285  local buildtype = vim.fn.matchstr(vim.fn.execute('version'), [[\v\cbuild type:?\s*[^\n\r\t]+]])
286  if buildtype == '' then
287    health.error('failed to get build type from :version')
288  elseif
289    vim.regex([[\v(MinSizeRel|RelWithDebInfo|Release(Fast|Safe|Small)?)]]):match_str(buildtype)
290  then
291    health.ok(buildtype)
292  else
293    health.info(buildtype)
294    health.warn('Non-optimized debug build. Nvim will be slower.', {
295      'Install a different Nvim package, or rebuild with `CMAKE_BUILD_TYPE=RelWithDebInfo` (CMake) or `-Doptimize=ReleaseFast` (Zig).',
296      suggest_faq,
297    })
298  end
299
300  -- check for slow shell invocation
301  local slow_cmd_time = 1.5e9
302  local start_time = vim.uv.hrtime()
303  -- Vimscript's system() is used to actually invoke a shell
304  vim.fn.system('echo 1')
305  local elapsed_time = vim.uv.hrtime() - start_time
306  if elapsed_time > slow_cmd_time then
307    health.warn(
308      'Slow shell invocation (took ' .. vim.fn.printf('%.2f', elapsed_time / 1e9) .. ' seconds).'
309    )
310  end
311
312  check_watchers()
313  check_limits()
314end
315
316-- Load the remote plugin manifest file and check for unregistered plugins
317local function check_rplugin_manifest()
318  health.start('Remote Plugins')
319
320  local existing_rplugins = {} --- @type table<string,string>
321  --- @type {path:string}[]
322  local items = vim.fn['remote#host#PluginsForHost']('python3')
323  for _, item in ipairs(items) do
324    existing_rplugins[item.path] = 'python3'
325  end
326
327  local require_update = false
328  --- @param path string
329  local function handle_path(path)
330    --- @type string[]
331    local python_glob = vim.fn.glob(path .. '/rplugin/python*', true, true)
332    if vim.tbl_isempty(python_glob) then
333      return
334    end
335
336    local python_dir = assert(python_glob[1])
337    local python_version = vim.fs.basename(python_dir)
338
339    --- @type string[]
340    local scripts = vim.fn.glob(python_dir .. '/*.py', true, true)
341    vim.list_extend(scripts, vim.fn.glob(python_dir .. '/*/__init__.py', true, true))
342
343    for _, script in ipairs(scripts) do
344      local contents = vim.fn.join(vim.fn.readfile(script))
345      if vim.regex([[\<\%(from\|import\)\s\+neovim\>]]):match_str(contents) then
346        if vim.regex([[[\/]__init__\.py$]]):match_str(script) then
347          script = vim.fs.normalize(vim.fs.dirname(script))
348        end
349        if not existing_rplugins[script] then
350          local msg = vim.fn.printf('"%s" is not registered.', vim.fs.basename(path))
351          if python_version == 'pythonx' then
352            if vim.fn.has('python3') == 0 then
353              msg = msg .. ' (python3 not available)'
354            end
355          elseif vim.fn.has(python_version) == 0 then
356            msg = msg .. vim.fn.printf(' (%s not available)', python_version)
357          else
358            require_update = true
359          end
360
361          health.warn(msg)
362        end
363
364        break
365      end
366    end
367  end
368
369  --- @type string[]
370  local paths = vim.fn.map(vim.split(vim.o.runtimepath, ','), 'resolve(v:val)')
371
372  for _, path in ipairs(paths) do
373    handle_path(path)
374  end
375
376  if require_update then
377    health.warn('Out of date', { 'Run `:UpdateRemotePlugins`' })
378  else
379    health.ok('Up to date')
380  end
381end
382
383---@async
384local function check_tmux()
385  if not vim.env.TMUX or vim.fn.executable('tmux') == 0 then
386    return
387  end
388
389  ---@async
390  ---@param option string
391  local get_tmux_option = function(option)
392    local cmd = { 'tmux', 'show-option', '-qvg', option } -- try global scope
393    local ok, out = system(cmd)
394    local val = vim.fn.substitute(out, [[\v(\s|\r|\n)]], '', 'g')
395    if not ok then
396      health.error(('command failed: %s\n%s'):format(vim.inspect(cmd), out))
397      return 'error'
398    elseif val == '' then
399      cmd = { 'tmux', 'show-option', '-qvgs', option } -- try session scope
400      ok, out = system(cmd)
401      val = vim.fn.substitute(out, [[\v(\s|\r|\n)]], '', 'g')
402      if not ok then
403        health.error(('command failed: %s\n%s'):format(vim.inspect(cmd), out))
404        return 'error'
405      end
406    end
407    return val
408  end
409
410  health.start('tmux')
411
412  health.warn('tmux is detected. Images may not display correctly.')
413
414  -- check escape-time
415  local suggestions =
416    { 'set escape-time in ~/.tmux.conf:\nset-option -sg escape-time 10', suggest_faq }
417  local tmux_esc_time = get_tmux_option('escape-time')
418  if tmux_esc_time ~= 'error' then
419    if tmux_esc_time == '' then
420      health.error('`escape-time` is not set', suggestions)
421    else
422      local tmux_esc_time_ms = vim._tointeger(tmux_esc_time)
423      if not tmux_esc_time_ms then
424        health.error('`escape-time` (' .. tmux_esc_time .. ') is not an integer', suggestions)
425      elseif tmux_esc_time_ms > 300 then
426        health.error('`escape-time` (' .. tmux_esc_time .. ') is higher than 300ms', suggestions)
427      else
428        health.ok('escape-time: ' .. tmux_esc_time)
429      end
430    end
431  end
432
433  -- check focus-events
434  local tmux_focus_events = get_tmux_option('focus-events')
435  if tmux_focus_events ~= 'error' then
436    if tmux_focus_events == '' or tmux_focus_events ~= 'on' then
437      health.warn(
438        "`focus-events` is not enabled. |'autoread'| may not work.",
439        { '(tmux 1.9+ only) Set `focus-events` in ~/.tmux.conf:\nset-option -g focus-events on' }
440      )
441    else
442      health.ok('focus-events: ' .. tmux_focus_events)
443    end
444  end
445
446  -- check default-terminal and $TERM
447  health.info('$TERM: ' .. vim.env.TERM)
448  local cmd = { 'tmux', 'show-option', '-qvg', 'default-terminal' }
449  local ok, out = system(cmd)
450  local tmux_default_term = vim.fn.substitute(out, [[\v(\s|\r|\n)]], '', 'g')
451  if tmux_default_term == '' then
452    cmd = { 'tmux', 'show-option', '-qvgs', 'default-terminal' }
453    ok, out = system(cmd)
454    tmux_default_term = vim.fn.substitute(out, [[\v(\s|\r|\n)]], '', 'g')
455  end
456
457  if not ok then
458    health.error(('command failed: %s\n%s'):format(vim.inspect(cmd), out))
459  elseif tmux_default_term ~= vim.env.TERM then
460    health.info('default-terminal: ' .. tmux_default_term)
461    health.error(
462      '$TERM differs from the tmux `default-terminal` setting. Colors might look wrong.',
463      { '$TERM may have been set by some rc (.bashrc, .zshrc, ...).' }
464    )
465  elseif
466    not vim.regex([[\v(tmux-256color|tmux-direct|screen-256color)]]):match_str(assert(vim.env.TERM))
467  then
468    health.error(
469      '$TERM should be "screen-256color", "tmux-256color", or "tmux-direct" in tmux. Colors might look wrong.',
470      {
471        'Set default-terminal in ~/.tmux.conf:\nset-option -g default-terminal "screen-256color"',
472        suggest_faq,
473      }
474    )
475  end
476
477  -- check for RGB capabilities
478  local _, info = system({ 'tmux', 'show-messages', '-T' })
479  local has_setrgbb = vim.fn.stridx(info, ' setrgbb: (string)') ~= -1
480  local has_setrgbf = vim.fn.stridx(info, ' setrgbf: (string)') ~= -1
481  if not has_setrgbb or not has_setrgbf then
482    health.warn(
483      "True color support could not be detected. |'termguicolors'| won't work properly.",
484      {
485        "Add the following to your tmux configuration file, replacing XXX by the value of $TERM outside of tmux:\nset-option -a terminal-features 'XXX:RGB'",
486        "For older tmux versions use this instead:\nset-option -a terminal-overrides 'XXX:Tc'",
487      }
488    )
489  end
490end
491
492-- Note: this is part of check_terminal().
493local function check_graphics()
494  local supported, msg = require('vim.ui.img')._supported()
495
496  if supported then
497    if msg then
498      health.ok(('Graphics protocol: supported (%s)'):format(msg))
499    else
500      health.ok('Graphics protocol: supported')
501    end
502  else
503    health.error('Graphics protocol: not supported by this terminal.')
504  end
505end
506
507-- Note: this is part of check_terminal().
508---@async
509local function check_infocmp()
510  if vim.fn.executable('infocmp') == 0 then
511    return
512  end
513
514  local cmd = { 'infocmp', '-L' }
515  local ok, out = system(cmd)
516  local kbs_entry = vim.fn.matchstr(out, 'key_backspace=[^,[:space:]]*')
517  local kdch1_entry = vim.fn.matchstr(out, 'key_dc=[^,[:space:]]*')
518
519  if
520    not ok
521    and (
522      vim.fn.has('win32') == 0
523      or vim.fn.matchstr(
524          out,
525          [[infocmp: couldn't open terminfo file .\+\%(conemu\|vtpcon\|win32con\)]]
526        )
527        == ''
528    )
529  then
530    health.error(('command failed: %s\n%s'):format(vim.inspect(cmd), out))
531  else
532    health.info(
533      vim.fn.printf(
534        'key_backspace (kbs) terminfo entry: `%s`',
535        (kbs_entry == '' and '? (not found)' or kbs_entry)
536      )
537    )
538
539    health.info(
540      vim.fn.printf(
541        'key_dc (kdch1) terminfo entry: `%s`',
542        (kdch1_entry == '' and '? (not found)' or kdch1_entry)
543      )
544    )
545  end
546end
547
548---@async
549local function check_terminal()
550  health.start('Terminal')
551
552  check_graphics()
553
554  check_infocmp()
555
556  for _, env_var in ipairs({
557    'XTERM_VERSION',
558    'VTE_VERSION',
559    'TERM_PROGRAM',
560    'COLORTERM',
561    'SSH_TTY',
562  }) do
563    if vim.env[env_var] then
564      health.info(string.format('$%s="%s"', env_var, vim.env[env_var]))
565    end
566  end
567end
568
569---@async
570local function check_external_tools()
571  health.start('External Tools')
572
573  if vim.fn.executable('rg') == 1 then
574    local rg_path = vim.fn.exepath('rg')
575    local rg_job = run_system({ rg_path, '-V' })
576    if rg_job.code == 0 then
577      health.ok(('%s (%s)'):format(vim.trim(assert(rg_job.stdout)), rg_path))
578    else
579      health.warn('found `rg` but failed to run `rg -V`', { rg_job.stderr })
580    end
581  else
582    health.warn('ripgrep not available')
583  end
584
585  local open_cmd, err = vim.ui._get_open_cmd()
586  if open_cmd then
587    health.ok(('vim.ui.open: handler found (%s)'):format(open_cmd[1]))
588  else
589    --- @cast err string
590    health.warn(err)
591  end
592
593  -- `vim.pack` prefers git 2.36 but tries to work with 2.x.
594  if vim.fn.executable('git') == 1 then
595    local git = vim.fn.exepath('git')
596    local version = run_system({ 'git', 'version' }).stdout or ''
597    health.ok(('%s (%s)'):format(vim.trim(version), git))
598  else
599    health.warn('git not available (required by `vim.pack`)')
600  end
601
602  if vim.fn.executable('curl') == 1 then
603    local curl_path = vim.fn.exepath('curl')
604    local curl_job = run_system({ curl_path, '--version' })
605
606    if curl_job.code == 0 then
607      local curl_out = curl_job.stdout
608      if not curl_out or curl_out == '' then
609        health.warn(
610          string.format('`%s --version` produced no output', curl_path),
611          { curl_job.stderr }
612        )
613        return
614      end
615      local curl_version = vim.version.parse(curl_out)
616      if not curl_version then
617        health.warn('Unable to parse curl version from `curl --version`')
618        return
619      end
620      if vim.version.le(curl_version, { 7, 12, 3 }) then
621        health.warn(('curl version %s not compatible'):format(curl_version))
622        return
623      end
624      local lines = { string.format('curl %s (%s)', curl_version, curl_path) }
625
626      for line in vim.gsplit(curl_out, '\n', { plain = true }) do
627        if line ~= '' then
628          table.insert(lines, line)
629        end
630      end
631
632      -- Add subtitle only if any env var is present
633      local added_env_header = false
634      for _, var in ipairs({
635        'curl_ca_bundle',
636        'curl_home',
637        'curl_ssl_backend',
638        'ssl_cert_dir',
639        'ssl_cert_file',
640        'https_proxy',
641        'http_proxy',
642        'all_proxy',
643        'no_proxy',
644      } --[[@as string[] ]]) do
645        local val = vim.env[var]
646        if not val then
647          var = var:upper()
648          val = vim.env[var]
649        end
650        if val then
651          if not added_env_header then
652            table.insert(lines, 'curl-related environment variables:')
653            added_env_header = true
654          end
655          table.insert(lines, string.format('  %s=%s', var, val))
656        end
657      end
658
659      health.ok(table.concat(lines, '\n'))
660    else
661      health.warn('curl is installed but failed to run `curl --version`', { curl_job.stderr })
662    end
663  else
664    health.error('curl not found', {
665      'Required for vim.net.request() to function.',
666      'Install curl using your package manager.',
667    })
668  end
669end
670
671local function detect_terminal()
672  local e = vim.env
673  if e.TERM_PROGRAM then
674    local v = e.TERM_PROGRAM_VERSION --- @type string?
675    return e.TERM_PROGRAM_VERSION and (e.TERM_PROGRAM .. ' ' .. v) or e.TERM_PROGRAM
676  end
677
678  local map = {
679    KITTY_WINDOW_ID = 'kitty',
680    ALACRITTY_SOCKET = 'alacritty',
681    ALACRITTY_LOG = 'alacritty',
682    WEZTERM_EXECUTABLE = 'wezterm',
683    KONSOLE_VERSION = function()
684      return 'konsole ' .. e.KONSOLE_VERSION
685    end,
686    VTE_VERSION = function()
687      return 'vte ' .. e.VTE_VERSION
688    end,
689  }
690
691  for key, val in pairs(map) do
692    local env = e[key] --- @type string?
693    if env then
694      return type(val) == 'function' and val() or val
695    end
696  end
697
698  return 'unknown'
699end
700
701---@async
702---@param nvim_version string
703local function check_stable_version(nvim_version)
704  local ok, output =
705    system({ 'git', 'ls-remote', '--tags', 'https://github.com/neovim/neovim' }, 5000)
706  if not ok or output == '' then
707    return
708  end
709  local stable_sha = assert(
710    output:match('(%x+)%s+refs/tags/stable%^{}') or output:match('(%x+)%s+refs/tags/stable\n')
711  )
712  local latest_version = assert(output:match(stable_sha .. '%s+refs/tags/v?(%d+%.%d+%.%d+)%^{}'))
713  local current_version = assert(nvim_version:match('v?(%d+%.%d+%.%d+)'))
714  local current = vim.version.parse(current_version)
715  local latest = vim.version.parse(latest_version)
716  if current and latest and vim.version.lt(current, latest) then
717    vim.health.warn(('Nvim %s is available (current: %s)'):format(latest_version, current_version))
718  else
719    vim.health.ok(('Up to date (%s)'):format(current_version))
720  end
721end
722
723---@async
724---@param commit string
725local function check_head_hash(commit)
726  local ok, output = system(
727    { 'git', 'ls-remote', 'https://github.com/neovim/neovim', 'HEAD', 'refs/tags/nightly' },
728    5000
729  )
730  if not ok or output == '' then
731    return
732  end
733
734  local refs = {} ---@type table<string, string?>
735  for line in output:gmatch('[^\n]+') do
736    local sha, ref = line:match('^(%x+)%s+(%S+)$')
737    if sha and ref then
738      refs[ref] = sha
739    end
740  end
741
742  local head_sha = assert(refs['HEAD'])
743  local nightly_sha = refs['refs/tags/nightly']
744
745  if vim.startswith(head_sha, commit) then
746    vim.health.ok('Up to date (HEAD)')
747  elseif nightly_sha and vim.startswith(nightly_sha, commit) then
748    vim.health.ok('Up to date (nightly)')
749  else
750    vim.health.warn(
751      ('Build is outdated. Local: %s, HEAD: %s%s'):format(
752        commit,
753        head_sha:sub(1, 12),
754        nightly_sha and (', Nightly: ' .. nightly_sha:sub(1, 12)) or ''
755      )
756    )
757  end
758end
759
760---@async
761local function check_sysinfo()
762  vim.health.start('System Info')
763
764  -- Use :version because `vim.version().build` returns "Homebrew" for brew installs.
765  local version_out = vim.api.nvim_exec2('version', { output = true }).output --[[@as string]]
766  local nvim_version = version_out:match('NVIM (v[^\n]+)') or 'unknown'
767  local commit = (version_out:match('%+g(%x+)') or ''):sub(1, 12)
768
769  if vim.fn.executable('git') ~= 1 then
770    vim.health.warn('Cannot check for updates: git not found')
771  elseif vim.trim(commit) ~= '' then
772    check_head_hash(commit)
773  else
774    check_stable_version(nvim_version)
775  end
776
777  local os_info = vim.uv.os_uname()
778  local os_string = os_info.sysname .. ' ' .. os_info.release
779  local terminal = detect_terminal()
780  local term_env = vim.env.TERM or 'unknown'
781
782  vim.health.info(('Nvim version: `%s` %s'):format(nvim_version, commit))
783  vim.health.info('Operating system: ' .. os_string)
784  vim.health.info('Terminal: ' .. terminal)
785  vim.health.info('$TERM: ' .. term_env)
786
787  local body = vim.text.indent(
788    0,
789    string.format(
790      [[
791    ## Problem
792
793    Describe the problem (concisely).
794
795    ## Steps to reproduce
796
797    ```
798    nvim --clean
799    ```
800
801    ## Expected behavior
802
803    ## System info
804
805    - Nvim version (nvim -v): `%s` neovim/neovim@%s
806    - Vim (not Nvim) behaves the same?: ?
807    - Operating system/version: %s
808    - Terminal name/version: %s
809    - $TERM environment variable: `%s`
810    - Installation: ?
811
812]],
813      nvim_version,
814      commit,
815      os_string,
816      terminal,
817      term_env
818    )
819  )
820
821  nvim_on('FileType', nil, { pattern = 'checkhealth', once = true }, function(ev)
822    local buf = ev.buf
823    local win = vim.fn.bufwinid(buf)
824    if win == -1 then
825      return
826    end
827    local encoded_body = vim.uri_encode(body) --- @type string
828    local issue_url = 'https://github.com/neovim/neovim/issues/new?type=Bug&body=' .. encoded_body
829
830    --- Opens the prefilled issue from the checkhealth winbar.
831    ---@diagnostic disable-next-line: global-in-non-module
832    _G.nvim_health_bugreport_open = function()
833      vim.ui.open(issue_url)
834    end
835    vim.wo[win].winbar =
836      '%#WarningMsg#%@v:lua.nvim_health_bugreport_open@▶ Create Bug Report on GitHub%X%*'
837
838    vim.api.nvim_create_autocmd('BufDelete', {
839      buf = buf,
840      once = true,
841      command = 'lua _G.nvim_health_bugreport_open = nil',
842    })
843  end)
844end
845
846---@async
847function M.check()
848  check_sysinfo()
849  check_config()
850  check_runtime()
851  check_performance()
852  check_rplugin_manifest()
853  check_terminal()
854  check_tmux()
855  check_external_tools()
856end
857
858return M