2 " Last Change: 2015 Sep 29
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 --trust-model always".
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. Default is
104 " let g:GPGPossibleRecipients=[
105 " \"Example User <example@example.com>",
106 " \"Other User <otherexample@example.com>"
111 " If set to 1, use pipes instead of temporary files when interacting with
112 " gnupg. When set to 1, this can cause terminal-based gpg agents to not
113 " display correctly when prompting for passwords. Defaults to 0.
116 " If set, specifies the directory that will be used for GPG's homedir.
117 " This corresponds to gpg's --homedir option. This variable is a Vim
118 " string. Default is unset.
121 " If set, overrides the default set of file patterns that determine
122 " whether this plugin will be activated. Defaults to
123 " '*.\(gpg\|asc\|pgp\)'.
127 " In some cases gvim can't decrypt files
129 " This is caused by the fact that a running gvim has no TTY and thus gpg is
130 " not able to ask for the passphrase by itself. This is a problem for Windows
131 " and Linux versions of gvim and could not be solved unless a "terminal
132 " emulation" is implemented for gvim. To circumvent this you have to use any
133 " combination of gpg-agent and a graphical pinentry program:
136 " you need to provide the passphrase for the needed key to gpg-agent
137 " in a terminal before you open files with gvim which require this key.
140 " you will get a popup window every time you open a file that needs to
143 " - gpgagent and pinentry:
144 " you will get a popup window the first time you open a file that
145 " needs to be decrypted.
149 " - Mathieu Clabaut for inspirations through his vimspell.vim script.
150 " - Richard Bronosky for patch to enable ".pgp" suffix.
151 " - Erik Remmelzwaal for patch to enable windows support and patient beta
153 " - Lars Becker for patch to make gpg2 working.
154 " - Thomas Arendsen Hein for patch to convert encoding of gpg output.
155 " - Karl-Heinz Ruskowski for patch to fix unknown recipients and trust model
156 " and patient beta testing.
157 " - Giel van Schijndel for patch to get GPG_TTY dynamically.
158 " - Sebastian Luettich for patch to fix issue with symmetric encryption an set
160 " - Tim Swast for patch to generate signed files.
161 " - James Vega for patches for better '*.asc' handling, better filename
162 " escaping and better handling of multiple keyrings.
164 " Section: Plugin header {{{1
166 " guard against multiple loads {{{2
167 if (exists("g:loaded_gnupg") || &cp || exists("#GnuPG"))
170 let g:loaded_gnupg = '2.5'
173 " check for correct vim version {{{2
175 echohl ErrorMsg | echo 'plugin gnupg.vim requires Vim version >= 7.2' | echohl None
179 " Section: Autocmd setup {{{1
181 if (!exists("g:GPGFilePattern"))
182 let g:GPGFilePattern = '*.\(gpg\|asc\|pgp\)'
189 exe "autocmd BufReadCmd " . g:GPGFilePattern . " call s:GPGInit(1) |" .
190 \ " call s:GPGDecrypt(1)"
191 exe "autocmd FileReadCmd " . g:GPGFilePattern . " call s:GPGInit(0) |" .
192 \ " call s:GPGDecrypt(0)"
194 " convert all text to encrypted text before writing
195 " We check for GPGCorrespondingTo to avoid triggering on writes in GPG Options/Recipient windows
196 exe "autocmd BufWriteCmd,FileWriteCmd " . g:GPGFilePattern . " if !exists('b:GPGCorrespondingTo') |" .
197 \ " call s:GPGInit(0) |" .
198 \ " call s:GPGEncrypt() |" .
201 " cleanup on leaving vim
202 exe "autocmd VimLeave " . g:GPGFilePattern . " call s:GPGCleanup()"
205 " Section: Constants {{{1
207 let s:GPGMagicString = "\t \t"
208 let s:keyPattern = '\%(0x\)\=[[:xdigit:]]\{8,16}'
210 " Section: Highlight setup {{{1
212 highlight default link GPGWarning WarningMsg
213 highlight default link GPGError ErrorMsg
214 highlight default link GPGHighlightUnknownRecipient ErrorMsg
216 " Section: Functions {{{1
218 " Function: s:shellescape(s[, special]) {{{2
220 " Calls shellescape(), also taking into account 'shellslash'
221 " when on Windows and using $COMSPEC as the shell.
223 " Returns: shellescaped string
225 function s:shellescape(s, ...)
226 let special = a:0 ? a:1 : 0
227 if exists('+shellslash') && &shell == $COMSPEC
228 let ssl = &shellslash
231 let escaped = shellescape(a:s, special)
233 let &shellslash = ssl
235 let escaped = shellescape(a:s, special)
241 " Function: s:GPGInit(bufread) {{{2
243 " initialize the plugin
244 " The bufread argument specifies whether this was called due to BufReadCmd
246 function s:GPGInit(bufread)
247 call s:GPGDebug(3, printf(">>>>>>>> Entering s:GPGInit(%d)", a:bufread))
249 " For FileReadCmd, we're reading the contents into another buffer. If that
250 " buffer is also destined to be encrypted, then these settings will have
251 " already been set, otherwise don't set them since it limits the
252 " functionality of the cleartext buffer.
254 " we don't want a swap file, as it writes unencrypted data to disk
257 " if persistent undo is present, disable it for this buffer
258 if exists('+undofile')
262 " first make sure nothing is written to ~/.viminfo while editing
267 " the rest only has to be run once
272 " check what gpg command to use
273 if (!exists("g:GPGExecutable"))
274 let g:GPGExecutable = "gpg --trust-model always"
277 " check if gpg-agent is allowed
278 if (!exists("g:GPGUseAgent"))
279 let g:GPGUseAgent = 1
282 " check if symmetric encryption is preferred
283 if (!exists("g:GPGPreferSymmetric"))
284 let g:GPGPreferSymmetric = 0
287 " check if armored files are preferred
288 if (!exists("g:GPGPreferArmor"))
289 " .asc files should be armored as that's what the extension is used for
290 if expand('<afile>') =~ '\.asc$'
291 let g:GPGPreferArmor = 1
293 let g:GPGPreferArmor = 0
297 " check if signed files are preferred
298 if (!exists("g:GPGPreferSign"))
299 let g:GPGPreferSign = 0
302 " start with empty default recipients if none is defined so far
303 if (!exists("g:GPGDefaultRecipients"))
304 let g:GPGDefaultRecipients = []
307 if (!exists("g:GPGPossibleRecipients"))
308 let g:GPGPossibleRecipients = []
312 " prefer not to use pipes since it can garble gpg agent display
313 if (!exists("g:GPGUsePipes"))
314 let g:GPGUsePipes = 0
317 " allow alternate gnupg homedir
318 if (!exists('g:GPGHomedir'))
319 let g:GPGHomedir = ''
323 call s:GPGDebug(1, "gnupg.vim ". g:loaded_gnupg)
325 let s:GPGCommand = g:GPGExecutable
327 " don't use tty in gvim except for windows: we get their a tty for free.
328 " FIXME find a better way to avoid an error.
329 " with this solution only --use-agent will work
330 if (has("gui_running") && !has("gui_win32"))
331 let s:GPGCommand .= " --no-tty"
334 " setup shell environment for unix and windows
335 let s:shellredirsave = &shellredir
336 let s:shellsave = &shell
337 let s:shelltempsave = &shelltemp
338 " noshelltemp isn't currently supported on Windows, but it doesn't cause any
339 " errors and this future proofs us against requiring changes if Windows
340 " gains noshelltemp functionality
341 let s:shelltemp = !g:GPGUsePipes
343 " unix specific settings
344 let s:shellredir = ">%s 2>&1"
345 let s:shell = '/bin/sh'
346 let s:stderrredirnull = '2>/dev/null'
348 " windows specific settings
349 let s:shellredir = '>%s'
351 let s:stderrredirnull = '2>nul'
354 call s:GPGDebug(3, "shellredirsave: " . s:shellredirsave)
355 call s:GPGDebug(3, "shellsave: " . s:shellsave)
356 call s:GPGDebug(3, "shelltempsave: " . s:shelltempsave)
358 call s:GPGDebug(3, "shell: " . s:shell)
359 call s:GPGDebug(3, "shellcmdflag: " . &shellcmdflag)
360 call s:GPGDebug(3, "shellxquote: " . &shellxquote)
361 call s:GPGDebug(3, "shellredir: " . s:shellredir)
362 call s:GPGDebug(3, "stderrredirnull: " . s:stderrredirnull)
364 call s:GPGDebug(3, "shell implementation: " . resolve(s:shell))
366 " find the supported algorithms
367 let output = s:GPGSystem({ 'level': 2, 'args': '--version' })
369 let gpgversion = substitute(output, '^gpg (GnuPG) \([0-9]\+\.\d\+\).*', '\1', '')
370 let s:GPGPubkey = substitute(output, ".*Pubkey: \\(.\\{-}\\)\n.*", "\\1", "")
371 let s:GPGCipher = substitute(output, ".*Cipher: \\(.\\{-}\\)\n.*", "\\1", "")
372 let s:GPGHash = substitute(output, ".*Hash: \\(.\\{-}\\)\n.*", "\\1", "")
373 let s:GPGCompress = substitute(output, ".*Compress.\\{-}: \\(.\\{-}\\)\n.*", "\\1", "")
375 " determine if gnupg can use the gpg-agent
376 if (str2float(gpgversion) >= 2.1 || (exists("$GPG_AGENT_INFO") && g:GPGUseAgent == 1))
377 if (!exists("$GPG_TTY") && !has("gui_running"))
378 " Need to determine the associated tty by running a command in the
379 " shell. We can't use system() here because that doesn't run in a shell
380 " connected to a tty, so it's rather useless.
382 " Save/restore &modified so the buffer isn't incorrectly marked as
383 " modified just by detecting the correct tty value.
384 " Do the &undolevels dance so the :read and :delete don't get added into
385 " the undo tree, as the user needn't be aware of these.
386 let [mod, levels] = [&l:modified, &undolevels]
389 let $GPG_TTY = getline('.')
391 let [&l:modified, &undolevels] = [mod, levels]
392 " redraw is needed since we're using silent to run !tty, c.f. :help :!
397 echom "$GPG_TTY is not set and the `tty` command failed! gpg-agent might not work."
401 let s:GPGCommand .= " --use-agent"
403 let s:GPGCommand .= " --no-use-agent"
406 call s:GPGDebug(2, "public key algorithms: " . s:GPGPubkey)
407 call s:GPGDebug(2, "cipher algorithms: " . s:GPGCipher)
408 call s:GPGDebug(2, "hashing algorithms: " . s:GPGHash)
409 call s:GPGDebug(2, "compression algorithms: " . s:GPGCompress)
410 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGInit()")
414 " Function: s:GPGCleanup() {{{2
416 " cleanup on leaving vim
418 function s:GPGCleanup()
419 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGCleanup()")
425 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGCleanup()")
428 " Function: s:GPGDecrypt(bufread) {{{2
430 " decrypt the buffer and find all recipients of the encrypted file
431 " The bufread argument specifies whether this was called due to BufReadCmd
433 function s:GPGDecrypt(bufread)
434 call s:GPGDebug(3, printf(">>>>>>>> Entering s:GPGDecrypt(%d)", a:bufread))
436 " get the filename of the current buffer
437 let filename = expand("<afile>:p")
439 " clear GPGRecipients and GPGOptions
440 if type(g:GPGDefaultRecipients) == type([])
441 let b:GPGRecipients = copy(g:GPGDefaultRecipients)
443 let b:GPGRecipients = []
445 echom "g:GPGDefaultRecipients is not a Vim list, please correct this in your vimrc!"
448 let b:GPGOptions = []
450 " file name minus extension
451 let autocmd_filename = fnameescape(expand('<afile>:r'))
453 " File doesn't exist yet, so nothing to decrypt
454 if !filereadable(filename)
455 " Allow the user to define actions for GnuPG buffers
456 silent doautocmd User GnuPG
457 " call the autocommand for the file minus .gpg$
458 silent execute ':doautocmd BufNewFile ' . autocmd_filename
459 call s:GPGDebug(2, 'called BufNewFile autocommand for ' . autocmd_filename)
461 " This is a new file, so force the user to edit the recipient list if
462 " they open a new file and public keys are preferred
463 if (g:GPGPreferSymmetric == 0)
464 call s:GPGEditRecipients()
470 " Only let this if the file actually exists, otherwise GPG functionality
471 " will be disabled when editing a buffer that doesn't yet have a backing
473 let b:GPGEncrypted = 0
475 " find the recipients of the file
476 let cmd = { 'level': 3 }
477 let cmd.args = '--verbose --decrypt --list-only --dry-run --no-use-agent --logger-fd 1 ' . s:shellescape(filename)
478 let output = s:GPGSystem(cmd)
480 " Suppress the "N more lines" message when editing a file, not when reading
481 " the contents of a file into a buffer
482 let silent = a:bufread ? 'silent ' : ''
484 let asymmPattern = 'gpg: public key is ' . s:keyPattern
485 " check if the file is symmetric/asymmetric encrypted
486 if (match(output, "gpg: encrypted with [[:digit:]]\\+ passphrase") >= 0)
487 " file is symmetric encrypted
488 let b:GPGEncrypted = 1
489 call s:GPGDebug(1, "this file is symmetric encrypted")
491 let b:GPGOptions += ["symmetric"]
493 " find the used cipher algorithm
494 let cipher = substitute(output, ".*gpg: \\([^ ]\\+\\) encrypted data.*", "\\1", "")
495 if (match(s:GPGCipher, "\\<" . cipher . "\\>") >= 0)
496 let b:GPGOptions += ["cipher-algo " . cipher]
497 call s:GPGDebug(1, "cipher-algo is " . cipher)
500 echom "The cipher " . cipher . " is not known by the local gpg command. Using default!"
504 elseif (match(output, asymmPattern) >= 0)
505 " file is asymmetric encrypted
506 let b:GPGEncrypted = 1
507 call s:GPGDebug(1, "this file is asymmetric encrypted")
509 let b:GPGOptions += ["encrypt"]
511 " find the used public keys
512 let start = match(output, asymmPattern)
514 let start = start + strlen("gpg: public key is ")
515 let recipient = matchstr(output, s:keyPattern, start)
516 call s:GPGDebug(1, "recipient is " . recipient)
517 let name = s:GPGNameToID(recipient)
519 let b:GPGRecipients += [name]
520 call s:GPGDebug(1, "name of recipient is " . name)
522 let b:GPGRecipients += [recipient]
524 echom "The recipient \"" . recipient . "\" is not in your public keyring!"
527 let start = match(output, asymmPattern, start)
530 " file is not encrypted
531 let b:GPGEncrypted = 0
532 call s:GPGDebug(1, "this file is not encrypted")
534 echom "File is not encrypted, all GPG functions disabled!"
536 exe printf('%sr %s', silent, fnameescape(filename))
537 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGDecrypt()")
542 silent execute ':doautocmd BufReadPre ' . autocmd_filename
543 call s:GPGDebug(2, 'called BufReadPre autocommand for ' . autocmd_filename)
545 silent execute ':doautocmd FileReadPre ' . autocmd_filename
546 call s:GPGDebug(2, 'called FileReadPre autocommand for ' . autocmd_filename)
549 " check if the message is armored
550 if (match(output, "gpg: armor header") >= 0)
551 call s:GPGDebug(1, "this file is armored")
552 let b:GPGOptions += ["armor"]
555 " finally decrypt the buffer content
556 " since even with the --quiet option passphrase typos will be reported,
557 " we must redirect stderr (using shell temporarily)
558 call s:GPGDebug(1, "decrypting file")
559 let cmd = { 'level': 1, 'ex': silent . 'r !' }
560 let cmd.args = '--quiet --decrypt ' . s:shellescape(filename, 1)
561 call s:GPGExecute(cmd)
563 if (v:shell_error) " message could not be decrypted
565 let blackhole = input("Message could not be decrypted! (Press ENTER)")
567 " Only wipeout the buffer if we were creating one to start with.
568 " FileReadCmd just reads the content into the existing buffer
572 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGDecrypt()")
577 " In order to make :undo a no-op immediately after the buffer is read,
578 " we need to do this dance with 'undolevels'. Actually discarding the undo
579 " history requires performing a change after setting 'undolevels' to -1 and,
580 " luckily, we have one we need to do (delete the extra line from the :r
582 let levels = &undolevels
584 " :lockmarks doesn't actually prevent '[,'] from being overwritten, so we
585 " need to manually set them ourselves instead
589 let &undolevels = levels
590 " call the autocommand for the file minus .gpg$
591 silent execute ':doautocmd BufReadPost ' . autocmd_filename
592 call s:GPGDebug(2, 'called BufReadPost autocommand for ' . autocmd_filename)
594 " call the autocommand for the file minus .gpg$
595 silent execute ':doautocmd FileReadPost ' . autocmd_filename
596 call s:GPGDebug(2, 'called FileReadPost autocommand for ' . autocmd_filename)
599 " Allow the user to define actions for GnuPG buffers
600 silent doautocmd User GnuPG
605 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGDecrypt()")
608 " Function: s:GPGEncrypt() {{{2
610 " encrypts the buffer to all previous recipients
612 function s:GPGEncrypt()
613 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGEncrypt()")
615 " FileWriteCmd is only called when a portion of a buffer is being written to
616 " disk. Since Vim always sets the '[,'] marks to the part of a buffer that
617 " is being written, that can be used to determine whether BufWriteCmd or
618 " FileWriteCmd triggered us.
619 if [line("'["), line("']")] == [1, line('$')]
620 let auType = 'BufWrite'
622 let auType = 'FileWrite'
625 " file name minus extension
626 let autocmd_filename = fnameescape(expand('<afile>:r'))
628 silent exe ':doautocmd '. auType .'Pre '. autocmd_filename
629 call s:GPGDebug(2, 'called '. auType .'Pre autocommand for ' . autocmd_filename)
631 " store encoding and switch to a safe one
632 if (&fileencoding != &encoding)
633 let s:GPGEncoding = &encoding
634 let &encoding = &fileencoding
635 call s:GPGDebug(2, "encoding was \"" . s:GPGEncoding . "\", switched to \"" . &encoding . "\"")
637 let s:GPGEncoding = ""
638 call s:GPGDebug(2, "encoding and fileencoding are the same (\"" . &encoding . "\"), not switching")
641 " guard for unencrypted files
642 if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
644 let blackhole = input("Message could not be encrypted! (Press ENTER)")
646 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEncrypt()")
650 " initialize GPGOptions if not happened before
651 if (!exists("b:GPGOptions") || empty(b:GPGOptions))
652 let b:GPGOptions = []
653 if (exists("g:GPGPreferSymmetric") && g:GPGPreferSymmetric == 1)
654 let b:GPGOptions += ["symmetric"]
655 let b:GPGRecipients = []
657 let b:GPGOptions += ["encrypt"]
659 if (exists("g:GPGPreferArmor") && g:GPGPreferArmor == 1)
660 let b:GPGOptions += ["armor"]
662 if (exists("g:GPGPreferSign") && g:GPGPreferSign == 1)
663 let b:GPGOptions += ["sign"]
665 call s:GPGDebug(1, "no options set, so using default options: " . string(b:GPGOptions))
668 " built list of options
670 for option in b:GPGOptions
671 let options = options . " --" . option . " "
674 if (!exists('b:GPGRecipients'))
675 let b:GPGRecipients = []
678 " check here again if all recipients are available in the keyring
679 let recipients = s:GPGCheckRecipients(b:GPGRecipients)
681 " check if there are unknown recipients and warn
682 if !empty(recipients.unknown)
684 echom "Please use GPGEditRecipients to correct!!"
688 " Let user know whats happend and copy known_recipients back to buffer
689 let dummy = input("Press ENTER to quit")
692 " built list of recipients
693 let options .= ' ' . join(map(recipients.valid, '"-r ".v:val'), ' ')
696 let destfile = tempname()
697 let cmd = { 'level': 1, 'ex': "'[,']w !" }
698 let cmd.args = '--quiet --no-encrypt-to ' . options
699 let cmd.redirect = '>' . s:shellescape(destfile, 1)
700 silent call s:GPGExecute(cmd)
703 if (s:GPGEncoding != "")
704 let &encoding = s:GPGEncoding
705 call s:GPGDebug(2, "restored encoding \"" . &encoding . "\"")
708 if (v:shell_error) " message could not be encrypted
709 " Command failed, so clean up the tempfile
710 call delete(destfile)
712 let blackhole = input("Message could not be encrypted! (Press ENTER)")
714 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEncrypt()")
718 call rename(destfile, resolve(expand('<afile>')))
719 if auType == 'BufWrite'
723 silent exe ':doautocmd '. auType .'Post '. autocmd_filename
724 call s:GPGDebug(2, 'called '. auType .'Post autocommand for ' . autocmd_filename)
726 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEncrypt()")
729 " Function: s:GPGViewRecipients() {{{2
731 " echo the recipients
733 function s:GPGViewRecipients()
734 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGViewRecipients()")
736 " guard for unencrypted files
737 if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
739 echom "File is not encrypted, all GPG functions disabled!"
741 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGViewRecipients()")
745 let recipients = s:GPGCheckRecipients(b:GPGRecipients)
747 echo 'This file has following recipients (Unknown recipients have a prepended "!"):'
748 " echo the recipients
749 for name in recipients.valid
750 let name = s:GPGIDToName(name)
754 " echo the unknown recipients
756 for name in recipients.unknown
757 let name = "!" . name
762 " check if there is any known recipient
763 if empty(recipients.valid)
765 echom 'There are no known recipients!'
769 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGViewRecipients()")
772 " Function: s:GPGEditRecipients() {{{2
774 " create a scratch buffer with all recipients to add/remove recipients
776 function s:GPGEditRecipients()
777 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGEditRecipients()")
779 " guard for unencrypted files
780 if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
782 echom "File is not encrypted, all GPG functions disabled!"
784 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEditRecipients()")
788 " only do this if it isn't already a GPGRecipients_* buffer
789 if (match(bufname("%"), "^\\(GPGRecipients_\\|GPGOptions_\\)") != 0 && match(bufname("%"), "\.\\(gpg\\|asc\\|pgp\\)$") >= 0)
792 let buffername = bufname("%")
793 let editbuffername = "GPGRecipients_" . buffername
795 " check if this buffer exists
796 if (!bufexists(editbuffername))
797 " create scratch buffer
798 execute 'silent! split ' . fnameescape(editbuffername)
800 " add a autocommand to regenerate the recipients after a write
801 autocmd BufHidden,BufUnload,BufWriteCmd <buffer> call s:GPGFinishRecipientsBuffer()
803 if (bufwinnr(editbuffername) >= 0)
804 " switch to scratch buffer window
805 execute 'silent! ' . bufwinnr(editbuffername) . "wincmd w"
807 " split scratch buffer window
808 execute 'silent! sbuffer ' . fnameescape(editbuffername)
810 " add a autocommand to regenerate the recipients after a write
811 autocmd BufHidden,BufUnload,BufWriteCmd <buffer> call s:GPGFinishRecipientsBuffer()
818 " Mark the buffer as a scratch buffer
819 setlocal buftype=acwrite
820 setlocal bufhidden=hide
826 " so we know for which other buffer this edit buffer is
827 let b:GPGCorrespondingTo = buffername
829 " put some comments to the scratch buffer
830 silent put ='GPG: ----------------------------------------------------------------------'
831 silent put ='GPG: Please edit the list of recipients, one recipient per line.'
832 silent put ='GPG: Unknown recipients have a prepended \"!\".'
833 silent put ='GPG: Lines beginning with \"GPG:\" are removed automatically.'
834 silent put ='GPG: Data after recipients between and including \"(\" and \")\" is ignored.'
835 silent put ='GPG: Closing this buffer commits changes.'
836 silent put ='GPG: ----------------------------------------------------------------------'
839 let recipients = s:GPGCheckRecipients(getbufvar(b:GPGCorrespondingTo, "GPGRecipients"))
841 " if there are no known or unknown recipients, use the default ones
842 if (empty(recipients.valid) && empty(recipients.unknown))
843 if (type(g:GPGDefaultRecipients) == type([]))
844 let recipients = s:GPGCheckRecipients(g:GPGDefaultRecipients)
847 echom "g:GPGDefaultRecipients is not a Vim list, please correct this in your vimrc!"
852 " put the recipients in the scratch buffer
853 for name in recipients.valid
854 let name = s:GPGIDToName(name)
858 " put the unknown recipients in the scratch buffer
859 let syntaxPattern = ''
860 if !empty(recipients.unknown)
861 let flaggedNames = map(recipients.unknown, '"!".v:val')
862 call append('$', flaggedNames)
863 let syntaxPattern = '\(' . join(flaggedNames, '\|') . '\)'
866 for line in g:GPGPossibleRecipients
867 silent put ='GPG: '.line
871 if (has("syntax") && exists("g:syntax_on"))
872 highlight clear GPGUnknownRecipient
873 if !empty(syntaxPattern)
874 execute 'syntax match GPGUnknownRecipient "' . syntaxPattern . '"'
875 highlight link GPGUnknownRecipient GPGHighlightUnknownRecipient
878 syntax match GPGComment "^GPG:.*$"
879 execute 'syntax match GPGComment "' . s:GPGMagicString . '.*$"'
880 highlight clear GPGComment
881 highlight link GPGComment Comment
884 " delete the empty first line
887 " jump to the first recipient
892 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEditRecipients()")
895 " Function: s:GPGFinishRecipientsBuffer() {{{2
897 " create a new recipient list from RecipientsBuffer
899 function s:GPGFinishRecipientsBuffer()
900 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGFinishRecipientsBuffer()")
902 " guard for unencrypted files
903 if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
905 echom "File is not encrypted, all GPG functions disabled!"
907 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGFinishRecipientsBuffer()")
911 " go to buffer before doing work
912 if (bufnr("%") != expand("<abuf>"))
913 " switch to scratch buffer window
914 execute 'silent! ' . bufwinnr(expand("<afile>")) . "wincmd w"
917 " delete the autocommand
920 " get the recipients from the scratch buffer
922 let lines = getline(1,"$")
923 for recipient in lines
924 let matches = matchlist(recipient, '^\(.\{-}\)\%(' . s:GPGMagicString . '(ID:\s\+\(' . s:keyPattern . '\)\s\+.*\)\=$')
926 let recipient = matches[2] ? matches[2] : matches[1]
928 " delete all spaces at beginning and end of the recipient
929 " also delete a '!' at the beginning of the recipient
930 let recipient = substitute(recipient, "^[[:space:]!]*\\(.\\{-}\\)[[:space:]]*$", "\\1", "")
932 " delete comment lines
933 let recipient = substitute(recipient, "^GPG:.*$", "", "")
935 " only do this if the line is not empty
937 let gpgid = s:GPGNameToID(recipient)
939 if (match(recipients, gpgid) < 0)
940 let recipients += [gpgid]
943 if (match(recipients, recipient) < 0)
944 let recipients += [recipient]
946 echom "The recipient \"" . recipient . "\" is not in your public keyring!"
953 " write back the new recipient list to the corresponding buffer and mark it
954 " as modified. Buffer is now for sure an encrypted buffer.
955 call setbufvar(b:GPGCorrespondingTo, "GPGRecipients", recipients)
956 call setbufvar(b:GPGCorrespondingTo, "&mod", 1)
957 call setbufvar(b:GPGCorrespondingTo, "GPGEncrypted", 1)
959 " check if there is any known recipient
962 echom 'There are no known recipients!'
966 " reset modified flag
969 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGFinishRecipientsBuffer()")
972 " Function: s:GPGViewOptions() {{{2
974 " echo the recipients
976 function s:GPGViewOptions()
977 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGViewOptions()")
979 " guard for unencrypted files
980 if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
982 echom "File is not encrypted, all GPG functions disabled!"
984 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGViewOptions()")
988 if (exists("b:GPGOptions"))
989 echo 'This file has following options:'
991 for option in b:GPGOptions
996 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGViewOptions()")
999 " Function: s:GPGEditOptions() {{{2
1001 " create a scratch buffer with all recipients to add/remove recipients
1003 function s:GPGEditOptions()
1004 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGEditOptions()")
1006 " guard for unencrypted files
1007 if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
1009 echom "File is not encrypted, all GPG functions disabled!"
1011 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEditOptions()")
1015 " only do this if it isn't already a GPGOptions_* buffer
1016 if (match(bufname("%"), "^\\(GPGRecipients_\\|GPGOptions_\\)") != 0 && match(bufname("%"), "\.\\(gpg\\|asc\\|pgp\\)$") >= 0)
1019 let buffername = bufname("%")
1020 let editbuffername = "GPGOptions_" . buffername
1022 " check if this buffer exists
1023 if (!bufexists(editbuffername))
1024 " create scratch buffer
1025 execute 'silent! split ' . fnameescape(editbuffername)
1027 " add a autocommand to regenerate the options after a write
1028 autocmd BufHidden,BufUnload,BufWriteCmd <buffer> call s:GPGFinishOptionsBuffer()
1030 if (bufwinnr(editbuffername) >= 0)
1031 " switch to scratch buffer window
1032 execute 'silent! ' . bufwinnr(editbuffername) . "wincmd w"
1034 " split scratch buffer window
1035 execute 'silent! sbuffer ' . fnameescape(editbuffername)
1037 " add a autocommand to regenerate the options after a write
1038 autocmd BufHidden,BufUnload,BufWriteCmd <buffer> call s:GPGFinishOptionsBuffer()
1045 " Mark the buffer as a scratch buffer
1046 setlocal buftype=nofile
1049 setlocal nobuflisted
1052 " so we know for which other buffer this edit buffer is
1053 let b:GPGCorrespondingTo = buffername
1055 " put some comments to the scratch buffer
1056 silent put ='GPG: ----------------------------------------------------------------------'
1057 silent put ='GPG: THERE IS NO CHECK OF THE ENTERED OPTIONS!'
1058 silent put ='GPG: YOU NEED TO KNOW WHAT YOU ARE DOING!'
1059 silent put ='GPG: IF IN DOUBT, QUICKLY EXIT USING :x OR :bd.'
1060 silent put ='GPG: Please edit the list of options, one option per line.'
1061 silent put ='GPG: Please refer to the gpg documentation for valid options.'
1062 silent put ='GPG: Lines beginning with \"GPG:\" are removed automatically.'
1063 silent put ='GPG: Closing this buffer commits changes.'
1064 silent put ='GPG: ----------------------------------------------------------------------'
1066 " put the options in the scratch buffer
1067 let options = getbufvar(b:GPGCorrespondingTo, "GPGOptions")
1069 for option in options
1073 " delete the empty first line
1076 " jump to the first option
1080 if (has("syntax") && exists("g:syntax_on"))
1081 syntax match GPGComment "^GPG:.*$"
1082 highlight clear GPGComment
1083 highlight link GPGComment Comment
1087 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEditOptions()")
1090 " Function: s:GPGFinishOptionsBuffer() {{{2
1092 " create a new option list from OptionsBuffer
1094 function s:GPGFinishOptionsBuffer()
1095 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGFinishOptionsBuffer()")
1097 " guard for unencrypted files
1098 if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
1100 echom "File is not encrypted, all GPG functions disabled!"
1102 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGFinishOptionsBuffer()")
1106 " go to buffer before doing work
1107 if (bufnr("%") != expand("<abuf>"))
1108 " switch to scratch buffer window
1109 execute 'silent! ' . bufwinnr(expand("<afile>")) . "wincmd w"
1112 " clear options and unknownOptions
1114 let unknownOptions = []
1116 " delete the autocommand
1119 " get the options from the scratch buffer
1120 let lines = getline(1, "$")
1122 " delete all spaces at beginning and end of the option
1123 " also delete a '!' at the beginning of the option
1124 let option = substitute(option, "^[[:space:]!]*\\(.\\{-}\\)[[:space:]]*$", "\\1", "")
1125 " delete comment lines
1126 let option = substitute(option, "^GPG:.*$", "", "")
1128 " only do this if the line is not empty
1129 if (!empty(option) && match(options, option) < 0)
1130 let options += [option]
1134 " write back the new option list to the corresponding buffer and mark it
1136 call setbufvar(b:GPGCorrespondingTo, "GPGOptions", options)
1137 call setbufvar(b:GPGCorrespondingTo, "&mod", 1)
1139 " reset modified flag
1142 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGFinishOptionsBuffer()")
1145 " Function: s:GPGCheckRecipients(tocheck) {{{2
1147 " check if recipients are known
1148 " Returns: dictionary of recipients, {'valid': [], 'unknown': []}
1150 function s:GPGCheckRecipients(tocheck)
1151 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGCheckRecipients()")
1153 let recipients = {'valid': [], 'unknown': []}
1155 if (type(a:tocheck) == type([]))
1156 for recipient in a:tocheck
1157 let gpgid = s:GPGNameToID(recipient)
1159 if (match(recipients.valid, gpgid) < 0)
1160 call add(recipients.valid, gpgid)
1163 if (match(recipients.unknown, recipient) < 0)
1164 call add(recipients.unknown, recipient)
1166 echom "The recipient \"" . recipient . "\" is not in your public keyring!"
1173 call s:GPGDebug(2, "recipients are: " . string(recipients.valid))
1174 call s:GPGDebug(2, "unknown recipients are: " . string(recipients.unknown))
1176 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGCheckRecipients()")
1180 " Function: s:GPGNameToID(name) {{{2
1182 " find GPG key ID corresponding to a name
1183 " Returns: ID for the given name
1185 function s:GPGNameToID(name)
1186 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGNameToID()")
1188 " ask gpg for the id for a name
1189 let cmd = { 'level': 2 }
1190 let cmd.args = '--quiet --with-colons --fixed-list-mode --list-keys ' . s:shellescape(a:name)
1191 let output = s:GPGSystem(cmd)
1193 " when called with "--with-colons" gpg encodes its output _ALWAYS_ as UTF-8,
1194 " so convert it, if necessary
1195 if (&encoding != "utf-8")
1196 let output = iconv(output, "utf-8", &encoding)
1198 let lines = split(output, "\n")
1200 " parse the output of gpg
1206 let has_strftime = exists('*strftime')
1207 let choices = "The name \"" . a:name . "\" is ambiguous. Please select the correct key:\n"
1210 let fields = split(line, ":")
1212 " search for the next pub
1213 if (fields[0] == "pub")
1214 " check if this key has already been processed
1215 if has_key(seen_keys, fields[4])
1220 let seen_keys[fields[4]] = 1
1222 " Ignore keys which are not usable for encryption
1223 if fields[11] !~? 'e'
1227 let identity = fields[4]
1228 let gpgids += [identity]
1230 let choices = choices . counter . ": ID: 0x" . identity . " created at " . strftime("%c", fields[5]) . "\n"
1232 let choices = choices . counter . ": ID: 0x" . identity . "\n"
1234 let counter = counter+1
1236 " search for the next uid
1237 elseif (!skip_key && fields[0] == "uid")
1238 let choices = choices . " " . fields[9] . "\n"
1243 " counter > 1 means we have more than one results
1246 let choices = choices . "Enter number: "
1247 let answer = input(choices, "0")
1248 while (answer == "")
1249 let answer = input("Enter number: ", "0")
1253 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGNameToID()")
1254 return get(gpgids, answer, "")
1257 " Function: s:GPGIDToName(identity) {{{2
1259 " find name corresponding to a GPG key ID
1260 " Returns: Name for the given ID
1262 function s:GPGIDToName(identity)
1263 call s:GPGDebug(3, ">>>>>>>> Entering s:GPGIDToName()")
1265 " TODO is the encryption subkey really unique?
1267 " ask gpg for the id for a name
1268 let cmd = { 'level': 2 }
1269 let cmd.args = '--quiet --with-colons --fixed-list-mode --list-keys ' . a:identity
1270 let output = s:GPGSystem(cmd)
1272 " when called with "--with-colons" gpg encodes its output _ALWAYS_ as UTF-8,
1273 " so convert it, if necessary
1274 if (&encoding != "utf-8")
1275 let output = iconv(output, "utf-8", &encoding)
1277 let lines = split(output, "\n")
1279 " parse the output of gpg
1283 let fields = split(line, ":")
1285 if !pubseen " search for the next pub
1286 if (fields[0] == "pub")
1287 " Ignore keys which are not usable for encryption
1288 if fields[11] !~? 'e'
1294 else " search for the next uid
1295 if (fields[0] == "uid")
1297 if exists("*strftime")
1298 let uid = fields[9] . s:GPGMagicString . "(ID: 0x" . a:identity . " created at " . strftime("%c", fields[5]) . ")"
1300 let uid = fields[9] . s:GPGMagicString . "(ID: 0x" . a:identity . ")"
1307 call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGIDToName()")
1311 " Function: s:GPGPreCmd() {{{2
1313 " Setup the environment for running the gpg command
1315 function s:GPGPreCmd()
1316 let &shellredir = s:shellredir
1317 let &shell = s:shell
1318 let &shelltemp = s:shelltemp
1319 " Force C locale so GPG output is consistent
1320 let s:messages = v:lang
1325 " Function: s:GPGPostCmd() {{{2
1327 " Restore the user's environment after running the gpg command
1329 function s:GPGPostCmd()
1330 let &shellredir = s:shellredirsave
1331 let &shell = s:shellsave
1332 let &shelltemp = s:shelltempsave
1333 execute 'language messages' s:messages
1334 " Workaround a bug in the interaction between console vim and
1335 " pinentry-curses by forcing Vim to re-detect and setup its terminal
1338 silent doautocmd TermChanged
1341 " Function: s:GPGSystem(dict) {{{2
1343 " run g:GPGCommand using system(), logging the commandline and output. This
1344 " uses temp files (regardless of how 'shelltemp' is set) to hold the output of
1345 " the command, so it must not be used for sensitive commands.
1346 " Recognized keys are:
1347 " level - Debug level at which the commandline and output will be logged
1348 " args - Arguments to be given to g:GPGCommand
1350 " Returns: command output
1352 function s:GPGSystem(dict)
1353 let commandline = s:GPGCommand
1354 if (!empty(g:GPGHomedir))
1355 let commandline .= ' --homedir ' . s:shellescape(g:GPGHomedir)
1357 let commandline .= ' ' . a:dict.args
1358 let commandline .= ' ' . s:stderrredirnull
1359 call s:GPGDebug(a:dict.level, "command: ". commandline)
1362 let output = system(commandline)
1365 call s:GPGDebug(a:dict.level, "rc: ". v:shell_error)
1366 call s:GPGDebug(a:dict.level, "output: ". output)
1370 " Function: s:GPGExecute(dict) {{{2
1372 " run g:GPGCommand using :execute, logging the commandline
1373 " Recognized keys are:
1374 " level - Debug level at which the commandline will be logged
1375 " args - Arguments to be given to g:GPGCommand
1376 " ex - Ex command which will be :executed
1377 " redirect - Shell redirect to use, if needed
1379 function s:GPGExecute(dict)
1380 let commandline = printf('%s%s', a:dict.ex, s:GPGCommand)
1381 if (!empty(g:GPGHomedir))
1382 let commandline .= ' --homedir ' . s:shellescape(g:GPGHomedir, 1)
1384 let commandline .= ' ' . a:dict.args
1385 if (has_key(a:dict, 'redirect'))
1386 let commandline .= ' ' . a:dict.redirect
1388 let commandline .= ' ' . s:stderrredirnull
1389 call s:GPGDebug(a:dict.level, "command: " . commandline)
1395 call s:GPGDebug(a:dict.level, "rc: ". v:shell_error)
1398 " Function: s:GPGDebug(level, text) {{{2
1400 " output debug message, if this message has high enough importance
1401 " only define function if GPGDebugLevel set at all
1403 function s:GPGDebug(level, text)
1404 if exists("g:GPGDebugLevel") && g:GPGDebugLevel >= a:level
1405 if exists("g:GPGDebugLog")
1406 execute "redir >> " . g:GPGDebugLog
1407 silent echom "GnuPG: " . a:text
1410 echom "GnuPG: " . a:text
1415 " Section: Commands {{{1
1417 command! GPGViewRecipients call s:GPGViewRecipients()
1418 command! GPGEditRecipients call s:GPGEditRecipients()
1419 command! GPGViewOptions call s:GPGViewOptions()
1420 command! GPGEditOptions call s:GPGEditOptions()
1422 " Section: Menu {{{1
1425 amenu <silent> Plugin.GnuPG.View\ Recipients :GPGViewRecipients<CR>
1426 amenu <silent> Plugin.GnuPG.Edit\ Recipients :GPGEditRecipients<CR>
1427 amenu <silent> Plugin.GnuPG.View\ Options :GPGViewOptions<CR>
1428 amenu <silent> Plugin.GnuPG.Edit\ Options :GPGEditOptions<CR>
1431 " vim600: set foldmethod=marker foldlevel=0 :