52 lines
1.3 KiB
Lua
52 lines
1.3 KiB
Lua
local M = {}
|
|
|
|
-- paste_code_from_clipboard:
|
|
-- The user copies a code block from the website (which includes a first line with the file path),
|
|
-- and then runs :ChatGPTPaste.
|
|
-- We retrieve the clipboard content, extract the first line as a path, and the rest as code.
|
|
function M.paste_code_from_clipboard()
|
|
local clipboard_content = vim.fn.getreg('+')
|
|
if clipboard_content == "" then
|
|
vim.api.nvim_err_writeln("Clipboard is empty. Copy the code block from the website first.")
|
|
return
|
|
end
|
|
|
|
local lines = {}
|
|
for line in clipboard_content:gmatch("[^\r\n]+") do
|
|
table.insert(lines, line)
|
|
end
|
|
|
|
if #lines == 0 then
|
|
vim.api.nvim_err_writeln("No content in clipboard to parse.")
|
|
return
|
|
end
|
|
|
|
local filepath = lines[1]
|
|
local code_lines = {}
|
|
for i = 2, #lines do
|
|
table.insert(code_lines, lines[i])
|
|
end
|
|
|
|
local code = table.concat(code_lines, "\n")
|
|
M.write_file(filepath, code)
|
|
print("Wrote file: " .. filepath)
|
|
end
|
|
|
|
function M.write_file(filepath, content)
|
|
-- Create directories if needed
|
|
local dir = filepath:match("(.*/)")
|
|
if dir and dir ~= "" then
|
|
vim.fn.mkdir(dir, "p")
|
|
end
|
|
|
|
local f = io.open(filepath, "w")
|
|
if f then
|
|
f:write(content)
|
|
f:close()
|
|
else
|
|
vim.api.nvim_err_writeln("Failed to write file: " .. filepath)
|
|
end
|
|
end
|
|
|
|
return M
|