Skip to content

Instantly share code, notes, and snippets.

@rodolfoap
Forked from nickali/decode-gpg.lua
Last active November 27, 2024 07:19
Show Gist options
  • Save rodolfoap/a50b5fa7758c302ad74fcafe93c46efc to your computer and use it in GitHub Desktop.
Save rodolfoap/a50b5fa7758c302ad74fcafe93c46efc to your computer and use it in GitHub Desktop.
local gpgGroup = vim.api.nvim_create_augroup("customGpg", { clear = true })
vim.api.nvim_create_autocmd({ "BufReadPre", "FileReadPre" }, {
pattern = "*.gpg",
group = gpgGroup,
callback = function()
-- Make sure nothing is written to shada file while editing an encrypted file.
vim.opt_local.shada = nil
-- We don't want a swap file, as it writes unencrypted data to disk
vim.opt_local.swapfile = false
-- Switch to binary mode to read the encrypted file
vim.opt_local.bin = true
-- Save the current 'ch' value to a buffer-local variable
vim.b.ch_save = vim.opt_local.ch:get()
vim.cmd "set ch=2"
end,
})
vim.api.nvim_create_autocmd({ "BufReadPost", "FileReadPost" }, {
pattern = "*.gpg",
group = gpgGroup,
callback = function()
vim.cmd "'[,']!gpg -d 2> /dev/null"
-- Switch to normal mode for editing
vim.opt_local.bin = false
-- Restore the 'ch' value from the buffer-local variable
vim.opt_local.ch = vim.b.ch_save
vim.cmd "unlet b:ch_save"
vim.cmd(":doautocmd BufReadPost " .. vim.fn.expand "%:r")
end,
})
-- Convert all text to encrypted text before writing
vim.api.nvim_create_autocmd({ "BufWritePre", "FileWritePre" }, {
pattern = "*.gpg",
group = gpgGroup,
callback = function()
-- Switch to binary mode to write the encrypted file
vim.opt_local.bin = true
-- So we can avoid the armor option
vim.cmd("'[,']!gpg -e 2>/dev/null")
end,
})
-- Undo the encryption so we are back in the normal text, directly after the file has been written.
vim.api.nvim_create_autocmd({ "BufWritePost", "FileWritePost" }, {
pattern = "*.gpg",
group = gpgGroup,
callback = function()
vim.cmd("u")
-- Switch to normal mode for editing
vim.opt_local.bin = false
end,
})
-- Return an empty table to satisfy plugin loader requirements
return {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment