2 " Last Change: 2015 Jul 26
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, otherwise the system chooses what is run
79 " when "gpg" is called. Defaults to "gpg".
82 " If set to 0 a possible available gpg-agent won't be used. Defaults to 1.
84 " g:GPGPreferSymmetric
85 " If set to 1 symmetric encryption is preferred for new files. Defaults to 0.
88 " If set to 1 armored data is preferred for new files. Defaults to 0
89 " unless a "*.asc" file is being edited.
92 " If set to 1 signed data is preferred for new files. Defaults to 0.
94 " g:GPGDefaultRecipients
95 " If set, these recipients are used as defaults when no other recipient is
96 " defined. This variable is a Vim list. Default is unset.
98 " g:GPGPossibleRecipients
99 " If set, these contents are loaded into the recipients dialog. This
100 " allows to add commented lines with possible recipients to the list,
101 " which can be uncommented to select the actual recipients. Example:
103 " let g:GPGPossibleRecipients=[
104 " \"Example User <example@example.com>",
105 " \"Other User <otherexample@example.com>"
110 " If set to 1, use pipes instead of temporary files when interacting with
111 " gnupg. When set to 1, this can cause terminal-based gpg agents to not
112 " display correctly when prompting for passwords. Defaults to 0.
115 " If set, specifies the directory that will be used for GPG's homedir.
116 " This corresponds to gpg's --homedir option. This variable is a Vim
120 " If set, overrides the default set of file patterns that determine
121 " whether this plugin will be activated. Defaults to
122 " '*.\(gpg\|asc\|pgp\)'.
126 " In some cases gvim can't decrypt files
128 " This is caused by the fact that a running gvim has no TTY and thus gpg is
129 " not able to ask for the passphrase by itself. This is a problem for Windows
130 " and Linux versions of gvim and could not be solved unless a "terminal
131 " emulation" is implemented for gvim. To circumvent this you have to use any
132 " combination of gpg-agent and a graphical pinentry program:
135 " you need to provide the passphrase for the needed key to gpg-agent
136 " in a terminal before you open files with gvim which require this key.
139 " you will get a popup window every time you open a file that needs to
142 " - gpgagent and pinentry:
143 " you will get a popup window the first time you open a file that
144 " needs to be decrypted.
148 " - Mathieu Clabaut for inspirations through his vimspell.vim script.
149 " - Richard Bronosky for patch to enable ".pgp" suffix.
150 " - Erik Remmelzwaal for patch to enable windows support and patient beta
152 " - Lars Becker for patch to make gpg2 working.
153 " - Thomas Arendsen Hein for patch to convert encoding of gpg output.
154 " - Karl-Heinz Ruskowski for patch to fix unknown recipients and trust model
155 " and patient beta testing.
156 " - Giel van Schijndel for patch to get GPG_TTY dynamically.
157 " - Sebastian Luettich for patch to fix issue with symmetric encryption an set
159 " - Tim Swast for patch to generate signed files.
160 " - James Vega for patches for better '*.asc' handling, better filename
161 " escaping and better handling of multiple keyrings.
163 " Section: Plugin header {{{1
165 " guard against multiple loads {{{2
166 if (exists("g:loaded_gnupg") || &cp || exists("#GnuPG"))
169 let g:loaded_gnupg = '2.5'
172 " check for correct vim version {{{2
174 echohl ErrorMsg | echo 'plugin gnupg.vim requires Vim version >= 7.2' | echohl None
178 " Section: Autocmd setup {{{1
180 if (!exists("g:GPGFilePattern"))
181 let g:GPGFilePattern = '*.\(gpg\|asc\|pgp\)'
188 exe "autocmd BufReadCmd " . g:GPGFilePattern . " call s:GPGInit(1) |" .
189 \ " call s:GPGDecrypt(1) |"
190 exe "autocmd FileReadCmd " . g:GPGFilePattern . " call s:GPGInit(0) |" .
191 \ " call s:GPGDecrypt(0)"
193 " convert all text to encrypted text before writing
194 " We check for GPGCorrespondingTo to avoid triggering on writes in GPG Options/Recipient windows
195 exe "autocmd BufWriteCmd,FileWriteCmd " . g:GPGFilePattern . " if !exists('b:GPGCorrespondingTo') |" .
196 \ " call s:GPGInit(0) |" .
197 \ " call s:GPGEncrypt() |" .
200 " cleanup on leaving vim
201 exe "autocmd VimLeave " . g:GPGFilePattern . " call s:GPGCleanup()"
204 " Section: Constants {{{1
206 let s:GPGMagicString = "\t \t"
207 let s:keyPattern = '\%(0x\)\=[[:xdigit:]]\{8,16}'
209 " Section: Highlight setup {{{1
211 highlight default link GPGWarning WarningMsg
212 highlight default link GPGError ErrorMsg
213 highlight default link GPGHighlightUnknownRecipient ErrorMsg
215 " Section: Functions {{{1
217 " Function: s:GPGInit(bufread) {{{2
219 " initialize the plugin
220 " The bufread argument specifies whether this was called due to BufReadCmd
222 function s:GPGInit(bufread)
223 call s:GPGDebug(3, printf(">>>>>>>> Entering s:GPGInit(%d)", a:bufread))
225 " For FileReadCmd, we're reading the contents into another buffer. If that
226 " buffer is also destined to be encrypted, then these settings will have
227 " already been set, otherwise don't set them since it limits the
228 " functionality of the cleartext buffer.
230 " we don't want a swap file, as it writes unencrypted data to disk
233 " if persistent undo is present, disable it for this buffer
234 if exists('+undofile')
238 " first make sure nothing is written to ~/.viminfo while editing
243 " the rest only has to be run once
248 " check what gpg command to use
249 if (!exists("g:GPGExecutable"))
250 let g:GPGExecutable = "gpg --trust-model always"
253 " check if gpg-agent is allowed
254 if (!exists("g:GPGUseAgent"))
255 let g:GPGUseAgent = 1
258 " check if symmetric encryption is preferred
259 if (!exists("g:GPGPreferSymmetric"))
260 let g:GPGPreferSymmetric = 0
263 " check if armored files are preferred
264 if (!exists("g:GPGPreferArmor"))
265 " .asc files should be armored as that's what the extension is used for
266 if expand('<afile>') =~ '\.asc$'
267 let g:GPGPreferArmor = 1
269 let g:GPGPreferArmor = 0
273 " check if signed files are preferred
274 if (!exists("g:GPGPreferSign"))
275 let g:GPGPreferSign = 0
278 " start with empty default recipients if none is defined so far
279 if (!exists("g:GPGDefaultRecipients"))
280 let g:GPGDefaultRecipients = []
283 if (!exists("g:GPGPossibleRecipients"))
284 let g:GPGPossibleRecipients = []
288 " prefer not to use pipes since it can garble gpg agent display
289 if (!exists("g:GPGUsePipes"))
290 let g:GPGUsePipes = 0
293 " allow alternate gnupg homedir
294 if (!exists('g:GPGHomedir'))
295 let g:GPGHomedir = ''
299 call s:GPGDebug(1, "gnupg.vim ". g:loaded_gnupg)
301 let s:GPGCommand = g:GPGExecutable
303 " don't use tty in gvim except for windows: we get their a tty for free.
304 " FIXME find a better way to avoid an error.
305 " with this solution only --use-agent will work
306 if (has("gui_running") && !has("gui_win32"))
307 let s:GPGCommand = s:GPGCommand . " --no-tty"
310 " setup shell environment for unix and windows
311 let s:shellredirsave = &shellredir
312 let s:shellsave = &shell
313 let s:shelltempsave = &shelltemp
314 " noshelltemp isn't currently supported on Windows, but it doesn't cause any
315 " errors and this future proofs us against requiring changes if Windows
316 " gains noshelltemp functionality
317 let s:shelltemp = !g:GPGUsePipes
319 " unix specific settings
320 let s:shellredir = ">%s 2>&1"
321 let s:shell = '/bin/sh'
322 let s:stderrredirnull = '2>/dev/null'
323 let s:GPGCommand = "LANG=C LC_ALL=C " . s:GPGCommand
325 " windows specific settings
326 let s:shellredir = '>%s'
328 let s:stderrredirnull = '2>nul'
331 call s:GPGDebug(3, "shellredirsave: " . s:shellredirsave)
332 call s:GPGDebug(3, "shellsave: " . s:shellsave)
333 call s:GPGDebug(3, "shelltempsave: " . s:shelltempsave)
335 call s:GPGDebug(3, "shell: " . s:shell)
336 call s:GPGDebug(3, "shellcmdflag: " . &shellcmdflag)
337 call s:GPGDebug(3, "shellxquote: " . &shellxquote)
338 call s:GPGDebug(3, "shellredir: " . s:shellredir)
339 call s:GPGDebug(3, "stderrredirnull: " . s:stderrredirnull)
341 call s:GPGDebug(3, "shell implementation: " . resolve(s:shell))
343 " find the supported algorithms
344 let output = s:GPGSystem({ 'level': 2, 'args': '--version' })
346 let gpgversion = substitute(output, '^gpg (GnuPG) \([0-9]\+\.\d\+\).*', '\1', '')
347 let s:GPGPubkey = substitute(output, ".*Pubkey: \\(.\\{-}\\)\n.*", "\\1", "")
348 let s:GPGCipher = substitute(output, ".*Cipher: \\(.\\{-}\\)\n.*", "\\1", "")
349 let s:GPGHash = substitute(output, ".*Hash: \\(.\\{-}\\)\n.*", "\\1", "")
350 let s:GPGCompress = substitute(output, ".*Compress.\\{-}: \\(.\\{-}\\)\n.*", "\\1", "")
352 " determine if gnupg can use the gpg-agent
353 if (str2float(gpgversion) >= 2.1 || (exists("$GPG_AGENT_INFO") && g:GPGUseAgent == 1))
354 if (!exists("$GPG_TTY") && !has("gui_running"))
355 " Need to determine the associated tty by running a command in the
356 " shell. We can't use system() here because that doesn't run in a shell
357 " connected to a tty, so it's rather useless.
359 " Save/restore &modified so the buffer isn't incorrectly marked as
360 " modified just by detecting the correct tty value.
361 " Do the &undolevels dance so the :read and :delete don't get added into
362 " the undo tree, as the user needn't be aware of these.
363 let [mod, levels] = [&l:modified, &undolevels]
366 let $GPG_TTY = getline('.')
368 let [&l:modified, &undolevels] = [mod, levels]
369 " redraw is needed since we're using silent to run !tty, c.f. :help :!
374 echom "$GPG_TTY is not set and the `tty` command failed! gpg-agent might not work."
378 let s:GPGCommand = s:GPGCommand . " --use-agent"
380 let s:GPGCommand = s:GPGCommand . " --no-use-agent"
383 call s:GPGDebug(2, "public key algorithms: " . s:GPGPubkey)
384 call s:GPGDebug(2, "cipher algorithms: " . s:GPGCipher)
385 call s:GPGDebug(2, "hashing algorithms: " . s:GPGHash)
386 call s:GPGDebug(2, "compression algorithms: " . s:GPGCompress)
387 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGInit()")
391 " Function: s:GPGCleanup() {{{2
393 " cleanup on leaving vim
395 function s:GPGCleanup()
396 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGCleanup()")
402 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGCleanup()")
405 " Function: s:GPGDecrypt(bufread) {{{2
407 " decrypt the buffer and find all recipients of the encrypted file
408 " The bufread argument specifies whether this was called due to BufReadCmd
410 function s:GPGDecrypt(bufread)
411 call s:GPGDebug(3, printf(">>>>>>>> Entering s:GPGDecrypt(%d)", a:bufread))
413 " get the filename of the current buffer
414 let filename = expand("<afile>:p")
416 " clear GPGRecipients and GPGOptions
417 if type(g:GPGDefaultRecipients) == type([])
418 let b:GPGRecipients = copy(g:GPGDefaultRecipients)
420 let b:GPGRecipients = []
422 echom "g:GPGDefaultRecipients is not a Vim list, please correct this in your vimrc!"
425 let b:GPGOptions = []
427 " File doesn't exist yet, so nothing to decrypt
428 if !filereadable(filename)
429 " Allow the user to define actions for GnuPG buffers
430 silent doautocmd User GnuPG
431 " call the autocommand for the file minus .gpg$
432 silent execute ':doautocmd BufNewFile ' . fnameescape(expand('<afile>:r'))
433 call s:GPGDebug(2, 'called BufNewFile autocommand for ' . fnameescape(expand('<afile>:r')))
435 " This is a new file, so force the user to edit the recipient list if
436 " they open a new file and public keys are preferred
437 if (exists("g:GPGPreferSymmetric") && g:GPGPreferSymmetric == 0)
438 call s:GPGEditRecipients()
444 " Only let this if the file actually exists, otherwise GPG functionality
445 " will be disabled when editing a buffer that doesn't yet have a backing
447 let b:GPGEncrypted = 0
449 " find the recipients of the file
450 let cmd = { 'level': 3 }
451 let cmd.args = '--verbose --decrypt --list-only --dry-run --no-use-agent --logger-fd 1 ' . shellescape(filename)
452 let output = s:GPGSystem(cmd)
454 " Suppress the "N more lines" message when editing a file, not when reading
455 " the contents of a file into a buffer
456 let silent = a:bufread ? 'silent ' : ''
458 let asymmPattern = 'gpg: public key is ' . s:keyPattern
459 " check if the file is symmetric/asymmetric encrypted
460 if (match(output, "gpg: encrypted with [[:digit:]]\\+ passphrase") >= 0)
461 " file is symmetric encrypted
462 let b:GPGEncrypted = 1
463 call s:GPGDebug(1, "this file is symmetric encrypted")
465 let b:GPGOptions += ["symmetric"]
467 " find the used cipher algorithm
468 let cipher = substitute(output, ".*gpg: \\([^ ]\\+\\) encrypted data.*", "\\1", "")
469 if (match(s:GPGCipher, "\\<" . cipher . "\\>") >= 0)
470 let b:GPGOptions += ["cipher-algo " . cipher]
471 call s:GPGDebug(1, "cipher-algo is " . cipher)
474 echom "The cipher " . cipher . " is not known by the local gpg command. Using default!"
478 elseif (match(output, asymmPattern) >= 0)
479 " file is asymmetric encrypted
480 let b:GPGEncrypted = 1
481 call s:GPGDebug(1, "this file is asymmetric encrypted")
483 let b:GPGOptions += ["encrypt"]
485 " find the used public keys
486 let start = match(output, asymmPattern)
488 let start = start + strlen("gpg: public key is ")
489 let recipient = matchstr(output, s:keyPattern, start)
490 call s:GPGDebug(1, "recipient is " . recipient)
491 let name = s:GPGNameToID(recipient)
493 let b:GPGRecipients += [name]
494 call s:GPGDebug(1, "name of recipient is " . name)
496 let b:GPGRecipients += [recipient]
498 echom "The recipient \"" . recipient . "\" is not in your public keyring!"
501 let start = match(output, asymmPattern, start)
504 " file is not encrypted
505 let b:GPGEncrypted = 0
506 call s:GPGDebug(1, "this file is not encrypted")
508 echom "File is not encrypted, all GPG functions disabled!"
510 exe printf('%sr %s', silent, fnameescape(filename))
511 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGDecrypt()")
516 silent execute ':doautocmd BufReadPre ' . fnameescape(expand('<afile>:r'))
517 call s:GPGDebug(2, 'called BufReadPre autocommand for ' . fnameescape(expand('<afile>:r')))
519 silent execute ':doautocmd FileReadPre ' . fnameescape(expand('<afile>:r'))
520 call s:GPGDebug(2, 'called FileReadPre autocommand for ' . fnameescape(expand('<afile>:r')))
523 " check if the message is armored
524 if (match(output, "gpg: armor header") >= 0)
525 call s:GPGDebug(1, "this file is armored")
526 let b:GPGOptions += ["armor"]
529 " finally decrypt the buffer content
530 " since even with the --quiet option passphrase typos will be reported,
531 " we must redirect stderr (using shell temporarily)
532 call s:GPGDebug(1, "decrypting file")
533 let cmd = { 'level': 1, 'ex': silent . 'r !' }
534 let cmd.args = '--quiet --decrypt ' . shellescape(filename, 1)
535 call s:GPGExecute(cmd)
537 if (v:shell_error) " message could not be decrypted
539 let blackhole = input("Message could not be decrypted! (Press ENTER)")
541 " Only wipeout the buffer if we were creating one to start with.
542 " FileReadCmd just reads the content into the existing buffer
546 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGDecrypt()")
551 " In order to make :undo a no-op immediately after the buffer is read,
552 " we need to do this dance with 'undolevels'. Actually discarding the undo
553 " history requires performing a change after setting 'undolevels' to -1 and,
554 " luckily, we have one we need to do (delete the extra line from the :r
556 let levels = &undolevels
558 " :lockmarks doesn't actually prevent '[,'] from being overwritten, so we
559 " need to manually set them ourselves instead
563 let &undolevels = levels
564 " call the autocommand for the file minus .gpg$
565 silent execute ':doautocmd BufReadPost ' . fnameescape(expand('<afile>:r'))
566 call s:GPGDebug(2, 'called BufReadPost autocommand for ' . fnameescape(expand('<afile>:r')))
568 " call the autocommand for the file minus .gpg$
569 silent execute ':doautocmd FileReadPost ' . fnameescape(expand('<afile>:r'))
570 call s:GPGDebug(2, 'called FileReadPost autocommand for ' . fnameescape(expand('<afile>:r')))
573 " Allow the user to define actions for GnuPG buffers
574 silent doautocmd User GnuPG
579 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGDecrypt()")
582 " Function: s:GPGEncrypt() {{{2
584 " encrypts the buffer to all previous recipients
586 function s:GPGEncrypt()
587 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGEncrypt()")
589 " FileWriteCmd is only called when a portion of a buffer is being written to
590 " disk. Since Vim always sets the '[,'] marks to the part of a buffer that
591 " is being written, that can be used to determine whether BufWriteCmd or
592 " FileWriteCmd triggered us.
593 if [line("'["), line("']")] == [1, line('$')]
594 let auType = 'BufWrite'
596 let auType = 'FileWrite'
599 silent exe ':doautocmd '. auType .'Pre '. fnameescape(expand('<afile>:r'))
600 call s:GPGDebug(2, 'called '. auType .'Pre autocommand for ' . fnameescape(expand('<afile>:r')))
602 " store encoding and switch to a safe one
603 if (&fileencoding != &encoding)
604 let s:GPGEncoding = &encoding
605 let &encoding = &fileencoding
606 call s:GPGDebug(2, "encoding was \"" . s:GPGEncoding . "\", switched to \"" . &encoding . "\"")
608 let s:GPGEncoding = ""
609 call s:GPGDebug(2, "encoding and fileencoding are the same (\"" . &encoding . "\"), not switching")
612 " guard for unencrypted files
613 if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
615 let blackhole = input("Message could not be encrypted! (Press ENTER)")
617 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEncrypt()")
621 " initialize GPGOptions if not happened before
622 if (!exists("b:GPGOptions") || empty(b:GPGOptions))
623 let b:GPGOptions = []
624 if (exists("g:GPGPreferSymmetric") && g:GPGPreferSymmetric == 1)
625 let b:GPGOptions += ["symmetric"]
626 let b:GPGRecipients = []
628 let b:GPGOptions += ["encrypt"]
630 if (exists("g:GPGPreferArmor") && g:GPGPreferArmor == 1)
631 let b:GPGOptions += ["armor"]
633 if (exists("g:GPGPreferSign") && g:GPGPreferSign == 1)
634 let b:GPGOptions += ["sign"]
636 call s:GPGDebug(1, "no options set, so using default options: " . string(b:GPGOptions))
639 " built list of options
641 for option in b:GPGOptions
642 let options = options . " --" . option . " "
645 if (!exists('b:GPGRecipients'))
646 let b:GPGRecipients = []
649 " check here again if all recipients are available in the keyring
650 let recipients = s:GPGCheckRecipients(b:GPGRecipients)
652 " check if there are unknown recipients and warn
653 if !empty(recipients.unknown)
655 echom "Please use GPGEditRecipients to correct!!"
659 " Let user know whats happend and copy known_recipients back to buffer
660 let dummy = input("Press ENTER to quit")
663 " built list of recipients
664 let options .= ' ' . join(map(recipients.valid, '"-r ".v:val'), ' ')
667 let destfile = tempname()
668 let cmd = { 'level': 1, 'ex': "'[,']w !" }
669 let cmd.args = '--quiet --no-encrypt-to ' . options
670 let cmd.redirect = '>' . shellescape(destfile, 1)
671 silent call s:GPGExecute(cmd)
674 if (s:GPGEncoding != "")
675 let &encoding = s:GPGEncoding
676 call s:GPGDebug(2, "restored encoding \"" . &encoding . "\"")
679 if (v:shell_error) " message could not be encrypted
680 " Command failed, so clean up the tempfile
681 call delete(destfile)
683 let blackhole = input("Message could not be encrypted! (Press ENTER)")
685 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEncrypt()")
689 call rename(destfile, resolve(expand('<afile>')))
690 if auType == 'BufWrite'
694 silent exe ':doautocmd '. auType .'Post '. fnameescape(expand('<afile>:r'))
695 call s:GPGDebug(2, 'called '. auType .'Post autocommand for ' . fnameescape(expand('<afile>:r')))
697 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEncrypt()")
700 " Function: s:GPGViewRecipients() {{{2
702 " echo the recipients
704 function s:GPGViewRecipients()
705 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGViewRecipients()")
707 " guard for unencrypted files
708 if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
710 echom "File is not encrypted, all GPG functions disabled!"
712 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGViewRecipients()")
716 let recipients = s:GPGCheckRecipients(b:GPGRecipients)
718 echo 'This file has following recipients (Unknown recipients have a prepended "!"):'
719 " echo the recipients
720 for name in recipients.valid
721 let name = s:GPGIDToName(name)
725 " echo the unknown recipients
727 for name in recipients.unknown
728 let name = "!" . name
733 " check if there is any known recipient
734 if empty(recipients.valid)
736 echom 'There are no known recipients!'
740 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGViewRecipients()")
743 " Function: s:GPGEditRecipients() {{{2
745 " create a scratch buffer with all recipients to add/remove recipients
747 function s:GPGEditRecipients()
748 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGEditRecipients()")
750 " guard for unencrypted files
751 if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
753 echom "File is not encrypted, all GPG functions disabled!"
755 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEditRecipients()")
759 " only do this if it isn't already a GPGRecipients_* buffer
760 if (match(bufname("%"), "^\\(GPGRecipients_\\|GPGOptions_\\)") != 0 && match(bufname("%"), "\.\\(gpg\\|asc\\|pgp\\)$") >= 0)
763 let buffername = bufname("%")
764 let editbuffername = "GPGRecipients_" . buffername
766 " check if this buffer exists
767 if (!bufexists(editbuffername))
768 " create scratch buffer
769 execute 'silent! split ' . fnameescape(editbuffername)
771 " add a autocommand to regenerate the recipients after a write
772 autocmd BufHidden,BufUnload,BufWriteCmd <buffer> call s:GPGFinishRecipientsBuffer()
774 if (bufwinnr(editbuffername) >= 0)
775 " switch to scratch buffer window
776 execute 'silent! ' . bufwinnr(editbuffername) . "wincmd w"
778 " split scratch buffer window
779 execute 'silent! sbuffer ' . fnameescape(editbuffername)
781 " add a autocommand to regenerate the recipients after a write
782 autocmd BufHidden,BufUnload,BufWriteCmd <buffer> call s:GPGFinishRecipientsBuffer()
789 " Mark the buffer as a scratch buffer
790 setlocal buftype=acwrite
791 setlocal bufhidden=hide
797 " so we know for which other buffer this edit buffer is
798 let b:GPGCorrespondingTo = buffername
800 " put some comments to the scratch buffer
801 silent put ='GPG: ----------------------------------------------------------------------'
802 silent put ='GPG: Please edit the list of recipients, one recipient per line.'
803 silent put ='GPG: Unknown recipients have a prepended \"!\".'
804 silent put ='GPG: Lines beginning with \"GPG:\" are removed automatically.'
805 silent put ='GPG: Data after recipients between and including \"(\" and \")\" is ignored.'
806 silent put ='GPG: Closing this buffer commits changes.'
807 silent put ='GPG: ----------------------------------------------------------------------'
810 let recipients = s:GPGCheckRecipients(getbufvar(b:GPGCorrespondingTo, "GPGRecipients"))
812 " if there are no known or unknown recipients, use the default ones
813 if (empty(recipients.valid) && empty(recipients.unknown))
814 if (type(g:GPGDefaultRecipients) == type([]))
815 let recipients = s:GPGCheckRecipients(g:GPGDefaultRecipients)
818 echom "g:GPGDefaultRecipients is not a Vim list, please correct this in your vimrc!"
823 " put the recipients in the scratch buffer
824 for name in recipients.valid
825 let name = s:GPGIDToName(name)
829 " put the unknown recipients in the scratch buffer
830 let syntaxPattern = ''
831 if !empty(recipients.unknown)
832 let flaggedNames = map(recipients.unknown, '"!".v:val')
833 call append('$', flaggedNames)
834 let syntaxPattern = '\(' . join(flaggedNames, '\|') . '\)'
837 for line in g:GPGPossibleRecipients
838 silent put ='GPG: '.line
842 if (has("syntax") && exists("g:syntax_on"))
843 highlight clear GPGUnknownRecipient
844 if !empty(syntaxPattern)
845 execute 'syntax match GPGUnknownRecipient "' . syntaxPattern . '"'
846 highlight link GPGUnknownRecipient GPGHighlightUnknownRecipient
849 syntax match GPGComment "^GPG:.*$"
850 execute 'syntax match GPGComment "' . s:GPGMagicString . '.*$"'
851 highlight clear GPGComment
852 highlight link GPGComment Comment
855 " delete the empty first line
858 " jump to the first recipient
863 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEditRecipients()")
866 " Function: s:GPGFinishRecipientsBuffer() {{{2
868 " create a new recipient list from RecipientsBuffer
870 function s:GPGFinishRecipientsBuffer()
871 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGFinishRecipientsBuffer()")
873 " guard for unencrypted files
874 if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
876 echom "File is not encrypted, all GPG functions disabled!"
878 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGFinishRecipientsBuffer()")
882 " go to buffer before doing work
883 if (bufnr("%") != expand("<abuf>"))
884 " switch to scratch buffer window
885 execute 'silent! ' . bufwinnr(expand("<afile>")) . "wincmd w"
888 " delete the autocommand
891 " get the recipients from the scratch buffer
893 let lines = getline(1,"$")
894 for recipient in lines
895 let matches = matchlist(recipient, '^\(.\{-}\)\%(' . s:GPGMagicString . '(ID:\s\+\(' . s:keyPattern . '\)\s\+.*\)\=$')
897 let recipient = matches[2] ? matches[2] : matches[1]
899 " delete all spaces at beginning and end of the recipient
900 " also delete a '!' at the beginning of the recipient
901 let recipient = substitute(recipient, "^[[:space:]!]*\\(.\\{-}\\)[[:space:]]*$", "\\1", "")
903 " delete comment lines
904 let recipient = substitute(recipient, "^GPG:.*$", "", "")
906 " only do this if the line is not empty
908 let gpgid = s:GPGNameToID(recipient)
910 if (match(recipients, gpgid) < 0)
911 let recipients += [gpgid]
914 if (match(recipients, recipient) < 0)
915 let recipients += [recipient]
917 echom "The recipient \"" . recipient . "\" is not in your public keyring!"
924 " write back the new recipient list to the corresponding buffer and mark it
925 " as modified. Buffer is now for sure an encrypted buffer.
926 call setbufvar(b:GPGCorrespondingTo, "GPGRecipients", recipients)
927 call setbufvar(b:GPGCorrespondingTo, "&mod", 1)
928 call setbufvar(b:GPGCorrespondingTo, "GPGEncrypted", 1)
930 " check if there is any known recipient
933 echom 'There are no known recipients!'
937 " reset modified flag
940 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGFinishRecipientsBuffer()")
943 " Function: s:GPGViewOptions() {{{2
945 " echo the recipients
947 function s:GPGViewOptions()
948 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGViewOptions()")
950 " guard for unencrypted files
951 if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
953 echom "File is not encrypted, all GPG functions disabled!"
955 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGViewOptions()")
959 if (exists("b:GPGOptions"))
960 echo 'This file has following options:'
962 for option in b:GPGOptions
967 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGViewOptions()")
970 " Function: s:GPGEditOptions() {{{2
972 " create a scratch buffer with all recipients to add/remove recipients
974 function s:GPGEditOptions()
975 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGEditOptions()")
977 " guard for unencrypted files
978 if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
980 echom "File is not encrypted, all GPG functions disabled!"
982 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEditOptions()")
986 " only do this if it isn't already a GPGOptions_* buffer
987 if (match(bufname("%"), "^\\(GPGRecipients_\\|GPGOptions_\\)") != 0 && match(bufname("%"), "\.\\(gpg\\|asc\\|pgp\\)$") >= 0)
990 let buffername = bufname("%")
991 let editbuffername = "GPGOptions_" . buffername
993 " check if this buffer exists
994 if (!bufexists(editbuffername))
995 " create scratch buffer
996 execute 'silent! split ' . fnameescape(editbuffername)
998 " add a autocommand to regenerate the options after a write
999 autocmd BufHidden,BufUnload,BufWriteCmd <buffer> call s:GPGFinishOptionsBuffer()
1001 if (bufwinnr(editbuffername) >= 0)
1002 " switch to scratch buffer window
1003 execute 'silent! ' . bufwinnr(editbuffername) . "wincmd w"
1005 " split scratch buffer window
1006 execute 'silent! sbuffer ' . fnameescape(editbuffername)
1008 " add a autocommand to regenerate the options after a write
1009 autocmd BufHidden,BufUnload,BufWriteCmd <buffer> call s:GPGFinishOptionsBuffer()
1016 " Mark the buffer as a scratch buffer
1017 setlocal buftype=nofile
1020 setlocal nobuflisted
1023 " so we know for which other buffer this edit buffer is
1024 let b:GPGCorrespondingTo = buffername
1026 " put some comments to the scratch buffer
1027 silent put ='GPG: ----------------------------------------------------------------------'
1028 silent put ='GPG: THERE IS NO CHECK OF THE ENTERED OPTIONS!'
1029 silent put ='GPG: YOU NEED TO KNOW WHAT YOU ARE DOING!'
1030 silent put ='GPG: IF IN DOUBT, QUICKLY EXIT USING :x OR :bd.'
1031 silent put ='GPG: Please edit the list of options, one option per line.'
1032 silent put ='GPG: Please refer to the gpg documentation for valid options.'
1033 silent put ='GPG: Lines beginning with \"GPG:\" are removed automatically.'
1034 silent put ='GPG: Closing this buffer commits changes.'
1035 silent put ='GPG: ----------------------------------------------------------------------'
1037 " put the options in the scratch buffer
1038 let options = getbufvar(b:GPGCorrespondingTo, "GPGOptions")
1040 for option in options
1044 " delete the empty first line
1047 " jump to the first option
1051 if (has("syntax") && exists("g:syntax_on"))
1052 syntax match GPGComment "^GPG:.*$"
1053 highlight clear GPGComment
1054 highlight link GPGComment Comment
1058 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEditOptions()")
1061 " Function: s:GPGFinishOptionsBuffer() {{{2
1063 " create a new option list from OptionsBuffer
1065 function s:GPGFinishOptionsBuffer()
1066 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGFinishOptionsBuffer()")
1068 " guard for unencrypted files
1069 if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
1071 echom "File is not encrypted, all GPG functions disabled!"
1073 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGFinishOptionsBuffer()")
1077 " go to buffer before doing work
1078 if (bufnr("%") != expand("<abuf>"))
1079 " switch to scratch buffer window
1080 execute 'silent! ' . bufwinnr(expand("<afile>")) . "wincmd w"
1083 " clear options and unknownOptions
1085 let unknownOptions = []
1087 " delete the autocommand
1090 " get the options from the scratch buffer
1091 let lines = getline(1, "$")
1093 " delete all spaces at beginning and end of the option
1094 " also delete a '!' at the beginning of the option
1095 let option = substitute(option, "^[[:space:]!]*\\(.\\{-}\\)[[:space:]]*$", "\\1", "")
1096 " delete comment lines
1097 let option = substitute(option, "^GPG:.*$", "", "")
1099 " only do this if the line is not empty
1100 if (!empty(option) && match(options, option) < 0)
1101 let options += [option]
1105 " write back the new option list to the corresponding buffer and mark it
1107 call setbufvar(b:GPGCorrespondingTo, "GPGOptions", options)
1108 call setbufvar(b:GPGCorrespondingTo, "&mod", 1)
1110 " reset modified flag
1113 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGFinishOptionsBuffer()")
1116 " Function: s:GPGCheckRecipients(tocheck) {{{2
1118 " check if recipients are known
1119 " Returns: dictionary of recipients, {'valid': [], 'unknown': []}
1121 function s:GPGCheckRecipients(tocheck)
1122 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGCheckRecipients()")
1124 let recipients = {'valid': [], 'unknown': []}
1126 if (type(a:tocheck) == type([]))
1127 for recipient in a:tocheck
1128 let gpgid = s:GPGNameToID(recipient)
1130 if (match(recipients.valid, gpgid) < 0)
1131 call add(recipients.valid, gpgid)
1134 if (match(recipients.unknown, recipient) < 0)
1135 call add(recipients.unknown, recipient)
1137 echom "The recipient \"" . recipient . "\" is not in your public keyring!"
1144 call s:GPGDebug(2, "recipients are: " . string(recipients.valid))
1145 call s:GPGDebug(2, "unknown recipients are: " . string(recipients.unknown))
1147 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGCheckRecipients()")
1151 " Function: s:GPGNameToID(name) {{{2
1153 " find GPG key ID corresponding to a name
1154 " Returns: ID for the given name
1156 function s:GPGNameToID(name)
1157 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGNameToID()")
1159 " ask gpg for the id for a name
1160 let cmd = { 'level': 2 }
1161 let cmd.args = '--quiet --with-colons --fixed-list-mode --list-keys ' . shellescape(a:name)
1162 let output = s:GPGSystem(cmd)
1164 " when called with "--with-colons" gpg encodes its output _ALWAYS_ as UTF-8,
1165 " so convert it, if necessary
1166 if (&encoding != "utf-8")
1167 let output = iconv(output, "utf-8", &encoding)
1169 let lines = split(output, "\n")
1171 " parse the output of gpg
1177 let has_strftime = exists('*strftime')
1178 let choices = "The name \"" . a:name . "\" is ambiguous. Please select the correct key:\n"
1181 let fields = split(line, ":")
1183 " search for the next pub
1184 if (fields[0] == "pub")
1185 " check if this key has already been processed
1186 if has_key(seen_keys, fields[4])
1191 let seen_keys[fields[4]] = 1
1193 " Ignore keys which are not usable for encryption
1194 if fields[11] !~? 'e'
1198 let identity = fields[4]
1199 let gpgids += [identity]
1201 let choices = choices . counter . ": ID: 0x" . identity . " created at " . strftime("%c", fields[5]) . "\n"
1203 let choices = choices . counter . ": ID: 0x" . identity . "\n"
1205 let counter = counter+1
1207 " search for the next uid
1208 elseif (!skip_key && fields[0] == "uid")
1209 let choices = choices . " " . fields[9] . "\n"
1214 " counter > 1 means we have more than one results
1217 let choices = choices . "Enter number: "
1218 let answer = input(choices, "0")
1219 while (answer == "")
1220 let answer = input("Enter number: ", "0")
1224 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGNameToID()")
1225 return get(gpgids, answer, "")
1228 " Function: s:GPGIDToName(identity) {{{2
1230 " find name corresponding to a GPG key ID
1231 " Returns: Name for the given ID
1233 function s:GPGIDToName(identity)
1234 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGIDToName()")
1236 " TODO is the encryption subkey really unique?
1238 " ask gpg for the id for a name
1239 let cmd = { 'level': 2 }
1240 let cmd.args = '--quiet --with-colons --fixed-list-mode --list-keys ' . a:identity
1241 let output = s:GPGSystem(cmd)
1243 " when called with "--with-colons" gpg encodes its output _ALWAYS_ as UTF-8,
1244 " so convert it, if necessary
1245 if (&encoding != "utf-8")
1246 let output = iconv(output, "utf-8", &encoding)
1248 let lines = split(output, "\n")
1250 " parse the output of gpg
1254 let fields = split(line, ":")
1256 if !pubseen " search for the next pub
1257 if (fields[0] == "pub")
1258 " Ignore keys which are not usable for encryption
1259 if fields[11] !~? 'e'
1265 else " search for the next uid
1266 if (fields[0] == "uid")
1268 if exists("*strftime")
1269 let uid = fields[9] . s:GPGMagicString . "(ID: 0x" . a:identity . " created at " . strftime("%c", fields[5]) . ")"
1271 let uid = fields[9] . s:GPGMagicString . "(ID: 0x" . a:identity . ")"
1278 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGIDToName()")
1282 function s:GPGPreCmd()
1283 let &shellredir = s:shellredir
1284 let &shell = s:shell
1285 let &shelltemp = s:shelltemp
1288 function s:GPGPostCmd()
1289 let &shellredir = s:shellredirsave
1290 let &shell = s:shellsave
1291 let &shelltemp = s:shelltempsave
1292 " Workaround a bug in the interaction between console vim and
1293 " pinentry-curses by forcing Vim to re-detect and setup its terminal
1296 silent doautocmd TermChanged
1299 " Function: s:GPGSystem(dict) {{{2
1301 " run g:GPGCommand using system(), logging the commandline and output. This
1302 " uses temp files (regardless of how 'shelltemp' is set) to hold the output of
1303 " the command, so it must not be used for sensitive commands.
1304 " Recognized keys are:
1305 " level - Debug level at which the commandline and output will be logged
1306 " args - Arguments to be given to g:GPGCommand
1308 " Returns: command output
1310 function s:GPGSystem(dict)
1311 let commandline = s:GPGCommand
1312 if (!empty(g:GPGHomedir))
1313 let commandline .= ' --homedir ' . shellescape(g:GPGHomedir)
1315 let commandline .= ' ' . a:dict.args
1316 let commandline .= ' ' . s:stderrredirnull
1317 call s:GPGDebug(a:dict.level, "command: ". commandline)
1320 let output = system(commandline)
1323 call s:GPGDebug(a:dict.level, "rc: ". v:shell_error)
1324 call s:GPGDebug(a:dict.level, "output: ". output)
1328 " Function: s:GPGExecute(dict) {{{2
1330 " run g:GPGCommand using :execute, logging the commandline
1331 " Recognized keys are:
1332 " level - Debug level at which the commandline will be logged
1333 " args - Arguments to be given to g:GPGCommand
1334 " ex - Ex command which will be :executed
1335 " redirect - Shell redirect to use, if needed
1337 function s:GPGExecute(dict)
1338 let commandline = printf('%s%s', a:dict.ex, s:GPGCommand)
1339 if (!empty(g:GPGHomedir))
1340 let commandline .= ' --homedir ' . shellescape(g:GPGHomedir, 1)
1342 let commandline .= ' ' . a:dict.args
1343 if (has_key(a:dict, 'redirect'))
1344 let commandline .= ' ' . a:dict.redirect
1346 let commandline .= ' ' . s:stderrredirnull
1347 call s:GPGDebug(a:dict.level, "command: " . commandline)
1353 call s:GPGDebug(a:dict.level, "rc: ". v:shell_error)
1356 " Function: s:GPGDebug(level, text) {{{2
1358 " output debug message, if this message has high enough importance
1359 " only define function if GPGDebugLevel set at all
1361 function s:GPGDebug(level, text)
1362 if exists("g:GPGDebugLevel") && g:GPGDebugLevel >= a:level
1363 if exists("g:GPGDebugLog")
1364 execute "redir >> " . g:GPGDebugLog
1365 silent echom "GnuPG: " . a:text
1368 echom "GnuPG: " . a:text
1373 " Section: Commands {{{1
1375 command! GPGViewRecipients call s:GPGViewRecipients()
1376 command! GPGEditRecipients call s:GPGEditRecipients()
1377 command! GPGViewOptions call s:GPGViewOptions()
1378 command! GPGEditOptions call s:GPGEditOptions()
1380 " Section: Menu {{{1
1383 amenu <silent> Plugin.GnuPG.View\ Recipients :GPGViewRecipients<CR>
1384 amenu <silent> Plugin.GnuPG.Edit\ Recipients :GPGEditRecipients<CR>
1385 amenu <silent> Plugin.GnuPG.View\ Options :GPGViewOptions<CR>
1386 amenu <silent> Plugin.GnuPG.Edit\ Options :GPGEditOptions<CR>
1389 " vim600: set foldmethod=marker foldlevel=0 :