robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
11.6 KiB295 linesraw
1--- @brief
2---
3--- WARNING: This is an experimental feature intended to replace the builtin message + cmdline
4--- presentation layer.
5---
6--- To enable this feature (default opts shown, see also 'messagesopt'):
7--- ```lua
8--- require('vim._core.ui2').enable({
9---   enable = true, -- Whether to enable or disable the UI.
10---   msg = { -- Options related to the message module.
11---     ---@type string|table<string, 'cmd'|'msg'|'pager'> Default message target
12---     ---or table mapping |ui-messages| kinds, triggers and IDs to a target.
13---     ---Table keys are matched as a Lua pattern to the message ID. 'default'
14---     ---mapping applies to any omitted kind: { default = 'cmd', progress = 'msg' }.
15---     targets = 'cmd',
16---     dialog = { -- Options related to dialog window.
17---       height = 0.5, -- Maximum height.
18---     },
19---     msg = { -- Options related to msg window.
20---       height = 0.5, -- Maximum height.
21---     },
22---     pager = { -- Options related to message window.
23---       height = 0.999, -- Maximum height.
24---     },
25---   },
26--- })
27--- ```
28---
29--- ui2 behavior is also configured by these 'messagesopt' items: "pager", "timeout".
30--- Example:
31--- ```vim
32--- set messagesopt+=maxheight:50,pager:<CR>,timeout:4000
33--- ```
34---
35--- There are four special windows/buffers for presenting messages and cmdline:
36--- - "cmd": Cmdline. Also used by default for messages, 'showcmd', 'showmode', 'ruler'.
37--- - "msg": Message window. Shows ephemeral messages; useful if 'cmdheight' is 0.
38--- - "pager": Pager window. Shows |:messages|, allows navigating all messages.
39--- - "dialog": Dialog window. Shows modal prompts that wait for user input.
40---
41--- In each of the special buffers, 'filetype' is set as listed above ("cmd", "msg", …). Handle the
42--- [FileType] event to configure any local options for these windows/buffers.
43---
44--- Unlike the legacy [hit-enter] prompt, messages exceeding 'cmdheight' are collapsed, followed by
45--- a `[+x]` "spill" indicator, where `x` is number of overflow lines. To see all messages, do either:
46--- - |g<| at any time.
47--- - Type the "pager" char (if configured in 'messagesopt'), immediately after an interactive [:] command.
48
49local api = vim.api
50local nvim_on = require('vim._core.util').nvim_on
51local M = {
52  ns = api.nvim_create_namespace('nvim.ui2'),
53  augroup = api.nvim_create_augroup('nvim.ui2'),
54  cmdheight = vim.o.cmdheight, -- 'cmdheight' option value set by user.
55  redrawing = false, -- True when redrawing to display UI event.
56  wins = { cmd = -1, dialog = -1, msg = -1, pager = -1 },
57  bufs = { cmd = -1, dialog = -1, msg = -1, pager = -1 },
58  cfg = {
59    enable = true,
60    msg = { -- Options related to the message module.
61      ---@type table<string, 'cmd'|'msg'|'pager'> Kind specific message targets.
62      targets = { default = 'cmd' },
63      dialog = { -- Options related to dialog window.
64        height = 0.5, -- Maximum height.
65      },
66      msg = { -- Options related to msg window.
67        height = 0.5, -- Maximum height.
68      },
69      pager = { -- Options related to message window.
70        height = 0.999, -- Maximum height.
71      },
72    },
73  },
74}
75
76---Ensure target buffers and windows are still valid.
77function M.check_targets()
78  local curtab = api.nvim_get_current_tabpage()
79  for i, type in ipairs({ 'cmd', 'dialog', 'msg', 'pager' }) do
80    local buf = api.nvim_buf_is_valid(M.bufs[type]) and M.bufs[type]
81    local win = api.nvim_win_is_valid(M.wins[type]) and M.wins[type]
82    local floating = win and api.nvim_win_get_config(win).zindex
83    local setopt = not buf or not win or not floating
84    M.bufs[type] = buf or api.nvim_create_buf(false, false)
85
86    if not win or not floating then
87      -- Open a new window when closed or no longer floating (e.g. wincmd J).
88      local cfg = { col = 0, row = 1, width = 10000, height = 1, noautocmd = true }
89      cfg.focusable = false
90      cfg.style = 'minimal'
91      cfg.relative = 'laststatus'
92      cfg.anchor = type ~= 'cmd' and 'SE' or nil
93      cfg.mouse = type == 'pager' or nil
94      cfg.border = type ~= 'msg' and 'none' or nil
95      cfg._cmdline_offset = type == 'cmd' and 0 or nil
96      cfg.hide = type ~= 'cmd' or M.cmdheight == 0 or nil
97      -- kZIndexMessages < cmd zindex < kZIndexCmdlinePopupMenu (grid_defs.h), pager below others.
98      cfg.zindex = 201 - i
99      -- Open the window without fileinfo notifications
100      vim._with({ silent = true }, function()
101        M.wins[type] = api.nvim_open_win(M.bufs[type], false, cfg)
102      end)
103    elseif api.nvim_win_get_tabpage(M.wins[type]) ~= curtab then
104      api.nvim_win_set_config(M.wins[type], { win = api.nvim_tabpage_get_win(curtab) })
105    end
106    if win and floating and api.nvim_win_get_buf(win) ~= M.bufs[type] then
107      api.nvim_win_set_buf(win, M.bufs[type])
108      setopt = true
109    end
110
111    if setopt then
112      -- Set options without firing OptionSet and BufFilePost.
113      vim._with({ win = M.wins[type], noautocmd = true }, function()
114        api.nvim_set_option_value('eventignorewin', 'all,-FileType', { scope = 'local' })
115        api.nvim_set_option_value('wrap', true, { scope = 'local' })
116        api.nvim_set_option_value('linebreak', false, { scope = 'local' })
117        api.nvim_set_option_value('smoothscroll', true, { scope = 'local' })
118        api.nvim_set_option_value('breakindent', false, { scope = 'local' })
119        api.nvim_set_option_value('foldenable', false, { scope = 'local' })
120        api.nvim_set_option_value('showbreak', '', { scope = 'local' })
121        api.nvim_set_option_value('spell', false, { scope = 'local' })
122        api.nvim_set_option_value('swapfile', false, { scope = 'local' })
123        api.nvim_set_option_value('modeline', false, { scope = 'local' })
124        api.nvim_set_option_value('modifiable', true, { scope = 'local' })
125        api.nvim_set_option_value('bufhidden', 'hide', { scope = 'local' })
126        api.nvim_set_option_value('buftype', 'nofile', { scope = 'local' })
127        -- Use MsgArea except in the msg window. Hide Search highlighting except in the pager.
128        local search_hide = 'Search:,CurSearch:,IncSearch:'
129        local hl = 'Normal:MsgArea,' .. search_hide
130        if type == 'pager' then
131          hl = 'Normal:MsgArea'
132        elseif type == 'msg' then
133          hl = search_hide
134        elseif type == 'cmd' then
135          api.nvim_set_option_value('winpinned', true, { scope = 'local' })
136        end
137        api.nvim_set_option_value('winhighlight', hl, { scope = 'local' })
138      end)
139      api.nvim_buf_set_name(M.bufs[type], ('[%s]'):format(type:sub(1, 1):upper() .. type:sub(2)))
140      -- Fire FileType with window context to let the user reconfigure local options.
141      vim._with({ win = M.wins[type] }, function()
142        api.nvim_set_option_value('filetype', type, { scope = 'local' })
143      end)
144
145      if type == 'pager' then
146        -- Close pager with `q`, same as `checkhealth`
147        api.nvim_buf_set_keymap(M.bufs.pager, 'n', 'q', '<Cmd>wincmd c<CR>')
148      elseif M.msg[type] then
149        M.msg[type].prev_msg = '' -- Will no longer be visible.
150      end
151    end
152  end
153end
154
155--- @param redraw_msg boolean
156--- @param event string
157--- @param ... any
158local function ui_callback(redraw_msg, event, ...)
159  local handler = M.msg[event] or M.cmd[event] --[[@as function]]
160  M.check_targets()
161  handler(...)
162  -- Cmdline mode, non-fast message and non-empty showcmd require an immediate redraw.
163  if
164    (M.cmd[event] or redraw_msg or (event == 'msg_showcmd' and select(1, ...)[1]))
165    and event ~= 'cmdline_hide'
166  then
167    M.redrawing = true
168    api.nvim__redraw({
169      flush = handler ~= M.cmd.cmdline_hide or nil,
170      cursor = handler == M.cmd[event] and true or nil,
171      win = handler == M.cmd[event] and M.wins.cmd or nil,
172    })
173    M.redrawing = false
174  end
175end
176local scheduled_ui_callback = vim.schedule_wrap(ui_callback)
177
178--- @param name string
179--- @param value any
180--- @param new_name string
181local function validate_old_cfg(name, value, new_name)
182  if value ~= nil then
183    error(
184      ([[ui2: config key %q was removed, set %q in the 'messagesopt' option instead]]):format(
185        name,
186        new_name
187      )
188    )
189  end
190end
191
192---@nodoc
193---@class (private) vim._core.ui2.Opts
194---@field enable? boolean
195---@field pager_char? string
196---@field msg? {
197---   targets?: 'cmd'|'msg'|'pager'|table<string,'cmd'|'msg'|'pager'>,
198---   dialog?: { height?: number },
199---   msg?: { height?: number, timeout?: integer },
200---   pager?: { height?: number },
201---   cmd?: { height?: integer },
202--- }
203---@param opts? vim._core.ui2.Opts
204function M.enable(opts)
205  opts = opts or {}
206  vim.validate('opts', opts, 'table', true)
207  local msg = opts.msg or {}
208  validate_old_cfg('pager_char', opts.pager_char, 'pager')
209  validate_old_cfg('msg.msg.timeout', (msg.msg or {}).timeout, 'timeout')
210  validate_old_cfg('msg.cmd.height', (msg.cmd or {}).height, 'maxheight')
211  -- The deep merge preserves the required defaults in M.cfg.
212  ---@diagnostic disable-next-line: assign-type-mismatch
213  M.cfg = vim.tbl_deep_extend('keep', opts, M.cfg)
214  M.cfg.msg.targets = type(M.cfg.msg.targets) == 'table' and M.cfg.msg.targets
215    or { default = M.cfg.msg.targets }
216  M.cfg.msg.targets.default = M.cfg.msg.targets.default or 'cmd'
217  if #api.nvim_list_uis() == 0 then
218    return -- Don't prevent stdout messaging when no UIs are attached.
219  end
220
221  if M.cfg.enable == false then
222    -- Detach and cleanup windows, buffers and autocommands.
223    for _, win in pairs(M.wins) do
224      pcall(api.nvim_win_close, win, true)
225    end
226    for _, buf in pairs(M.bufs) do
227      pcall(api.nvim_buf_delete, buf, {})
228    end
229    api.nvim_clear_autocmds({ group = M.augroup })
230    vim.ui_detach(M.ns)
231    return
232  end
233
234  M.cmd = require('vim._core.ui2.cmdline')
235  M.msg = require('vim._core.ui2.messages')
236  M.msg.on_option_changed()
237  vim.ui_attach(M.ns, { ext_messages = true, set_cmdheight = false }, function(event, ...)
238    if not (M.msg[event] or M.cmd[event]) then
239      return
240    end
241    -- Ensure cmdline is placed after a scheduled message in block mode.
242    if vim.in_fast_event() or (event == 'cmdline_show' and M.cmd.srow > 0) then
243      scheduled_ui_callback(false, event, ...)
244    else
245      ui_callback(event == 'msg_show', event, ...)
246    end
247    return true
248  end)
249
250  -- The visibility and appearance of the cmdline and message window is
251  -- dependent on some option values. Reconfigure windows when option value
252  -- has changed and after VimEnter when the user configured value is known.
253  -- TODO: Reconsider what is needed when this module is enabled by default early in startup.
254  --- @param value integer
255  local function check_cmdheight(value)
256    M.check_targets()
257    -- 'cmdheight' set; (un)hide cmdline window and set its height.
258    local cfg = { height = math.max(value, 1), hide = value == 0 }
259    api.nvim_win_set_config(M.wins.cmd, cfg)
260    M.cmdheight = value
261  end
262
263  if vim.v.vim_did_enter == 0 then
264    vim.schedule(function()
265      check_cmdheight(vim.o.cmdheight)
266      M.msg.on_option_changed()
267    end)
268  end
269
270  nvim_on('OptionSet', M.augroup, {
271    pattern = { 'cmdheight', 'fillchars', 'laststatus', 'messagesopt' },
272    desc = 'Handle message/pager option changes.',
273  }, function(ev)
274    if ev.match == 'cmdheight' then
275      check_cmdheight(vim.v.option_new)
276    else
277      M.msg.on_option_changed()
278    end
279    M.msg.set_pos()
280  end)
281
282  nvim_on({ 'VimResized', 'TabEnter' }, M.augroup, {
283    desc = 'Set cmdline and message window dimensions after shell resize or tabpage change.',
284  }, function(ev)
285    M.msg.on_option_changed() -- 'messagesopt':maxheight is relative to 'lines'.
286    M.check_targets()
287    -- After a tabpage was closed unhide the msg window on the current tabpage.
288    if ev.event == 'TabEnter' and next(M.msg.msg.ids) ~= nil then
289      api.nvim_win_set_config(M.wins.msg, { hide = false, width = M.msg.msg.width })
290    end
291    M.msg.set_pos()
292  end)
293end
294
295return M