Fixed.
[elisp/epg.git] / epa.el
diff --git a/epa.el b/epa.el
index 44d8431..40cc0ab 100644 (file)
--- a/epa.el
+++ b/epa.el
@@ -27,6 +27,8 @@
 (require 'font-lock)
 (require 'widget)
 (eval-when-compile (require 'wid-edit))
+(require 'mail-utils)
+(require 'derived)
 
 (defgroup epa nil
   "The EasyPG Assistant"
@@ -59,6 +61,11 @@ the separate window."
   :type 'integer
   :group 'epa)
 
+(defcustom epa-mail-modes '(mail-mode message-mode)
+  "List of major-modes to compose mails."
+  :type 'list
+  :group 'epa)
+
 (defgroup epa-faces nil
   "Faces for epa-mode."
   :group 'epa)
@@ -172,6 +179,7 @@ the separate window."
 (defvar epa-key nil)
 (defvar epa-list-keys-arguments nil)
 (defvar epa-info-buffer nil)
+(defvar epa-last-coding-system-specified nil)
 
 (defvar epa-keys-mode-map
   (let ((keymap (make-sparse-keymap)))
@@ -330,6 +338,9 @@ If ARG is non-nil, mark the current line."
 
 ;;;###autoload
 (defun epa-list-keys (&optional name mode)
+  "List all keys matched with NAME from the keyring.
+If MODE is non-nil, it reads the private keyring.  Otherwise, it
+reads the public keyring."
   (interactive
    (if current-prefix-arg
        (let ((name (read-string "Pattern: "
@@ -460,6 +471,26 @@ If SECRET is non-nil, list secret keys instead of public keys."
          (delete-window (get-buffer-window epa-keys-buffer)))
       (kill-buffer epa-keys-buffer))))
 
+(defun epa--format-fingerprint-1 (fingerprint unit-size block-size)
+  (let ((unit 0))
+    (with-temp-buffer
+      (insert fingerprint)
+      (goto-char (point-min))
+      (while (progn
+              (goto-char (+ (point) unit-size))
+              (not (eobp)))
+       (setq unit (1+ unit))
+       (insert (if (= (% unit block-size) 0) "  " " ")))
+      (buffer-string))))
+
+(defun epa--format-fingerprint (fingerprint)
+  (if fingerprint
+      (if (= (length fingerprint) 40)
+         ;; 1234 5678 9ABC DEF0 1234  5678 9ABC DEF0 1234 5678
+         (epa--format-fingerprint-1 fingerprint 4 5)
+       ;; 12 34 56 78 9A BC DE F0  12 34 56 78 9A BC DE F0
+       (epa--format-fingerprint-1 fingerprint 2 8))))
+
 (defun epa--show-key (key)
   (let* ((primary-sub-key (car (epg-key-sub-key-list key)))
         (entry (assoc (epg-sub-key-id primary-sub-key)
@@ -523,7 +554,7 @@ If SECRET is non-nil, list secret keys instead of public keys."
                         (epg-sub-key-capability (car pointer))
                         " ")
              "\n\tFingerprint: "
-             (epg-sub-key-fingerprint (car pointer))
+             (epa--format-fingerprint (epg-sub-key-fingerprint (car pointer)))
              "\n")
       (setq pointer (cdr pointer)))
     (goto-char (point-min))
@@ -535,6 +566,8 @@ If SECRET is non-nil, list secret keys instead of public keys."
       (save-selected-window
        (unless epa-info-buffer
          (setq epa-info-buffer (generate-new-buffer "*Info*")))
+       (if (get-buffer-window epa-info-buffer)
+           (delete-window (get-buffer-window epa-info-buffer)))
        (save-excursion
          (set-buffer epa-info-buffer)
          (let ((inhibit-read-only t)
@@ -571,7 +604,8 @@ If SECRET is non-nil, list secret keys instead of public keys."
 
 (defun epa-progress-callback-function (context what char current total
                                               handback)
-  (message "%s: %d%% (%d/%d)" what
+  (message "%s%d%% (%d/%d)" (or handback
+                               (concat what ": "))
           (if (> total 0) (floor (* (/ current (float total)) 100)) 0)
           current total))
 
@@ -592,7 +626,9 @@ If SECRET is non-nil, list secret keys instead of public keys."
     (epg-context-set-passphrase-callback context
                                         #'epa-passphrase-callback-function)
     (epg-context-set-progress-callback context
-                                      #'epa-progress-callback-function)
+                                      #'epa-progress-callback-function
+                                      (format "Decrypting %s..."
+                                              (file-name-nondirectory file)))
     (message "Decrypting %s..." (file-name-nondirectory file))
     (epg-decrypt-file context file plain)
     (message "Decrypting %s...wrote %s" (file-name-nondirectory file)
@@ -610,7 +646,9 @@ If SECRET is non-nil, list secret keys instead of public keys."
         (plain (if (equal (file-name-extension file) "sig")
                    (file-name-sans-extension file))))
     (epg-context-set-progress-callback context
-                                      #'epa-progress-callback-function)
+                                      #'epa-progress-callback-function
+                                      (format "Verifying %s..."
+                                              (file-name-nondirectory file)))
     (message "Verifying %s..." (file-name-nondirectory file))
     (epg-verify-file context file plain)
     (message "Verifying %s...done" (file-name-nondirectory file))
@@ -618,42 +656,54 @@ If SECRET is non-nil, list secret keys instead of public keys."
        (epa-display-info (epg-verify-result-to-string
                           (epg-context-result-for context 'verify))))))
 
-;;;###autoload
-(defun epa-sign-file (file signers mode)
-  "Sign FILE by SIGNERS keys selected."
-  (interactive
-   (list (expand-file-name (read-file-name "File: "))
-        (epa-select-keys (epg-make-context epa-protocol)
-                         "Select keys for signing.
-If no one is selected, default secret key is used.  "
-                         nil t)
-        (catch 'done
-          (while t
-            (message "Signature type (n,c,d,?) ")
-            (let ((c (read-char)))
-              (cond ((eq c ?c)
-                     (throw 'done 'clear))
-                    ((eq c ?d)
-                     (throw 'done 'detached))
-                    ((eq c ??)
-                     (with-output-to-temp-buffer "*Help*"
-                       (save-excursion
-                         (set-buffer standard-output)
-                         (insert "\
+(defun epa--read-signature-type ()
+  (let (type c)
+    (while (null type)
+      (message "Signature type (n,c,d,?) ")
+      (setq c (read-char))
+      (cond ((eq c ?c)
+            (setq type 'clear))
+           ((eq c ?d)
+            (setq type 'detached))
+           ((eq c ??)
+            (with-output-to-temp-buffer "*Help*"
+              (save-excursion
+                (set-buffer standard-output)
+                (insert "\
 n - Create a normal signature
 c - Create a cleartext signature
 d - Create a detached signature
 ? - Show this help
 "))))
-                    (t
-                     (throw 'done nil))))))))
+           (t
+            (setq type 'normal))))))
+
+;;;###autoload
+(defun epa-sign-file (file signers mode)
+  "Sign FILE by SIGNERS keys selected."
+  (interactive
+   (let ((verbose current-prefix-arg))
+     (list (expand-file-name (read-file-name "File: "))
+          (if verbose
+              (epa-select-keys (epg-make-context epa-protocol)
+                               "Select keys for signing.
+If no one is selected, default secret key is used.  "
+                               nil t))
+          (if verbose
+              (epa--read-signature-type)
+            'clear))))
   (let ((signature (concat file
-                          (if (or epa-armor
-                                  (not (memq mode '(nil t normal detached))))
-                              ".asc"
+                          (if (eq epa-protocol 'OpenPGP)
+                              (if (or epa-armor
+                                      (not (memq mode
+                                                 '(nil t normal detached))))
+                                  ".asc"
+                                (if (memq mode '(t detached))
+                                    ".sig"
+                                  ".gpg"))
                             (if (memq mode '(t detached))
-                                ".sig"
-                              ".gpg"))))
+                                ".p7s"
+                              ".p7m"))))
        (context (epg-make-context epa-protocol)))
     (epg-context-set-armor context epa-armor)
     (epg-context-set-textmode context epa-textmode)
@@ -661,7 +711,9 @@ d - Create a detached signature
     (epg-context-set-passphrase-callback context
                                         #'epa-passphrase-callback-function)
     (epg-context-set-progress-callback context
-                                      #'epa-progress-callback-function)
+                                      #'epa-progress-callback-function
+                                      (format "Signing %s..."
+                                              (file-name-nondirectory file)))
     (message "Signing %s..." (file-name-nondirectory file))
     (epg-sign-file context file signature mode)
     (message "Signing %s...wrote %s" (file-name-nondirectory file)
@@ -675,14 +727,18 @@ d - Create a detached signature
         (epa-select-keys (epg-make-context epa-protocol)
                          "Select recipients for encryption.
 If no one is selected, symmetric encryption will be performed.  ")))
-  (let ((cipher (concat file (if epa-armor ".asc" ".gpg")))
+  (let ((cipher (concat file (if (eq epa-protocol 'OpenPGP)
+                                (if epa-armor ".asc" ".gpg")
+                              ".p7m")))
        (context (epg-make-context epa-protocol)))
     (epg-context-set-armor context epa-armor)
     (epg-context-set-textmode context epa-textmode)
     (epg-context-set-passphrase-callback context
                                         #'epa-passphrase-callback-function)
     (epg-context-set-progress-callback context
-                                      #'epa-progress-callback-function)
+                                      #'epa-progress-callback-function
+                                      (format "Encrypting %s..."
+                                              (file-name-nondirectory file)))
     (message "Encrypting %s..." (file-name-nondirectory file))
     (epg-encrypt-file context file recipients cipher)
     (message "Encrypting %s...wrote %s" (file-name-nondirectory file)
@@ -700,17 +756,38 @@ Don't use this command in Lisp programs!"
       (epg-context-set-passphrase-callback context
                                           #'epa-passphrase-callback-function)
       (epg-context-set-progress-callback context
-                                        #'epa-progress-callback-function)
+                                        #'epa-progress-callback-function
+                                        "Decrypting...")
       (message "Decrypting...")
       (setq plain (epg-decrypt-string context (buffer-substring start end)))
       (message "Decrypting...done")
-      (delete-region start end)
-      (goto-char start)
-      (insert (epa--decode-coding-string plain coding-system-for-read))
+      (setq plain (epa--decode-coding-string
+                  plain
+                  (or coding-system-for-read
+                      (get-text-property start 'epa-coding-system-used))))
+      (if (y-or-n-p "Replace the original text? ")
+         (let ((inhibit-read-only t)
+               buffer-read-only)
+           (delete-region start end)
+           (goto-char start)
+           (insert plain))
+       (let ((epa-popup-info-window t))
+         (epa-display-info plain)))
       (if (epg-context-result-for context 'verify)
          (epa-display-info (epg-verify-result-to-string
                             (epg-context-result-for context 'verify)))))))
 
+(defun epa--find-coding-system-for-mime-charset (mime-charset)
+  (if (featurep 'xemacs)
+      (if (fboundp 'find-coding-system)
+         (find-coding-system mime-charset))
+    (let ((pointer (coding-system-list)))
+      (while (and pointer
+                 (eq (coding-system-get (car pointer) 'mime-charset)
+                     mime-charset))
+       (setq pointer (cdr pointer)))
+      pointer)))
+
 ;;;###autoload
 (defun epa-decrypt-armor-in-region (start end)
   "Decrypt OpenPGP armors in the current region between START and END.
@@ -721,7 +798,7 @@ Don't use this command in Lisp programs!"
     (save-restriction
       (narrow-to-region start end)
       (goto-char start)
-      (let (armor-start armor-end charset coding-system)
+      (let (armor-start armor-end)
        (while (re-search-forward "-----BEGIN PGP MESSAGE-----$" nil t)
          (setq armor-start (match-beginning 0)
                armor-end (re-search-forward "^-----END PGP MESSAGE-----$"
@@ -729,15 +806,25 @@ Don't use this command in Lisp programs!"
          (unless armor-end
            (error "No armor tail"))
          (goto-char armor-start)
-         (if (re-search-forward "^Charset: \\(.*\\)" armor-end t)
-             (setq charset (match-string 1)))
-         (if coding-system-for-read
-             (setq coding-system coding-system-for-read)
-           (if charset
-               (setq coding-system (intern (downcase charset)))
-             (setq coding-system 'utf-8)))
-         (let ((coding-system-for-read coding-system))
-           (epa-decrypt-region start end)))))))
+         (let ((coding-system-for-read
+                (or coding-system-for-read
+                    (if (re-search-forward "^Charset: \\(.*\\)" armor-end t)
+                        (epa--find-coding-system-for-mime-charset
+                         (intern (downcase (match-string 1))))))))
+           (epa-decrypt-region armor-start armor-end)))))))
+
+;;;###autoload
+(defun epa-decrypt ()
+  "Decrypt OpenPGP armors in the current buffer.
+
+Don't use this command in Lisp programs!"
+  (interactive)
+  (epa-decrypt-armor-in-region (point-min) (point-max)))
+
+(if (fboundp 'select-safe-coding-system)
+    (defalias 'epa--select-safe-coding-system 'select-safe-coding-system)
+  (defun epa--select-safe-coding-system (from to)
+    buffer-file-coding-system))
 
 ;;;###autoload
 (defun epa-verify-region (start end)
@@ -747,11 +834,14 @@ Don't use this command in Lisp programs!"
   (interactive "r")
   (let ((context (epg-make-context epa-protocol)))
     (epg-context-set-progress-callback context
-                                      #'epa-progress-callback-function)
+                                      #'epa-progress-callback-function
+                                      "Verifying...")
     (epg-verify-string context
                       (epa--encode-coding-string
                        (buffer-substring start end)
-                       coding-system-for-write))
+                       (or coding-system-for-write
+                           (get-text-property start
+                                              'epa-coding-system-used))))
     (if (epg-context-result-for context 'verify)
        (epa-display-info (epg-verify-result-to-string
                           (epg-context-result-for context 'verify))))))
@@ -782,36 +872,33 @@ Don't use this command in Lisp programs!"
          (epa-verify-region armor-start armor-end))))))
 
 ;;;###autoload
+(defun epa-verify ()
+  "Verify OpenPGP cleartext signed messages in the current buffer.
+
+Don't use this command in Lisp programs!"
+  (interactive)
+  (epa-verify-cleartext-in-region (point-min) (point-max)))
+
+;;;###autoload
 (defun epa-sign-region (start end signers mode)
   "Sign the current region between START and END by SIGNERS keys selected.
 
 Don't use this command in Lisp programs!"
   (interactive
-   (list (region-beginning) (region-end)
-        (epa-select-keys (epg-make-context epa-protocol)
-                         "Select keys for signing.
+   (let ((verbose current-prefix-arg))
+     (setq epa-last-coding-system-specified
+          (or coding-system-for-write
+              (epa--select-safe-coding-system
+               (region-beginning) (region-end))))
+     (list (region-beginning) (region-end)
+          (if verbose
+              (epa-select-keys (epg-make-context epa-protocol)
+                               "Select keys for signing.
 If no one is selected, default secret key is used.  "
-                         nil t)
-        (catch 'done
-          (while t
-            (message "Signature type (n,c,d,?) ")
-            (let ((c (read-char)))
-              (cond ((eq c ?c)
-                     (throw 'done 'clear))
-                    ((eq c ?d)
-                     (throw 'done 'detached))
-                    ((eq c ??)
-                     (with-output-to-temp-buffer "*Help*"
-                       (save-excursion
-                         (set-buffer standard-output)
-                         (insert "\
-n - Create a normal signature
-c - Create a cleartext signature
-d - Create a detached signature
-? - Show this help
-"))))
-                    (t
-                     (throw 'done nil))))))))
+                               nil t))
+          (if verbose
+              (epa--read-signature-type)
+            'clear))))
   (save-excursion
     (let ((context (epg-make-context epa-protocol))
          signature)
@@ -823,16 +910,73 @@ d - Create a detached signature
       (epg-context-set-passphrase-callback context
                                           #'epa-passphrase-callback-function)
       (epg-context-set-progress-callback context
-                                        #'epa-progress-callback-function)
+                                        #'epa-progress-callback-function
+                                        "Signing...")
       (message "Signing...")
       (setq signature (epg-sign-string context
                                       (epa--encode-coding-string
                                        (buffer-substring start end)
-                                       coding-system-for-write)
+                                       epa-last-coding-system-specified)
                                       mode))
       (message "Signing...done")
       (delete-region start end)
-      (insert (epa--decode-coding-string signature coding-system-for-read)))))
+      (goto-char start)
+      (add-text-properties (point)
+                          (progn
+                            (insert (epa--decode-coding-string
+                                     signature
+                                     (or coding-system-for-read
+                                         epa-last-coding-system-specified)))
+                            (point))
+                          (list 'epa-coding-system-used
+                                epa-last-coding-system-specified
+                                'front-sticky nil
+                                'rear-nonsticky t
+                                'start-open t
+                                'end-open t)))))
+
+(if (fboundp 'derived-mode-p)
+    (defalias 'epa--derived-mode-p 'derived-mode-p)
+  (defun epa--derived-mode-p (&rest modes)
+    "Non-nil if the current major mode is derived from one of MODES.
+Uses the `derived-mode-parent' property of the symbol to trace backwards."
+    (let ((parent major-mode))
+      (while (and (not (memq parent modes))
+                 (setq parent (get parent 'derived-mode-parent))))
+      parent)))
+
+(defun epa--mail-mode-p ()
+  (let ((pointer epa-mail-modes))
+    (while (and pointer
+               (epa--derived-mode-p (car pointer)))
+      (setq pointer (cdr pointer)))
+    pointer))
+
+;;;###autoload
+(defun epa-sign (start end signers mode)
+  "Sign the current buffer.
+
+Don't use this command in Lisp programs!"
+  (interactive
+   (save-excursion
+     (goto-char (point-min))
+     (if (and (epa--mail-mode-p)
+             (search-forward mail-header-separator nil t))
+        (forward-line))
+     (setq epa-last-coding-system-specified
+          (or coding-system-for-write
+              (epa--select-safe-coding-system (point) (point-max))))
+     (let ((verbose current-prefix-arg))
+       (list (point) (point-max)
+            (if verbose
+                (epa-select-keys (epg-make-context epa-protocol)
+                                 "Select keys for signing.
+If no one is selected, default secret key is used.  "
+                                 nil t))
+            (if verbose
+                (epa--read-signature-type)
+              'clear)))))
+  (epa-sign-region start end signers mode))
 
 ;;;###autoload
 (defun epa-encrypt-region (start end recipients)
@@ -840,10 +984,15 @@ d - Create a detached signature
 
 Don't use this command in Lisp programs!"
   (interactive
-   (list (region-beginning) (region-end)
-        (epa-select-keys (epg-make-context epa-protocol)
-                         "Select recipients for encryption.
-If no one is selected, symmetric encryption will be performed.  ")))
+   (progn
+     (setq epa-last-coding-system-specified
+          (or coding-system-for-write
+              (epa--select-safe-coding-system
+               (region-beginning) (region-end))))
+     (list (region-beginning) (region-end)
+          (epa-select-keys (epg-make-context epa-protocol)
+                           "Select recipients for encryption.
+If no one is selected, symmetric encryption will be performed.  "))))
   (save-excursion
     (let ((context (epg-make-context epa-protocol))
          cipher)
@@ -854,16 +1003,76 @@ If no one is selected, symmetric encryption will be performed.  ")))
       (epg-context-set-passphrase-callback context
                                           #'epa-passphrase-callback-function)
       (epg-context-set-progress-callback context
-                                        #'epa-progress-callback-function)
+                                        #'epa-progress-callback-function
+                                        "Encrypting...")
       (message "Encrypting...")
       (setq cipher (epg-encrypt-string context
                                       (epa--encode-coding-string
                                        (buffer-substring start end)
-                                       coding-system-for-write)
+                                       epa-last-coding-system-specified)
                                       recipients))
       (message "Encrypting...done")
       (delete-region start end)
-      (insert cipher))))
+      (goto-char start)
+      (add-text-properties (point)
+                          (progn
+                            (insert cipher)
+                            (point))
+                          (list 'epa-coding-system-used
+                                epa-last-coding-system-specified
+                                'front-sticky nil
+                                'rear-nonsticky t
+                                'start-open t
+                                'end-open t)))))
+
+;;;###autoload
+(defun epa-encrypt (start end recipients)
+  "Encrypt the current buffer.
+
+Don't use this command in Lisp programs!"
+  (interactive
+   (save-excursion
+     (let (recipients)
+       (goto-char (point-min))
+       (when (epa--mail-mode-p)
+        (save-restriction
+          (narrow-to-region (point)
+                            (if (search-forward mail-header-separator nil 0)
+                                (match-beginning 0)
+                              (point)))
+          (setq recipients
+                (mail-strip-quoted-names
+                 (mapconcat #'identity
+                            (nconc (mail-fetch-field "to" nil nil t)
+                                   (mail-fetch-field "cc" nil nil t)
+                                   (mail-fetch-field "bcc" nil nil t))
+                            ","))))
+        (if recipients
+            (setq recipients (delete ""
+                                     (split-string recipients "[ \t\n]+"))))
+        (goto-char (point-min))
+        (if (search-forward mail-header-separator nil t)
+            (forward-line)))
+       (setq epa-last-coding-system-specified
+            (or coding-system-for-write
+                (epa--select-safe-coding-system (point) (point-max))))
+       (list (point) (point-max)
+            (if current-prefix-arg
+                (epa-select-keys
+                 (epg-make-context epa-protocol)
+                 "Select recipients for encryption.
+If no one is selected, symmetric encryption will be performed.  "
+                 recipients)
+              (if recipients
+                  (delq nil
+                        (apply #'nconc
+                               (mapcar
+                                (lambda (recipient)
+                                  (epg-list-keys
+                                   (epg-make-context epa-protocol)
+                                   (concat "<" recipient ">")))
+                                recipients)))))))))
+  (epa-encrypt-region start end recipients))
 
 ;;;###autoload
 (defun epa-delete-keys (keys &optional allow-secret)
@@ -922,6 +1131,37 @@ Don't use this command in Lisp programs!"
                           (epg-context-result-for context 'import))))))
 
 ;;;###autoload
+(defun epa-import-armor-in-region (start end)
+  "Import keys in the OpenPGP armor format in the current region
+between START and END.
+
+Don't use this command in Lisp programs!"
+  (interactive "r")
+  (save-excursion
+    (save-restriction
+      (narrow-to-region start end)
+      (goto-char start)
+      (let (armor-start armor-end)
+       (while (re-search-forward
+               "-----BEGIN \\(PGP \\(PUBLIC\\|PRIVATE\\) KEY BLOCK\\)-----$"
+               nil t)
+         (setq armor-start (match-beginning 0)
+               armor-end (re-search-forward
+                          (concat "^-----END " (match-string 1) "-----$")
+                          nil t))
+         (unless armor-end
+           (error "No armor tail"))
+         (epa-import-keys-region armor-start armor-end))))))
+
+;;;###autoload
+(defun epa-import ()
+  "Import keys in the OpenPGP armor format in the current buffer.
+
+Don't use this command in Lisp programs!"
+  (interactive)
+  (epa-import-armor-in-region (point-min) (point-max)))
+
+;;;###autoload
 (defun epa-export-keys (keys file)
   "Export selected KEYS to FILE.
 
@@ -978,7 +1218,8 @@ Don't use this command in Lisp programs!"
     (epg-context-set-passphrase-callback context
                                         #'epa-passphrase-callback-function)
     (epg-context-set-progress-callback context
-                                      #'epa-progress-callback-function)
+                                      #'epa-progress-callback-function
+                                      "Signing keys...")
     (message "Signing keys...")
     (epg-sign-keys context keys local)
     (message "Signing keys...done")))