robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
8.2 KiB224 linesraw
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 = {
13  cquit = true,
14  exit = true,
15  quit = true,
16  quitall = true,
17  restart = true,
18  view = true,
19  visual = true,
20  wq = true,
21  wqall = true,
22  xall = true,
23  xit = 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()
36  local lines = io.lines()
37  local getline = function()
38    local line = lines()
39    -- Strip trailing CR so CRLF input (e.g. Windows pipes) works like LF.
40    return line and (line:gsub('\r$', '')) or nil
41  end
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?
51  while vim._core.ex_docmd(getline) do
52    vim.wait(0) -- Run pending events (vim.schedule() callbacks, RPC).
53  end
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.
64  local ok, p = pcall(api.nvim_parse_cmd, assert(lines[1]), {})
65  if ok and (p.cmd == 'append' or p.cmd == 'insert' or p.cmd == 'change') then
66    return vim.list_contains({ unpack(lines, 2) }, '.')
67  end
68
69  local feed = { 'if v:false' }
70  vim.list_extend(feed, lines)
71  feed[#feed + 1] = 'endif'
72  local i = 0
73  local complete = true
74  -- Silenced: probing an incomplete block emits e.g. E126/E990 when the reader hits EOF.
75  vim._with({ silent = true, emsg_silent = true }, function()
76    vim._core.ex_docmd(function()
77      i = i + 1
78      if i > #feed then
79        complete = false
80        return nil
81      end
82      return feed[i]
83    end)
84  end)
85  return complete
86end
87
88--- Ex-mode 'statuscolumn': ":", or blank for continuation lines (`:func` body, `:append` text, …).
89function M._statuscolumn()
90  return 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()
97  local cmdwin = require('vim._core.cmdwin')
98  local caller = api.nvim_get_current_win()
99  cmdwin.open(':')
100  if api.nvim_get_current_win() == caller then
101    return -- cmdwin failed to open (E1292 already echoed).
102  end
103  local buf = api.nvim_get_current_buf()
104  api.nvim_buf_set_name(buf, N_('[Ex mode]'))
105  local block_start = api.nvim_buf_line_count(buf)
106  cont_lines = {}
107  vim.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
112  local function put(out, text)
113    for _, l in ipairs(vim.split(text, '\n', { trimempty = true })) do
114      out[#out + 1] = '" ' .. l
115    end
116  end
117
118  api.nvim_echo({ { N_('Entering Ex mode.  Type "visual" to go to Normal mode.') } }, true, {})
119
120  local function run()
121    if not api.nvim_win_is_valid(caller) then
122      cmdwin._cleanup() -- Caller window is gone: end Ex mode.
123      return
124    end
125    local line = api.nvim_get_current_line()
126    local lnum = api.nvim_win_get_cursor(0)[1]
127    if lnum >= block_start then
128      -- Multiline commands: collect continuation lines until the block is complete.
129      local block = api.nvim_buf_get_lines(buf, block_start - 1, lnum, false)
130      if not block_complete(block) then
131        cont_lines[lnum + 1] = true -- Mark the continuation line.
132        api.nvim_buf_set_lines(buf, lnum, lnum, false, { '' })
133        api.nvim_win_set_cursor(0, { lnum + 1, 0 })
134        return
135      end
136      line = table.concat(block, '\n')
137    end
138    local parse_ok, parsed = pcall(api.nvim_parse_cmd, assert(line:match('^[^\n]*')), {})
139    if parse_ok and not line:find('\n') and exit_cmds[parsed.cmd] then
140      vim.fn.histadd('cmd', line)
141      cmdwin._cleanup() -- Focuses the caller window.
142      vim.cmd.stopinsert()
143      if parsed.cmd ~= 'visual' and parsed.cmd ~= 'view' or #parsed.args > 0 then
144        --- @type boolean, string?
145        local ok, err = pcall(vim.cmd --[[@as function]], line) -- May exit Nvim.
146        if not ok then
147          util.echo_err(util.cmd_errmsg(tostring(err)))
148        end
149      end
150      return
151    end
152
153    local out = {} --- @type string[]
154    local prev_lnum = api.nvim_win_get_cursor(caller)[1]
155    local prev_tick = vim.b[api.nvim_win_get_buf(caller)].changedtick
156    if line == '' then
157      -- Empty line: advance one line (POSIX ex "+"); auto-print below shows it.
158      if prev_lnum >= api.nvim_buf_line_count(api.nvim_win_get_buf(caller)) then
159        put(out, N_('E501: At end-of-file'))
160      else
161        api.nvim_win_set_cursor(caller, { prev_lnum + 1, 0 })
162      end
163    else
164      local ok, res = pcall(api.nvim_win_call, caller, function()
165        return api.nvim_exec2(line, { output = true })
166      end)
167      if ok then
168        put(out, res.output)
169      else
170        put(out, util.cmd_errmsg(tostring(res)))
171      end
172      vim.fn.histadd('cmd', line)
173    end
174
175    if 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.
178      local wins = vim.tbl_filter(
179        --- @param w integer
180        function(w)
181          return api.nvim_win_get_buf(w) ~= buf
182        end,
183        api.nvim_list_wins()
184      )
185      if #wins == 0 then
186        vim.cmd.quit() -- Only the cmdwin is left: exit.
187        return
188      end
189      caller = assert(wins[1])
190    end
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).
194    local typed_text = parse_ok
195      and (parsed.cmd == 'append' or parsed.cmd == 'insert' or parsed.cmd == 'change')
196    local cbuf = api.nvim_win_get_buf(caller)
197    local cur = api.nvim_win_get_cursor(caller)[1]
198    if
199      #out == 0
200      and not typed_text
201      -- Bare range (":1") prints even when the cursor is already on line 1.
202      and (
203        (parse_ok and parsed.cmd == '')
204        or cur ~= prev_lnum
205        or vim.b[cbuf].changedtick ~= prev_tick
206      )
207    then
208      put(out, api.nvim_buf_get_lines(cbuf, cur - 1, cur, false)[1] or '')
209    end
210
211    -- Keep-open: record the transcript and park the cursor on a fresh last line.
212    out[#out + 1] = ''
213    api.nvim_buf_set_lines(buf, -1, -1, false, out)
214    block_start = api.nvim_buf_line_count(buf)
215    api.nvim_win_set_cursor(0, { block_start, 0 })
216  end
217
218  vim.keymap.set({ 'n', 'i' }, '<CR>', run, { buffer = buf })
219  vim.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.
221  api.nvim_feedkeys('i', 'ni', false)
222end
223
224return M