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