]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-mua.el
emacs: Fix mail composition under Emacs 23
[notmuch] / emacs / notmuch-mua.el
1 ;; notmuch-mua.el --- emacs style mail-user-agent
2 ;;
3 ;; Copyright © David Edmondson
4 ;;
5 ;; This file is part of Notmuch.
6 ;;
7 ;; Notmuch is free software: you can redistribute it and/or modify it
8 ;; under the terms of the GNU General Public License as published by
9 ;; the Free Software Foundation, either version 3 of the License, or
10 ;; (at your option) any later version.
11 ;;
12 ;; Notmuch is distributed in the hope that it will be useful, but
13 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 ;; General Public License for more details.
16 ;;
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with Notmuch.  If not, see <http://www.gnu.org/licenses/>.
19 ;;
20 ;; Authors: David Edmondson <dme@dme.org>
21
22 (require 'message)
23 (require 'mm-view)
24 (require 'format-spec)
25
26 (require 'notmuch-lib)
27 (require 'notmuch-address)
28
29 (eval-when-compile (require 'cl))
30
31 (declare-function notmuch-show-insert-bodypart "notmuch-show" (msg part depth &optional hide))
32
33 ;;
34
35 (defcustom notmuch-mua-send-hook '(notmuch-mua-message-send-hook)
36   "Hook run before sending messages."
37   :type 'hook
38   :group 'notmuch-send
39   :group 'notmuch-hooks)
40
41 (defcustom notmuch-mua-compose-in 'current-window
42   (concat
43    "Where to create the mail buffer used to compose a new message.
44 Possible values are `current-window' (default), `new-window' and
45 `new-frame'. If set to `current-window', the mail buffer will be
46 displayed in the current window, so the old buffer will be
47 restored when the mail buffer is killed. If set to `new-window'
48 or `new-frame', the mail buffer will be displayed in a new
49 window/frame that will be destroyed when the buffer is killed.
50 You may want to customize `message-kill-buffer-on-exit'
51 accordingly."
52    (when (< emacs-major-version 24)
53            " Due to a known bug in Emacs 23, you should not set
54 this to `new-window' if `message-kill-buffer-on-exit' is
55 disabled: this would result in an incorrect behavior."))
56   :group 'notmuch-send
57   :type '(choice (const :tag "Compose in the current window" current-window)
58                  (const :tag "Compose mail in a new window"  new-window)
59                  (const :tag "Compose mail in a new frame"   new-frame)))
60
61 (defcustom notmuch-mua-user-agent-function 'notmuch-mua-user-agent-full
62   "Function used to generate a `User-Agent:' string. If this is
63 `nil' then no `User-Agent:' will be generated."
64   :type '(choice (const :tag "No user agent string" nil)
65                  (const :tag "Full" notmuch-mua-user-agent-full)
66                  (const :tag "Notmuch" notmuch-mua-user-agent-notmuch)
67                  (const :tag "Emacs" notmuch-mua-user-agent-emacs)
68                  (function :tag "Custom user agent function"
69                            :value notmuch-mua-user-agent-full))
70   :group 'notmuch-send)
71
72 (defcustom notmuch-mua-hidden-headers '("^User-Agent:")
73   "Headers that are added to the `message-mode' hidden headers
74 list."
75   :type '(repeat string)
76   :group 'notmuch-send)
77
78 (defgroup notmuch-reply nil
79   "Replying to messages in notmuch"
80   :group 'notmuch)
81
82 (defcustom notmuch-mua-cite-function 'message-cite-original
83   "*Function for citing an original message.
84 Predefined functions include `message-cite-original' and
85 `message-cite-original-without-signature'.
86 Note that these functions use `mail-citation-hook' if that is non-nil."
87   :type '(radio (function-item message-cite-original)
88                 (function-item message-cite-original-without-signature)
89                 (function-item sc-cite-original)
90                 (function :tag "Other"))
91   :link '(custom-manual "(message)Insertion Variables")
92   :group 'notmuch-reply)
93
94 ;;
95
96 (defun notmuch-mua-get-switch-function ()
97   "Get a switch function according to `notmuch-mua-compose-in'."
98   (cond ((eq notmuch-mua-compose-in 'current-window)
99          'switch-to-buffer)
100         ((eq notmuch-mua-compose-in 'new-window)
101          'switch-to-buffer-other-window)
102         ((eq notmuch-mua-compose-in 'new-frame)
103          'switch-to-buffer-other-frame)
104         (t (error "Invalid value for `notmuch-mua-compose-in'"))))
105
106 (defun notmuch-mua-maybe-set-window-dedicated ()
107   "Set the selected window as dedicated according to
108 `notmuch-mua-compose-in'."
109   (when (or (eq notmuch-mua-compose-in 'new-frame)
110             (eq notmuch-mua-compose-in 'new-window))
111     (set-window-dedicated-p (selected-window) t)))
112
113 (defun notmuch-mua-user-agent-full ()
114   "Generate a `User-Agent:' string suitable for notmuch."
115   (concat (notmuch-mua-user-agent-notmuch)
116           " "
117           (notmuch-mua-user-agent-emacs)))
118
119 (defun notmuch-mua-user-agent-notmuch ()
120   "Generate a `User-Agent:' string suitable for notmuch."
121   (let ((notmuch-version (if (string= notmuch-emacs-version "unknown")
122                              (notmuch-cli-version)
123                            notmuch-emacs-version)))
124     (concat "Notmuch/" notmuch-version " (http://notmuchmail.org)")))
125
126 (defun notmuch-mua-user-agent-emacs ()
127   "Generate a `User-Agent:' string suitable for notmuch."
128   (concat "Emacs/" emacs-version " (" system-configuration ")"))
129
130 (defun notmuch-mua-add-more-hidden-headers ()
131   "Add some headers to the list that are hidden by default."
132   (mapc (lambda (header)
133           (when (not (member header message-hidden-headers))
134             (push header message-hidden-headers)))
135         notmuch-mua-hidden-headers))
136
137 (defun notmuch-mua-reply-crypto (parts)
138   "Add mml sign-encrypt flag if any part of original message is encrypted."
139   (loop for part in parts
140         if (notmuch-match-content-type (plist-get part :content-type) "multipart/encrypted")
141           do (mml-secure-message-sign-encrypt)
142         else if (notmuch-match-content-type (plist-get part :content-type) "multipart/*")
143           do (notmuch-mua-reply-crypto (plist-get part :content))))
144
145 (defun notmuch-mua-get-quotable-parts (parts)
146   (loop for part in parts
147         if (notmuch-match-content-type (plist-get part :content-type) "multipart/alternative")
148           collect (let* ((subparts (plist-get part :content))
149                         (types (mapcar (lambda (part) (plist-get part :content-type)) subparts))
150                         (chosen-type (car (notmuch-multipart/alternative-choose types))))
151                    (loop for part in (reverse subparts)
152                          if (notmuch-match-content-type (plist-get part :content-type) chosen-type)
153                          return part))
154         else if (notmuch-match-content-type (plist-get part :content-type) "multipart/*")
155           append (notmuch-mua-get-quotable-parts (plist-get part :content))
156         else if (notmuch-match-content-type (plist-get part :content-type) "text/*")
157           collect part))
158
159 (defun notmuch-mua-insert-quotable-part (message part)
160   ;; We don't want text properties leaking from the show renderer into
161   ;; the reply so we use a temp buffer. Also we don't want hooks, such
162   ;; as notmuch-wash-*, to be run on the quotable part so we set
163   ;; notmuch-show-insert-text/plain-hook to nil.
164   (insert (with-temp-buffer
165             (let ((notmuch-show-insert-text/plain-hook nil))
166               ;; Show the part but do not add buttons.
167               (notmuch-show-insert-bodypart message part 0 'no-buttons))
168             (buffer-substring-no-properties (point-min) (point-max)))))
169
170 ;; There is a bug in emacs 23's message.el that results in a newline
171 ;; not being inserted after the References header, so the next header
172 ;; is concatenated to the end of it. This function fixes the problem,
173 ;; while guarding against the possibility that some current or future
174 ;; version of emacs has the bug fixed.
175 (defun notmuch-mua-insert-references (original-func header references)
176   (funcall original-func header references)
177   (unless (bolp) (insert "\n")))
178
179 (defun notmuch-mua-reply (query-string &optional sender reply-all)
180   (let ((args '("reply" "--format=sexp" "--format-version=1"))
181         (process-crypto notmuch-show-process-crypto)
182         reply
183         original)
184     (when process-crypto
185       (setq args (append args '("--decrypt"))))
186
187     (if reply-all
188         (setq args (append args '("--reply-to=all")))
189       (setq args (append args '("--reply-to=sender"))))
190     (setq args (append args (list query-string)))
191
192     ;; Get the reply object as SEXP, and parse it into an elisp object.
193     (setq reply (apply #'notmuch-call-notmuch-sexp args))
194
195     ;; Extract the original message to simplify the following code.
196     (setq original (plist-get reply :original))
197
198     ;; Extract the headers of both the reply and the original message.
199     (let* ((original-headers (plist-get original :headers))
200            (reply-headers (plist-get reply :reply-headers)))
201
202       ;; If sender is non-nil, set the From: header to its value.
203       (when sender
204         (plist-put reply-headers :From sender))
205       (let
206           ;; Overlay the composition window on that being used to read
207           ;; the original message.
208           ((same-window-regexps '("\\*mail .*")))
209
210         ;; We modify message-header-format-alist to get around a bug in message.el.
211         ;; See the comment above on notmuch-mua-insert-references.
212         (let ((message-header-format-alist
213                (loop for pair in message-header-format-alist
214                      if (eq (car pair) 'References)
215                      collect (cons 'References
216                                    (apply-partially
217                                     'notmuch-mua-insert-references
218                                     (cdr pair)))
219                      else
220                      collect pair)))
221           (notmuch-mua-mail (plist-get reply-headers :To)
222                             (plist-get reply-headers :Subject)
223                             (notmuch-headers-plist-to-alist reply-headers)
224                             nil (notmuch-mua-get-switch-function))))
225
226       ;; Insert the message body - but put it in front of the signature
227       ;; if one is present, and after any other content
228       ;; message*setup-hooks may have added to the message body already.
229       (save-restriction
230         (message-goto-body)
231         (narrow-to-region (point) (point-max))
232         (goto-char (point-max))
233         (if (re-search-backward message-signature-separator nil t)
234             (if message-signature-insert-empty-line
235                 (forward-line -1))
236           (goto-char (point-max))))
237
238       (let ((from (plist-get original-headers :From))
239             (date (plist-get original-headers :Date))
240             (start (point)))
241
242         ;; notmuch-mua-cite-function constructs a citation line based
243         ;; on the From and Date headers of the original message, which
244         ;; are assumed to be in the buffer.
245         (insert "From: " from "\n")
246         (insert "Date: " date "\n\n")
247
248         ;; Get the parts of the original message that should be quoted; this includes
249         ;; all the text parts, except the non-preferred ones in a multipart/alternative.
250         (let ((quotable-parts (notmuch-mua-get-quotable-parts (plist-get original :body))))
251           (mapc (apply-partially 'notmuch-mua-insert-quotable-part original) quotable-parts))
252
253         (set-mark (point))
254         (goto-char start)
255         ;; Quote the original message according to the user's configured style.
256         (funcall notmuch-mua-cite-function)))
257
258     ;; Crypto processing based crypto content of the original message
259     (when process-crypto
260       (notmuch-mua-reply-crypto (plist-get original :body))))
261
262   ;; Push mark right before signature, if any.
263   (message-goto-signature)
264   (unless (eobp)
265     (end-of-line -1))
266   (push-mark)
267
268   (message-goto-body)
269   (set-buffer-modified-p nil))
270
271 (define-derived-mode notmuch-message-mode message-mode "Message[Notmuch]"
272   "Notmuch message composition mode. Mostly like `message-mode'"
273   (when notmuch-address-command
274     (notmuch-address-setup)))
275
276 (put 'notmuch-message-mode 'flyspell-mode-predicate 'mail-mode-flyspell-verify)
277
278 (define-key notmuch-message-mode-map (kbd "C-c C-c") #'notmuch-mua-send-and-exit)
279 (define-key notmuch-message-mode-map (kbd "C-c C-s") #'notmuch-mua-send)
280
281 (defun notmuch-mua-pop-to-buffer (name)
282   "Pop to buffer NAME, and warn if it already exists and is
283 modified. This function is notmuch addaptation of
284 `message-pop-to-buffer'."
285   (let ((buffer (get-buffer name)))
286     (if (and buffer
287              (buffer-name buffer))
288         (let ((window (get-buffer-window buffer 0)))
289           (if window
290               ;; Raise the frame already displaying the message buffer.
291               (progn
292                 (gnus-select-frame-set-input-focus (window-frame window))
293                 (select-window window))
294             (funcall (notmuch-mua-get-switch-function) buffer)
295             (set-buffer buffer))
296           (when (and (buffer-modified-p)
297                      (not (prog1
298                               (y-or-n-p
299                                "Message already being composed; erase? ")
300                             (message nil))))
301             (error "Message being composed")))
302       (funcall (notmuch-mua-get-switch-function) name)
303       (set-buffer name))
304     (erase-buffer)
305     (notmuch-message-mode)))
306
307 (defun notmuch-mua-mail (&optional to subject other-headers continue
308                                    switch-function yank-action send-actions
309                                    return-action &rest ignored)
310   "Invoke the notmuch mail composition window."
311   (interactive)
312
313   (when notmuch-mua-user-agent-function
314     (let ((user-agent (funcall notmuch-mua-user-agent-function)))
315       (when (not (string= "" user-agent))
316         (push (cons 'User-Agent user-agent) other-headers))))
317
318   (unless (assq 'From other-headers)
319     (push (cons 'From (concat
320                        (notmuch-user-name) " <" (notmuch-user-primary-email) ">")) other-headers))
321
322   (notmuch-mua-pop-to-buffer (message-buffer-name "mail" to))
323   (let ((args (list yank-action send-actions)))
324     ;; message-setup-1 in Emacs 23 does not accept return-action
325     ;; argument. Pass it only if it is supplied by the caller. This
326     ;; will never be the case when we're called by `compose-mail' in
327     ;; Emacs 23.
328     (when return-action (nconc args '(return-action)))
329     (apply 'message-setup-1
330            ;; The following sexp is copied from `message-mail'
331            (nconc
332             `((To . ,(or to "")) (Subject . ,(or subject "")))
333             ;; C-h f compose-mail says that headers should be specified as
334             ;; (string . value); however all the rest of message expects
335             ;; headers to be symbols, not strings (eg message-header-format-alist).
336             ;; http://lists.gnu.org/archive/html/emacs-devel/2011-01/msg00337.html
337             ;; We need to convert any string input, eg from rmail-start-mail.
338             (dolist (h other-headers other-headers)
339               (if (stringp (car h)) (setcar h (intern (capitalize (car h)))))))
340            args))
341   (notmuch-fcc-header-setup)
342   (message-sort-headers)
343   (message-hide-headers)
344   (set-buffer-modified-p nil)
345   (notmuch-mua-maybe-set-window-dedicated)
346
347   (message-goto-to))
348
349 (defcustom notmuch-identities nil
350   "Identities that can be used as the From: address when composing a new message.
351
352 If this variable is left unset, then a list will be constructed from the
353 name and addresses configured in the notmuch configuration file."
354   :type '(repeat string)
355   :group 'notmuch-send)
356
357 (defcustom notmuch-always-prompt-for-sender nil
358   "Always prompt for the From: address when composing or forwarding a message.
359
360 This is not taken into account when replying to a message, because in that case
361 the From: header is already filled in by notmuch."
362   :type 'boolean
363   :group 'notmuch-send)
364
365 (defvar notmuch-mua-sender-history nil)
366
367 ;; Workaround: Running `ido-completing-read' in emacs 23.1, 23.2 and 23.3
368 ;; without some explicit initialization fill freeze the operation.
369 ;; Hence, we advice `ido-completing-read' to ensure required initialization
370 ;; is done.
371 (if (and (= emacs-major-version 23) (< emacs-minor-version 4))
372     (defadvice ido-completing-read (before notmuch-ido-mode-init activate)
373       (ido-init-completion-maps)
374       (add-hook 'minibuffer-setup-hook 'ido-minibuffer-setup)
375       (add-hook 'choose-completion-string-functions
376                 'ido-choose-completion-string)
377       (ad-disable-advice 'ido-completing-read 'before 'notmuch-ido-mode-init)
378       (ad-activate 'ido-completing-read)))
379
380 (defun notmuch-mua-prompt-for-sender ()
381   "Prompt for a sender from the user's configured identities."
382   (if notmuch-identities
383       (ido-completing-read "Send mail from: " notmuch-identities
384                            nil nil nil 'notmuch-mua-sender-history
385                            (car notmuch-identities))
386     (let* ((name (notmuch-user-name))
387            (addrs (cons (notmuch-user-primary-email)
388                         (notmuch-user-other-email)))
389            (address
390             (ido-completing-read (concat "Sender address for " name ": ") addrs
391                                  nil nil nil 'notmuch-mua-sender-history
392                                  (car addrs))))
393       (concat name " <" address ">"))))
394
395 (put 'notmuch-mua-new-mail 'notmuch-prefix-doc "... and prompt for sender")
396 (defun notmuch-mua-new-mail (&optional prompt-for-sender)
397   "Compose new mail.
398
399 If PROMPT-FOR-SENDER is non-nil, the user will be prompted for
400 the From: address first."
401   (interactive "P")
402   (let ((other-headers
403          (when (or prompt-for-sender notmuch-always-prompt-for-sender)
404            (list (cons 'From (notmuch-mua-prompt-for-sender))))))
405     (notmuch-mua-mail nil nil other-headers nil (notmuch-mua-get-switch-function))))
406
407 (defun notmuch-mua-new-forward-message (&optional prompt-for-sender)
408   "Invoke the notmuch message forwarding window.
409
410 The current buffer must contain an RFC2822 message to forward.
411
412 If PROMPT-FOR-SENDER is non-nil, the user will be prompted for
413 the From: address first."
414   (let* ((cur (current-buffer))
415          (message-forward-decoded-p nil)
416          (subject (message-make-forward-subject))
417          (other-headers
418           (when (or prompt-for-sender notmuch-always-prompt-for-sender)
419             (list (cons 'From (notmuch-mua-prompt-for-sender))))))
420     (notmuch-mua-mail nil subject other-headers nil (notmuch-mua-get-switch-function))
421     (message-forward-make-body cur)
422     ;; `message-forward-make-body' shows the User-agent header.  Hide
423     ;; it again.
424     (message-hide-headers)
425     (set-buffer-modified-p nil)))
426
427 (defun notmuch-mua-new-reply (query-string &optional prompt-for-sender reply-all)
428   "Compose a reply to the message identified by QUERY-STRING.
429
430 If PROMPT-FOR-SENDER is non-nil, the user will be prompted for
431 the From: address first.  If REPLY-ALL is non-nil, the message
432 will be addressed to all recipients of the source message."
433
434 ;; In current emacs (24.3) select-active-regions is set to t by
435 ;; default. The reply insertion code sets the region to the quoted
436 ;; message to make it easy to delete (kill-region or C-w). These two
437 ;; things combine to put the quoted message in the primary selection.
438 ;;
439 ;; This is not what the user wanted and is a privacy risk (accidental
440 ;; pasting of the quoted message). We can avoid some of the problems
441 ;; by let-binding select-active-regions to nil. This fixes if the
442 ;; primary selection was previously in a non-emacs window but not if
443 ;; it was in an emacs window. To avoid the problem in the latter case
444 ;; we deactivate mark.
445
446   (let ((sender
447          (when prompt-for-sender
448            (notmuch-mua-prompt-for-sender)))
449         (select-active-regions nil))
450     (notmuch-mua-reply query-string sender reply-all)
451     (deactivate-mark)))
452
453 (defun notmuch-mua-send-and-exit (&optional arg)
454   (interactive "P")
455   (let ((message-fcc-handler-function #'notmuch-fcc-handler))
456     (message-send-and-exit arg)))
457
458 (defun notmuch-mua-send (&optional arg)
459   (interactive "P")
460   (let ((message-fcc-handler-function #'notmuch-fcc-handler))
461     (message-send arg)))
462
463 (defun notmuch-mua-kill-buffer ()
464   (interactive)
465   (message-kill-buffer))
466
467 (defun notmuch-mua-message-send-hook ()
468   "The default function used for `notmuch-mua-send-hook', this
469 simply runs the corresponding `message-mode' hook functions."
470   (run-hooks 'message-send-hook))
471
472 ;;
473
474 (define-mail-user-agent 'notmuch-user-agent
475   'notmuch-mua-mail 'notmuch-mua-send-and-exit
476   'notmuch-mua-kill-buffer 'notmuch-mua-send-hook)
477
478 ;; Add some more headers to the list that `message-mode' hides when
479 ;; composing a message.
480 (notmuch-mua-add-more-hidden-headers)
481
482 ;;
483
484 (provide 'notmuch-mua)