]> ruderich.org/simon Gitweb - config/dotfiles.git/blob - vim/plugin/gnupg.vim
plugin: add gnupg.vim
[config/dotfiles.git] / vim / plugin / gnupg.vim
1 " Name:    gnupg.vim
2 " Last Change: 2015 Jul 26
3 " Maintainer:  James McCoy <vega.james@gmail.com>
4 " Original Author:  Markus Braun <markus.braun@krawel.de>
5 " Summary: Vim plugin for transparent editing of gpg encrypted files.
6 " License: This program is free software; you can redistribute it and/or
7 "          modify it under the terms of the GNU General Public License
8 "          as published by the Free Software Foundation; either version
9 "          2 of the License, or (at your option) any later version.
10 "          See http://www.gnu.org/copyleft/gpl-2.0.txt
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".
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. Example:
102 "
103 "       let g:GPGPossibleRecipients=[
104 "         \"Example User <example@example.com>",
105 "         \"Other User <otherexample@example.com>"
106 "       \]
107 "
108 "
109 "   g:GPGUsePipes
110 "     If set to 1, use pipes instead of temporary files when interacting with
111 "     gnupg.  When set to 1, this can cause terminal-based gpg agents to not
112 "     display correctly when prompting for passwords.  Defaults to 0.
113 "
114 "   g:GPGHomedir
115 "     If set, specifies the directory that will be used for GPG's homedir.
116 "     This corresponds to gpg's --homedir option.  This variable is a Vim
117 "     string.
118 "
119 "   g:GPGFilePattern
120 "     If set, overrides the default set of file patterns that determine
121 "     whether this plugin will be activated.  Defaults to
122 "     '*.\(gpg\|asc\|pgp\)'.
123 "
124 " Known Issues: {{{2
125 "
126 "   In some cases gvim can't decrypt files
127
128 "   This is caused by the fact that a running gvim has no TTY and thus gpg is
129 "   not able to ask for the passphrase by itself. This is a problem for Windows
130 "   and Linux versions of gvim and could not be solved unless a "terminal
131 "   emulation" is implemented for gvim. To circumvent this you have to use any
132 "   combination of gpg-agent and a graphical pinentry program:
133 "
134 "     - gpg-agent only:
135 "         you need to provide the passphrase for the needed key to gpg-agent
136 "         in a terminal before you open files with gvim which require this key.
137 "
138 "     - pinentry only:
139 "         you will get a popup window every time you open a file that needs to
140 "         be decrypted.
141 "
142 "     - gpgagent and pinentry:
143 "         you will get a popup window the first time you open a file that
144 "         needs to be decrypted.
145 "
146 " Credits: {{{2
147 "
148 "   - Mathieu Clabaut for inspirations through his vimspell.vim script.
149 "   - Richard Bronosky for patch to enable ".pgp" suffix.
150 "   - Erik Remmelzwaal for patch to enable windows support and patient beta
151 "     testing.
152 "   - Lars Becker for patch to make gpg2 working.
153 "   - Thomas Arendsen Hein for patch to convert encoding of gpg output.
154 "   - Karl-Heinz Ruskowski for patch to fix unknown recipients and trust model
155 "     and patient beta testing.
156 "   - Giel van Schijndel for patch to get GPG_TTY dynamically.
157 "   - Sebastian Luettich for patch to fix issue with symmetric encryption an set
158 "     recipients.
159 "   - Tim Swast for patch to generate signed files.
160 "   - James Vega for patches for better '*.asc' handling, better filename
161 "     escaping and better handling of multiple keyrings.
162 "
163 " Section: Plugin header {{{1
164
165 " guard against multiple loads {{{2
166 if (exists("g:loaded_gnupg") || &cp || exists("#GnuPG"))
167   finish
168 endif
169 let g:loaded_gnupg = '2.5'
170 let s:GPGInitRun = 0
171
172 " check for correct vim version {{{2
173 if (v:version < 702)
174   echohl ErrorMsg | echo 'plugin gnupg.vim requires Vim version >= 7.2' | echohl None
175   finish
176 endif
177
178 " Section: Autocmd setup {{{1
179
180 if (!exists("g:GPGFilePattern"))
181   let g:GPGFilePattern = '*.\(gpg\|asc\|pgp\)'
182 endif
183
184 augroup GnuPG
185   autocmd!
186
187   " do the decryption
188   exe "autocmd BufReadCmd " . g:GPGFilePattern .  " call s:GPGInit(1) |" .
189                                                 \ " call s:GPGDecrypt(1) |"
190   exe "autocmd FileReadCmd " . g:GPGFilePattern . " call s:GPGInit(0) |" .
191                                                 \ " call s:GPGDecrypt(0)"
192
193   " convert all text to encrypted text before writing
194   " We check for GPGCorrespondingTo to avoid triggering on writes in GPG Options/Recipient windows
195   exe "autocmd BufWriteCmd,FileWriteCmd " . g:GPGFilePattern . " if !exists('b:GPGCorrespondingTo') |" .
196                                                              \ " call s:GPGInit(0) |" .
197                                                              \ " call s:GPGEncrypt() |" .
198                                                              \ " endif"
199
200   " cleanup on leaving vim
201   exe "autocmd VimLeave " . g:GPGFilePattern .    " call s:GPGCleanup()"
202 augroup END
203
204 " Section: Constants {{{1
205
206 let s:GPGMagicString = "\t \t"
207 let s:keyPattern = '\%(0x\)\=[[:xdigit:]]\{8,16}'
208
209 " Section: Highlight setup {{{1
210
211 highlight default link GPGWarning WarningMsg
212 highlight default link GPGError ErrorMsg
213 highlight default link GPGHighlightUnknownRecipient ErrorMsg
214
215 " Section: Functions {{{1
216
217 " Function: s:GPGInit(bufread) {{{2
218 "
219 " initialize the plugin
220 " The bufread argument specifies whether this was called due to BufReadCmd
221 "
222 function s:GPGInit(bufread)
223   call s:GPGDebug(3, printf(">>>>>>>> Entering s:GPGInit(%d)", a:bufread))
224
225   " For FileReadCmd, we're reading the contents into another buffer.  If that
226   " buffer is also destined to be encrypted, then these settings will have
227   " already been set, otherwise don't set them since it limits the
228   " functionality of the cleartext buffer.
229   if a:bufread
230     " we don't want a swap file, as it writes unencrypted data to disk
231     setl noswapfile
232
233     " if persistent undo is present, disable it for this buffer
234     if exists('+undofile')
235       setl noundofile
236     endif
237
238     " first make sure nothing is written to ~/.viminfo while editing
239     " an encrypted file.
240     set viminfo=
241   endif
242
243   " the rest only has to be run once
244   if s:GPGInitRun
245     return
246   endif
247
248   " check what gpg command to use
249   if (!exists("g:GPGExecutable"))
250     let g:GPGExecutable = "gpg --trust-model always"
251   endif
252
253   " check if gpg-agent is allowed
254   if (!exists("g:GPGUseAgent"))
255     let g:GPGUseAgent = 1
256   endif
257
258   " check if symmetric encryption is preferred
259   if (!exists("g:GPGPreferSymmetric"))
260     let g:GPGPreferSymmetric = 0
261   endif
262
263   " check if armored files are preferred
264   if (!exists("g:GPGPreferArmor"))
265     " .asc files should be armored as that's what the extension is used for
266     if expand('<afile>') =~ '\.asc$'
267       let g:GPGPreferArmor = 1
268     else
269       let g:GPGPreferArmor = 0
270     endif
271   endif
272
273   " check if signed files are preferred
274   if (!exists("g:GPGPreferSign"))
275     let g:GPGPreferSign = 0
276   endif
277
278   " start with empty default recipients if none is defined so far
279   if (!exists("g:GPGDefaultRecipients"))
280     let g:GPGDefaultRecipients = []
281   endif
282
283   if (!exists("g:GPGPossibleRecipients"))
284     let g:GPGPossibleRecipients = []
285   endif
286
287
288   " prefer not to use pipes since it can garble gpg agent display
289   if (!exists("g:GPGUsePipes"))
290     let g:GPGUsePipes = 0
291   endif
292
293   " allow alternate gnupg homedir
294   if (!exists('g:GPGHomedir'))
295     let g:GPGHomedir = ''
296   endif
297
298   " print version
299   call s:GPGDebug(1, "gnupg.vim ". g:loaded_gnupg)
300
301   let s:GPGCommand = g:GPGExecutable
302
303   " don't use tty in gvim except for windows: we get their a tty for free.
304   " FIXME find a better way to avoid an error.
305   "       with this solution only --use-agent will work
306   if (has("gui_running") && !has("gui_win32"))
307     let s:GPGCommand = s:GPGCommand . " --no-tty"
308   endif
309
310   " setup shell environment for unix and windows
311   let s:shellredirsave = &shellredir
312   let s:shellsave = &shell
313   let s:shelltempsave = &shelltemp
314   " noshelltemp isn't currently supported on Windows, but it doesn't cause any
315   " errors and this future proofs us against requiring changes if Windows
316   " gains noshelltemp functionality
317   let s:shelltemp = !g:GPGUsePipes
318   if (has("unix"))
319     " unix specific settings
320     let s:shellredir = ">%s 2>&1"
321     let s:shell = '/bin/sh'
322     let s:stderrredirnull = '2>/dev/null'
323     let s:GPGCommand = "LANG=C LC_ALL=C " . s:GPGCommand
324   else
325     " windows specific settings
326     let s:shellredir = '>%s'
327     let s:shell = &shell
328     let s:stderrredirnull = '2>nul'
329   endif
330
331   call s:GPGDebug(3, "shellredirsave: " . s:shellredirsave)
332   call s:GPGDebug(3, "shellsave: " . s:shellsave)
333   call s:GPGDebug(3, "shelltempsave: " . s:shelltempsave)
334
335   call s:GPGDebug(3, "shell: " . s:shell)
336   call s:GPGDebug(3, "shellcmdflag: " . &shellcmdflag)
337   call s:GPGDebug(3, "shellxquote: " . &shellxquote)
338   call s:GPGDebug(3, "shellredir: " . s:shellredir)
339   call s:GPGDebug(3, "stderrredirnull: " . s:stderrredirnull)
340
341   call s:GPGDebug(3, "shell implementation: " . resolve(s:shell))
342
343   " find the supported algorithms
344   let output = s:GPGSystem({ 'level': 2, 'args': '--version' })
345
346   let gpgversion = substitute(output, '^gpg (GnuPG) \([0-9]\+\.\d\+\).*', '\1', '')
347   let s:GPGPubkey = substitute(output, ".*Pubkey: \\(.\\{-}\\)\n.*", "\\1", "")
348   let s:GPGCipher = substitute(output, ".*Cipher: \\(.\\{-}\\)\n.*", "\\1", "")
349   let s:GPGHash = substitute(output, ".*Hash: \\(.\\{-}\\)\n.*", "\\1", "")
350   let s:GPGCompress = substitute(output, ".*Compress.\\{-}: \\(.\\{-}\\)\n.*", "\\1", "")
351
352   " determine if gnupg can use the gpg-agent
353   if (str2float(gpgversion) >= 2.1 || (exists("$GPG_AGENT_INFO") && g:GPGUseAgent == 1))
354     if (!exists("$GPG_TTY") && !has("gui_running"))
355       " Need to determine the associated tty by running a command in the
356       " shell.  We can't use system() here because that doesn't run in a shell
357       " connected to a tty, so it's rather useless.
358       "
359       " Save/restore &modified so the buffer isn't incorrectly marked as
360       " modified just by detecting the correct tty value.
361       " Do the &undolevels dance so the :read and :delete don't get added into
362       " the undo tree, as the user needn't be aware of these.
363       let [mod, levels] = [&l:modified, &undolevels]
364       set undolevels=-1
365       silent read !tty
366       let $GPG_TTY = getline('.')
367       silent delete
368       let [&l:modified, &undolevels] = [mod, levels]
369       " redraw is needed since we're using silent to run !tty, c.f. :help :!
370       redraw!
371       if (v:shell_error)
372         let $GPG_TTY = ""
373         echohl GPGWarning
374         echom "$GPG_TTY is not set and the `tty` command failed! gpg-agent might not work."
375         echohl None
376       endif
377     endif
378     let s:GPGCommand = s:GPGCommand . " --use-agent"
379   else
380     let s:GPGCommand = s:GPGCommand . " --no-use-agent"
381   endif
382
383   call s:GPGDebug(2, "public key algorithms: " . s:GPGPubkey)
384   call s:GPGDebug(2, "cipher algorithms: " . s:GPGCipher)
385   call s:GPGDebug(2, "hashing algorithms: " . s:GPGHash)
386   call s:GPGDebug(2, "compression algorithms: " . s:GPGCompress)
387   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGInit()")
388   let s:GPGInitRun = 1
389 endfunction
390
391 " Function: s:GPGCleanup() {{{2
392 "
393 " cleanup on leaving vim
394 "
395 function s:GPGCleanup()
396   call s:GPGDebug(3, ">>>>>>>> Entering s:GPGCleanup()")
397
398   " wipe out screen
399   new +only
400   redraw!
401
402   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGCleanup()")
403 endfunction
404
405 " Function: s:GPGDecrypt(bufread) {{{2
406 "
407 " decrypt the buffer and find all recipients of the encrypted file
408 " The bufread argument specifies whether this was called due to BufReadCmd
409 "
410 function s:GPGDecrypt(bufread)
411   call s:GPGDebug(3, printf(">>>>>>>> Entering s:GPGDecrypt(%d)", a:bufread))
412
413   " get the filename of the current buffer
414   let filename = expand("<afile>:p")
415
416   " clear GPGRecipients and GPGOptions
417   if type(g:GPGDefaultRecipients) == type([])
418     let b:GPGRecipients = copy(g:GPGDefaultRecipients)
419   else
420     let b:GPGRecipients = []
421     echohl GPGWarning
422     echom "g:GPGDefaultRecipients is not a Vim list, please correct this in your vimrc!"
423     echohl None
424   endif
425   let b:GPGOptions = []
426
427   " File doesn't exist yet, so nothing to decrypt
428   if !filereadable(filename)
429     " Allow the user to define actions for GnuPG buffers
430     silent doautocmd User GnuPG
431     " call the autocommand for the file minus .gpg$
432     silent execute ':doautocmd BufNewFile ' . fnameescape(expand('<afile>:r'))
433     call s:GPGDebug(2, 'called BufNewFile autocommand for ' . fnameescape(expand('<afile>:r')))
434
435     " This is a new file, so force the user to edit the recipient list if
436     " they open a new file and public keys are preferred
437     if (exists("g:GPGPreferSymmetric") && g:GPGPreferSymmetric == 0)
438         call s:GPGEditRecipients()
439     endif
440
441     return
442   endif
443
444   " Only let this if the file actually exists, otherwise GPG functionality
445   " will be disabled when editing a buffer that doesn't yet have a backing
446   " file
447   let b:GPGEncrypted = 0
448
449   " find the recipients of the file
450   let cmd = { 'level': 3 }
451   let cmd.args = '--verbose --decrypt --list-only --dry-run --no-use-agent --logger-fd 1 ' . shellescape(filename)
452   let output = s:GPGSystem(cmd)
453
454   " Suppress the "N more lines" message when editing a file, not when reading
455   " the contents of a file into a buffer
456   let silent = a:bufread ? 'silent ' : ''
457
458   let asymmPattern = 'gpg: public key is ' . s:keyPattern
459   " check if the file is symmetric/asymmetric encrypted
460   if (match(output, "gpg: encrypted with [[:digit:]]\\+ passphrase") >= 0)
461     " file is symmetric encrypted
462     let b:GPGEncrypted = 1
463     call s:GPGDebug(1, "this file is symmetric encrypted")
464
465     let b:GPGOptions += ["symmetric"]
466
467     " find the used cipher algorithm
468     let cipher = substitute(output, ".*gpg: \\([^ ]\\+\\) encrypted data.*", "\\1", "")
469     if (match(s:GPGCipher, "\\<" . cipher . "\\>") >= 0)
470       let b:GPGOptions += ["cipher-algo " . cipher]
471       call s:GPGDebug(1, "cipher-algo is " . cipher)
472     else
473       echohl GPGWarning
474       echom "The cipher " . cipher . " is not known by the local gpg command. Using default!"
475       echo
476       echohl None
477     endif
478   elseif (match(output, asymmPattern) >= 0)
479     " file is asymmetric encrypted
480     let b:GPGEncrypted = 1
481     call s:GPGDebug(1, "this file is asymmetric encrypted")
482
483     let b:GPGOptions += ["encrypt"]
484
485     " find the used public keys
486     let start = match(output, asymmPattern)
487     while (start >= 0)
488       let start = start + strlen("gpg: public key is ")
489       let recipient = matchstr(output, s:keyPattern, start)
490       call s:GPGDebug(1, "recipient is " . recipient)
491       let name = s:GPGNameToID(recipient)
492       if !empty(name)
493         let b:GPGRecipients += [name]
494         call s:GPGDebug(1, "name of recipient is " . name)
495       else
496         let b:GPGRecipients += [recipient]
497         echohl GPGWarning
498         echom "The recipient \"" . recipient . "\" is not in your public keyring!"
499         echohl None
500       end
501       let start = match(output, asymmPattern, start)
502     endwhile
503   else
504     " file is not encrypted
505     let b:GPGEncrypted = 0
506     call s:GPGDebug(1, "this file is not encrypted")
507     echohl GPGWarning
508     echom "File is not encrypted, all GPG functions disabled!"
509     echohl None
510     exe printf('%sr %s', silent, fnameescape(filename))
511     call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGDecrypt()")
512     return
513   endif
514
515   if a:bufread
516     silent execute ':doautocmd BufReadPre ' . fnameescape(expand('<afile>:r'))
517     call s:GPGDebug(2, 'called BufReadPre autocommand for ' . fnameescape(expand('<afile>:r')))
518   else
519     silent execute ':doautocmd FileReadPre ' . fnameescape(expand('<afile>:r'))
520     call s:GPGDebug(2, 'called FileReadPre autocommand for ' . fnameescape(expand('<afile>:r')))
521   endif
522
523   " check if the message is armored
524   if (match(output, "gpg: armor header") >= 0)
525     call s:GPGDebug(1, "this file is armored")
526     let b:GPGOptions += ["armor"]
527   endif
528
529   " finally decrypt the buffer content
530   " since even with the --quiet option passphrase typos will be reported,
531   " we must redirect stderr (using shell temporarily)
532   call s:GPGDebug(1, "decrypting file")
533   let cmd = { 'level': 1, 'ex': silent . 'r !' }
534   let cmd.args = '--quiet --decrypt ' . shellescape(filename, 1)
535   call s:GPGExecute(cmd)
536
537   if (v:shell_error) " message could not be decrypted
538     echohl GPGError
539     let blackhole = input("Message could not be decrypted! (Press ENTER)")
540     echohl None
541     " Only wipeout the buffer if we were creating one to start with.
542     " FileReadCmd just reads the content into the existing buffer
543     if a:bufread
544       silent bwipeout!
545     endif
546     call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGDecrypt()")
547     return
548   endif
549
550   if a:bufread
551     " In order to make :undo a no-op immediately after the buffer is read,
552     " we need to do this dance with 'undolevels'.  Actually discarding the undo
553     " history requires performing a change after setting 'undolevels' to -1 and,
554     " luckily, we have one we need to do (delete the extra line from the :r
555     " command)
556     let levels = &undolevels
557     set undolevels=-1
558     " :lockmarks doesn't actually prevent '[,'] from being overwritten, so we
559     " need to manually set them ourselves instead
560     silent 1delete
561     1mark [
562     $mark ]
563     let &undolevels = levels
564     " call the autocommand for the file minus .gpg$
565     silent execute ':doautocmd BufReadPost ' . fnameescape(expand('<afile>:r'))
566     call s:GPGDebug(2, 'called BufReadPost autocommand for ' . fnameescape(expand('<afile>:r')))
567   else
568     " call the autocommand for the file minus .gpg$
569     silent execute ':doautocmd FileReadPost ' . fnameescape(expand('<afile>:r'))
570     call s:GPGDebug(2, 'called FileReadPost autocommand for ' . fnameescape(expand('<afile>:r')))
571   endif
572
573   " Allow the user to define actions for GnuPG buffers
574   silent doautocmd User GnuPG
575
576   " refresh screen
577   redraw!
578
579   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGDecrypt()")
580 endfunction
581
582 " Function: s:GPGEncrypt() {{{2
583 "
584 " encrypts the buffer to all previous recipients
585 "
586 function s:GPGEncrypt()
587   call s:GPGDebug(3, ">>>>>>>> Entering s:GPGEncrypt()")
588
589   " FileWriteCmd is only called when a portion of a buffer is being written to
590   " disk.  Since Vim always sets the '[,'] marks to the part of a buffer that
591   " is being written, that can be used to determine whether BufWriteCmd or
592   " FileWriteCmd triggered us.
593   if [line("'["), line("']")] == [1, line('$')]
594     let auType = 'BufWrite'
595   else
596     let auType = 'FileWrite'
597   endif
598
599   silent exe ':doautocmd '. auType .'Pre '. fnameescape(expand('<afile>:r'))
600   call s:GPGDebug(2, 'called '. auType .'Pre autocommand for ' . fnameescape(expand('<afile>:r')))
601
602   " store encoding and switch to a safe one
603   if (&fileencoding != &encoding)
604     let s:GPGEncoding = &encoding
605     let &encoding = &fileencoding
606     call s:GPGDebug(2, "encoding was \"" . s:GPGEncoding . "\", switched to \"" . &encoding . "\"")
607   else
608     let s:GPGEncoding = ""
609     call s:GPGDebug(2, "encoding and fileencoding are the same (\"" . &encoding . "\"), not switching")
610   endif
611
612   " guard for unencrypted files
613   if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
614     echohl GPGError
615     let blackhole = input("Message could not be encrypted! (Press ENTER)")
616     echohl None
617     call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEncrypt()")
618     return
619   endif
620
621   " initialize GPGOptions if not happened before
622   if (!exists("b:GPGOptions") || empty(b:GPGOptions))
623     let b:GPGOptions = []
624     if (exists("g:GPGPreferSymmetric") && g:GPGPreferSymmetric == 1)
625       let b:GPGOptions += ["symmetric"]
626       let b:GPGRecipients = []
627     else
628       let b:GPGOptions += ["encrypt"]
629     endif
630     if (exists("g:GPGPreferArmor") && g:GPGPreferArmor == 1)
631       let b:GPGOptions += ["armor"]
632     endif
633     if (exists("g:GPGPreferSign") && g:GPGPreferSign == 1)
634       let b:GPGOptions += ["sign"]
635     endif
636     call s:GPGDebug(1, "no options set, so using default options: " . string(b:GPGOptions))
637   endif
638
639   " built list of options
640   let options = ""
641   for option in b:GPGOptions
642     let options = options . " --" . option . " "
643   endfor
644
645   if (!exists('b:GPGRecipients'))
646     let b:GPGRecipients = []
647   endif
648
649   " check here again if all recipients are available in the keyring
650   let recipients = s:GPGCheckRecipients(b:GPGRecipients)
651
652   " check if there are unknown recipients and warn
653   if !empty(recipients.unknown)
654     echohl GPGWarning
655     echom "Please use GPGEditRecipients to correct!!"
656     echo
657     echohl None
658
659     " Let user know whats happend and copy known_recipients back to buffer
660     let dummy = input("Press ENTER to quit")
661   endif
662
663   " built list of recipients
664   let options .= ' ' . join(map(recipients.valid, '"-r ".v:val'), ' ')
665
666   " encrypt the buffer
667   let destfile = tempname()
668   let cmd = { 'level': 1, 'ex': "'[,']w !" }
669   let cmd.args = '--quiet --no-encrypt-to ' . options
670   let cmd.redirect = '>' . shellescape(destfile, 1)
671   silent call s:GPGExecute(cmd)
672
673   " restore encoding
674   if (s:GPGEncoding != "")
675     let &encoding = s:GPGEncoding
676     call s:GPGDebug(2, "restored encoding \"" . &encoding . "\"")
677   endif
678
679   if (v:shell_error) " message could not be encrypted
680     " Command failed, so clean up the tempfile
681     call delete(destfile)
682     echohl GPGError
683     let blackhole = input("Message could not be encrypted! (Press ENTER)")
684     echohl None
685     call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEncrypt()")
686     return
687   endif
688
689   call rename(destfile, resolve(expand('<afile>')))
690   if auType == 'BufWrite'
691     setl nomodified
692   endif
693
694   silent exe ':doautocmd '. auType .'Post '. fnameescape(expand('<afile>:r'))
695   call s:GPGDebug(2, 'called '. auType .'Post autocommand for ' . fnameescape(expand('<afile>:r')))
696
697   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEncrypt()")
698 endfunction
699
700 " Function: s:GPGViewRecipients() {{{2
701 "
702 " echo the recipients
703 "
704 function s:GPGViewRecipients()
705   call s:GPGDebug(3, ">>>>>>>> Entering s:GPGViewRecipients()")
706
707   " guard for unencrypted files
708   if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
709     echohl GPGWarning
710     echom "File is not encrypted, all GPG functions disabled!"
711     echohl None
712     call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGViewRecipients()")
713     return
714   endif
715
716   let recipients = s:GPGCheckRecipients(b:GPGRecipients)
717
718   echo 'This file has following recipients (Unknown recipients have a prepended "!"):'
719   " echo the recipients
720   for name in recipients.valid
721     let name = s:GPGIDToName(name)
722     echo name
723   endfor
724
725   " echo the unknown recipients
726   echohl GPGWarning
727   for name in recipients.unknown
728     let name = "!" . name
729     echo name
730   endfor
731   echohl None
732
733   " check if there is any known recipient
734   if empty(recipients.valid)
735     echohl GPGError
736     echom 'There are no known recipients!'
737     echohl None
738   endif
739
740   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGViewRecipients()")
741 endfunction
742
743 " Function: s:GPGEditRecipients() {{{2
744 "
745 " create a scratch buffer with all recipients to add/remove recipients
746 "
747 function s:GPGEditRecipients()
748   call s:GPGDebug(3, ">>>>>>>> Entering s:GPGEditRecipients()")
749
750   " guard for unencrypted files
751   if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
752     echohl GPGWarning
753     echom "File is not encrypted, all GPG functions disabled!"
754     echohl None
755     call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEditRecipients()")
756     return
757   endif
758
759   " only do this if it isn't already a GPGRecipients_* buffer
760   if (match(bufname("%"), "^\\(GPGRecipients_\\|GPGOptions_\\)") != 0 && match(bufname("%"), "\.\\(gpg\\|asc\\|pgp\\)$") >= 0)
761
762     " save buffer name
763     let buffername = bufname("%")
764     let editbuffername = "GPGRecipients_" . buffername
765
766     " check if this buffer exists
767     if (!bufexists(editbuffername))
768       " create scratch buffer
769       execute 'silent! split ' . fnameescape(editbuffername)
770
771       " add a autocommand to regenerate the recipients after a write
772       autocmd BufHidden,BufUnload,BufWriteCmd <buffer> call s:GPGFinishRecipientsBuffer()
773     else
774       if (bufwinnr(editbuffername) >= 0)
775         " switch to scratch buffer window
776         execute 'silent! ' . bufwinnr(editbuffername) . "wincmd w"
777       else
778         " split scratch buffer window
779         execute 'silent! sbuffer ' . fnameescape(editbuffername)
780
781         " add a autocommand to regenerate the recipients after a write
782         autocmd BufHidden,BufUnload,BufWriteCmd <buffer> call s:GPGFinishRecipientsBuffer()
783       endif
784
785       " empty the buffer
786       silent %delete
787     endif
788
789     " Mark the buffer as a scratch buffer
790     setlocal buftype=acwrite
791     setlocal bufhidden=hide
792     setlocal noswapfile
793     setlocal nowrap
794     setlocal nobuflisted
795     setlocal nonumber
796
797     " so we know for which other buffer this edit buffer is
798     let b:GPGCorrespondingTo = buffername
799
800     " put some comments to the scratch buffer
801     silent put ='GPG: ----------------------------------------------------------------------'
802     silent put ='GPG: Please edit the list of recipients, one recipient per line.'
803     silent put ='GPG: Unknown recipients have a prepended \"!\".'
804     silent put ='GPG: Lines beginning with \"GPG:\" are removed automatically.'
805     silent put ='GPG: Data after recipients between and including \"(\" and \")\" is ignored.'
806     silent put ='GPG: Closing this buffer commits changes.'
807     silent put ='GPG: ----------------------------------------------------------------------'
808
809     " get the recipients
810     let recipients = s:GPGCheckRecipients(getbufvar(b:GPGCorrespondingTo, "GPGRecipients"))
811
812     " if there are no known or unknown recipients, use the default ones
813     if (empty(recipients.valid) && empty(recipients.unknown))
814       if (type(g:GPGDefaultRecipients) == type([]))
815         let recipients = s:GPGCheckRecipients(g:GPGDefaultRecipients)
816       else
817         echohl GPGWarning
818         echom "g:GPGDefaultRecipients is not a Vim list, please correct this in your vimrc!"
819         echohl None
820       endif
821     endif
822
823     " put the recipients in the scratch buffer
824     for name in recipients.valid
825       let name = s:GPGIDToName(name)
826       silent put =name
827     endfor
828
829     " put the unknown recipients in the scratch buffer
830     let syntaxPattern = ''
831     if !empty(recipients.unknown)
832       let flaggedNames = map(recipients.unknown, '"!".v:val')
833       call append('$', flaggedNames)
834       let syntaxPattern = '\(' . join(flaggedNames, '\|') . '\)'
835     endif
836
837     for line in g:GPGPossibleRecipients
838         silent put ='GPG: '.line
839     endfor
840
841     " define highlight
842     if (has("syntax") && exists("g:syntax_on"))
843       highlight clear GPGUnknownRecipient
844       if !empty(syntaxPattern)
845         execute 'syntax match GPGUnknownRecipient    "' . syntaxPattern . '"'
846         highlight link GPGUnknownRecipient  GPGHighlightUnknownRecipient
847       endif
848
849       syntax match GPGComment "^GPG:.*$"
850       execute 'syntax match GPGComment "' . s:GPGMagicString . '.*$"'
851       highlight clear GPGComment
852       highlight link GPGComment Comment
853     endif
854
855     " delete the empty first line
856     silent 1delete
857
858     " jump to the first recipient
859     silent $
860
861   endif
862
863   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEditRecipients()")
864 endfunction
865
866 " Function: s:GPGFinishRecipientsBuffer() {{{2
867 "
868 " create a new recipient list from RecipientsBuffer
869 "
870 function s:GPGFinishRecipientsBuffer()
871   call s:GPGDebug(3, ">>>>>>>> Entering s:GPGFinishRecipientsBuffer()")
872
873   " guard for unencrypted files
874   if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
875     echohl GPGWarning
876     echom "File is not encrypted, all GPG functions disabled!"
877     echohl None
878     call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGFinishRecipientsBuffer()")
879     return
880   endif
881
882   " go to buffer before doing work
883   if (bufnr("%") != expand("<abuf>"))
884     " switch to scratch buffer window
885     execute 'silent! ' . bufwinnr(expand("<afile>")) . "wincmd w"
886   endif
887
888   " delete the autocommand
889   autocmd! * <buffer>
890
891   " get the recipients from the scratch buffer
892   let recipients = []
893   let lines = getline(1,"$")
894   for recipient in lines
895     let matches = matchlist(recipient, '^\(.\{-}\)\%(' . s:GPGMagicString . '(ID:\s\+\(' . s:keyPattern . '\)\s\+.*\)\=$')
896
897     let recipient = matches[2] ? matches[2] : matches[1]
898
899     " delete all spaces at beginning and end of the recipient
900     " also delete a '!' at the beginning of the recipient
901     let recipient = substitute(recipient, "^[[:space:]!]*\\(.\\{-}\\)[[:space:]]*$", "\\1", "")
902
903     " delete comment lines
904     let recipient = substitute(recipient, "^GPG:.*$", "", "")
905
906     " only do this if the line is not empty
907     if !empty(recipient)
908       let gpgid = s:GPGNameToID(recipient)
909       if !empty(gpgid)
910         if (match(recipients, gpgid) < 0)
911           let recipients += [gpgid]
912         endif
913       else
914         if (match(recipients, recipient) < 0)
915           let recipients += [recipient]
916           echohl GPGWarning
917           echom "The recipient \"" . recipient . "\" is not in your public keyring!"
918           echohl None
919         endif
920       endif
921     endif
922   endfor
923
924   " write back the new recipient list to the corresponding buffer and mark it
925   " as modified. Buffer is now for sure an encrypted buffer.
926   call setbufvar(b:GPGCorrespondingTo, "GPGRecipients", recipients)
927   call setbufvar(b:GPGCorrespondingTo, "&mod", 1)
928   call setbufvar(b:GPGCorrespondingTo, "GPGEncrypted", 1)
929
930   " check if there is any known recipient
931   if empty(recipients)
932     echohl GPGError
933     echom 'There are no known recipients!'
934     echohl None
935   endif
936
937   " reset modified flag
938   setl nomodified
939
940   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGFinishRecipientsBuffer()")
941 endfunction
942
943 " Function: s:GPGViewOptions() {{{2
944 "
945 " echo the recipients
946 "
947 function s:GPGViewOptions()
948   call s:GPGDebug(3, ">>>>>>>> Entering s:GPGViewOptions()")
949
950   " guard for unencrypted files
951   if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
952     echohl GPGWarning
953     echom "File is not encrypted, all GPG functions disabled!"
954     echohl None
955     call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGViewOptions()")
956     return
957   endif
958
959   if (exists("b:GPGOptions"))
960     echo 'This file has following options:'
961     " echo the options
962     for option in b:GPGOptions
963       echo option
964     endfor
965   endif
966
967   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGViewOptions()")
968 endfunction
969
970 " Function: s:GPGEditOptions() {{{2
971 "
972 " create a scratch buffer with all recipients to add/remove recipients
973 "
974 function s:GPGEditOptions()
975   call s:GPGDebug(3, ">>>>>>>> Entering s:GPGEditOptions()")
976
977   " guard for unencrypted files
978   if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
979     echohl GPGWarning
980     echom "File is not encrypted, all GPG functions disabled!"
981     echohl None
982     call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEditOptions()")
983     return
984   endif
985
986   " only do this if it isn't already a GPGOptions_* buffer
987   if (match(bufname("%"), "^\\(GPGRecipients_\\|GPGOptions_\\)") != 0 && match(bufname("%"), "\.\\(gpg\\|asc\\|pgp\\)$") >= 0)
988
989     " save buffer name
990     let buffername = bufname("%")
991     let editbuffername = "GPGOptions_" . buffername
992
993     " check if this buffer exists
994     if (!bufexists(editbuffername))
995       " create scratch buffer
996       execute 'silent! split ' . fnameescape(editbuffername)
997
998       " add a autocommand to regenerate the options after a write
999       autocmd BufHidden,BufUnload,BufWriteCmd <buffer> call s:GPGFinishOptionsBuffer()
1000     else
1001       if (bufwinnr(editbuffername) >= 0)
1002         " switch to scratch buffer window
1003         execute 'silent! ' . bufwinnr(editbuffername) . "wincmd w"
1004       else
1005         " split scratch buffer window
1006         execute 'silent! sbuffer ' . fnameescape(editbuffername)
1007
1008         " add a autocommand to regenerate the options after a write
1009         autocmd BufHidden,BufUnload,BufWriteCmd <buffer> call s:GPGFinishOptionsBuffer()
1010       endif
1011
1012       " empty the buffer
1013       silent %delete
1014     endif
1015
1016     " Mark the buffer as a scratch buffer
1017     setlocal buftype=nofile
1018     setlocal noswapfile
1019     setlocal nowrap
1020     setlocal nobuflisted
1021     setlocal nonumber
1022
1023     " so we know for which other buffer this edit buffer is
1024     let b:GPGCorrespondingTo = buffername
1025
1026     " put some comments to the scratch buffer
1027     silent put ='GPG: ----------------------------------------------------------------------'
1028     silent put ='GPG: THERE IS NO CHECK OF THE ENTERED OPTIONS!'
1029     silent put ='GPG: YOU NEED TO KNOW WHAT YOU ARE DOING!'
1030     silent put ='GPG: IF IN DOUBT, QUICKLY EXIT USING :x OR :bd.'
1031     silent put ='GPG: Please edit the list of options, one option per line.'
1032     silent put ='GPG: Please refer to the gpg documentation for valid options.'
1033     silent put ='GPG: Lines beginning with \"GPG:\" are removed automatically.'
1034     silent put ='GPG: Closing this buffer commits changes.'
1035     silent put ='GPG: ----------------------------------------------------------------------'
1036
1037     " put the options in the scratch buffer
1038     let options = getbufvar(b:GPGCorrespondingTo, "GPGOptions")
1039
1040     for option in options
1041       silent put =option
1042     endfor
1043
1044     " delete the empty first line
1045     silent 1delete
1046
1047     " jump to the first option
1048     silent $
1049
1050     " define highlight
1051     if (has("syntax") && exists("g:syntax_on"))
1052       syntax match GPGComment "^GPG:.*$"
1053       highlight clear GPGComment
1054       highlight link GPGComment Comment
1055     endif
1056   endif
1057
1058   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGEditOptions()")
1059 endfunction
1060
1061 " Function: s:GPGFinishOptionsBuffer() {{{2
1062 "
1063 " create a new option list from OptionsBuffer
1064 "
1065 function s:GPGFinishOptionsBuffer()
1066   call s:GPGDebug(3, ">>>>>>>> Entering s:GPGFinishOptionsBuffer()")
1067
1068   " guard for unencrypted files
1069   if (exists("b:GPGEncrypted") && b:GPGEncrypted == 0)
1070     echohl GPGWarning
1071     echom "File is not encrypted, all GPG functions disabled!"
1072     echohl None
1073     call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGFinishOptionsBuffer()")
1074     return
1075   endif
1076
1077   " go to buffer before doing work
1078   if (bufnr("%") != expand("<abuf>"))
1079     " switch to scratch buffer window
1080     execute 'silent! ' . bufwinnr(expand("<afile>")) . "wincmd w"
1081   endif
1082
1083   " clear options and unknownOptions
1084   let options = []
1085   let unknownOptions = []
1086
1087   " delete the autocommand
1088   autocmd! * <buffer>
1089
1090   " get the options from the scratch buffer
1091   let lines = getline(1, "$")
1092   for option in lines
1093     " delete all spaces at beginning and end of the option
1094     " also delete a '!' at the beginning of the option
1095     let option = substitute(option, "^[[:space:]!]*\\(.\\{-}\\)[[:space:]]*$", "\\1", "")
1096     " delete comment lines
1097     let option = substitute(option, "^GPG:.*$", "", "")
1098
1099     " only do this if the line is not empty
1100     if (!empty(option) && match(options, option) < 0)
1101       let options += [option]
1102     endif
1103   endfor
1104
1105   " write back the new option list to the corresponding buffer and mark it
1106   " as modified
1107   call setbufvar(b:GPGCorrespondingTo, "GPGOptions", options)
1108   call setbufvar(b:GPGCorrespondingTo, "&mod", 1)
1109
1110   " reset modified flag
1111   setl nomodified
1112
1113   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGFinishOptionsBuffer()")
1114 endfunction
1115
1116 " Function: s:GPGCheckRecipients(tocheck) {{{2
1117 "
1118 " check if recipients are known
1119 " Returns: dictionary of recipients, {'valid': [], 'unknown': []}
1120 "
1121 function s:GPGCheckRecipients(tocheck)
1122   call s:GPGDebug(3, ">>>>>>>> Entering s:GPGCheckRecipients()")
1123
1124   let recipients = {'valid': [], 'unknown': []}
1125
1126   if (type(a:tocheck) == type([]))
1127     for recipient in a:tocheck
1128       let gpgid = s:GPGNameToID(recipient)
1129       if !empty(gpgid)
1130         if (match(recipients.valid, gpgid) < 0)
1131           call add(recipients.valid, gpgid)
1132         endif
1133       else
1134         if (match(recipients.unknown, recipient) < 0)
1135           call add(recipients.unknown, recipient)
1136           echohl GPGWarning
1137           echom "The recipient \"" . recipient . "\" is not in your public keyring!"
1138           echohl None
1139         endif
1140       end
1141     endfor
1142   endif
1143
1144   call s:GPGDebug(2, "recipients are: " . string(recipients.valid))
1145   call s:GPGDebug(2, "unknown recipients are: " . string(recipients.unknown))
1146
1147   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGCheckRecipients()")
1148   return recipients
1149 endfunction
1150
1151 " Function: s:GPGNameToID(name) {{{2
1152 "
1153 " find GPG key ID corresponding to a name
1154 " Returns: ID for the given name
1155 "
1156 function s:GPGNameToID(name)
1157   call s:GPGDebug(3, ">>>>>>>> Entering s:GPGNameToID()")
1158
1159   " ask gpg for the id for a name
1160   let cmd = { 'level': 2 }
1161   let cmd.args = '--quiet --with-colons --fixed-list-mode --list-keys ' . shellescape(a:name)
1162   let output = s:GPGSystem(cmd)
1163
1164   " when called with "--with-colons" gpg encodes its output _ALWAYS_ as UTF-8,
1165   " so convert it, if necessary
1166   if (&encoding != "utf-8")
1167     let output = iconv(output, "utf-8", &encoding)
1168   endif
1169   let lines = split(output, "\n")
1170
1171   " parse the output of gpg
1172   let pubseen = 0
1173   let counter = 0
1174   let gpgids = []
1175   let seen_keys = {}
1176   let skip_key = 0
1177   let has_strftime = exists('*strftime')
1178   let choices = "The name \"" . a:name . "\" is ambiguous. Please select the correct key:\n"
1179   for line in lines
1180
1181     let fields = split(line, ":")
1182
1183     " search for the next pub
1184     if (fields[0] == "pub")
1185       " check if this key has already been processed
1186       if has_key(seen_keys, fields[4])
1187         let skip_key = 1
1188         continue
1189       endif
1190       let skip_key = 0
1191       let seen_keys[fields[4]] = 1
1192
1193       " Ignore keys which are not usable for encryption
1194       if fields[11] !~? 'e'
1195         continue
1196       endif
1197
1198       let identity = fields[4]
1199       let gpgids += [identity]
1200       if has_strftime
1201         let choices = choices . counter . ": ID: 0x" . identity . " created at " . strftime("%c", fields[5]) . "\n"
1202       else
1203         let choices = choices . counter . ": ID: 0x" . identity . "\n"
1204       endif
1205       let counter = counter+1
1206       let pubseen = 1
1207     " search for the next uid
1208     elseif (!skip_key && fields[0] == "uid")
1209       let choices = choices . "   " . fields[9] . "\n"
1210     endif
1211
1212   endfor
1213
1214   " counter > 1 means we have more than one results
1215   let answer = 0
1216   if (counter > 1)
1217     let choices = choices . "Enter number: "
1218     let answer = input(choices, "0")
1219     while (answer == "")
1220       let answer = input("Enter number: ", "0")
1221     endwhile
1222   endif
1223
1224   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGNameToID()")
1225   return get(gpgids, answer, "")
1226 endfunction
1227
1228 " Function: s:GPGIDToName(identity) {{{2
1229 "
1230 " find name corresponding to a GPG key ID
1231 " Returns: Name for the given ID
1232 "
1233 function s:GPGIDToName(identity)
1234   call s:GPGDebug(3, ">>>>>>>> Entering s:GPGIDToName()")
1235
1236   " TODO is the encryption subkey really unique?
1237
1238   " ask gpg for the id for a name
1239   let cmd = { 'level': 2 }
1240   let cmd.args = '--quiet --with-colons --fixed-list-mode --list-keys ' . a:identity
1241   let output = s:GPGSystem(cmd)
1242
1243   " when called with "--with-colons" gpg encodes its output _ALWAYS_ as UTF-8,
1244   " so convert it, if necessary
1245   if (&encoding != "utf-8")
1246     let output = iconv(output, "utf-8", &encoding)
1247   endif
1248   let lines = split(output, "\n")
1249
1250   " parse the output of gpg
1251   let pubseen = 0
1252   let uid = ""
1253   for line in lines
1254     let fields = split(line, ":")
1255
1256     if !pubseen " search for the next pub
1257       if (fields[0] == "pub")
1258         " Ignore keys which are not usable for encryption
1259         if fields[11] !~? 'e'
1260           continue
1261         endif
1262
1263         let pubseen = 1
1264       endif
1265     else " search for the next uid
1266       if (fields[0] == "uid")
1267         let pubseen = 0
1268         if exists("*strftime")
1269           let uid = fields[9] . s:GPGMagicString . "(ID: 0x" . a:identity . " created at " . strftime("%c", fields[5]) . ")"
1270         else
1271           let uid = fields[9] . s:GPGMagicString . "(ID: 0x" . a:identity . ")"
1272         endif
1273         break
1274       endif
1275     endif
1276   endfor
1277
1278   call s:GPGDebug(3, "<<<<<<<< Leaving s:GPGIDToName()")
1279   return uid
1280 endfunction
1281
1282 function s:GPGPreCmd()
1283   let &shellredir = s:shellredir
1284   let &shell = s:shell
1285   let &shelltemp = s:shelltemp
1286 endfunction
1287
1288 function s:GPGPostCmd()
1289   let &shellredir = s:shellredirsave
1290   let &shell = s:shellsave
1291   let &shelltemp = s:shelltempsave
1292   " Workaround a bug in the interaction between console vim and
1293   " pinentry-curses by forcing Vim to re-detect and setup its terminal
1294   " settings
1295   let &term = &term
1296   silent doautocmd TermChanged
1297 endfunction
1298
1299 " Function: s:GPGSystem(dict) {{{2
1300 "
1301 " run g:GPGCommand using system(), logging the commandline and output.  This
1302 " uses temp files (regardless of how 'shelltemp' is set) to hold the output of
1303 " the command, so it must not be used for sensitive commands.
1304 " Recognized keys are:
1305 " level - Debug level at which the commandline and output will be logged
1306 " args - Arguments to be given to g:GPGCommand
1307 "
1308 " Returns: command output
1309 "
1310 function s:GPGSystem(dict)
1311   let commandline = s:GPGCommand
1312   if (!empty(g:GPGHomedir))
1313     let commandline .= ' --homedir ' . shellescape(g:GPGHomedir)
1314   endif
1315   let commandline .= ' ' . a:dict.args
1316   let commandline .= ' ' . s:stderrredirnull
1317   call s:GPGDebug(a:dict.level, "command: ". commandline)
1318
1319   call s:GPGPreCmd()
1320   let output = system(commandline)
1321   call s:GPGPostCmd()
1322
1323   call s:GPGDebug(a:dict.level, "rc: ". v:shell_error)
1324   call s:GPGDebug(a:dict.level, "output: ". output)
1325   return output
1326 endfunction
1327
1328 " Function: s:GPGExecute(dict) {{{2
1329 "
1330 " run g:GPGCommand using :execute, logging the commandline
1331 " Recognized keys are:
1332 " level - Debug level at which the commandline will be logged
1333 " args - Arguments to be given to g:GPGCommand
1334 " ex - Ex command which will be :executed
1335 " redirect - Shell redirect to use, if needed
1336 "
1337 function s:GPGExecute(dict)
1338   let commandline = printf('%s%s', a:dict.ex, s:GPGCommand)
1339   if (!empty(g:GPGHomedir))
1340     let commandline .= ' --homedir ' . shellescape(g:GPGHomedir, 1)
1341   endif
1342   let commandline .= ' ' . a:dict.args
1343   if (has_key(a:dict, 'redirect'))
1344     let commandline .= ' ' . a:dict.redirect
1345   endif
1346   let commandline .= ' ' . s:stderrredirnull
1347   call s:GPGDebug(a:dict.level, "command: " . commandline)
1348
1349   call s:GPGPreCmd()
1350   execute commandline
1351   call s:GPGPostCmd()
1352
1353   call s:GPGDebug(a:dict.level, "rc: ". v:shell_error)
1354 endfunction
1355
1356 " Function: s:GPGDebug(level, text) {{{2
1357 "
1358 " output debug message, if this message has high enough importance
1359 " only define function if GPGDebugLevel set at all
1360 "
1361 function s:GPGDebug(level, text)
1362   if exists("g:GPGDebugLevel") && g:GPGDebugLevel >= a:level
1363     if exists("g:GPGDebugLog")
1364       execute "redir >> " . g:GPGDebugLog
1365       silent echom "GnuPG: " . a:text
1366       redir END
1367     else
1368       echom "GnuPG: " . a:text
1369     endif
1370   endif
1371 endfunction
1372
1373 " Section: Commands {{{1
1374
1375 command! GPGViewRecipients call s:GPGViewRecipients()
1376 command! GPGEditRecipients call s:GPGEditRecipients()
1377 command! GPGViewOptions call s:GPGViewOptions()
1378 command! GPGEditOptions call s:GPGEditOptions()
1379
1380 " Section: Menu {{{1
1381
1382 if (has("menu"))
1383   amenu <silent> Plugin.GnuPG.View\ Recipients :GPGViewRecipients<CR>
1384   amenu <silent> Plugin.GnuPG.Edit\ Recipients :GPGEditRecipients<CR>
1385   amenu <silent> Plugin.GnuPG.View\ Options :GPGViewOptions<CR>
1386   amenu <silent> Plugin.GnuPG.Edit\ Options :GPGEditOptions<CR>
1387 endif
1388
1389 " vim600: set foldmethod=marker foldlevel=0 :