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