robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
2.1 KiB74 linesraw
1local M = {}
2
3--- Return the OSC 52 escape sequence
4---
5--- @param clipboard string The clipboard to read from or write to
6--- @param contents string The Base64 encoded contents to write to the clipboard, or '?' to read
7---                        from the clipboard
8local function osc52(clipboard, contents)
9  return string.format('\027]52;%s;%s\027\\', clipboard, contents)
10end
11
12--- @param reg string
13--- @return fun(lines: string[])
14function M.copy(reg)
15  local clipboard = reg == '+' and 'c' or 'p'
16  return function(lines)
17    local s = table.concat(lines, '\n')
18    -- The data to be written here can be quite long.
19    vim.api.nvim_ui_send(osc52(clipboard, vim.base64.encode(s)))
20  end
21end
22
23--- @param reg string
24--- @return fun(): string[]|0
25function M.paste(reg)
26  local clipboard = reg == '+' and 'c' or 'p'
27  return function()
28    local contents = nil --- @type string?
29    -- timeout=0: we manage the staged 1s/9s timeout via vim.wait below.
30    local id = vim.tty.request(osc52(clipboard, '?'), { timeout = 0 }, function(resp)
31      local encoded = resp:match('\027%]52;%w?;([A-Za-z0-9+/=]*)')
32      if encoded then
33        contents = vim.base64.decode(encoded)
34        return true
35      end
36    end)
37
38    -- Wait 1s first for terminals that respond quickly
39    local ok, res = vim.wait(1000, function()
40      return contents ~= nil
41    end)
42
43    if res == -1 then
44      -- If no response was received after 1s, print a message and keep waiting
45      vim.api.nvim_echo(
46        { { 'Waiting for OSC 52 response from the terminal. Press Ctrl-C to interrupt...' } },
47        false,
48        {}
49      )
50      ok, res = vim.wait(9000, function()
51        return contents ~= nil
52      end)
53    end
54
55    if not ok then
56      pcall(vim.api.nvim_del_autocmd, id)
57      if res == -1 then
58        vim.notify(
59          'Timed out waiting for a clipboard response from the terminal',
60          vim.log.levels.WARN
61        )
62      elseif res == -2 then
63        -- Clear message area
64        vim.api.nvim_echo({ { '' } }, false)
65      end
66      return 0
67    end
68
69    -- If we get here, contents should be non-nil
70    return vim.split(assert(contents), '\n')
71  end
72end
73
74return M