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