robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1--- Ex mode. 2--- - `run()`: non-interactive (`nvim -es`): executes stdin as Ex commands. 3--- - `open()`: interactive (`[count]q:`, `nvim -e`), a keep-open "cmdwin" REPL. 4 5local api =vim . api 6local N_ =vim . fn . gettext 7local util =require ( 'vim._core.util' ) 8 9local M ={} 10 11--- Commands that end Ex mode before executing (in the caller window). 12local exit_cmds ={ 13cquit =true , 14exit =true , 15quit =true , 16quitall =true , 17restart =true , 18view =true , 19visual =true , 20wq =true , 21wqall =true , 22xall =true , 23xit =true , 24} 25 26--- Continuation lines (of a multiline cmd), for the statuscolumn. 27--- @type table<integer, true> 28local cont_lines ={} 29 30--- Non-interactive "script mode" ("nvim -es", fka "Ex-mode", but POSIX behavior was dropped): 31--- Executes stdin as Ex commands, until EOF. 32--- 33--- Stdin is not consumed as typeahead: fd 0 is read directly (`io.lines()`), so `:lua` script lines 34--- can also read stdin as data via `io.read()`. 35function M . run () 36local lines =io . lines () 37local getline =function () 38local line =lines () 39-- Strip trailing CR so CRLF input (e.g. Windows pipes) works like LF. 40return line and ( line : gsub ( '\r$' , '' )) or nil 41end 42-- Instead of per-line `nvim_exec2`, this runs one `do_cmdline` per logical command with 43-- `getline` as the line-getter, in order to preserve these behaviors: 44-- - :append/:function/:if/heredocs pull continuation lines from stdin. #7679 45-- - Errors are emitted, not thrown (nvim_exec2 turns the first error into an exception): 46-- execution continues with the next command, `ex_exitval` still sets the exit code, and 47-- "-V1" shows errors on stderr. 48-- - Output (:print, :set, …) to stdout as each command executes. 49-- 50-- TODO: could enhance nvim_exec2 instead? 51while vim . _core . ex_docmd ( getline ) do 52vim . wait ( 0 ) -- Run pending events (vim.schedule() callbacks, RPC). 53end 54end 55 56--- Whether `lines` form a complete command block: no `:append` text, `:function` body, heredoc, or 57--- :if/:while/:for/:try block is awaiting continuation lines. Feeds the lines to do_cmdline(), 58--- which groups multiline constructs even when skipping (false `:if`), without executing anything. 59--- If the construct is still open it consumes the sentinel "endif" and asks the getter for more. 60--- @param lines string[] 61--- @return boolean 62local function block_complete ( lines ) 63-- :append/etc. not grouped by the skipped-:if below: collect until the "." terminator. 64local ok , p =pcall ( api . nvim_parse_cmd , assert ( lines [ 1 ]), {} ) 65if ok and ( p . cmd == 'append' or p . cmd == 'insert' or p . cmd == 'change' ) then 66return vim . list_contains ( { unpack ( lines , 2 ) } , '.' ) 67end 68 69local feed ={ 'if v:false' } 70vim . list_extend ( feed , lines ) 71feed [ # feed + 1 ] ='endif' 72local i =0 73local complete =true 74-- Silenced: probing an incomplete block emits e.g. E126/E990 when the reader hits EOF. 75vim . _with ( { silent =true , emsg_silent =true } , function () 76vim . _core . ex_docmd ( function () 77i =i + 1 78if i > # feed then 79complete =false 80return nil 81end 82return feed [ i ] 83end ) 84end ) 85return complete 86end 87 88--- Ex-mode 'statuscolumn': ":", or blank for continuation lines (`:func` body, `:append` text, …). 89function M . _statuscolumn () 90return cont_lines [ vim . v . lnum ] and ' ' or ':' 91end 92 93--- Interactive Ex-mode: keep-open cmdwin REPL. `<CR>` executes the current line against the caller 94--- window and keeps the cmdwin open; command output is presented as comment ('"') lines. Multiline 95--- commands (`:append`, etc.) are collected until the block is complete. 96function M . open () 97local cmdwin =require ( 'vim._core.cmdwin' ) 98local caller =api . nvim_get_current_win () 99cmdwin . open ( ':' ) 100if api . nvim_get_current_win () == caller then 101return -- cmdwin failed to open (E1292 already echoed). 102end 103local buf =api . nvim_get_current_buf () 104api . nvim_buf_set_name ( buf , N_ ( '[Ex mode]' )) 105local block_start =api . nvim_buf_line_count ( buf ) 106cont_lines ={} 107vim . wo [ 0 ][ 0 ]. statuscolumn ='%#NonText#%{v:lua.require("vim._core.exmode")._statuscolumn()}' 108 109--- Formats `text` (possibly multiline) as transcript comment lines. 110--- @param out string[] 111--- @param text string 112local function put ( out , text ) 113for _ , l in ipairs ( vim . split ( text , '\n' , { trimempty =true } )) do 114out [ # out + 1 ] ='" ' .. l 115end 116end 117 118api . nvim_echo ( { { N_ ( 'Entering Ex mode. Type "visual" to go to Normal mode.' ) } } , true , {} ) 119 120local function run () 121if not api . nvim_win_is_valid ( caller ) then 122cmdwin . _cleanup () -- Caller window is gone: end Ex mode. 123return 124end 125local line =api . nvim_get_current_line () 126local lnum =api . nvim_win_get_cursor ( 0 )[ 1 ] 127if lnum >= block_start then 128-- Multiline commands: collect continuation lines until the block is complete. 129local block =api . nvim_buf_get_lines ( buf , block_start - 1 , lnum , false ) 130if not block_complete ( block ) then 131cont_lines [ lnum + 1 ] =true -- Mark the continuation line. 132api . nvim_buf_set_lines ( buf , lnum , lnum , false , { '' } ) 133api . nvim_win_set_cursor ( 0 , { lnum + 1 , 0 } ) 134return 135end 136line =table . concat ( block , '\n' ) 137end 138local parse_ok , parsed =pcall ( api . nvim_parse_cmd , assert ( line : match ( '^[^\n]*' )), {} ) 139if parse_ok and not line : find ( '\n' ) and exit_cmds [ parsed . cmd ] then 140vim . fn . histadd ( 'cmd' , line ) 141cmdwin . _cleanup () -- Focuses the caller window. 142vim . cmd . stopinsert () 143if parsed . cmd ~= 'visual' and parsed . cmd ~= 'view' or # parsed . args > 0 then 144--- @type boolean, string? 145local ok , err =pcall ( vim . cmd --[[@as function]] , line ) -- May exit Nvim. 146if not ok then 147util . echo_err ( util . cmd_errmsg ( tostring ( err ))) 148end 149end 150return 151end 152 153local out ={} --- @type string[] 154local prev_lnum =api . nvim_win_get_cursor ( caller )[ 1 ] 155local prev_tick =vim . b [ api . nvim_win_get_buf ( caller )]. changedtick 156if line == '' then 157-- Empty line: advance one line (POSIX ex "+"); auto-print below shows it. 158if prev_lnum >= api . nvim_buf_line_count ( api . nvim_win_get_buf ( caller )) then 159put ( out , N_ ( 'E501: At end-of-file' )) 160else 161api . nvim_win_set_cursor ( caller , { prev_lnum + 1 , 0 } ) 162end 163else 164local ok , res =pcall ( api . nvim_win_call , caller , function () 165return api . nvim_exec2 ( line , { output =true } ) 166end ) 167if ok then 168put ( out , res . output ) 169else 170put ( out , util . cmd_errmsg ( tostring ( res ))) 171end 172vim . fn . histadd ( 'cmd' , line ) 173end 174 175if not api . nvim_win_is_valid ( caller ) then 176-- The command closed the caller window (e.g. ":close"): continue Ex mode against a 177-- remaining window, or end it. 178local wins =vim . tbl_filter ( 179--- @param w integer 180function ( w ) 181return api . nvim_win_get_buf ( w ) ~= buf 182end , 183api . nvim_list_wins () 184) 185if # wins == 0 then 186vim . cmd . quit () -- Only the cmdwin is left: exit. 187return 188end 189caller =assert ( wins [ 1 ]) 190end 191 192-- Ex-mode feature: auto-print the current line after a cursor move or buffer change, unless the 193-- cmd already printed something (e.g. ":5,6print" should not redundantly auto-print). 194local typed_text =parse_ok 195and ( parsed . cmd == 'append' or parsed . cmd == 'insert' or parsed . cmd == 'change' ) 196local cbuf =api . nvim_win_get_buf ( caller ) 197local cur =api . nvim_win_get_cursor ( caller )[ 1 ] 198if 199# out == 0 200and not typed_text 201-- Bare range (":1") prints even when the cursor is already on line 1. 202and ( 203( parse_ok and parsed . cmd == '' ) 204or cur ~= prev_lnum 205or vim . b [ cbuf ]. changedtick ~= prev_tick 206) 207then 208put ( out , api . nvim_buf_get_lines ( cbuf , cur - 1 , cur , false )[ 1 ] or '' ) 209end 210 211-- Keep-open: record the transcript and park the cursor on a fresh last line. 212out [ # out + 1 ] ='' 213api . nvim_buf_set_lines ( buf , - 1 , - 1 , false , out ) 214block_start =api . nvim_buf_line_count ( buf ) 215api . nvim_win_set_cursor ( 0 , { block_start , 0 } ) 216end 217 218vim . keymap . set ( { 'n' , 'i' } , '<CR>' , run , { buffer =buf } ) 219vim . keymap . set ( { 'n' , 'i' } , '<NL>' , run , { buffer =buf } ) 220-- Enter Insert mode before any already-typed keys, so `1q:cmd<CR>` types "cmd" into the REPL. 221api . nvim_feedkeys ( 'i' , 'ni' , false ) 222end 223 224return M