robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
7.1 KiB209 linesraw
1local M = {}
2
3--- Send `payload` to the host terminal and listen for `TermResponse`, calling `on_response` for
4--- each response. Cleans up after `opts.timeout` ms if the callback never returns `true`.
5---
6--- The autocommand is removed when:
7--- - `on_response()` returns `true`
8--- - the timeout fires (and `opts.on_timeout` is called, if given)
9--- - the caller explicitly deletes the returned autocmd id
10---
11---@param payload string Sequence to send via nvim_ui_send(). Use empty string ('') to just register
12---                      a listener (no sending).
13---@param opts? { timeout?: integer, on_timeout?: fun(), group?: integer|string, chan?: integer } #
14---       - `timeout` (default: 1000) ms to wait before giving up, or 0 for never (caller must remove the autocmd).
15---       - `on_timeout` optional fn called when the timeout fires.
16---       - `group`: augroup for the TermResponse autocmd.
17---       - `chan`: only handle responses from this channel.
18---@param on_response fun(resp:string):boolean? Called for each TermResponse. Return `true` to stop listening.
19---@return integer # autocmd id of the TermResponse handler.
20function M.request(payload, opts, on_response)
21  vim.validate('payload', payload, 'string')
22  vim.validate('opts', opts, 'table', true)
23  vim.validate('on_response', on_response, 'function')
24
25  opts = opts or {}
26  local timeout = opts.timeout or 1000
27  local timer ---@type uv.uv_timer_t?
28  if timeout > 0 then
29    timer = assert(vim.uv.new_timer())
30  end
31
32  local id = require('vim._core.util').nvim_on(
33    'TermResponse',
34    opts.group,
35    { nested = true },
36    ---@param ev {data: vim.event.termresponse.data}
37    function(ev)
38      if opts.chan and ev.data.chan ~= opts.chan then
39        return
40      end
41      local stop = on_response(ev.data.sequence)
42      -- If on_response is done, cancel the timeout so on_timeout doesn't fire spuriously.
43      if stop and timer and not timer:is_closing() then
44        timer:close()
45      end
46      return stop
47    end
48  )
49
50  if payload ~= '' then
51    vim.api.nvim_ui_send(payload)
52  end
53
54  if timer then
55    timer:start(timeout, 0, function()
56      vim.schedule(function()
57        pcall(vim.api.nvim_del_autocmd, id)
58        if opts.on_timeout then
59          opts.on_timeout()
60        end
61      end)
62      if not timer:is_closing() then
63        timer:close()
64      end
65    end)
66  end
67
68  return id
69end
70
71--- Query the host terminal emulator for terminfo capabilities.
72---
73--- This function sends the XTGETTCAP DCS sequence to the host terminal emulator asking the terminal
74--- to send us its terminal capabilities. These are strings that are normally taken from a terminfo
75--- file, however an up to date terminfo database is not always available (particularly on remote
76--- machines), and many terminals continue to misidentify themselves or do not provide their own
77--- terminfo file, making the terminfo database unreliable.
78---
79--- Querying the terminal guarantees that we get a truthful answer, but only if the host terminal
80--- emulator supports the XTGETTCAP sequence.
81---
82--- @param caps string|table A terminal capability or list of capabilities to query
83--- @param opts? { timeout?: integer, on_timeout?: fun(), group?: integer|string, chan?: integer }
84--- @param on_response fun(cap:string, found:boolean, seq:string?) Called for each capability in
85---        `caps`. `found` is true if the capability was found, else false. `seq` is the control
86---        sequence if found, or nil for boolean capabilities.
87---@overload fun(caps:string|table, on_response:fun(cap:string, found:boolean, seq:string?))
88function M.query(caps, opts, on_response)
89  if type(opts) == 'function' then
90    on_response = opts
91    opts = {}
92  end
93
94  vim.validate('caps', caps, { 'string', 'table' })
95  vim.validate('opts', opts, 'table', true)
96  vim.validate('on_response', on_response, 'function')
97
98  opts = opts or {}
99
100  if type(caps) ~= 'table' then
101    caps = { caps }
102  end
103
104  local pending = {} ---@type table<string, boolean>
105  for _, v in ipairs(caps) do
106    pending[v] = true
107  end
108
109  local encoded = {} ---@type string[]
110  for i = 1, #caps do
111    encoded[i] = vim.text.hexencode(caps[i])
112  end
113  local payload = ('\027P+q%s\027\\'):format(table.concat(encoded, ';'))
114
115  M.request(payload, {
116    timeout = opts.timeout,
117    group = opts.group,
118    chan = opts.chan,
119    on_timeout = function()
120      -- Call the callback for all capabilities that were not found.
121      for k in pairs(pending) do
122        on_response(k, false, nil)
123      end
124      if opts.on_timeout then
125        opts.on_timeout()
126      end
127    end,
128  }, function(resp)
129    local k, rest = resp:match('^\027P1%+r(%x+)(.*)$')
130    if not k or not rest then
131      return
132    end
133    local cap = vim.text.hexdecode(k)
134    if not cap or not pending[cap] then
135      -- Received a response for a capability we didn't request. This can happen if there are
136      -- multiple concurrent XTGETTCAP requests
137      return
138    end
139
140    local seq ---@type string?
141    if rest:match('^=%x+$') then
142      seq = vim.text.hexdecode(rest:sub(2))
143      if not seq then
144        return -- Ignore malformed responses and leave the capability pending.
145      end
146      seq = seq:gsub('\\E', '\027'):gsub('%%p%d', ''):gsub('\\(%d+)', string.char)
147    end
148
149    on_response(cap, true, seq)
150    pending[cap] = nil
151
152    return next(pending) == nil
153  end)
154end
155
156--- Send an APC sequence to the terminal and call `on_response` for each APC response received.
157--- Cleans up after {timeout} milliseconds if no response is received.
158---
159--- `on_response` receives the full APC sequence including the `\027_` prefix.
160--- Return `true` from `on_response` to stop listening.
161---
162---@param payload string APC sequence to send (full escape sequence including prefix/suffix)
163---@param opts {timeout?:integer, chan?:integer} Options table (timeout in milliseconds, default 1000)
164---@param on_response fun(resp:string):boolean? Callback invoked for each APC TermResponse
165---@overload fun(payload:string, on_response:fun(resp:string):boolean?)
166function M.query_apc(payload, opts, on_response)
167  if type(opts) == 'function' then
168    on_response = opts
169    opts = {}
170  end
171
172  vim.validate('payload', payload, 'string')
173  vim.validate('opts', opts, 'table')
174  vim.validate('on_response', on_response, 'function')
175
176  M.request(payload, opts, function(resp)
177    if resp:match('^\027_') then
178      return on_response(resp)
179    end
180  end)
181end
182
183--- Displays error even when this code runs in the context of the client
184--- @param msg string
185local function broadcast_error(msg)
186  vim.rpcnotify(0, 'nvim_echo', {
187    {
188      msg,
189    },
190  }, true, { err = true })
191end
192
193--- Get user overrides for terminfo entries as a table. See |$NVIM_TERMDEFS|
194function M._get_termdefs()
195  local termdefs_raw = os.getenv('NVIM_TERMDEFS')
196  if termdefs_raw ~= nil then
197    local ok, termdefs_or_err = pcall(vim.json.decode, termdefs_raw)
198    if not ok then
199      broadcast_error('E557: Failed to parse $NVIM_TERMDEFS: ' .. vim.inspect(termdefs_or_err))
200      return
201    elseif type(termdefs_or_err) ~= 'table' or vim.isarray(termdefs_or_err) then
202      broadcast_error('E557: expected $NVIM_TERMDEFS to be table. :help $NVIM_TERMDEFS')
203      return
204    end
205    return termdefs_or_err
206  end
207end
208
209return M