health.lua 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. --- @brief
  2. ---<pre>help
  3. --- vim.health is a minimal framework to help users troubleshoot configuration and
  4. --- any other environment conditions that a plugin might care about. Nvim ships
  5. --- with healthchecks for configuration, performance, python support, ruby
  6. --- support, clipboard support, and more.
  7. ---
  8. --- To run all healthchecks, use: >vim
  9. ---
  10. --- :checkhealth
  11. --- <
  12. --- Plugin authors are encouraged to write new healthchecks. |health-dev|
  13. ---
  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. ---
  50. --- *g:health*
  51. --- g:health Dictionary with the following optional keys:
  52. --- - `style` (`'float'|nil`) Set to "float" to display :checkhealth in
  53. --- a floating window instead of the default behavior.
  54. ---
  55. --- Example: >lua
  56. --- vim.g.health = { style = 'float' }
  57. ---
  58. --- --------------------------------------------------------------------------------
  59. --- Create a healthcheck *health-dev*
  60. ---
  61. --- Healthchecks are functions that check the user environment, configuration, or
  62. --- any other prerequisites that a plugin cares about. Nvim ships with
  63. --- healthchecks in:
  64. --- - $VIMRUNTIME/autoload/health/
  65. --- - $VIMRUNTIME/lua/vim/lsp/health.lua
  66. --- - $VIMRUNTIME/lua/vim/treesitter/health.lua
  67. --- - and more...
  68. ---
  69. --- To add a new healthcheck for your own plugin, simply create a "health.lua"
  70. --- module on 'runtimepath' that returns a table with a "check()" function. Then
  71. --- |:checkhealth| will automatically find and invoke the function.
  72. ---
  73. --- For example if your plugin is named "foo", define your healthcheck module at
  74. --- one of these locations (on 'runtimepath'):
  75. --- - lua/foo/health/init.lua
  76. --- - lua/foo/health.lua
  77. ---
  78. --- If your plugin also provides a submodule named "bar" for which you want
  79. --- a separate healthcheck, define the healthcheck at one of these locations:
  80. --- - lua/foo/bar/health/init.lua
  81. --- - lua/foo/bar/health.lua
  82. ---
  83. --- All such health modules must return a Lua table containing a `check()`
  84. --- function.
  85. ---
  86. --- Copy this sample code into `lua/foo/health.lua`, replacing "foo" in the path
  87. --- with your plugin name: >lua
  88. ---
  89. --- local M = {}
  90. ---
  91. --- M.check = function()
  92. --- vim.health.start("foo report")
  93. --- -- make sure setup function parameters are ok
  94. --- if check_setup() then
  95. --- vim.health.ok("Setup is correct")
  96. --- else
  97. --- vim.health.error("Setup is incorrect")
  98. --- end
  99. --- -- do some more checking
  100. --- -- ...
  101. --- end
  102. ---
  103. --- return M
  104. ---</pre>
  105. local M = {}
  106. local s_output = {} ---@type string[]
  107. -- From a path return a list [{name}, {func}, {type}] representing a healthcheck
  108. local function filepath_to_healthcheck(path)
  109. path = vim.fs.normalize(path)
  110. local name --- @type string
  111. local func --- @type string
  112. local filetype --- @type string
  113. if path:find('vim$') then
  114. name = vim.fs.basename(path):gsub('%.vim$', '')
  115. func = 'health#' .. name .. '#check'
  116. filetype = 'v'
  117. else
  118. local subpath = path:gsub('.*/lua/', '')
  119. if vim.fs.basename(subpath) == 'health.lua' then
  120. -- */health.lua
  121. name = vim.fs.dirname(subpath)
  122. else
  123. -- */health/init.lua
  124. name = vim.fs.dirname(vim.fs.dirname(subpath))
  125. end
  126. name = assert(name:gsub('/', '.')) --- @type string
  127. func = 'require("' .. name .. '.health").check()'
  128. filetype = 'l'
  129. end
  130. return { name, func, filetype }
  131. end
  132. --- @param plugin_names string
  133. --- @return table<any,string[]> { {name, func, type}, ... } representing healthchecks
  134. local function get_healthcheck_list(plugin_names)
  135. local healthchecks = {} --- @type table<any,string[]>
  136. local plugin_names_list = vim.split(plugin_names, ' ')
  137. for _, p in pairs(plugin_names_list) do
  138. -- support vim/lsp/health{/init/}.lua as :checkhealth vim.lsp
  139. p = p:gsub('%.', '/')
  140. p = p:gsub('*', '**')
  141. local paths = vim.api.nvim_get_runtime_file('autoload/health/' .. p .. '.vim', true)
  142. vim.list_extend(
  143. paths,
  144. vim.api.nvim_get_runtime_file('lua/**/' .. p .. '/health/init.lua', true)
  145. )
  146. vim.list_extend(paths, vim.api.nvim_get_runtime_file('lua/**/' .. p .. '/health.lua', true))
  147. if vim.tbl_count(paths) == 0 then
  148. healthchecks[#healthchecks + 1] = { p, '', '' } -- healthcheck not found
  149. else
  150. local unique_paths = {} --- @type table<string, boolean>
  151. for _, v in pairs(paths) do
  152. unique_paths[v] = true
  153. end
  154. paths = {}
  155. for k, _ in pairs(unique_paths) do
  156. paths[#paths + 1] = k
  157. end
  158. for _, v in ipairs(paths) do
  159. healthchecks[#healthchecks + 1] = filepath_to_healthcheck(v)
  160. end
  161. end
  162. end
  163. return healthchecks
  164. end
  165. --- @param plugin_names string
  166. --- @return table<string, string[]> {name: [func, type], ..} representing healthchecks
  167. local function get_healthcheck(plugin_names)
  168. local health_list = get_healthcheck_list(plugin_names)
  169. local healthchecks = {} --- @type table<string, string[]>
  170. for _, c in pairs(health_list) do
  171. if c[1] ~= 'vim' then
  172. healthchecks[c[1]] = { c[2], c[3] }
  173. end
  174. end
  175. return healthchecks
  176. end
  177. --- Indents lines *except* line 1 of a multiline string.
  178. ---
  179. --- @param s string
  180. --- @param columns integer
  181. --- @return string
  182. local function indent_after_line1(s, columns)
  183. return (vim.text.indent(columns, s):gsub('^%s+', ''))
  184. end
  185. --- Changes ':h clipboard' to ':help |clipboard|'.
  186. ---
  187. --- @param s string
  188. --- @return string
  189. local function help_to_link(s)
  190. return vim.fn.substitute(s, [[\v:h%[elp] ([^|][^"\r\n ]+)]], [[:help |\1|]], [[g]])
  191. end
  192. --- Format a message for a specific report item.
  193. ---
  194. --- @param status string
  195. --- @param msg string
  196. --- @param ... string|string[] Optional advice
  197. --- @return string
  198. local function format_report_message(status, msg, ...)
  199. local output = '- ' .. status
  200. if status ~= '' then
  201. output = output .. ' '
  202. end
  203. output = output .. indent_after_line1(msg, 2)
  204. local varargs = ...
  205. -- Optional parameters
  206. if varargs then
  207. if type(varargs) == 'string' then
  208. varargs = { varargs }
  209. end
  210. output = output .. '\n - ADVICE:'
  211. -- Report each suggestion
  212. for _, v in ipairs(varargs) do
  213. if v then
  214. output = output .. '\n - ' .. indent_after_line1(v, 6) --- @type string
  215. end
  216. end
  217. end
  218. return help_to_link(output)
  219. end
  220. --- @param output string
  221. local function collect_output(output)
  222. vim.list_extend(s_output, vim.split(output, '\n'))
  223. end
  224. --- Starts a new report. Most plugins should call this only once, but if
  225. --- you want different sections to appear in your report, call this once
  226. --- per section.
  227. ---
  228. --- @param name string
  229. function M.start(name)
  230. local input = string.format('\n%s ~', name)
  231. collect_output(input)
  232. end
  233. --- Reports an informational message.
  234. ---
  235. --- @param msg string
  236. function M.info(msg)
  237. local input = format_report_message('', msg)
  238. collect_output(input)
  239. end
  240. --- Reports a "success" message.
  241. ---
  242. --- @param msg string
  243. function M.ok(msg)
  244. local input = format_report_message('OK', msg)
  245. collect_output(input)
  246. end
  247. --- Reports a warning.
  248. ---
  249. --- @param msg string
  250. --- @param ... string|string[] Optional advice
  251. function M.warn(msg, ...)
  252. local input = format_report_message('WARNING', msg, ...)
  253. collect_output(input)
  254. end
  255. --- Reports an error.
  256. ---
  257. --- @param msg string
  258. --- @param ... string|string[] Optional advice
  259. function M.error(msg, ...)
  260. local input = format_report_message('ERROR', msg, ...)
  261. collect_output(input)
  262. end
  263. local path2name = function(path)
  264. if path:match('%.lua$') then
  265. -- Lua: transform "../lua/vim/lsp/health.lua" into "vim.lsp"
  266. -- Get full path, make sure all slashes are '/'
  267. path = vim.fs.normalize(path)
  268. -- Remove everything up to the last /lua/ folder
  269. path = path:gsub('^.*/lua/', '')
  270. -- Remove the filename (health.lua) or (health/init.lua)
  271. path = vim.fs.dirname(path:gsub('/init%.lua$', ''))
  272. -- Change slashes to dots
  273. path = path:gsub('/', '.')
  274. return path
  275. else
  276. -- Vim: transform "../autoload/health/provider.vim" into "provider"
  277. return vim.fn.fnamemodify(path, ':t:r')
  278. end
  279. end
  280. local PATTERNS = { '/autoload/health/*.vim', '/lua/**/**/health.lua', '/lua/**/**/health/init.lua' }
  281. --- :checkhealth completion function used by cmdexpand.c get_healthcheck_names()
  282. M._complete = function()
  283. local unique = vim ---@type table<string,boolean>
  284. ---@param pattern string
  285. .iter(vim.tbl_map(function(pattern)
  286. return vim.tbl_map(path2name, vim.api.nvim_get_runtime_file(pattern, true))
  287. end, PATTERNS))
  288. :flatten()
  289. ---@param t table<string,boolean>
  290. :fold({}, function(t, name)
  291. t[name] = true -- Remove duplicates
  292. return t
  293. end)
  294. -- vim.health is this file, which is not a healthcheck
  295. unique['vim'] = nil
  296. local rv = vim.tbl_keys(unique)
  297. table.sort(rv)
  298. return rv
  299. end
  300. --- Runs the specified healthchecks.
  301. --- Runs all discovered healthchecks if plugin_names is empty.
  302. ---
  303. --- @param mods string command modifiers that affect splitting a window.
  304. --- @param plugin_names string glob of plugin names, split on whitespace. For example, using
  305. --- `:checkhealth vim.* nvim` will healthcheck `vim.lsp`, `vim.treesitter`
  306. --- and `nvim` modules.
  307. function M._check(mods, plugin_names)
  308. local healthchecks = plugin_names == '' and get_healthcheck('*') or get_healthcheck(plugin_names)
  309. local emptybuf = vim.fn.bufnr('$') == 1 and vim.fn.getline(1) == '' and 1 == vim.fn.line('$')
  310. local bufnr = vim.api.nvim_create_buf(true, true)
  311. if
  312. vim.g.health
  313. and type(vim.g.health) == 'table'
  314. and vim.tbl_get(vim.g.health, 'style') == 'float'
  315. then
  316. local max_height = math.floor(vim.o.lines * 0.8)
  317. local max_width = 80
  318. local float_bufnr, float_winid = vim.lsp.util.open_floating_preview({}, '', {
  319. height = max_height,
  320. width = max_width,
  321. offset_x = math.floor((vim.o.columns - max_width) / 2),
  322. offset_y = math.floor((vim.o.lines - max_height) / 2) - 1,
  323. relative = 'editor',
  324. })
  325. vim.api.nvim_set_current_win(float_winid)
  326. vim.bo[float_bufnr].modifiable = true
  327. vim.wo[float_winid].list = false
  328. else
  329. -- When no command modifiers are used:
  330. -- - If the current buffer is empty, open healthcheck directly.
  331. -- - If not specified otherwise open healthcheck in a tab.
  332. local buf_cmd = #mods > 0 and (mods .. ' sbuffer') or emptybuf and 'buffer' or 'tab sbuffer'
  333. vim.cmd(buf_cmd .. ' ' .. bufnr)
  334. end
  335. if vim.fn.bufexists('health://') == 1 then
  336. vim.cmd.bwipe('health://')
  337. end
  338. vim.cmd.file('health://')
  339. vim.cmd.setfiletype('checkhealth')
  340. -- This should only happen when doing `:checkhealth vim`
  341. if next(healthchecks) == nil then
  342. vim.fn.setline(1, 'ERROR: No healthchecks found.')
  343. return
  344. end
  345. vim.cmd.redraw()
  346. vim.print('Running healthchecks...')
  347. for name, value in vim.spairs(healthchecks) do
  348. local func = value[1]
  349. local type = value[2]
  350. s_output = {}
  351. if func == '' then
  352. s_output = {}
  353. M.error('No healthcheck found for "' .. name .. '" plugin.')
  354. end
  355. if type == 'v' then
  356. vim.fn.call(func, {})
  357. else
  358. local f = assert(loadstring(func))
  359. local ok, output = pcall(f) ---@type boolean, string
  360. if not ok then
  361. M.error(
  362. string.format('Failed to run healthcheck for "%s" plugin. Exception:\n%s\n', name, output)
  363. )
  364. end
  365. end
  366. -- in the event the healthcheck doesn't return anything
  367. -- (the plugin author should avoid this possibility)
  368. if next(s_output) == nil then
  369. s_output = {}
  370. M.error('The healthcheck report for "' .. name .. '" plugin is empty.')
  371. end
  372. local header = {
  373. string.rep('=', 78),
  374. -- Example: `foo.health: [ …] require("foo.health").check()`
  375. ('%s: %s%s'):format(name, (' '):rep(76 - name:len() - func:len()), func),
  376. '',
  377. }
  378. -- remove empty line after header from report_start
  379. if s_output[1] == '' then
  380. local tmp = {} ---@type string[]
  381. for i = 2, #s_output do
  382. tmp[#tmp + 1] = s_output[i]
  383. end
  384. s_output = {}
  385. for _, v in ipairs(tmp) do
  386. s_output[#s_output + 1] = v
  387. end
  388. end
  389. s_output[#s_output + 1] = ''
  390. s_output = vim.list_extend(header, s_output)
  391. vim.fn.append(vim.fn.line('$'), s_output)
  392. vim.cmd.redraw()
  393. end
  394. -- Clear the 'Running healthchecks...' message.
  395. vim.cmd.redraw()
  396. vim.print('')
  397. -- Quit with 'q' inside healthcheck buffers.
  398. vim.keymap.set('n', 'q', function()
  399. if not pcall(vim.cmd.close) then
  400. vim.cmd.bdelete()
  401. end
  402. end, { buffer = bufnr, silent = true, noremap = true, nowait = true })
  403. -- Once we're done writing checks, set nomodifiable.
  404. vim.bo[bufnr].modifiable = false
  405. end
  406. return M