robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1-- For "--listen", ":restart", and related remote/server functionality. 2 3local util =require ( 'vim._core.util' ) 4 5local M ={} 6 7--- Called by builtin serverlist(). Returns the combined server list (own + peers). 8--- 9---@class vim.ServerInfo 10---@field addr string Server address (socket path, named pipe, or TCP host:port). 11---@field pid integer PID of the Nvim process. 12---@field own boolean True if this server belongs to the current Nvim instance. 13---@field active integer Timestamp of last user activity. 14 15--- @param opts? table Options: 16--- - opts.peer (boolean): If true, also discover peer servers. 17--- - opts.info (boolean): If true, return a list of |vim.ServerInfo| dicts 18--- instead of a list of addresses. Implies peer=true. 19--- @param addrs string[] Internal ("own") addresses, from server_address_list. 20--- @return string[]|vim.ServerInfo[] 21function M . serverlist ( opts , addrs ) 22if type ( opts ) ~= 'table' then 23return addrs 24end 25 26local want_info =opts . info == true 27if opts . peer ~= true and not want_info then 28return addrs 29end 30 31local seen ={} ---@type table<string, true> 32for _ , a in ipairs ( addrs ) do 33seen [ a ] =true 34end 35 36local peers ---@type string[]|vim.ServerInfo[] 37if want_info then 38local self_pid =vim . fn . getpid () 39local self_active =vim . v . useractive 40peers =vim . tbl_map ( function ( addr ) 41return { 42addr =addr , 43pid =self_pid , 44own =true , 45active =self_active , 46} 47end , addrs ) 48else 49peers =addrs 50end 51 52-- Discover peer servers in stdpath("run"). 53-- TODO: track TCP servers, somehow. 54-- TODO: support Windows named pipes. 55local root =vim . fs . normalize ( vim . fn . stdpath ( 'run' ) .. '/..' ) 56local socket_paths =vim . fs . find ( function ( name , _ ) 57return name : match ( 'nvim.*' ) 58end , { path =root , type ='socket' , limit =math . huge } ) 59 60for _ , socket in ipairs ( socket_paths ) do 61if not seen [ socket ] then 62local ok , chan =pcall ( vim . fn . sockconnect , 'pipe' , socket , { rpc =true } ) 63if ok and chan and chan > 0 then 64--- @cast chan integer 65-- Check that the server is responding 66-- TODO: do we need a timeout or error handling here? 67local ok_rpc , peer_info =pcall ( 68vim . fn . rpcrequest , 69chan , 70'nvim_exec_lua' , 71[[return { pid = vim.fn.getpid(), active = vim.v.useractive, }]] , 72{} 73) 74 75if ok_rpc and type ( peer_info ) == 'table' then 76---@cast peer_info vim.ServerInfo 77seen [ socket ] =true 78if want_info then 79table . insert ( peers , { 80addr =socket , 81pid =peer_info . pid , 82own =false , 83active =peer_info . active , 84} ) 85else 86table . insert ( peers , socket ) 87end 88end 89pcall ( vim . fn . chanclose , chan ) 90end 91end 92end 93 94return peers 95end 96 97-- (Windows only) Canonical --listen address persisted across restarts. 98M . restart_canonical_addr =nil ---@type string? 99 100--- (Windows only) 101--- Called on the new server via nvim_exec_lua RPC from the old server (:restart). 102--- Windows named pipes can't be rebound immediately, so the new server starts on a 103--- temporary bootstrap address and polls until the canonical address is reclaimable. 104--- @param canonical_addr string The original --listen address to reclaim. 105--- @param expected_uis integer Number of UIs expected to reattach (0 = don't wait). 106function M . rebind_after_restart ( canonical_addr , expected_uis ) 107M . restart_canonical_addr =canonical_addr 108local bootstrap_addr =vim . v . servername -- Temporary autogenerated address. 109local poll_ms =50 110local max_wait_ms =30000 111local timer =assert ( vim . uv . new_timer ()) 112 113-- Poll until the canonical address can be reclaimed (or timeout). 114local poll_elapsed =0 115timer : start ( poll_ms , poll_ms , function () 116vim . schedule ( function () 117if timer : is_closing () then 118return 119end 120poll_elapsed =poll_elapsed + poll_ms 121if poll_elapsed >= max_wait_ms then 122timer : stop () 123timer : close () 124return 125end 126if not vim . list_contains ( vim . fn . serverlist (), canonical_addr ) then 127local ok =vim . _with ( { log_level =5 } , function () 128return pcall ( vim . fn . serverstart , canonical_addr ) 129end ) 130if not ok then 131return -- pipe still held by old server; retry next tick 132end 133end 134 135-- Wait for UIs to reattach, then retire the bootstrap address. 136local elapsed =0 137timer : stop () 138timer : start ( poll_ms , poll_ms , function () 139vim . schedule ( function () 140if timer : is_closing () then 141return 142end 143elapsed =elapsed + poll_ms 144local all_uis =expected_uis <= 0 or # vim . api . nvim_list_uis () >= expected_uis 145if all_uis or elapsed >= max_wait_ms then 146if canonical_addr ~= bootstrap_addr then 147vim . _with ( { log_level =5 } , function () 148pcall ( vim . fn . serverstop , bootstrap_addr ) 149end ) 150end 151timer : stop () 152timer : close () 153end 154end ) 155end ) 156end ) 157end ) 158end 159 160-- Called by ex_restart(). Saves the current session and calls ex_restart() (again) with the 161-- updated arguments. 162-- 163-- TODO: https://github.com/neovim/neovim/issues/34204 164-- 165--- @param eap vim._core.ExCmdArgs 166--- @param extra { quit_cmd: string } 167function M . ex_session_restart ( eap , extra ) 168local after_cmd =eap . args -- User-provided [command]. 169assert ( not after_cmd : find ( ']==]' )) 170 171-- Use custom +cmd if given. 172local quit_cmd =extra . quit_cmd == '' and 'qall' or extra . quit_cmd 173 174-- Preserve v:this_session in the restarted Nvim. 175local this_session =vim . v . this_session 176assert ( not this_session : find ( ']==]' )) 177 178-- Nvim temp "root dir": "/tmp/…/nvim.<user>/" 179local tmproot =vim . fs . abspath ( vim . fs . dirname ( vim . fs . dirname ( vim . fn . tempname ()))) 180assert ( not tmproot : find ( ']==]' )) 181local fd , session =vim . uv . fs_mkstemp ( vim . fs . joinpath ( tmproot , 'restart_session_XXXXXX' )) 182if not fd then 183error ( 'Failed to get temporary filename for restart session' ) 184end 185vim . uv . fs_close ( fd ) 186 187-- Write session 188local session_arg =vim . fn . fnameescape ( session ) 189vim . cmd ( '%argdelete' ) 190vim . cmd . mksession { session_arg , bang =true } 191 192-- Lua commands to restore the session and remove the session file 193local after_list ={} 194table . insert ( after_list , ( 'vim.cmd("source %s")' ): format ( session_arg )) 195table . insert ( after_list , ( 'pcall(vim.fs.rm, [==[%s]==])' ): format ( session )) 196table . insert ( after_list , ( 'vim.v.this_session = [==[%s]==]' ): format ( this_session )) 197if after_cmd ~= '' then 198table . insert ( after_list , ( 'vim.cmd([==[%s]==])' ): format ( after_cmd )) 199end 200local after ='lua ' .. table . concat ( after_list , ';' ) 201 202-- Restart Neovim and run our Lua commands 203local success , msg =pcall ( function () 204-- "+:::" dummy prefix tells the C handler that this is actually a non-bang restart. 205-- Then v:startreason (if any) can be preserved. 206vim . cmd . restart { '+:::' , quit_cmd , after , bang =true } 207end ) 208 209if not success then 210--- @cast msg string 211vim . fs . rm ( session , { force =true } ) 212 213-- Trim error message to be equivalent to `:restart!` 214if msg : find ( 'Vim:' ) then 215util . echo_err ( util . cmd_errmsg ( msg )) 216else 217error ( msg ) 218end 219end 220end 221 222return M