robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
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 ) 130path =vim . fs . abspath ( vim . fs . normalize ( path )) 131local name --- @type string 132local func --- @type string 133local filetype --- @type 'l'|'v' 134if path : find ( 'vim$' ) then 135name =vim . fs . basename ( path ): gsub ( '%.vim$' , '' ) 136func ='health#' .. name .. '#check' 137filetype ='v' 138else 139local rtp_lua =vim 140. iter ( vim . api . nvim_get_runtime_file ( 'lua/' , true )) 141: map ( function ( dir ) 142return vim . fs . abspath ( vim . fs . normalize ( dir )) 143end ) 144: find ( function ( dir ) 145return vim . fs . relpath ( dir , path ) 146end ) 147-- The healthcheck path came from nvim_get_runtime_file(), so a runtime directory must match. 148assert ( 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" 151local subpath =path : gsub ( '^' .. vim . pesc ( rtp_lua ), '' ): gsub ( '^/+' , '' ) 152if vim . fs . basename ( subpath ) == 'health.lua' then 153-- */health.lua 154name =vim . fs . dirname ( subpath ) 155else 156-- */health/init.lua 157name =vim . fs . dirname ( vim . fs . dirname ( subpath )) 158end 159name =name : gsub ( '/' , '.' ) 160 161func ='require("' .. name .. '.health").check()' 162filetype ='l' 163end 164return { 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 ) 170local healthchecks ={} --- @type [string, string, 'l'|'v'|''][] 171local plugin_names_list =vim . split ( plugin_names , ' ' ) 172for _ , p in pairs ( plugin_names_list ) do 173-- support vim/lsp/health{/init/}.lua as :checkhealth vim.lsp 174 175p =p : gsub ( '%.' , '/' ) 176p =p : gsub ( '*' , '**' ) 177 178local paths =vim . api . nvim_get_runtime_file ( 'autoload/health/' .. p .. '.vim' , true ) 179vim . list_extend ( 180paths , 181vim . api . nvim_get_runtime_file ( 'lua/**/' .. p .. '/health/init.lua' , true ) 182) 183vim . list_extend ( paths , vim . api . nvim_get_runtime_file ( 'lua/**/' .. p .. '/health.lua' , true )) 184 185if vim . tbl_count ( paths ) == 0 then 186healthchecks [ # healthchecks + 1 ] ={ p , '' , '' } -- healthcheck not found 187else 188local unique_paths ={} --- @type table<string, boolean> 189for _ , v in pairs ( paths ) do 190unique_paths [ v ] =true 191end 192paths ={} 193for k , _ in pairs ( unique_paths ) do 194paths [ # paths + 1 ] =k 195end 196 197for _ , v in ipairs ( paths ) do 198healthchecks [ # healthchecks + 1 ] =filepath_to_healthcheck ( v ) 199end 200end 201end 202return 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 ) 208local health_list =get_healthcheck_list ( plugin_names ) 209local healthchecks ={} --- @type table<string, [string, 'l'|'v'|'']> 210for _ , c in pairs ( health_list ) do 211if c [ 1 ] ~= 'vim' then 212healthchecks [ c [ 1 ]] ={ c [ 2 ], c [ 3 ] } 213end 214end 215 216return 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 ) 225return ( 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 ) 233return 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 , ... ) 243local output ='- ' .. status 244if status ~= '' then 245output =output .. ' ' 246end 247 248output =output .. indent_after_line1 ( msg , 2 ) 249 250local varargs =... 251 252-- Optional parameters 253if varargs then 254if type ( varargs ) == 'string' then 255varargs ={ varargs } 256end 257 258output =output .. '\n - ADVICE:' 259 260-- Report each suggestion 261for _ , v in ipairs ( varargs ) do 262if v then 263output =output .. '\n - ' .. indent_after_line1 ( v , 6 ) --- @type string 264end 265end 266end 267 268return help_to_link ( output ) 269end 270 271--- @param output string 272local function collect_output ( output ) 273vim . 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 ) 282local input =string . format ( '\n%s ~' , name ) 283collect_output ( input ) 284end 285 286--- Reports an informational message. 287--- 288--- @param msg string 289function M . info ( msg ) 290local input =format_report_message ( '' , msg ) 291collect_output ( input ) 292end 293 294--- Reports a "success" message. 295--- 296--- @param msg string 297function M . ok ( msg ) 298local input =format_report_message ( '✅ OK' , msg ) 299collect_output ( input ) 300end 301 302--- Reports a warning. 303--- 304--- @param msg string 305--- @param ... string|string[] Optional advice 306function M . warn ( msg , ... ) 307local input =format_report_message ( '⚠️ WARNING' , msg , ... ) 308collect_output ( input ) 309check_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 , ... ) 317local input =format_report_message ( '❌ ERROR' , msg , ... ) 318collect_output ( input ) 319check_summary [ 'error' ] =check_summary [ 'error' ] + 1 320end 321 322---@param path string 323---@return string 324local path2name =function ( path ) 325if 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 '/' 329path =vim . fs . normalize ( path ) 330 331-- Remove everything up to the last /lua/ folder 332path =path : gsub ( '^.*/lua/' , '' ) 333 334-- Remove the filename (health.lua) or (health/init.lua) 335path =vim . fs . dirname ( path : gsub ( '/init%.lua$' , '' )) 336 337-- Change slashes to dots 338path =path : gsub ( '/' , '.' ) 339 340return path 341else 342-- Vim: transform "../autoload/health/provider.vim" into "provider" 343return vim . fn . fnamemodify ( path , ':t:r' ) 344end 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> 351local unique =vim 352. iter ( vim . tbl_map ( function ( pattern ) 353return vim . tbl_map ( path2name , vim . api . nvim_get_runtime_file ( pattern , true )) 354end , PATTERNS )) 355: flatten () 356: fold ( {} , function ( t , name ) 357t [ name ] =true -- Remove duplicates 358return t 359end ) 360-- vim.health is this file, which is not a healthcheck 361unique [ 'vim' ] =nil 362local rv =vim . tbl_keys ( unique ) 363table . sort ( rv ) 364return rv 365end 366 367--- Gets the results heading for the current report section. 368--- 369---@return string 370local function get_summary () 371local s ='' 372local errors =check_summary [ 'error' ] 373local warns =check_summary [ 'warn' ] 374 375s =s .. ( warns > 0 and ( ' %2d ⚠️' ): format ( warns ) or '' ) 376s =s .. ( errors > 0 and ( ' %2d ❌' ): format ( errors ) or '' ) 377if errors == 0 and warns == 0 then 378s =s .. '✅' 379end 380 381return 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 ) 388local progress ={ kind ='progress' , source ='vim.health' , title ='checkhealth' } 389 390return function ( status , idx , fmt , ... ) 391progress . status =status 392local progress_percent =idx and math . floor ( idx / len * 100 ) or nil 393progress . percent =status == 'success' and nil or progress_percent 394progress . id =vim . api . nvim_echo ( { { fmt : format ( ... ) } } , false , progress ) 395vim . cmd . redraw () 396end 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 ) 406local plugin_names =eap . args 407local smods =eap . smods 408local healthchecks =plugin_names == '' and get_healthcheck ( '*' ) or get_healthcheck ( plugin_names ) 409 410local emptybuf =vim . fn . bufnr ( '$' ) == 1 and vim . fn . getline ( 1 ) == '' and 1 == vim . fn . line ( '$' ) 411 412local bufnr ---@type integer 413if vim . tbl_get ( vim . g , 'health' , 'style' ) == 'float' then 414local available_lines =vim . o . lines - 12 415local max_height =math . min ( math . floor ( vim . o . lines * 0.8 ), available_lines ) 416local max_width =80 417local float_winid 418bufnr , float_winid =vim . lsp . util . open_floating_preview ( {} , '' , { 419height =max_height , 420width =max_width , 421offset_x =math . floor (( vim . o . columns - max_width ) / 2 ), 422offset_y =math . floor (( available_lines - max_height ) / 2 ), 423relative ='editor' , 424close_events ={} , 425} ) 426vim . api . nvim_set_current_win ( float_winid ) 427vim . wo [ float_winid ]. list =false 428else 429bufnr =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. 433local has_mods =smods . tab > 0 or smods . split ~= '' or smods . horizontal or smods . vertical 434if has_mods then 435vim . cmd . sbuffer { bufnr , mods =smods } 436elseif emptybuf then 437vim . cmd . buffer ( bufnr ) 438else 439vim . cmd . sbuffer { bufnr , mods ={ tab =vim . api . nvim_tabpage_get_number ( 0 ) } } 440end 441end 442vim . bo [ bufnr ]. modifiable =true 443 444if vim . fn . bufexists ( 'health://' ) == 1 then 445vim . cmd . bwipe ( 'health://' ) 446end 447vim . cmd . file ( 'health://' ) 448 449-- This should only happen when doing `:checkhealth vim` 450if next ( healthchecks ) == nil then 451vim . fn . setline ( 1 , 'ERROR: No healthchecks found.' ) 452return 453end 454 455-- Show nvim-owned first (`vim.*`, `runtime/lua/vim/**/health.lua`). 456local names =vim . tbl_keys ( healthchecks ) --- @type string[] 457table . sort ( names , function ( a , b ) 458local a_nvim =vim . startswith ( a , 'vim.' ) 459local b_nvim =vim . startswith ( b , 'vim.' ) 460if a_nvim ~= b_nvim then 461return a_nvim 462end 463return a < b 464end ) 465 466local task --- @type vim.async.Task<nil> 467 468-- Quit with 'q' inside healthcheck buffers. 469vim . _with ( { buf =bufnr } , function () 470if 471vim . tbl_get ( vim . g , 'health' , 'style' ) == 'float' 472or vim . fn . maparg ( 'q' , 'n' , false , false ) == '' 473then 474vim . keymap . set ( 'n' , 'q' , function () 475task : close () 476if not pcall ( vim . cmd . close ) then 477vim . cmd . bdelete () 478end 479end , { buf =bufnr , silent =true , noremap =true , nowait =true } ) 480end 481end ) 482 483task =async . run ( 'checkhealth' , function () 484local total_checks =# names 485local progress_msg =progress_report ( total_checks ) 486local check_idx =1 487for _ , name in ipairs ( names ) do 488local value =healthchecks [ name ] 489progress_msg ( 'running' , check_idx , 'checking %s' , name ) 490local func =value [ 1 ] 491local type =value [ 2 ] 492s_output ={} 493check_summary ={ warn =0 , error =0 } 494 495if func == '' then 496M . error ( 'No healthcheck found for "' .. name .. '" plugin.' ) 497end 498if type == 'v' then 499vim . fn . call ( func , {} ) 500else 501local f =assert ( loadstring ( func )) 502--- @diagnostic disable-next-line: assign-type-mismatch 503local ok , output =async . pawait ( async . run ( name , f )) ---@type boolean, string 504async . await ( vim . schedule ) 505if not ok then 506M . error ( 507string . format ( 508'Failed to run healthcheck for "%s" plugin. Exception:\n%s\n' , 509name , 510output 511) 512) 513end 514end 515-- in the event the healthcheck doesn't return anything 516-- (the plugin author should avoid this possibility) 517if next ( s_output ) == nil then 518s_output ={} 519M . error ( 'The healthcheck report for "' .. name .. '" plugin is empty.' ) 520end 521 522local report =get_summary () 523local replen =vim . fn . strwidth ( report ) 524local header ={ 525string . 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 532if s_output [ 1 ] == '' then 533local tmp ={} ---@type string[] 534for i =2 , # s_output do 535tmp [ # tmp + 1 ] =s_output [ i ] 536end 537s_output ={} 538for _ , v in ipairs ( tmp ) do 539s_output [ # s_output + 1 ] =v 540end 541end 542s_output [ # s_output + 1 ] ='' 543s_output =vim . list_extend ( header , s_output ) 544 545if not vim . api . nvim_buf_is_valid ( bufnr ) then 546return 547end 548vim . api . nvim_buf_set_lines ( bufnr , check_idx == 1 and 0 or - 1 , - 1 , true , s_output ) 549 550check_idx =check_idx + 1 551end 552 553progress_msg ( 'success' , nil , 'checks done' ) 554 555if not vim . api . nvim_buf_is_valid ( bufnr ) then 556return 557end 558-- Once we're done writing checks, set nomodifiable. 559vim . bo [ bufnr ]. modifiable =false 560vim . _with ( { buf =bufnr } , function () 561vim . cmd . setfiletype ( 'checkhealth' ) 562end ) 563end ) 564 565local cancel_autocmd =vim . api . nvim_create_autocmd ( 'BufUnload' , { 566buffer =bufnr , 567once =true , 568callback =function () 569task : close () 570end , 571} ) 572task : on_complete ( function ( err ) 573pcall ( vim . api . nvim_del_autocmd , cancel_autocmd ) 574if err and err ~= 'closed' then 575error ( task : traceback ( err ), 0 ) 576end 577end ) 578end 579 580return M