health.lua 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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 string if it contains newlines.
  178. ---
  179. --- @param s string
  180. --- @param columns integer
  181. --- @return string
  182. local function indent_after_line1(s, columns)
  183. local lines = vim.split(s, '\n')
  184. local indent = string.rep(' ', columns)
  185. for i = 2, #lines do
  186. lines[i] = indent .. lines[i]
  187. end
  188. return table.concat(lines, '\n')
  189. end
  190. --- Changes ':h clipboard' to ':help |clipboard|'.
  191. ---
  192. --- @param s string
  193. --- @return string
  194. local function help_to_link(s)
  195. return vim.fn.substitute(s, [[\v:h%[elp] ([^|][^"\r\n ]+)]], [[:help |\1|]], [[g]])
  196. end
  197. --- Format a message for a specific report item.
  198. ---
  199. --- @param status string
  200. --- @param msg string
  201. --- @param ... string|string[] Optional advice
  202. --- @return string
  203. local function format_report_message(status, msg, ...)
  204. local output = '- ' .. status
  205. if status ~= '' then
  206. output = output .. ' '
  207. end
  208. output = output .. indent_after_line1(msg, 2)
  209. local varargs = ...
  210. -- Optional parameters
  211. if varargs then
  212. if type(varargs) == 'string' then
  213. varargs = { varargs }
  214. end
  215. output = output .. '\n - ADVICE:'
  216. -- Report each suggestion
  217. for _, v in ipairs(varargs) do
  218. if v then
  219. output = output .. '\n - ' .. indent_after_line1(v, 6) --- @type string
  220. end
  221. end
  222. end
  223. return help_to_link(output)
  224. end
  225. --- @param output string
  226. local function collect_output(output)
  227. vim.list_extend(s_output, vim.split(output, '\n'))
  228. end
  229. --- Starts a new report. Most plugins should call this only once, but if
  230. --- you want different sections to appear in your report, call this once
  231. --- per section.
  232. ---
  233. --- @param name string
  234. function M.start(name)
  235. local input = string.format('\n%s ~', name)
  236. collect_output(input)
  237. end
  238. --- Reports an informational message.
  239. ---
  240. --- @param msg string
  241. function M.info(msg)
  242. local input = format_report_message('', msg)
  243. collect_output(input)
  244. end
  245. --- Reports a "success" message.
  246. ---
  247. --- @param msg string
  248. function M.ok(msg)
  249. local input = format_report_message('OK', msg)
  250. collect_output(input)
  251. end
  252. --- Reports a warning.
  253. ---
  254. --- @param msg string
  255. --- @param ... string|string[] Optional advice
  256. function M.warn(msg, ...)
  257. local input = format_report_message('WARNING', msg, ...)
  258. collect_output(input)
  259. end
  260. --- Reports an error.
  261. ---
  262. --- @param msg string
  263. --- @param ... string|string[] Optional advice
  264. function M.error(msg, ...)
  265. local input = format_report_message('ERROR', msg, ...)
  266. collect_output(input)
  267. end
  268. local path2name = function(path)
  269. if path:match('%.lua$') then
  270. -- Lua: transform "../lua/vim/lsp/health.lua" into "vim.lsp"
  271. -- Get full path, make sure all slashes are '/'
  272. path = vim.fs.normalize(path)
  273. -- Remove everything up to the last /lua/ folder
  274. path = path:gsub('^.*/lua/', '')
  275. -- Remove the filename (health.lua) or (health/init.lua)
  276. path = vim.fs.dirname(path:gsub('/init%.lua$', ''))
  277. -- Change slashes to dots
  278. path = path:gsub('/', '.')
  279. return path
  280. else
  281. -- Vim: transform "../autoload/health/provider.vim" into "provider"
  282. return vim.fn.fnamemodify(path, ':t:r')
  283. end
  284. end
  285. local PATTERNS = { '/autoload/health/*.vim', '/lua/**/**/health.lua', '/lua/**/**/health/init.lua' }
  286. --- :checkhealth completion function used by cmdexpand.c get_healthcheck_names()
  287. M._complete = function()
  288. local unique = vim ---@type table<string,boolean>
  289. ---@param pattern string
  290. .iter(vim.tbl_map(function(pattern)
  291. return vim.tbl_map(path2name, vim.api.nvim_get_runtime_file(pattern, true))
  292. end, PATTERNS))
  293. :flatten()
  294. ---@param t table<string,boolean>
  295. :fold({}, function(t, name)
  296. t[name] = true -- Remove duplicates
  297. return t
  298. end)
  299. -- vim.health is this file, which is not a healthcheck
  300. unique['vim'] = nil
  301. local rv = vim.tbl_keys(unique)
  302. table.sort(rv)
  303. return rv
  304. end
  305. --- Runs the specified healthchecks.
  306. --- Runs all discovered healthchecks if plugin_names is empty.
  307. ---
  308. --- @param mods string command modifiers that affect splitting a window.
  309. --- @param plugin_names string glob of plugin names, split on whitespace. For example, using
  310. --- `:checkhealth vim.* nvim` will healthcheck `vim.lsp`, `vim.treesitter`
  311. --- and `nvim` modules.
  312. function M._check(mods, plugin_names)
  313. local healthchecks = plugin_names == '' and get_healthcheck('*') or get_healthcheck(plugin_names)
  314. local emptybuf = vim.fn.bufnr('$') == 1 and vim.fn.getline(1) == '' and 1 == vim.fn.line('$')
  315. local bufnr = vim.api.nvim_create_buf(true, true)
  316. if
  317. vim.g.health
  318. and type(vim.g.health) == 'table'
  319. and vim.tbl_get(vim.g.health, 'style') == 'float'
  320. then
  321. local max_height = math.floor(vim.o.lines * 0.8)
  322. local max_width = 80
  323. local float_bufnr, float_winid = vim.lsp.util.open_floating_preview({}, '', {
  324. height = max_height,
  325. width = max_width,
  326. offset_x = math.floor((vim.o.columns - max_width) / 2),
  327. offset_y = math.floor((vim.o.lines - max_height) / 2) - 1,
  328. relative = 'editor',
  329. })
  330. vim.api.nvim_set_current_win(float_winid)
  331. vim.bo[float_bufnr].modifiable = true
  332. vim.wo[float_winid].list = false
  333. else
  334. -- When no command modifiers are used:
  335. -- - If the current buffer is empty, open healthcheck directly.
  336. -- - If not specified otherwise open healthcheck in a tab.
  337. local buf_cmd = #mods > 0 and (mods .. ' sbuffer') or emptybuf and 'buffer' or 'tab sbuffer'
  338. vim.cmd(buf_cmd .. ' ' .. bufnr)
  339. end
  340. if vim.fn.bufexists('health://') == 1 then
  341. vim.cmd.bwipe('health://')
  342. end
  343. vim.cmd.file('health://')
  344. vim.cmd.setfiletype('checkhealth')
  345. -- This should only happen when doing `:checkhealth vim`
  346. if next(healthchecks) == nil then
  347. vim.fn.setline(1, 'ERROR: No healthchecks found.')
  348. return
  349. end
  350. vim.cmd.redraw()
  351. vim.print('Running healthchecks...')
  352. for name, value in vim.spairs(healthchecks) do
  353. local func = value[1]
  354. local type = value[2]
  355. s_output = {}
  356. if func == '' then
  357. s_output = {}
  358. M.error('No healthcheck found for "' .. name .. '" plugin.')
  359. end
  360. if type == 'v' then
  361. vim.fn.call(func, {})
  362. else
  363. local f = assert(loadstring(func))
  364. local ok, output = pcall(f) ---@type boolean, string
  365. if not ok then
  366. M.error(
  367. string.format('Failed to run healthcheck for "%s" plugin. Exception:\n%s\n', name, output)
  368. )
  369. end
  370. end
  371. -- in the event the healthcheck doesn't return anything
  372. -- (the plugin author should avoid this possibility)
  373. if next(s_output) == nil then
  374. s_output = {}
  375. M.error('The healthcheck report for "' .. name .. '" plugin is empty.')
  376. end
  377. local header = {
  378. string.rep('=', 78),
  379. -- Example: `foo.health: [ …] require("foo.health").check()`
  380. ('%s: %s%s'):format(name, (' '):rep(76 - name:len() - func:len()), func),
  381. '',
  382. }
  383. -- remove empty line after header from report_start
  384. if s_output[1] == '' then
  385. local tmp = {} ---@type string[]
  386. for i = 2, #s_output do
  387. tmp[#tmp + 1] = s_output[i]
  388. end
  389. s_output = {}
  390. for _, v in ipairs(tmp) do
  391. s_output[#s_output + 1] = v
  392. end
  393. end
  394. s_output[#s_output + 1] = ''
  395. s_output = vim.list_extend(header, s_output)
  396. vim.fn.append(vim.fn.line('$'), s_output)
  397. vim.cmd.redraw()
  398. end
  399. -- Clear the 'Running healthchecks...' message.
  400. vim.cmd.redraw()
  401. vim.print('')
  402. -- Quit with 'q' inside healthcheck buffers.
  403. vim.keymap.set('n', 'q', function()
  404. if not pcall(vim.cmd.close) then
  405. vim.cmd.bdelete()
  406. end
  407. end, { buffer = bufnr, silent = true, noremap = true, nowait = true })
  408. -- Once we're done writing checks, set nomodifiable.
  409. vim.bo[bufnr].modifiable = false
  410. end
  411. return M