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