2 " Last Change: 2015 Dec 17
3 " Maintainer: James McCoy <vega.james@gmail.com>
4 " Original Author: Markus Braun <markus.braun@krawel.de>
5 " Summary: Vim plugin for transparent editing of gpg encrypted files.
6 " License: This program is free software; you can redistribute it and/or
7 " modify it under the terms of the GNU General Public License
8 " as published by the Free Software Foundation; either version
9 " 2 of the License, or (at your option) any later version.
10 " See http://www.gnu.org/copyleft/gpl-2.0.txt
12 " Section: Documentation {{{1
16 " This script implements transparent editing of gpg encrypted files. The
17 " filename must have a ".gpg", ".pgp" or ".asc" suffix. When opening such
18 " a file the content is decrypted, when opening a new file the script will
19 " ask for the recipients of the encrypted file. The file content will be
20 " encrypted to all recipients before it is written. The script turns off
21 " viminfo, swapfile, and undofile to increase security.
25 " Copy the gnupg.vim file to the $HOME/.vim/plugin directory.
26 " Refer to ':help add-plugin', ':help add-global-plugin' and ':help
27 " runtimepath' for more details about Vim plugins.
29 " From "man 1 gpg-agent":
32 " You should always add the following lines to your .bashrc or whatever
33 " initialization file is used for all shell invocations:
38 " It is important that this environment variable always reflects the out‐
39 " put of the tty command. For W32 systems this option is not required.
42 " Most distributions provide software to ease handling of gpg and gpg-agent.
43 " Examples are keychain or seahorse.
45 " If there are specific actions that should take place when editing a
46 " GnuPG-managed buffer, an autocmd for the User event and GnuPG pattern can
47 " be defined. For example, the following will set 'textwidth' to 72 for all
48 " GnuPG-encrypted buffers:
50 " autocmd User GnuPG setl textwidth=72
52 " This will be triggered before any BufRead or BufNewFile autocmds, and
53 " therefore will not take precedence over settings specific to any filetype
59 " Opens a scratch buffer to change the list of recipients. Recipients that
60 " are unknown (not in your public key) are highlighted and have
61 " a prepended "!". Closing the buffer makes the changes permanent.
64 " Prints the list of recipients.
67 " Opens a scratch buffer to change the options for encryption (symmetric,
68 " asymmetric, signing). Closing the buffer makes the changes permanent.
69 " WARNING: There is no check of the entered options, so you need to know
73 " Prints the list of options.
78 " If set used as gpg executable. If unset, defaults to
79 " "gpg --trust-model always" if "gpg" is available, falling back to
80 " "gpg2 --trust-model always" if not.
83 " If set to 0 a possible available gpg-agent won't be used. Defaults to 1.
85 " g:GPGPreferSymmetric
86 " If set to 1 symmetric encryption is preferred for new files. Defaults to 0.
89 " If set to 1 armored data is preferred for new files. Defaults to 0
90 " unless a "*.asc" file is being edited.
93 " If set to 1 signed data is preferred for new files. Defaults to 0.
95 " g:GPGDefaultRecipients
96 " If set, these recipients are used as defaults when no other recipient is
97 " defined. This variable is a Vim list. Default is unset.
99 " g:GPGPossibleRecipients
100 " If set, these contents are loaded into the recipients dialog. This
101 " allows to add commented lines with possible recipients to the list,
102 " which can be uncommented to select the actual recipients. Default is
105 " let g:GPGPossibleRecipients=[
106 " \"Example User <example@example.com>",
107 " \"Other User <otherexample@example.com>"
112 " If set to 1, use pipes instead of temporary files when interacting with
113 " gnupg. When set to 1, this can cause terminal-based gpg agents to not
114 " display correctly when prompting for passwords. Defaults to 0.
117 " If set, specifies the directory that will be used for GPG's homedir.
118 " This corresponds to gpg's --homedir option. This variable is a Vim
119 " string. Default is unset.
122 " If set, overrides the default set of file patterns that determine
123 " whether this plugin will be activated. Defaults to
124 " '*.\(gpg\|asc\|pgp\)'.
128 " In some cases gvim can't decrypt files
130 " This is caused by the fact that a running gvim has no TTY and thus gpg is
131 " not able to ask for the passphrase by itself. This is a problem for Windows
132 " and Linux versions of gvim and could not be solved unless a "terminal
133 " emulation" is implemented for gvim. To circumvent this you have to use any
134 " combination of gpg-agent and a graphical pinentry program:
137 " you need to provide the passphrase for the needed key to gpg-agent
138 " in a terminal before you open files with gvim which require this key.
141 " you will get a popup window every time you open a file that needs to
144 " - gpgagent and pinentry:
145 " you will get a popup window the first time you open a file that
146 " needs to be decrypted.
148 " If you're using Vim <7.4.959, after the plugin runs any external command,
149 " Vim will no longer be able to yank to/paste from the X clipboard or
150 " primary selections. This is caused by a workaround for a different bug
151 " where Vim no longer recognizes the key codes for keys such as the arrow
152 " keys after running GnuPG. See the discussion at
153 " https://github.com/jamessan/vim-gnupg/issues/36 for more details.
157 " - Mathieu Clabaut for inspirations through his vimspell.vim script.
158 " - Richard Bronosky for patch to enable ".pgp" suffix.
159 " - Erik Remmelzwaal for patch to enable windows support and patient beta
161 " - Lars Becker for patch to make gpg2 working.
162 " - Thomas Arendsen Hein for patch to convert encoding of gpg output.
163 " - Karl-Heinz Ruskowski for patch to fix unknown recipients and trust model
164 " and patient beta testing.
165 " - Giel van Schijndel for patch to get GPG_TTY dynamically.
166 " - Sebastian Luettich for patch to fix issue with symmetric encryption an set
168 " - Tim Swast for patch to generate signed files.
169 " - James Vega for patches for better '*.asc' handling, better filename
170 " escaping and better handling of multiple keyrings.
172 " Section: Plugin header {{{1
174 " guard against multiple loads {{{2
175 if (exists("g:loaded_gnupg") || &cp || exists("#GnuPG"))
178 let g:loaded_gnupg = '2.5'
181 " check for correct vim version {{{2
183 echohl ErrorMsg | echo 'plugin gnupg.vim requires Vim version >= 7.2' | echohl None
187 " Section: Autocmd setup {{{1
189 if (!exists("g:GPGFilePattern"))
190 let g:GPGFilePattern = '*.\(gpg\|asc\|pgp\)'
197 exe "autocmd BufReadCmd " . g:GPGFilePattern . " call s:GPGInit(1) |" .
198 \ " call s:GPGDecrypt(1)"
199 exe "autocmd FileReadCmd " . g:GPGFilePattern . " call s:GPGInit(0) |" .
200 \ " call s:GPGDecrypt(0)"
202 " convert all text to encrypted text before writing
203 " We check for GPGCorrespondingTo to avoid triggering on writes in GPG Options/Recipient windows
204 exe "autocmd BufWriteCmd,FileWriteCmd " . g:GPGFilePattern . " if !exists('b:GPGCorrespondingTo') |" .
205 \ " call s:GPGInit(0) |" .
206 \ " call s:GPGEncrypt() |" .
209 " cleanup on leaving vim
210 exe "autocmd VimLeave " . g:GPGFilePattern . " call s:GPGCleanup()"
213 " Section: Constants {{{1
215 let s:GPGMagicString = "\t \t"
216 let s:keyPattern = '\%(0x\)\=[[:xdigit:]]\{8,16}'
218 " Section: Highlight setup {{{1
220 highlight default link GPGWarning WarningMsg
221 highlight default link GPGError ErrorMsg
222 highlight default link GPGHighlightUnknownRecipient ErrorMsg
224 " Section: Functions {{{1
226 " Function: s:shellescape(s[, special]) {{{2
228 " Calls shellescape(), also taking into account 'shellslash'
229 " when on Windows and using $COMSPEC as the shell.
231 " Returns: shellescaped string
233 function s:shellescape(s, ...)
234 let special = a:0 ? a:1 : 0
235 if exists('+shellslash') && &shell == $COMSPEC
236 let ssl = &shellslash
239 let escaped = shellescape(a:s, special)
241 let &shellslash = ssl
243 let escaped = shellescape(a:s, special)
249 " Function: s:GPGInit(bufread) {{{2
251 " initialize the plugin
252 " The bufread argument specifies whether this was called due to BufReadCmd
254 function s:GPGInit(bufread)
255 call s:GPGDebug(3, printf(">>>>>>>> Entering s:GPGInit(%d)", a:bufread))
257 " For FileReadCmd, we're reading the contents into another buffer. If that
258 " buffer is also destined to be encrypted, then these settings will have
259 " already been set, otherwise don't set them since it limits the
260 " functionality of the cleartext buffer.
262 " we don't want a swap file, as it writes unencrypted data to disk
265 " if persistent undo is present, disable it for this buffer
266 if exists('+undofile')
270 " first make sure nothing is written to ~/.viminfo while editing
275 " the rest only has to be run once
280 " check what gpg command to use
281 if (!exists("g:GPGExecutable"))
283 let g:GPGExecutable = "gpg --trust-model always"
285 let g:GPGExecutable = "gpg2 --trust-model always"
289 " check if gpg-agent is allowed
290 if (!exists("g:GPGUseAgent"))
291 let g:GPGUseAgent = 1
294 " check if symmetric encryption is preferred
295 if (!exists("g:GPGPreferSymmetric"))
296 let g:GPGPreferSymmetric = 0
299 " check if armored files are preferred
300 if (!exists("g:GPGPreferArmor"))
301 " .asc files should be armored as that's what the extension is used for
302 if expand('<afile>') =~ '\.asc$'
303 let g:GPGPreferArmor = 1
305 let g:GPGPreferArmor = 0
309 " check if signed files are preferred
310 if (!exists("g:GPGPreferSign"))
311 let g:GPGPreferSign = 0
314 " start with empty default recipients if none is defined so far
315 if (!exists("g:GPGDefaultRecipients"))
316 let g:GPGDefaultRecipients = []
319 if (!exists("g:GPGPossibleRecipients"))
320 let g:GPGPossibleRecipients = []
324 " prefer not to use pipes since it can garble gpg agent display
325 if (!exists("g:GPGUsePipes"))
326 let g:GPGUsePipes = 0
329 " allow alternate gnupg homedir
330 if (!exists('g:GPGHomedir'))
331 let g:GPGHomedir = ''
335 call s:GPGDebug(1, "gnupg.vim ". g:loaded_gnupg)
337 let s:GPGCommand = g:GPGExecutable
339 " don't use tty in gvim except for windows: we get their a tty for free.
340 " FIXME find a better way to avoid an error.
341 " with this solution only --use-agent will work
342 if (has("gui_running") && !has("gui_win32"))
343 let s:GPGCommand .= " --no-tty"
346 " setup shell environment for unix and windows
347 let s:shellredirsave = &shellredir
348 let s:shellsave = &shell
349 let s:shelltempsave = &shelltemp
350 " noshelltemp isn't currently supported on Windows, but it doesn't cause any
351 " errors and this future proofs us against requiring changes if Windows
352 " gains noshelltemp functionality
353 let s:shelltemp = !g:GPGUsePipes
355 " unix specific settings
356 let s:shellredir = ">%s 2>&1"
357 let s:shell = '/bin/sh'
358 let s:stderrredirnull = '2>/dev/null'
360 " windows specific settings
361 let s:shellredir = '>%s'
363 let s:stderrredirnull = '2>nul'
366 call s:GPGDebug(3, "shellredirsave: " . s:shellredirsave)
367 call s:GPGDebug(3, "shellsave: " . s:shellsave)
368 call s:GPGDebug(3, "shelltempsave: " . s:shelltempsave)
370 call s:GPGDebug(3, "shell: " . s:shell)
371 call s:GPGDebug(3, "shellcmdflag: " . &shellcmdflag)
372 call s:GPGDebug(3, "shellxquote: " . &shellxquote)
373 call s:GPGDebug(3, "shellredir: " . s:shellredir)
374 call s:GPGDebug(3, "stderrredirnull: " . s:stderrredirnull)
376 call s:GPGDebug(3, "shell implementation: " . resolve(s:shell))
378 " find the supported algorithms
379 let output = s:GPGSystem({ 'level': 2, 'args': '--version' })
381 let gpgversion = substitute(output, '^gpg (GnuPG) \([0-9]\+\.\d\+\).*', '\1', '')
382 let s:GPGPubkey = substitute(output, ".*Pubkey: \\(.\\{-}\\)\n.*", "\\1", "")
383 let s:GPGCipher = substitute(output, ".*Cipher: \\(.\\{-}\\)\n.*", "\\1", "")
384 let s:GPGHash = substitute(output, ".*Hash: \\(.\\{-}\\)\n.*", "\\1", "")
385 let s:GPGCompress = substitute(output, ".*Compress.\\{-}: \\(.\\{-}\\)\n.*", "\\1", "")
387 " determine if gnupg can use the gpg-agent
388 if (str2float(gpgversion) >= 2.1 || (exists("$GPG_AGENT_INFO") && g:GPGUseAgent == 1))
389 if (!exists("$GPG_TTY") && !has("gui_running"))
390 " Need to determine the associated tty by running a command in the
391 " shell. We can't use system() here because that doesn't run in a shell
392 " connected to a tty, so it's rather useless.
394 " Save/restore &modified so the buffer isn't incorrectly marked as
395 " modified just by detecting the correct tty value.
396 " Do the &undolevels dance so the :read and :delete don't get added into
397 " the undo tree, as the user needn't be aware of these.
398 let [mod, levels] = [&l:modified, &undolevels]
401 let $GPG_TTY = getline('.')
403 let [&l:modified, &undolevels] = [mod, levels]
404 " redraw is needed since we're using silent to run !tty, c.f. :help :!
409 echom "$GPG_TTY is not set and the `tty` command failed! gpg-agent might not work."
413 let s:GPGCommand .= " --use-agent"
415 let s:GPGCommand .= " --no-use-agent"
418 call s:GPGDebug(2, "public key algorithms: " . s:GPGPubkey)
419 call s:GPGDebug(2, "cipher algorithms: " . s:GPGCipher)
420 call s:GPGDebug(2, "hashing algorithms: " . s:GPGHash)
421 call s:GPGDebug(2, "compression algorithms: " . s:GPGCompress)
422 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGInit()")
426 " Function: s:GPGCleanup() {{{2
428 " cleanup on leaving vim
430 function s:GPGCleanup()
431 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGCleanup()")
437 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGCleanup()")
440 " Function: s:GPGDecrypt(bufread) {{{2
442 " decrypt the buffer and find all recipients of the encrypted file
443 " The bufread argument specifies whether this was called due to BufReadCmd
445 function s:GPGDecrypt(bufread)
446 call s:GPGDebug(3, printf(">>>>>>>> Entering s:GPGDecrypt(%d)", a:bufread))
448 " get the filename of the current buffer
449 let filename = expand("<afile>:p")
451 " clear GPGRecipients and GPGOptions
452 if type(g:GPGDefaultRecipients) == type([])
453 let b:GPGRecipients = copy(g:GPGDefaultRecipients)
455 let b:GPGRecipients = []
457 echom "g:GPGDefaultRecipients is not a Vim list, please correct this in your vimrc!"
460 let b:GPGOptions = []
462 " file name minus extension
463 let autocmd_filename = fnameescape(expand('<afile>:r'))
465 " File doesn't exist yet, so nothing to decrypt
466 if !filereadable(filename)
467 " Allow the user to define actions for GnuPG buffers
468 silent doautocmd User GnuPG
469 " call the autocommand for the file minus .gpg$
470 silent execute ':doautocmd BufNewFile ' . autocmd_filename
471 call s:GPGDebug(2, 'called BufNewFile autocommand for ' . autocmd_filename)
473 " This is a new file, so force the user to edit the recipient list if
474 " they open a new file and public keys are preferred
475 if (g:GPGPreferSymmetric == 0)
476 call s:GPGEditRecipients()
482 " Only let this if the file actually exists, otherwise GPG functionality
483 " will be disabled when editing a buffer that doesn't yet have a backing
485 let b:GPGEncrypted = 0
487 " find the recipients of the file
488 let cmd = { 'level': 3 }
489 let cmd.args = '--verbose --decrypt --list-only --dry-run --no-use-agent --logger-fd 1 ' . s:shellescape(filename)
490 let output = s:GPGSystem(cmd)
492 " Suppress the "N more lines" message when editing a file, not when reading
493 " the contents of a file into a buffer
494 let silent = a:bufread ? 'silent ' : ''
496 let asymmPattern = 'gpg: public key is ' . s:keyPattern
497 " check if the file is symmetric/asymmetric encrypted
498 if (match(output, "gpg: encrypted with [[:digit:]]\\+ passphrase") >= 0)
499 " file is symmetric encrypted
500 let b:GPGEncrypted = 1
501 call s:GPGDebug(1, "this file is symmetric encrypted")
503 let b:GPGOptions += ["symmetric"]
505 " find the used cipher algorithm
506 let cipher = substitute(output, ".*gpg: \\([^ ]\\+\\) encrypted data.*", "\\1", "")
507 if (match(s:GPGCipher, "\\<" . cipher . "\\>") >= 0)
508 let b:GPGOptions += ["cipher-algo " . cipher]
509 call s:GPGDebug(1, "cipher-algo is " . cipher)
512 echom "The cipher " . cipher . " is not known by the local gpg command. Using default!"
516 elseif (match(output, asymmPattern) >= 0)
517 " file is asymmetric encrypted
518 let b:GPGEncrypted = 1
519 call s:GPGDebug(1, "this file is asymmetric encrypted")
521 let b:GPGOptions += ["encrypt"]
523 " find the used public keys
524 let start = match(output, asymmPattern)
526 let start = start + strlen("gpg: public key is ")
527 let recipient = matchstr(output, s:keyPattern, start)
528 call s:GPGDebug(1, "recipient is " . recipient)
529 " In order to support anonymous communication, GnuPG allows eliding
530 " information in the encryption metadata specifying what keys the file
531 " was encrypted to (c.f., --throw-keyids and --hidden-recipient). In
532 " that case, the recipient(s) will be listed as having used a key of all
534 " Since this will obviously never actually be in a keyring, only try to
535 " convert to an ID or add to the recipients list if it's not a hidden
537 if recipient !~? '^0x0\+$'
538 let name = s:GPGNameToID(recipient)
540 let b:GPGRecipients += [name]
541 call s:GPGDebug(1, "name of recipient is " . name)
543 let b:GPGRecipients += [recipient]
545 echom "The recipient \"" . recipient . "\" is not in your public keyring!"
549 let start = match(output, asymmPattern, start)
552 " file is not encrypted
553 let b:GPGEncrypted = 0
554 call s:GPGDebug(1, "this file is not encrypted")
556 echom "File is not encrypted, all GPG functions disabled!"
558 exe printf('%sr %s', silent, fnameescape(filename))
559 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGDecrypt()")
564 silent execute ':doautocmd BufReadPre ' . autocmd_filename
565 call s:GPGDebug(2, 'called BufReadPre autocommand for ' . autocmd_filename)
567 silent execute ':doautocmd FileReadPre ' . autocmd_filename
568 call s:GPGDebug(2, 'called FileReadPre autocommand for ' . autocmd_filename)
571 " check if the message is armored
572 if (match(output, "gpg: armor header") >= 0)
573 call s:GPGDebug(1, "this file is armored")
574 let b:GPGOptions += ["armor"]
577 " finally decrypt the buffer content
578 " since even with the --quiet option passphrase typos will be reported,
579 " we must redirect stderr (using shell temporarily)
580 call s:GPGDebug(1, "decrypting file")
581 let cmd = { 'level': 1, 'ex': silent . 'r !' }
582 let cmd.args = '--quiet --decrypt ' . s:shellescape(filename, 1)
583 call s:GPGExecute(cmd)
585 if (v:shell_error) " message could not be decrypted
587 let blackhole = input("Message could not be decrypted! (Press ENTER)")
589 " Only wipeout the buffer if we were creating one to start with.
590 " FileReadCmd just reads the content into the existing buffer
594 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGDecrypt()")
599 " In order to make :undo a no-op immediately after the buffer is read,
600 " we need to do this dance with 'undolevels'. Actually discarding the undo
601 " history requires performing a change after setting 'undolevels' to -1 and,
602 " luckily, we have one we need to do (delete the extra line from the :r
604 let levels = &undolevels
606 " :lockmarks doesn't actually prevent '[,'] from being overwritten, so we
607 " need to manually set them ourselves instead
611 let &undolevels = levels
612 let &readonly = filereadable(filename) && filewritable(filename) == 0
613 " call the autocommand for the file minus .gpg$
614 silent execute ':doautocmd BufReadPost ' . autocmd_filename
615 call s:GPGDebug(2, 'called BufReadPost autocommand for ' . autocmd_filename)
617 " call the autocommand for the file minus .gpg$
618 silent execute ':doautocmd FileReadPost ' . autocmd_filename
619 call s:GPGDebug(2, 'called FileReadPost autocommand for ' . autocmd_filename)
622 " Allow the user to define actions for GnuPG buffers
623 silent doautocmd User GnuPG
628 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGDecrypt()")
631 " Function: s:GPGEncrypt() {{{2
633 " encrypts the buffer to all previous recipients
635 function s:GPGEncrypt()
636 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGEncrypt()")
638 " FileWriteCmd is only called when a portion of a buffer is being written to
639 " disk. Since Vim always sets the '[,'] marks to the part of a buffer that
640 " is being written, that can be used to determine whether BufWriteCmd or
641 " FileWriteCmd triggered us.
642 if [line("'["), line("']")] == [1, line('$')]
643 let auType = 'BufWrite'
645 let auType = 'FileWrite'
648 " file name minus extension
649 let autocmd_filename = fnameescape(expand('<afile>:r'))
651 silent exe ':doautocmd '. auType .'Pre '. autocmd_filename
652 call s:GPGDebug(2, 'called '. auType .'Pre autocommand for ' . autocmd_filename)
654 " store encoding and switch to a safe one
655 if (&fileencoding != &encoding)
656 let s:GPGEncoding = &encoding
657 let &encoding = &fileencoding
658 call s:GPGDebug(2, "encoding was \"" . s:GPGEncoding . "\", switched to \"" . &encoding . "\"")
660 let s:GPGEncoding = ""
661 call s:GPGDebug(2, "encoding and fileencoding are the same (\"" . &encoding . "\"), not switching")
664 " guard for unencrypted files
665 if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
667 let blackhole = input("Message could not be encrypted! (Press ENTER)")
669 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEncrypt()")
673 " initialize GPGOptions if not happened before
674 if (!exists("b:GPGOptions") || empty(b:GPGOptions))
675 let b:GPGOptions = []
676 if (exists("g:GPGPreferSymmetric") && g:GPGPreferSymmetric == 1)
677 let b:GPGOptions += ["symmetric"]
678 let b:GPGRecipients = []
680 let b:GPGOptions += ["encrypt"]
682 if (exists("g:GPGPreferArmor") && g:GPGPreferArmor == 1)
683 let b:GPGOptions += ["armor"]
685 if (exists("g:GPGPreferSign") && g:GPGPreferSign == 1)
686 let b:GPGOptions += ["sign"]
688 call s:GPGDebug(1, "no options set, so using default options: " . string(b:GPGOptions))
691 " built list of options
693 for option in b:GPGOptions
694 let options = options . " --" . option . " "
697 if (!exists('b:GPGRecipients'))
698 let b:GPGRecipients = []
701 " check here again if all recipients are available in the keyring
702 let recipients = s:GPGCheckRecipients(b:GPGRecipients)
704 " check if there are unknown recipients and warn
705 if !empty(recipients.unknown)
707 echom "Please use GPGEditRecipients to correct!!"
711 " Let user know whats happend and copy known_recipients back to buffer
712 let dummy = input("Press ENTER to quit")
715 " built list of recipients
716 let options .= ' ' . join(map(recipients.valid, '"-r ".v:val'), ' ')
719 let destfile = tempname()
720 let cmd = { 'level': 1, 'ex': "'[,']w !" }
721 let cmd.args = '--quiet --no-encrypt-to ' . options
722 let cmd.redirect = '>' . s:shellescape(destfile, 1)
723 silent call s:GPGExecute(cmd)
726 if (s:GPGEncoding != "")
727 let &encoding = s:GPGEncoding
728 call s:GPGDebug(2, "restored encoding \"" . &encoding . "\"")
731 if (v:shell_error) " message could not be encrypted
732 " Command failed, so clean up the tempfile
733 call delete(destfile)
735 let blackhole = input("Message could not be encrypted! (Press ENTER)")
737 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEncrypt()")
741 let filename = resolve(expand('<afile>'))
742 if rename(destfile, filename)
743 " Rename failed, so clean up the tempfile
744 call delete(destfile)
746 echom printf("\"%s\" E212: Can't open file for writing", filename)
751 if auType == 'BufWrite'
753 let &readonly = filereadable(filename) && filewritable(filename) == 0
756 silent exe ':doautocmd '. auType .'Post '. autocmd_filename
757 call s:GPGDebug(2, 'called '. auType .'Post autocommand for ' . autocmd_filename)
759 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEncrypt()")
762 " Function: s:GPGViewRecipients() {{{2
764 " echo the recipients
766 function s:GPGViewRecipients()
767 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGViewRecipients()")
769 " guard for unencrypted files
770 if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
772 echom "File is not encrypted, all GPG functions disabled!"
774 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGViewRecipients()")
778 let recipients = s:GPGCheckRecipients(b:GPGRecipients)
780 echo 'This file has following recipients (Unknown recipients have a prepended "!"):'
781 " echo the recipients
782 for name in recipients.valid
783 let name = s:GPGIDToName(name)
787 " echo the unknown recipients
789 for name in recipients.unknown
790 let name = "!" . name
795 " check if there is any known recipient
796 if empty(recipients.valid)
798 echom 'There are no known recipients!'
802 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGViewRecipients()")
805 " Function: s:GPGEditRecipients() {{{2
807 " create a scratch buffer with all recipients to add/remove recipients
809 function s:GPGEditRecipients()
810 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGEditRecipients()")
812 " guard for unencrypted files
813 if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
815 echom "File is not encrypted, all GPG functions disabled!"
817 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEditRecipients()")
821 " only do this if it isn't already a GPGRecipients_* buffer
822 if (match(bufname("%"), "^\\(GPGRecipients_\\|GPGOptions_\\)") != 0 && match(bufname("%"), "\.\\(gpg\\|asc\\|pgp\\)$") >= 0)
825 let buffername = bufname("%")
826 let editbuffername = "GPGRecipients_" . buffername
828 " check if this buffer exists
829 if (!bufexists(editbuffername))
830 " create scratch buffer
831 execute 'silent! split ' . fnameescape(editbuffername)
833 " add a autocommand to regenerate the recipients after a write
834 autocmd BufHidden,BufUnload,BufWriteCmd <buffer> call s:GPGFinishRecipientsBuffer()
836 if (bufwinnr(editbuffername) >= 0)
837 " switch to scratch buffer window
838 execute 'silent! ' . bufwinnr(editbuffername) . "wincmd w"
840 " split scratch buffer window
841 execute 'silent! sbuffer ' . fnameescape(editbuffername)
843 " add a autocommand to regenerate the recipients after a write
844 autocmd BufHidden,BufUnload,BufWriteCmd <buffer> call s:GPGFinishRecipientsBuffer()
851 " Mark the buffer as a scratch buffer
852 setlocal buftype=acwrite
853 setlocal bufhidden=hide
859 " so we know for which other buffer this edit buffer is
860 let b:GPGCorrespondingTo = buffername
862 " put some comments to the scratch buffer
863 silent put ='GPG: ----------------------------------------------------------------------'
864 silent put ='GPG: Please edit the list of recipients, one recipient per line.'
865 silent put ='GPG: Unknown recipients have a prepended \"!\".'
866 silent put ='GPG: Lines beginning with \"GPG:\" are removed automatically.'
867 silent put ='GPG: Data after recipients between and including \"(\" and \")\" is ignored.'
868 silent put ='GPG: Closing this buffer commits changes.'
869 silent put ='GPG: ----------------------------------------------------------------------'
872 let recipients = s:GPGCheckRecipients(getbufvar(b:GPGCorrespondingTo, "GPGRecipients"))
874 " if there are no known or unknown recipients, use the default ones
875 if (empty(recipients.valid) && empty(recipients.unknown))
876 if (type(g:GPGDefaultRecipients) == type([]))
877 let recipients = s:GPGCheckRecipients(g:GPGDefaultRecipients)
880 echom "g:GPGDefaultRecipients is not a Vim list, please correct this in your vimrc!"
885 " put the recipients in the scratch buffer
886 for name in recipients.valid
887 let name = s:GPGIDToName(name)
891 " put the unknown recipients in the scratch buffer
892 let syntaxPattern = ''
893 if !empty(recipients.unknown)
894 let flaggedNames = map(recipients.unknown, '"!".v:val')
895 call append('$', flaggedNames)
896 let syntaxPattern = '\(' . join(flaggedNames, '\|') . '\)'
899 for line in g:GPGPossibleRecipients
900 silent put ='GPG: '.line
904 if (has("syntax") && exists("g:syntax_on"))
905 highlight clear GPGUnknownRecipient
906 if !empty(syntaxPattern)
907 execute 'syntax match GPGUnknownRecipient "' . syntaxPattern . '"'
908 highlight link GPGUnknownRecipient GPGHighlightUnknownRecipient
911 syntax match GPGComment "^GPG:.*$"
912 execute 'syntax match GPGComment "' . s:GPGMagicString . '.*$"'
913 highlight clear GPGComment
914 highlight link GPGComment Comment
917 " delete the empty first line
920 " jump to the first recipient
925 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEditRecipients()")
928 " Function: s:GPGFinishRecipientsBuffer() {{{2
930 " create a new recipient list from RecipientsBuffer
932 function s:GPGFinishRecipientsBuffer()
933 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGFinishRecipientsBuffer()")
935 " guard for unencrypted files
936 if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
938 echom "File is not encrypted, all GPG functions disabled!"
940 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGFinishRecipientsBuffer()")
944 " go to buffer before doing work
945 if (bufnr("%") != expand("<abuf>"))
946 " switch to scratch buffer window
947 execute 'silent! ' . bufwinnr(expand("<afile>")) . "wincmd w"
950 " delete the autocommand
953 " get the recipients from the scratch buffer
955 let lines = getline(1,"$")
956 for recipient in lines
957 let matches = matchlist(recipient, '^\(.\{-}\)\%(' . s:GPGMagicString . '(ID:\s\+\(' . s:keyPattern . '\)\s\+.*\)\=$')
959 let recipient = matches[2] ? matches[2] : matches[1]
961 " delete all spaces at beginning and end of the recipient
962 " also delete a '!' at the beginning of the recipient
963 let recipient = substitute(recipient, "^[[:space:]!]*\\(.\\{-}\\)[[:space:]]*$", "\\1", "")
965 " delete comment lines
966 let recipient = substitute(recipient, "^GPG:.*$", "", "")
968 " only do this if the line is not empty
970 let gpgid = s:GPGNameToID(recipient)
972 if (match(recipients, gpgid) < 0)
973 let recipients += [gpgid]
976 if (match(recipients, recipient) < 0)
977 let recipients += [recipient]
979 echom "The recipient \"" . recipient . "\" is not in your public keyring!"
986 " write back the new recipient list to the corresponding buffer and mark it
987 " as modified. Buffer is now for sure an encrypted buffer.
988 call setbufvar(b:GPGCorrespondingTo, "GPGRecipients", recipients)
989 call setbufvar(b:GPGCorrespondingTo, "&mod", 1)
990 call setbufvar(b:GPGCorrespondingTo, "GPGEncrypted", 1)
992 " check if there is any known recipient
995 echom 'There are no known recipients!'
999 " reset modified flag
1002 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGFinishRecipientsBuffer()")
1005 " Function: s:GPGViewOptions() {{{2
1007 " echo the recipients
1009 function s:GPGViewOptions()
1010 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGViewOptions()")
1012 " guard for unencrypted files
1013 if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
1015 echom "File is not encrypted, all GPG functions disabled!"
1017 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGViewOptions()")
1021 if (exists("b:GPGOptions"))
1022 echo 'This file has following options:'
1024 for option in b:GPGOptions
1029 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGViewOptions()")
1032 " Function: s:GPGEditOptions() {{{2
1034 " create a scratch buffer with all recipients to add/remove recipients
1036 function s:GPGEditOptions()
1037 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGEditOptions()")
1039 " guard for unencrypted files
1040 if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
1042 echom "File is not encrypted, all GPG functions disabled!"
1044 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEditOptions()")
1048 " only do this if it isn't already a GPGOptions_* buffer
1049 if (match(bufname("%"), "^\\(GPGRecipients_\\|GPGOptions_\\)") != 0 && match(bufname("%"), "\.\\(gpg\\|asc\\|pgp\\)$") >= 0)
1052 let buffername = bufname("%")
1053 let editbuffername = "GPGOptions_" . buffername
1055 " check if this buffer exists
1056 if (!bufexists(editbuffername))
1057 " create scratch buffer
1058 execute 'silent! split ' . fnameescape(editbuffername)
1060 " add a autocommand to regenerate the options after a write
1061 autocmd BufHidden,BufUnload,BufWriteCmd <buffer> call s:GPGFinishOptionsBuffer()
1063 if (bufwinnr(editbuffername) >= 0)
1064 " switch to scratch buffer window
1065 execute 'silent! ' . bufwinnr(editbuffername) . "wincmd w"
1067 " split scratch buffer window
1068 execute 'silent! sbuffer ' . fnameescape(editbuffername)
1070 " add a autocommand to regenerate the options after a write
1071 autocmd BufHidden,BufUnload,BufWriteCmd <buffer> call s:GPGFinishOptionsBuffer()
1078 " Mark the buffer as a scratch buffer
1079 setlocal buftype=nofile
1082 setlocal nobuflisted
1085 " so we know for which other buffer this edit buffer is
1086 let b:GPGCorrespondingTo = buffername
1088 " put some comments to the scratch buffer
1089 silent put ='GPG: ----------------------------------------------------------------------'
1090 silent put ='GPG: THERE IS NO CHECK OF THE ENTERED OPTIONS!'
1091 silent put ='GPG: YOU NEED TO KNOW WHAT YOU ARE DOING!'
1092 silent put ='GPG: IF IN DOUBT, QUICKLY EXIT USING :x OR :bd.'
1093 silent put ='GPG: Please edit the list of options, one option per line.'
1094 silent put ='GPG: Please refer to the gpg documentation for valid options.'
1095 silent put ='GPG: Lines beginning with \"GPG:\" are removed automatically.'
1096 silent put ='GPG: Closing this buffer commits changes.'
1097 silent put ='GPG: ----------------------------------------------------------------------'
1099 " put the options in the scratch buffer
1100 let options = getbufvar(b:GPGCorrespondingTo, "GPGOptions")
1102 for option in options
1106 " delete the empty first line
1109 " jump to the first option
1113 if (has("syntax") && exists("g:syntax_on"))
1114 syntax match GPGComment "^GPG:.*$"
1115 highlight clear GPGComment
1116 highlight link GPGComment Comment
1120 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEditOptions()")
1123 " Function: s:GPGFinishOptionsBuffer() {{{2
1125 " create a new option list from OptionsBuffer
1127 function s:GPGFinishOptionsBuffer()
1128 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGFinishOptionsBuffer()")
1130 " guard for unencrypted files
1131 if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
1133 echom "File is not encrypted, all GPG functions disabled!"
1135 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGFinishOptionsBuffer()")
1139 " go to buffer before doing work
1140 if (bufnr("%") != expand("<abuf>"))
1141 " switch to scratch buffer window
1142 execute 'silent! ' . bufwinnr(expand("<afile>")) . "wincmd w"
1145 " clear options and unknownOptions
1147 let unknownOptions = []
1149 " delete the autocommand
1152 " get the options from the scratch buffer
1153 let lines = getline(1, "$")
1155 " delete all spaces at beginning and end of the option
1156 " also delete a '!' at the beginning of the option
1157 let option = substitute(option, "^[[:space:]!]*\\(.\\{-}\\)[[:space:]]*$", "\\1", "")
1158 " delete comment lines
1159 let option = substitute(option, "^GPG:.*$", "", "")
1161 " only do this if the line is not empty
1162 if (!empty(option) && match(options, option) < 0)
1163 let options += [option]
1167 " write back the new option list to the corresponding buffer and mark it
1169 call setbufvar(b:GPGCorrespondingTo, "GPGOptions", options)
1170 call setbufvar(b:GPGCorrespondingTo, "&mod", 1)
1172 " reset modified flag
1175 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGFinishOptionsBuffer()")
1178 " Function: s:GPGCheckRecipients(tocheck) {{{2
1180 " check if recipients are known
1181 " Returns: dictionary of recipients, {'valid': [], 'unknown': []}
1183 function s:GPGCheckRecipients(tocheck)
1184 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGCheckRecipients()")
1186 let recipients = {'valid': [], 'unknown': []}
1188 if (type(a:tocheck) == type([]))
1189 for recipient in a:tocheck
1190 let gpgid = s:GPGNameToID(recipient)
1192 if (match(recipients.valid, gpgid) < 0)
1193 call add(recipients.valid, gpgid)
1196 if (match(recipients.unknown, recipient) < 0)
1197 call add(recipients.unknown, recipient)
1199 echom "The recipient \"" . recipient . "\" is not in your public keyring!"
1206 call s:GPGDebug(2, "recipients are: " . string(recipients.valid))
1207 call s:GPGDebug(2, "unknown recipients are: " . string(recipients.unknown))
1209 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGCheckRecipients()")
1213 " Function: s:GPGNameToID(name) {{{2
1215 " find GPG key ID corresponding to a name
1216 " Returns: ID for the given name
1218 function s:GPGNameToID(name)
1219 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGNameToID()")
1221 " ask gpg for the id for a name
1222 let cmd = { 'level': 2 }
1223 let cmd.args = '--quiet --with-colons --fixed-list-mode --list-keys ' . s:shellescape(a:name)
1224 let output = s:GPGSystem(cmd)
1226 " when called with "--with-colons" gpg encodes its output _ALWAYS_ as UTF-8,
1227 " so convert it, if necessary
1228 if (&encoding != "utf-8")
1229 let output = iconv(output, "utf-8", &encoding)
1231 let lines = split(output, "\n")
1233 " parse the output of gpg
1239 let has_strftime = exists('*strftime')
1240 let choices = "The name \"" . a:name . "\" is ambiguous. Please select the correct key:\n"
1243 let fields = split(line, ":")
1245 " search for the next pub
1246 if (fields[0] == "pub")
1247 " check if this key has already been processed
1248 if has_key(seen_keys, fields[4])
1253 let seen_keys[fields[4]] = 1
1255 " Ignore keys which are not usable for encryption
1256 if fields[11] !~? 'e'
1260 let identity = fields[4]
1261 let gpgids += [identity]
1263 let choices = choices . counter . ": ID: 0x" . identity . " created at " . strftime("%c", fields[5]) . "\n"
1265 let choices = choices . counter . ": ID: 0x" . identity . "\n"
1267 let counter = counter+1
1269 " search for the next uid
1270 elseif (!skip_key && fields[0] == "uid")
1271 let choices = choices . " " . fields[9] . "\n"
1276 " counter > 1 means we have more than one results
1279 let choices = choices . "Enter number: "
1280 let answer = input(choices, "0")
1281 while (answer == "")
1282 let answer = input("Enter number: ", "0")
1286 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGNameToID()")
1287 return get(gpgids, answer, "")
1290 " Function: s:GPGIDToName(identity) {{{2
1292 " find name corresponding to a GPG key ID
1293 " Returns: Name for the given ID
1295 function s:GPGIDToName(identity)
1296 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGIDToName()")
1298 " TODO is the encryption subkey really unique?
1300 " ask gpg for the id for a name
1301 let cmd = { 'level': 2 }
1302 let cmd.args = '--quiet --with-colons --fixed-list-mode --list-keys ' . a:identity
1303 let output = s:GPGSystem(cmd)
1305 " when called with "--with-colons" gpg encodes its output _ALWAYS_ as UTF-8,
1306 " so convert it, if necessary
1307 if (&encoding != "utf-8")
1308 let output = iconv(output, "utf-8", &encoding)
1310 let lines = split(output, "\n")
1312 " parse the output of gpg
1316 let fields = split(line, ":")
1318 if !pubseen " search for the next pub
1319 if (fields[0] == "pub")
1320 " Ignore keys which are not usable for encryption
1321 if fields[11] !~? 'e'
1327 else " search for the next uid
1328 if (fields[0] == "uid")
1330 if exists("*strftime")
1331 let uid = fields[9] . s:GPGMagicString . "(ID: 0x" . a:identity . " created at " . strftime("%c", fields[5]) . ")"
1333 let uid = fields[9] . s:GPGMagicString . "(ID: 0x" . a:identity . ")"
1340 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGIDToName()")
1344 " Function: s:GPGPreCmd() {{{2
1346 " Setup the environment for running the gpg command
1348 function s:GPGPreCmd()
1349 let &shellredir = s:shellredir
1350 let &shell = s:shell
1351 let &shelltemp = s:shelltemp
1352 " Force C locale so GPG output is consistent
1353 let s:messages = v:lang
1358 " Function: s:GPGPostCmd() {{{2
1360 " Restore the user's environment after running the gpg command
1362 function s:GPGPostCmd()
1363 let &shellredir = s:shellredirsave
1364 let &shell = s:shellsave
1365 let &shelltemp = s:shelltempsave
1366 execute 'language messages' s:messages
1367 " Workaround a bug in the interaction between console vim and
1368 " pinentry-curses by forcing Vim to re-detect and setup its terminal
1371 silent doautocmd TermChanged
1374 " Function: s:GPGSystem(dict) {{{2
1376 " run g:GPGCommand using system(), logging the commandline and output. This
1377 " uses temp files (regardless of how 'shelltemp' is set) to hold the output of
1378 " the command, so it must not be used for sensitive commands.
1379 " Recognized keys are:
1380 " level - Debug level at which the commandline and output will be logged
1381 " args - Arguments to be given to g:GPGCommand
1383 " Returns: command output
1385 function s:GPGSystem(dict)
1386 let commandline = s:GPGCommand
1387 if (!empty(g:GPGHomedir))
1388 let commandline .= ' --homedir ' . s:shellescape(g:GPGHomedir)
1390 let commandline .= ' ' . a:dict.args
1391 let commandline .= ' ' . s:stderrredirnull
1392 call s:GPGDebug(a:dict.level, "command: ". commandline)
1395 let output = system(commandline)
1398 call s:GPGDebug(a:dict.level, "rc: ". v:shell_error)
1399 call s:GPGDebug(a:dict.level, "output: ". output)
1403 " Function: s:GPGExecute(dict) {{{2
1405 " run g:GPGCommand using :execute, logging the commandline
1406 " Recognized keys are:
1407 " level - Debug level at which the commandline will be logged
1408 " args - Arguments to be given to g:GPGCommand
1409 " ex - Ex command which will be :executed
1410 " redirect - Shell redirect to use, if needed
1412 function s:GPGExecute(dict)
1413 let commandline = printf('%s%s', a:dict.ex, s:GPGCommand)
1414 if (!empty(g:GPGHomedir))
1415 let commandline .= ' --homedir ' . s:shellescape(g:GPGHomedir, 1)
1417 let commandline .= ' ' . a:dict.args
1418 if (has_key(a:dict, 'redirect'))
1419 let commandline .= ' ' . a:dict.redirect
1421 let commandline .= ' ' . s:stderrredirnull
1422 call s:GPGDebug(a:dict.level, "command: " . commandline)
1428 call s:GPGDebug(a:dict.level, "rc: ". v:shell_error)
1431 " Function: s:GPGDebug(level, text) {{{2
1433 " output debug message, if this message has high enough importance
1434 " only define function if GPGDebugLevel set at all
1436 function s:GPGDebug(level, text)
1437 if exists("g:GPGDebugLevel") && g:GPGDebugLevel >= a:level
1438 if exists("g:GPGDebugLog")
1439 execute "redir >> " . g:GPGDebugLog
1440 silent echom "GnuPG: " . a:text
1443 echom "GnuPG: " . a:text
1448 " Section: Commands {{{1
1450 command! GPGViewRecipients call s:GPGViewRecipients()
1451 command! GPGEditRecipients call s:GPGEditRecipients()
1452 command! GPGViewOptions call s:GPGViewOptions()
1453 command! GPGEditOptions call s:GPGEditOptions()
1455 " Section: Menu {{{1
1458 amenu <silent> Plugin.GnuPG.View\ Recipients :GPGViewRecipients<CR>
1459 amenu <silent> Plugin.GnuPG.Edit\ Recipients :GPGEditRecipients<CR>
1460 amenu <silent> Plugin.GnuPG.View\ Options :GPGViewOptions<CR>
1461 amenu <silent> Plugin.GnuPG.Edit\ Options :GPGEditOptions<CR>
1464 " vim600: set foldmethod=marker foldlevel=0 :