robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
6.4 KiB206 linesraw
1--- @brief Command-line window (q:, q/, q?, c_CTRL-F).
2---
3--- Implements cmdwin as a normal window+buffer, instead of the legacy nested `state_enter` loop.
4--- - On confirm, curline is fed back through the cmdline via |nvim_feedkeys()|.
5--- - On cancel, curline is pre-filled in the ":" cmdline.
6
7local M = {}
8
9--- @class vim._core.cmdwin.State
10--- @field type ':'|'/'|'?'
11--- @field win integer   cmdwin window id
12--- @field buf integer   cmdwin buffer id
13--- @field caller_win integer  Window to return-to on close
14
15--- @type vim._core.cmdwin.State?
16local state = nil
17
18--- @type table<string, boolean>
19local cmdwin_types = { [':'] = true, ['/'] = true, ['?'] = true }
20
21--- Fills the cmdwin buffer with the cmdline history.
22--- @return boolean filled  Whether any lines were written.
23--- @param buf integer
24--- @param type ':'|'/'|'?'
25local function fill_history(buf, type)
26  local histname = type == ':' and 'cmd' or 'search'
27  local n = vim.fn.histnr(histname)
28  if n <= 0 then -- May be -1 if history is empty.
29    return false
30  end
31  local lines = {} --- @type string[]
32  for i = 1, n do
33    local h = vim.fn.histget(histname, i)
34    if h ~= '' then
35      -- One cmdwin line = one cmdline. Entry may have embedded newlines (e.g. via feedkeys or :execute).
36      lines[#lines + 1] = (h:gsub('\n', '\0'))
37    end
38  end
39  if #lines == 0 then
40    return false
41  end
42  vim.api.nvim_buf_set_lines(buf, 0, -1, false, lines)
43  return true
44end
45
46--- Open the command-line window.
47---
48--- @param type? ':'|'/'|'?' Default ':'.
49--- @param init_line? string  Pre-fill the last line (the "live" cmdline).
50--- @param init_col? integer  1-based cursor column in the last line.
51function M.open(type, init_line, init_col)
52  type = type or ':'
53  assert(cmdwin_types[type], 'cmdwin: unknown type: ' .. tostring(type))
54  if state ~= nil then
55    vim.api.nvim_echo(
56      { { 'E1292: Command-line window is already open', 'ErrorMsg' } },
57      true,
58      { err = true }
59    )
60    return
61  end
62
63  local caller = vim.api.nvim_get_current_win()
64
65  -- Split a horizontal window at the bottom, sized by 'cmdwinheight'.
66  local ok, err = pcall(function()
67    vim.cmd(('botright %dnew'):format(vim.o.cmdwinheight))
68  end)
69  if not ok then
70    vim.api.nvim_echo({ { tostring(err), 'ErrorMsg' } }, true, { err = true })
71    return
72  end
73  local win = vim.api.nvim_get_current_win()
74  local buf = vim.api.nvim_get_current_buf()
75
76  vim.bo[buf].buftype = 'nofile'
77  vim.bo[buf].bufhidden = 'wipe'
78  vim.bo[buf].swapfile = false
79  vim.bo[buf].buflisted = true -- #40431
80  vim.wo[win][0].foldenable = false
81  vim.wo[win][0].scrollbind = false
82  -- Show cmdwin-char via 'statuscolumn'.
83  vim.wo[win][0].statuscolumn = '%#NonText#' .. type
84
85  local filled = fill_history(buf, type)
86  init_line = init_line and init_line:gsub('\n', '\0') or ''
87
88  -- Append the in-flight cmdline as the last line (or only line if history is empty).
89  vim.api.nvim_buf_set_lines(buf, filled and -1 or 0, -1, false, { init_line })
90  local last = vim.api.nvim_buf_line_count(buf)
91  vim.api.nvim_win_set_cursor(win, { last, math.max(0, (init_col or 1) - 1) })
92
93  pcall(vim.api.nvim_buf_set_name, buf, '[Command Line]')
94  if type == ':' then
95    vim.bo[buf].filetype = 'vim'
96  end
97
98  if vim.o.wildchar == ('\t'):byte() then
99    vim.keymap.set('i', '<Tab>', '<C-X><C-V>', { buf = buf })
100    vim.keymap.set('n', '<Tab>', 'a<C-X><C-V>', { buf = buf })
101  end
102
103  vim.api.nvim__cmdwin_set(type, buf) -- Update the C-side globals.
104
105  state = {
106    type = type,
107    win = win,
108    buf = buf,
109    caller_win = caller,
110  }
111
112  -- Clean up when the (last-visible) cmdwin is closed by other means (`:q`, `:close`, etc.).
113  vim.api.nvim_create_autocmd({ 'WinClosed' }, {
114    buffer = buf,
115    nested = true,
116    callback = function(ev)
117      if state == nil then
118        return
119      end
120      local closing = tonumber(ev.match)
121      for _, w in ipairs(vim.fn.win_findbuf(buf)) do
122        if w ~= closing then
123          return -- Still visible elsewhere; keep cmdwin (and this autocmd) active.
124        end
125      end
126      M._cleanup()
127      return true -- Last cmdwin window gone; delete this autocmd.
128    end,
129  })
130
131  -- Clean up when the cmdwin is swapped to another buffer
132  vim.api.nvim_create_autocmd({ 'BufWinLeave' }, {
133    buffer = buf,
134    nested = true,
135    callback = function()
136      if state == nil then
137        return
138      end
139      -- We're the last cmdwin buffer (see BufWinLeave), so cleanup.
140      -- But don't delete the buffer, as the BufWinLeave code handles it.
141      M._cleanup { delbuf = false }
142      return true
143    end,
144  })
145
146  vim.api.nvim_exec_autocmds('CmdwinEnter', { pattern = type, modeline = false })
147end
148
149--- @private
150--- @param opts? {delbuf?: boolean}
151function M._cleanup(opts)
152  if state == nil then
153    return
154  end
155  local s = state
156  state = nil
157  pcall(vim.api.nvim__cmdwin_set, '', 0) -- Clear the C-side globals.
158  pcall(vim.api.nvim_exec_autocmds, 'CmdwinLeave', { pattern = s.type, modeline = false })
159  if (opts == nil or opts.delbuf ~= false) and vim.api.nvim_buf_is_valid(s.buf) then
160    pcall(vim.api.nvim_buf_delete, s.buf, { force = true })
161  end
162  -- Only return to caller_win for the current tabpage; avoid changing the current tab during an autocmd.
163  if
164    vim.api.nvim_win_is_valid(s.caller_win)
165    and vim.api.nvim_win_get_tabpage(s.caller_win) == vim.api.nvim_get_current_tabpage()
166  then
167    pcall(vim.api.nvim_set_current_win, s.caller_win)
168  end
169end
170
171--- cmdwin window, or nil if not open.
172--- @return integer?
173function M.win()
174  return state and vim.api.nvim_win_is_valid(state.win) and state.win or nil
175end
176
177--- Closes the cmdwin and returns its current line and type.
178--- @return string line, ':'|'/'|'?' type
179local function _close()
180  local line = vim.api.nvim_get_current_line()
181  local type = assert(state).type
182  M._cleanup()
183  return line, type
184end
185
186--- Confirm and execute the current line as a cmdline.
187function M.confirm()
188  if state == nil then -- Not in cmdwin (closed already?).
189    return
190  end
191  local line, type = _close()
192  line = line:gsub('%z', '\n'):gsub('(%c)', '\022%1') -- Escape control characters.
193  vim.api.nvim_feedkeys(type .. line .. '\r', 'nt', true)
194end
195
196--- Cancel: close the cmdwin and re-enter cmdline mode with the line pre-filled (no execute).
197function M.cancel()
198  if state == nil then -- Not in cmdwin (closed already?).
199    return
200  end
201  local line, type = _close()
202  line = line:gsub('%z', '\n'):gsub('(%c)', '\022%1') -- Escape control characters.
203  vim.api.nvim_feedkeys(type .. line, 'nt', true)
204end
205
206return M