health.lua 13 KB

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