aboutsummaryrefslogtreecommitdiff
path: root/lua/extregs/storage.lua
blob: c5324850d6bc92077e7882db6fec30d1dd20c97b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
local M = {}
M.cookie = 'NVIM_EXTREGS_JSON_V1'

local function validate(reg)
  if type(reg) ~= 'table' or type(reg.lines) ~= 'table' or type(reg.type) ~= 'string' then
    error('invalid yankreg: expected { lines = {...}, type = "v"|"V"|blockwise }')
  end
  return reg
end

function M.encode(reg)
  return M.cookie .. '\n' .. vim.json.encode(validate(reg)) .. '\n'
end

function M.decode(data)
  if data:sub(1, #M.cookie + 1) == M.cookie .. '\n' then
    return validate(vim.json.decode(data:sub(#M.cookie + 2)))
  end
  local lines = vim.split(data, '\n', { plain = true })
  if #lines > 1 and lines[#lines] == '' then table.remove(lines) end
  return { lines = lines, type = #lines > 1 and 'V' or 'v' }
end

return M