]> ruderich.org/simon Gitweb - config/dotfiles.git/blob - vim/plugin/gnupg.vim
plugin/gnupg.vim: update to upstream commit 97436d
[config/dotfiles.git] / vim / plugin / gnupg.vim
1 " Name:    gnupg.vim
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
11 "
12 " Section: Documentation {{{1
13 "
14 " Description: {{{2
15 "
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.
22 "
23 " Installation: {{{2
24 "
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.
28 "
29 "   From "man 1 gpg-agent":
30 "
31 "   ...
32 "   You should always add the following lines to your .bashrc or whatever
33 "   initialization file is used for all shell invocations:
34 "
35 "        GPG_TTY=`tty`
36 "        export GPG_TTY
37 "
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.
40 "   ...
41 "
42 "   Most distributions provide software to ease handling of gpg and gpg-agent.
43 "   Examples are keychain or seahorse.
44 "
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:
49 "
50 "       autocmd User GnuPG setl textwidth=72
51 "
52 "   This will be triggered before any BufRead or BufNewFile autocmds, and
53 "   therefore will not take precedence over settings specific to any filetype
54 "   that may get set.
55 "
56 " Commands: {{{2
57 "
58 "   :GPGEditRecipients
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.
62 "
63 "   :GPGViewRecipients
64 "     Prints the list of recipients.
65 "
66 "   :GPGEditOptions
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
70 "     what you are doing.
71 "
72 "   :GPGViewOptions
73 "     Prints the list of options.
74 "
75 " Variables: {{{2
76 "
77 "   g:GPGExecutable
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".
80 "
81 "   g:GPGUseAgent
82 "     If set to 0 a possible available gpg-agent won't be used. Defaults to 1.
83 "
84 "   g:GPGPreferSymmetric
85 "     If set to 1 symmetric encryption is preferred for new files. Defaults to 0.
86 "
87 "   g:GPGPreferArmor
88 "     If set to 1 armored data is preferred for new files. Defaults to 0
89 "     unless a "*.asc" file is being edited.
90 "
91 "   g:GPGPreferSign
92 "     If set to 1 signed data is preferred for new files. Defaults to 0.
93 "
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.
97 "
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
102 "     unset. Example:
103 "
104 "       let g:GPGPossibleRecipients=[
105 "         \"Example User <example@example.com>",
106 "         \"Other User <otherexample@example.com>"
107 "       \]
108 "
109 "
110 "   g:GPGUsePipes
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.
114 "
115 "   g:GPGHomedir
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.
119 "
120 "   g:GPGFilePattern
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\)'.
124 "
125 " Known Issues: {{{2
126 "
127 "   In some cases gvim can't decrypt files
128
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:
134 "
135 "     - gpg-agent only:
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.
138 "
139 "     - pinentry only:
140 "         you will get a popup window every time you open a file that needs to
141 "         be decrypted.
142 "
143 "     - gpgagent and pinentry:
144 "         you will get a popup window the first time you open a file that
145 "         needs to be decrypted.
146 "
147 " Credits: {{{2
148 "
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
152 "     testing.
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
159 "     recipients.
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.
163 "
164 " Section: Plugin header {{{1
165
166 " guard against multiple loads {{{2
167 if (exists("g:loaded_gnupg") || &cp || exists("#GnuPG"))
168   finish
169 endif
170 let g:loaded_gnupg = '2.5'
171 let s:GPGInitRun = 0
172
173 " check for correct vim version {{{2
174 if (v:version < 702)
175   echohl ErrorMsg | echo 'plugin gnupg.vim requires Vim version >= 7.2' | echohl None
176   finish
177 endif
178
179 " Section: Autocmd setup {{{1
180
181 if (!exists("g:GPGFilePattern"))
182   let g:GPGFilePattern = '*.\(gpg\|asc\|pgp\)'
183 endif
184
185 augroup GnuPG
186   autocmd!
187
188   " do the decryption
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)"
193
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() |" .
199                                                              \ " endif"
200
201   " cleanup on leaving vim
202   exe "autocmd VimLeave " . g:GPGFilePattern .    " call s:GPGCleanup()"
203 augroup END
204
205 " Section: Constants {{{1
206
207 let s:GPGMagicString = "\t \t"
208 let s:keyPattern = '\%(0x\)\=[[:xdigit:]]\{8,16}'
209
210 " Section: Highlight setup {{{1
211
212 highlight default link GPGWarning WarningMsg
213 highlight default link GPGError ErrorMsg
214 highlight default link GPGHighlightUnknownRecipient ErrorMsg
215
216 " Section: Functions {{{1
217
218 " Function: s:shellescape(s[, special]) {{{2
219 "
220 " Calls shellescape(), also taking into account 'shellslash'
221 " when on Windows and using $COMSPEC as the shell.
222 "
223 " Returns: shellescaped string
224 "
225 function s:shellescape(s, ...)
226   let special = a:0 ? a:1 : 0
227   if exists('+shellslash') && &shell == $COMSPEC
228     let ssl = &shellslash
229     set noshellslash
230
231     let escaped = shellescape(a:s, special)
232
233     let &shellslash = ssl
234   else
235     let escaped = shellescape(a:s, special)
236   endif
237
238   return escaped
239 endfunction
240
241 " Function: s:GPGInit(bufread) {{{2
242 "
243 " initialize the plugin
244 " The bufread argument specifies whether this was called due to BufReadCmd
245 "
246 function s:GPGInit(bufread)
247   call s:GPGDebug(3, printf(">>>>>>>> Entering s:GPGInit(%d)", a:bufread))
248
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.
253   if a:bufread
254     " we don't want a swap file, as it writes unencrypted data to disk
255     setl noswapfile
256
257     " if persistent undo is present, disable it for this buffer
258     if exists('+undofile')
259       setl noundofile
260     endif
261
262     " first make sure nothing is written to ~/.viminfo while editing
263     " an encrypted file.
264     set viminfo=
265   endif
266
267   " the rest only has to be run once
268   if s:GPGInitRun
269     return
270   endif
271
272   " check what gpg command to use
273   if (!exists("g:GPGExecutable"))
274     let g:GPGExecutable = "gpg --trust-model always"
275   endif
276
277   " check if gpg-agent is allowed
278   if (!exists("g:GPGUseAgent"))
279     let g:GPGUseAgent = 1
280   endif
281
282   " check if symmetric encryption is preferred
283   if (!exists("g:GPGPreferSymmetric"))
284     let g:GPGPreferSymmetric = 0
285   endif
286
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
292     else
293       let g:GPGPreferArmor = 0
294     endif
295   endif
296
297   " check if signed files are preferred
298   if (!exists("g:GPGPreferSign"))
299     let g:GPGPreferSign = 0
300   endif
301
302   " start with empty default recipients if none is defined so far
303   if (!exists("g:GPGDefaultRecipients"))
304     let g:GPGDefaultRecipients = []
305   endif
306
307   if (!exists("g:GPGPossibleRecipients"))
308     let g:GPGPossibleRecipients = []
309   endif
310
311
312   " prefer not to use pipes since it can garble gpg agent display
313   if (!exists("g:GPGUsePipes"))
314     let g:GPGUsePipes = 0
315   endif
316
317   " allow alternate gnupg homedir
318   if (!exists('g:GPGHomedir'))
319     let g:GPGHomedir = ''
320   endif
321
322   " print version
323   call s:GPGDebug(1, "gnupg.vim ". g:loaded_gnupg)
324
325   let s:GPGCommand = g:GPGExecutable
326
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"
332   endif
333
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
342   if (has("unix"))
343     " unix specific settings
344     let s:shellredir = ">%s 2>&1"
345     let s:shell = '/bin/sh'
346     let s:stderrredirnull = '2>/dev/null'
347   else
348     " windows specific settings
349     let s:shellredir = '>%s'
350     let s:shell = &shell
351     let s:stderrredirnull = '2>nul'
352   endif
353
354   call s:GPGDebug(3, "shellredirsave: " . s:shellredirsave)
355   call s:GPGDebug(3, "shellsave: " . s:shellsave)
356   call s:GPGDebug(3, "shelltempsave: " . s:shelltempsave)
357
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)
363
364   call s:GPGDebug(3, "shell implementation: " . resolve(s:shell))
365
366   " find the supported algorithms
367   let output = s:GPGSystem({ 'level': 2, 'args': '--version' })
368
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", "")
374
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.
381       "
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]
387       set undolevels=-1
388       silent read !tty
389       let $GPG_TTY = getline('.')
390       silent delete
391       let [&l:modified, &undolevels] = [mod, levels]
392       " redraw is needed since we're using silent to run !tty, c.f. :help :!
393       redraw!
394       if (v:shell_error)
395         let $GPG_TTY = ""
396         echohl GPGWarning
397         echom "$GPG_TTY is not set and the `tty` command failed! gpg-agent might not work."
398         echohl None
399       endif
400     endif
401     let s:GPGCommand .= " --use-agent"
402   else
403     let s:GPGCommand .= " --no-use-agent"
404   endif
405
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()")
411   let s:GPGInitRun = 1
412 endfunction
413
414 " Function: s:GPGCleanup() {{{2
415 "
416 " cleanup on leaving vim
417 "
418 function s:GPGCleanup()
419   call s:GPGDebug(3, ">>>>>>>> Entering s:GPGCleanup()")
420
421   " wipe out screen
422   new +only
423   redraw!
424
425   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGCleanup()")
426 endfunction
427
428 " Function: s:GPGDecrypt(bufread) {{{2
429 "
430 " decrypt the buffer and find all recipients of the encrypted file
431 " The bufread argument specifies whether this was called due to BufReadCmd
432 "
433 function s:GPGDecrypt(bufread)
434   call s:GPGDebug(3, printf(">>>>>>>> Entering s:GPGDecrypt(%d)", a:bufread))
435
436   " get the filename of the current buffer
437   let filename = expand("<afile>:p")
438
439   " clear GPGRecipients and GPGOptions
440   if type(g:GPGDefaultRecipients) == type([])
441     let b:GPGRecipients = copy(g:GPGDefaultRecipients)
442   else
443     let b:GPGRecipients = []
444     echohl GPGWarning
445     echom "g:GPGDefaultRecipients is not a Vim list, please correct this in your vimrc!"
446     echohl None
447   endif
448   let b:GPGOptions = []
449
450   " file name minus extension
451   let autocmd_filename = fnameescape(expand('<afile>:r'))
452
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)
460
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()
465     endif
466
467     return
468   endif
469
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
472   " file
473   let b:GPGEncrypted = 0
474
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)
479
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 ' : ''
483
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")
490
491     let b:GPGOptions += ["symmetric"]
492
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)
498     else
499       echohl GPGWarning
500       echom "The cipher " . cipher . " is not known by the local gpg command. Using default!"
501       echo
502       echohl None
503     endif
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")
508
509     let b:GPGOptions += ["encrypt"]
510
511     " find the used public keys
512     let start = match(output, asymmPattern)
513     while (start >= 0)
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)
518       if !empty(name)
519         let b:GPGRecipients += [name]
520         call s:GPGDebug(1, "name of recipient is " . name)
521       else
522         let b:GPGRecipients += [recipient]
523         echohl GPGWarning
524         echom "The recipient \"" . recipient . "\" is not in your public keyring!"
525         echohl None
526       end
527       let start = match(output, asymmPattern, start)
528     endwhile
529   else
530     " file is not encrypted
531     let b:GPGEncrypted = 0
532     call s:GPGDebug(1, "this file is not encrypted")
533     echohl GPGWarning
534     echom "File is not encrypted, all GPG functions disabled!"
535     echohl None
536     exe printf('%sr %s', silent, fnameescape(filename))
537     call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGDecrypt()")
538     return
539   endif
540
541   if a:bufread
542     silent execute ':doautocmd BufReadPre ' . autocmd_filename
543     call s:GPGDebug(2, 'called BufReadPre autocommand for ' . autocmd_filename)
544   else
545     silent execute ':doautocmd FileReadPre ' . autocmd_filename
546     call s:GPGDebug(2, 'called FileReadPre autocommand for ' . autocmd_filename)
547   endif
548
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"]
553   endif
554
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)
562
563   if (v:shell_error) " message could not be decrypted
564     echohl GPGError
565     let blackhole = input("Message could not be decrypted! (Press ENTER)")
566     echohl None
567     " Only wipeout the buffer if we were creating one to start with.
568     " FileReadCmd just reads the content into the existing buffer
569     if a:bufread
570       silent bwipeout!
571     endif
572     call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGDecrypt()")
573     return
574   endif
575
576   if a:bufread
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
581     " command)
582     let levels = &undolevels
583     set undolevels=-1
584     " :lockmarks doesn't actually prevent '[,'] from being overwritten, so we
585     " need to manually set them ourselves instead
586     silent 1delete
587     1mark [
588     $mark ]
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)
593   else
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)
597   endif
598
599   " Allow the user to define actions for GnuPG buffers
600   silent doautocmd User GnuPG
601
602   " refresh screen
603   redraw!
604
605   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGDecrypt()")
606 endfunction
607
608 " Function: s:GPGEncrypt() {{{2
609 "
610 " encrypts the buffer to all previous recipients
611 "
612 function s:GPGEncrypt()
613   call s:GPGDebug(3, ">>>>>>>> Entering s:GPGEncrypt()")
614
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'
621   else
622     let auType = 'FileWrite'
623   endif
624
625   " file name minus extension
626   let autocmd_filename = fnameescape(expand('<afile>:r'))
627
628   silent exe ':doautocmd '. auType .'Pre '. autocmd_filename
629   call s:GPGDebug(2, 'called '. auType .'Pre autocommand for ' . autocmd_filename)
630
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 . "\"")
636   else
637     let s:GPGEncoding = ""
638     call s:GPGDebug(2, "encoding and fileencoding are the same (\"" . &encoding . "\"), not switching")
639   endif
640
641   " guard for unencrypted files
642   if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
643     echohl GPGError
644     let blackhole = input("Message could not be encrypted! (Press ENTER)")
645     echohl None
646     call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEncrypt()")
647     return
648   endif
649
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 = []
656     else
657       let b:GPGOptions += ["encrypt"]
658     endif
659     if (exists("g:GPGPreferArmor") && g:GPGPreferArmor == 1)
660       let b:GPGOptions += ["armor"]
661     endif
662     if (exists("g:GPGPreferSign") && g:GPGPreferSign == 1)
663       let b:GPGOptions += ["sign"]
664     endif
665     call s:GPGDebug(1, "no options set, so using default options: " . string(b:GPGOptions))
666   endif
667
668   " built list of options
669   let options = ""
670   for option in b:GPGOptions
671     let options = options . " --" . option . " "
672   endfor
673
674   if (!exists('b:GPGRecipients'))
675     let b:GPGRecipients = []
676   endif
677
678   " check here again if all recipients are available in the keyring
679   let recipients = s:GPGCheckRecipients(b:GPGRecipients)
680
681   " check if there are unknown recipients and warn
682   if !empty(recipients.unknown)
683     echohl GPGWarning
684     echom "Please use GPGEditRecipients to correct!!"
685     echo
686     echohl None
687
688     " Let user know whats happend and copy known_recipients back to buffer
689     let dummy = input("Press ENTER to quit")
690   endif
691
692   " built list of recipients
693   let options .= ' ' . join(map(recipients.valid, '"-r ".v:val'), ' ')
694
695   " encrypt the buffer
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)
701
702   " restore encoding
703   if (s:GPGEncoding != "")
704     let &encoding = s:GPGEncoding
705     call s:GPGDebug(2, "restored encoding \"" . &encoding . "\"")
706   endif
707
708   if (v:shell_error) " message could not be encrypted
709     " Command failed, so clean up the tempfile
710     call delete(destfile)
711     echohl GPGError
712     let blackhole = input("Message could not be encrypted! (Press ENTER)")
713     echohl None
714     call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEncrypt()")
715     return
716   endif
717
718   call rename(destfile, resolve(expand('<afile>')))
719   if auType == 'BufWrite'
720     setl nomodified
721   endif
722
723   silent exe ':doautocmd '. auType .'Post '. autocmd_filename
724   call s:GPGDebug(2, 'called '. auType .'Post autocommand for ' . autocmd_filename)
725
726   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEncrypt()")
727 endfunction
728
729 " Function: s:GPGViewRecipients() {{{2
730 "
731 " echo the recipients
732 "
733 function s:GPGViewRecipients()
734   call s:GPGDebug(3, ">>>>>>>> Entering s:GPGViewRecipients()")
735
736   " guard for unencrypted files
737   if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
738     echohl GPGWarning
739     echom "File is not encrypted, all GPG functions disabled!"
740     echohl None
741     call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGViewRecipients()")
742     return
743   endif
744
745   let recipients = s:GPGCheckRecipients(b:GPGRecipients)
746
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)
751     echo name
752   endfor
753
754   " echo the unknown recipients
755   echohl GPGWarning
756   for name in recipients.unknown
757     let name = "!" . name
758     echo name
759   endfor
760   echohl None
761
762   " check if there is any known recipient
763   if empty(recipients.valid)
764     echohl GPGError
765     echom 'There are no known recipients!'
766     echohl None
767   endif
768
769   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGViewRecipients()")
770 endfunction
771
772 " Function: s:GPGEditRecipients() {{{2
773 "
774 " create a scratch buffer with all recipients to add/remove recipients
775 "
776 function s:GPGEditRecipients()
777   call s:GPGDebug(3, ">>>>>>>> Entering s:GPGEditRecipients()")
778
779   " guard for unencrypted files
780   if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
781     echohl GPGWarning
782     echom "File is not encrypted, all GPG functions disabled!"
783     echohl None
784     call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEditRecipients()")
785     return
786   endif
787
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)
790
791     " save buffer name
792     let buffername = bufname("%")
793     let editbuffername = "GPGRecipients_" . buffername
794
795     " check if this buffer exists
796     if (!bufexists(editbuffername))
797       " create scratch buffer
798       execute 'silent! split ' . fnameescape(editbuffername)
799
800       " add a autocommand to regenerate the recipients after a write
801       autocmd BufHidden,BufUnload,BufWriteCmd <buffer> call s:GPGFinishRecipientsBuffer()
802     else
803       if (bufwinnr(editbuffername) >= 0)
804         " switch to scratch buffer window
805         execute 'silent! ' . bufwinnr(editbuffername) . "wincmd w"
806       else
807         " split scratch buffer window
808         execute 'silent! sbuffer ' . fnameescape(editbuffername)
809
810         " add a autocommand to regenerate the recipients after a write
811         autocmd BufHidden,BufUnload,BufWriteCmd <buffer> call s:GPGFinishRecipientsBuffer()
812       endif
813
814       " empty the buffer
815       silent %delete
816     endif
817
818     " Mark the buffer as a scratch buffer
819     setlocal buftype=acwrite
820     setlocal bufhidden=hide
821     setlocal noswapfile
822     setlocal nowrap
823     setlocal nobuflisted
824     setlocal nonumber
825
826     " so we know for which other buffer this edit buffer is
827     let b:GPGCorrespondingTo = buffername
828
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: ----------------------------------------------------------------------'
837
838     " get the recipients
839     let recipients = s:GPGCheckRecipients(getbufvar(b:GPGCorrespondingTo, "GPGRecipients"))
840
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)
845       else
846         echohl GPGWarning
847         echom "g:GPGDefaultRecipients is not a Vim list, please correct this in your vimrc!"
848         echohl None
849       endif
850     endif
851
852     " put the recipients in the scratch buffer
853     for name in recipients.valid
854       let name = s:GPGIDToName(name)
855       silent put =name
856     endfor
857
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, '\|') . '\)'
864     endif
865
866     for line in g:GPGPossibleRecipients
867         silent put ='GPG: '.line
868     endfor
869
870     " define highlight
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
876       endif
877
878       syntax match GPGComment "^GPG:.*$"
879       execute 'syntax match GPGComment "' . s:GPGMagicString . '.*$"'
880       highlight clear GPGComment
881       highlight link GPGComment Comment
882     endif
883
884     " delete the empty first line
885     silent 1delete
886
887     " jump to the first recipient
888     silent $
889
890   endif
891
892   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEditRecipients()")
893 endfunction
894
895 " Function: s:GPGFinishRecipientsBuffer() {{{2
896 "
897 " create a new recipient list from RecipientsBuffer
898 "
899 function s:GPGFinishRecipientsBuffer()
900   call s:GPGDebug(3, ">>>>>>>> Entering s:GPGFinishRecipientsBuffer()")
901
902   " guard for unencrypted files
903   if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
904     echohl GPGWarning
905     echom "File is not encrypted, all GPG functions disabled!"
906     echohl None
907     call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGFinishRecipientsBuffer()")
908     return
909   endif
910
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"
915   endif
916
917   " delete the autocommand
918   autocmd! * <buffer>
919
920   " get the recipients from the scratch buffer
921   let recipients = []
922   let lines = getline(1,"$")
923   for recipient in lines
924     let matches = matchlist(recipient, '^\(.\{-}\)\%(' . s:GPGMagicString . '(ID:\s\+\(' . s:keyPattern . '\)\s\+.*\)\=$')
925
926     let recipient = matches[2] ? matches[2] : matches[1]
927
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", "")
931
932     " delete comment lines
933     let recipient = substitute(recipient, "^GPG:.*$", "", "")
934
935     " only do this if the line is not empty
936     if !empty(recipient)
937       let gpgid = s:GPGNameToID(recipient)
938       if !empty(gpgid)
939         if (match(recipients, gpgid) < 0)
940           let recipients += [gpgid]
941         endif
942       else
943         if (match(recipients, recipient) < 0)
944           let recipients += [recipient]
945           echohl GPGWarning
946           echom "The recipient \"" . recipient . "\" is not in your public keyring!"
947           echohl None
948         endif
949       endif
950     endif
951   endfor
952
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)
958
959   " check if there is any known recipient
960   if empty(recipients)
961     echohl GPGError
962     echom 'There are no known recipients!'
963     echohl None
964   endif
965
966   " reset modified flag
967   setl nomodified
968
969   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGFinishRecipientsBuffer()")
970 endfunction
971
972 " Function: s:GPGViewOptions() {{{2
973 "
974 " echo the recipients
975 "
976 function s:GPGViewOptions()
977   call s:GPGDebug(3, ">>>>>>>> Entering s:GPGViewOptions()")
978
979   " guard for unencrypted files
980   if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
981     echohl GPGWarning
982     echom "File is not encrypted, all GPG functions disabled!"
983     echohl None
984     call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGViewOptions()")
985     return
986   endif
987
988   if (exists("b:GPGOptions"))
989     echo 'This file has following options:'
990     " echo the options
991     for option in b:GPGOptions
992       echo option
993     endfor
994   endif
995
996   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGViewOptions()")
997 endfunction
998
999 " Function: s:GPGEditOptions() {{{2
1000 "
1001 " create a scratch buffer with all recipients to add/remove recipients
1002 "
1003 function s:GPGEditOptions()
1004   call s:GPGDebug(3, ">>>>>>>> Entering s:GPGEditOptions()")
1005
1006   " guard for unencrypted files
1007   if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
1008     echohl GPGWarning
1009     echom "File is not encrypted, all GPG functions disabled!"
1010     echohl None
1011     call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEditOptions()")
1012     return
1013   endif
1014
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)
1017
1018     " save buffer name
1019     let buffername = bufname("%")
1020     let editbuffername = "GPGOptions_" . buffername
1021
1022     " check if this buffer exists
1023     if (!bufexists(editbuffername))
1024       " create scratch buffer
1025       execute 'silent! split ' . fnameescape(editbuffername)
1026
1027       " add a autocommand to regenerate the options after a write
1028       autocmd BufHidden,BufUnload,BufWriteCmd <buffer> call s:GPGFinishOptionsBuffer()
1029     else
1030       if (bufwinnr(editbuffername) >= 0)
1031         " switch to scratch buffer window
1032         execute 'silent! ' . bufwinnr(editbuffername) . "wincmd w"
1033       else
1034         " split scratch buffer window
1035         execute 'silent! sbuffer ' . fnameescape(editbuffername)
1036
1037         " add a autocommand to regenerate the options after a write
1038         autocmd BufHidden,BufUnload,BufWriteCmd <buffer> call s:GPGFinishOptionsBuffer()
1039       endif
1040
1041       " empty the buffer
1042       silent %delete
1043     endif
1044
1045     " Mark the buffer as a scratch buffer
1046     setlocal buftype=nofile
1047     setlocal noswapfile
1048     setlocal nowrap
1049     setlocal nobuflisted
1050     setlocal nonumber
1051
1052     " so we know for which other buffer this edit buffer is
1053     let b:GPGCorrespondingTo = buffername
1054
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: ----------------------------------------------------------------------'
1065
1066     " put the options in the scratch buffer
1067     let options = getbufvar(b:GPGCorrespondingTo, "GPGOptions")
1068
1069     for option in options
1070       silent put =option
1071     endfor
1072
1073     " delete the empty first line
1074     silent 1delete
1075
1076     " jump to the first option
1077     silent $
1078
1079     " define highlight
1080     if (has("syntax") && exists("g:syntax_on"))
1081       syntax match GPGComment "^GPG:.*$"
1082       highlight clear GPGComment
1083       highlight link GPGComment Comment
1084     endif
1085   endif
1086
1087   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEditOptions()")
1088 endfunction
1089
1090 " Function: s:GPGFinishOptionsBuffer() {{{2
1091 "
1092 " create a new option list from OptionsBuffer
1093 "
1094 function s:GPGFinishOptionsBuffer()
1095   call s:GPGDebug(3, ">>>>>>>> Entering s:GPGFinishOptionsBuffer()")
1096
1097   " guard for unencrypted files
1098   if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
1099     echohl GPGWarning
1100     echom "File is not encrypted, all GPG functions disabled!"
1101     echohl None
1102     call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGFinishOptionsBuffer()")
1103     return
1104   endif
1105
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"
1110   endif
1111
1112   " clear options and unknownOptions
1113   let options = []
1114   let unknownOptions = []
1115
1116   " delete the autocommand
1117   autocmd! * <buffer>
1118
1119   " get the options from the scratch buffer
1120   let lines = getline(1, "$")
1121   for option in lines
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:.*$", "", "")
1127
1128     " only do this if the line is not empty
1129     if (!empty(option) && match(options, option) < 0)
1130       let options += [option]
1131     endif
1132   endfor
1133
1134   " write back the new option list to the corresponding buffer and mark it
1135   " as modified
1136   call setbufvar(b:GPGCorrespondingTo, "GPGOptions", options)
1137   call setbufvar(b:GPGCorrespondingTo, "&mod", 1)
1138
1139   " reset modified flag
1140   setl nomodified
1141
1142   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGFinishOptionsBuffer()")
1143 endfunction
1144
1145 " Function: s:GPGCheckRecipients(tocheck) {{{2
1146 "
1147 " check if recipients are known
1148 " Returns: dictionary of recipients, {'valid': [], 'unknown': []}
1149 "
1150 function s:GPGCheckRecipients(tocheck)
1151   call s:GPGDebug(3, ">>>>>>>> Entering s:GPGCheckRecipients()")
1152
1153   let recipients = {'valid': [], 'unknown': []}
1154
1155   if (type(a:tocheck) == type([]))
1156     for recipient in a:tocheck
1157       let gpgid = s:GPGNameToID(recipient)
1158       if !empty(gpgid)
1159         if (match(recipients.valid, gpgid) < 0)
1160           call add(recipients.valid, gpgid)
1161         endif
1162       else
1163         if (match(recipients.unknown, recipient) < 0)
1164           call add(recipients.unknown, recipient)
1165           echohl GPGWarning
1166           echom "The recipient \"" . recipient . "\" is not in your public keyring!"
1167           echohl None
1168         endif
1169       end
1170     endfor
1171   endif
1172
1173   call s:GPGDebug(2, "recipients are: " . string(recipients.valid))
1174   call s:GPGDebug(2, "unknown recipients are: " . string(recipients.unknown))
1175
1176   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGCheckRecipients()")
1177   return recipients
1178 endfunction
1179
1180 " Function: s:GPGNameToID(name) {{{2
1181 "
1182 " find GPG key ID corresponding to a name
1183 " Returns: ID for the given name
1184 "
1185 function s:GPGNameToID(name)
1186   call s:GPGDebug(3, ">>>>>>>> Entering s:GPGNameToID()")
1187
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)
1192
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)
1197   endif
1198   let lines = split(output, "\n")
1199
1200   " parse the output of gpg
1201   let pubseen = 0
1202   let counter = 0
1203   let gpgids = []
1204   let seen_keys = {}
1205   let skip_key = 0
1206   let has_strftime = exists('*strftime')
1207   let choices = "The name \"" . a:name . "\" is ambiguous. Please select the correct key:\n"
1208   for line in lines
1209
1210     let fields = split(line, ":")
1211
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])
1216         let skip_key = 1
1217         continue
1218       endif
1219       let skip_key = 0
1220       let seen_keys[fields[4]] = 1
1221
1222       " Ignore keys which are not usable for encryption
1223       if fields[11] !~? 'e'
1224         continue
1225       endif
1226
1227       let identity = fields[4]
1228       let gpgids += [identity]
1229       if has_strftime
1230         let choices = choices . counter . ": ID: 0x" . identity . " created at " . strftime("%c", fields[5]) . "\n"
1231       else
1232         let choices = choices . counter . ": ID: 0x" . identity . "\n"
1233       endif
1234       let counter = counter+1
1235       let pubseen = 1
1236     " search for the next uid
1237     elseif (!skip_key && fields[0] == "uid")
1238       let choices = choices . "   " . fields[9] . "\n"
1239     endif
1240
1241   endfor
1242
1243   " counter > 1 means we have more than one results
1244   let answer = 0
1245   if (counter > 1)
1246     let choices = choices . "Enter number: "
1247     let answer = input(choices, "0")
1248     while (answer == "")
1249       let answer = input("Enter number: ", "0")
1250     endwhile
1251   endif
1252
1253   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGNameToID()")
1254   return get(gpgids, answer, "")
1255 endfunction
1256
1257 " Function: s:GPGIDToName(identity) {{{2
1258 "
1259 " find name corresponding to a GPG key ID
1260 " Returns: Name for the given ID
1261 "
1262 function s:GPGIDToName(identity)
1263   call s:GPGDebug(3, ">>>>>>>> Entering s:GPGIDToName()")
1264
1265   " TODO is the encryption subkey really unique?
1266
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)
1271
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)
1276   endif
1277   let lines = split(output, "\n")
1278
1279   " parse the output of gpg
1280   let pubseen = 0
1281   let uid = ""
1282   for line in lines
1283     let fields = split(line, ":")
1284
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'
1289           continue
1290         endif
1291
1292         let pubseen = 1
1293       endif
1294     else " search for the next uid
1295       if (fields[0] == "uid")
1296         let pubseen = 0
1297         if exists("*strftime")
1298           let uid = fields[9] . s:GPGMagicString . "(ID: 0x" . a:identity . " created at " . strftime("%c", fields[5]) . ")"
1299         else
1300           let uid = fields[9] . s:GPGMagicString . "(ID: 0x" . a:identity . ")"
1301         endif
1302         break
1303       endif
1304     endif
1305   endfor
1306
1307   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGIDToName()")
1308   return uid
1309 endfunction
1310
1311 " Function: s:GPGPreCmd() {{{2
1312 "
1313 " Setup the environment for running the gpg command
1314 "
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
1321   language messages C
1322 endfunction
1323
1324
1325 " Function: s:GPGPostCmd() {{{2
1326 "
1327 " Restore the user's environment after running the gpg command
1328 "
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
1336   " settings
1337   let &term = &term
1338   silent doautocmd TermChanged
1339 endfunction
1340
1341 " Function: s:GPGSystem(dict) {{{2
1342 "
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
1349 "
1350 " Returns: command output
1351 "
1352 function s:GPGSystem(dict)
1353   let commandline = s:GPGCommand
1354   if (!empty(g:GPGHomedir))
1355     let commandline .= ' --homedir ' . s:shellescape(g:GPGHomedir)
1356   endif
1357   let commandline .= ' ' . a:dict.args
1358   let commandline .= ' ' . s:stderrredirnull
1359   call s:GPGDebug(a:dict.level, "command: ". commandline)
1360
1361   call s:GPGPreCmd()
1362   let output = system(commandline)
1363   call s:GPGPostCmd()
1364
1365   call s:GPGDebug(a:dict.level, "rc: ". v:shell_error)
1366   call s:GPGDebug(a:dict.level, "output: ". output)
1367   return output
1368 endfunction
1369
1370 " Function: s:GPGExecute(dict) {{{2
1371 "
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
1378 "
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)
1383   endif
1384   let commandline .= ' ' . a:dict.args
1385   if (has_key(a:dict, 'redirect'))
1386     let commandline .= ' ' . a:dict.redirect
1387   endif
1388   let commandline .= ' ' . s:stderrredirnull
1389   call s:GPGDebug(a:dict.level, "command: " . commandline)
1390
1391   call s:GPGPreCmd()
1392   execute commandline
1393   call s:GPGPostCmd()
1394
1395   call s:GPGDebug(a:dict.level, "rc: ". v:shell_error)
1396 endfunction
1397
1398 " Function: s:GPGDebug(level, text) {{{2
1399 "
1400 " output debug message, if this message has high enough importance
1401 " only define function if GPGDebugLevel set at all
1402 "
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
1408       redir END
1409     else
1410       echom "GnuPG: " . a:text
1411     endif
1412   endif
1413 endfunction
1414
1415 " Section: Commands {{{1
1416
1417 command! GPGViewRecipients call s:GPGViewRecipients()
1418 command! GPGEditRecipients call s:GPGEditRecipients()
1419 command! GPGViewOptions call s:GPGViewOptions()
1420 command! GPGEditOptions call s:GPGEditOptions()
1421
1422 " Section: Menu {{{1
1423
1424 if (has("menu"))
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>
1429 endif
1430
1431 " vim600: set foldmethod=marker foldlevel=0 :