1 ;;; notmuch-mua.el --- emacs style mail-user-agent -*- lexical-binding: t -*-
3 ;; Copyright © David Edmondson
5 ;; This file is part of Notmuch.
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.
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.
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/>.
20 ;; Authors: David Edmondson <dme@dme.org>
24 (eval-when-compile (require 'cl-lib))
28 (require 'format-spec)
30 (require 'notmuch-lib)
31 (require 'notmuch-address)
32 (require 'notmuch-draft)
33 (require 'notmuch-message)
35 (declare-function notmuch-show-insert-body "notmuch-show" (msg body depth))
36 (declare-function notmuch-fcc-header-setup "notmuch-maildir-fcc" ())
37 (declare-function notmuch-maildir-message-do-fcc "notmuch-maildir-fcc" ())
38 (declare-function notmuch-draft-postpone "notmuch-draft" ())
39 (declare-function notmuch-draft-save "notmuch-draft" ())
41 (defvar notmuch-show-indent-multipart)
42 (defvar notmuch-show-insert-header-p-function)
43 (defvar notmuch-show-max-text-part-size)
44 (defvar notmuch-show-insert-text/plain-hook)
48 (defcustom notmuch-mua-send-hook nil
49 "Hook run before sending messages."
52 :group 'notmuch-hooks)
54 (defcustom notmuch-mua-compose-in 'current-window
55 "Where to create the mail buffer used to compose a new message.
56 Possible values are `current-window' (default), `new-window' and
57 `new-frame'. If set to `current-window', the mail buffer will be
58 displayed in the current window, so the old buffer will be
59 restored when the mail buffer is killed. If set to `new-window'
60 or `new-frame', the mail buffer will be displayed in a new
61 window/frame that will be destroyed when the buffer is killed.
62 You may want to customize `message-kill-buffer-on-exit'
65 :type '(choice (const :tag "Compose in the current window" current-window)
66 (const :tag "Compose mail in a new window" new-window)
67 (const :tag "Compose mail in a new frame" new-frame)))
69 (defcustom notmuch-mua-user-agent-function nil
70 "Function used to generate a `User-Agent:' string.
71 If this is `nil' then no `User-Agent:' will be generated."
72 :type '(choice (const :tag "No user agent string" nil)
73 (const :tag "Full" notmuch-mua-user-agent-full)
74 (const :tag "Notmuch" notmuch-mua-user-agent-notmuch)
75 (const :tag "Emacs" notmuch-mua-user-agent-emacs)
76 (function :tag "Custom user agent function"
77 :value notmuch-mua-user-agent-full))
80 (defcustom notmuch-mua-hidden-headers nil
81 "Headers that are added to the `message-mode' hidden headers list."
82 :type '(repeat string)
85 (defgroup notmuch-reply nil
86 "Replying to messages in notmuch"
89 (defcustom notmuch-mua-cite-function 'message-cite-original
90 "Function for citing an original message.
92 Predefined functions include `message-cite-original' and
93 `message-cite-original-without-signature'. Note that these
94 functions use `mail-citation-hook' if that is non-nil."
95 :type '(radio (function-item message-cite-original)
96 (function-item message-cite-original-without-signature)
97 (function-item sc-cite-original)
98 (function :tag "Other"))
99 :link '(custom-manual "(message)Insertion Variables")
100 :group 'notmuch-reply)
102 (defcustom notmuch-mua-reply-insert-header-p-function
103 'notmuch-show-reply-insert-header-p-never
104 "Function to decide which parts get a header when replying.
106 This function specifies which parts of a mime message with
107 multiple parts get a header."
108 :type '(radio (const :tag "No part headers"
109 notmuch-show-reply-insert-header-p-never)
110 (const :tag "All except multipart/* and hidden parts"
111 notmuch-show-reply-insert-header-p-trimmed)
112 (const :tag "Only for included text parts"
113 notmuch-show-reply-insert-header-p-minimal)
114 (const :tag "Exactly as in show view"
115 notmuch-show-insert-header-p)
116 (function :tag "Other"))
117 :group 'notmuch-reply)
119 (defcustom notmuch-mua-attachment-regexp
120 "\\b\\(attache\?ment\\|attached\\|attach\\|pi[èe]ce\s+jointe?\\)\\b"
121 "Message body text indicating that an attachment is expected.
123 This is not used unless `notmuch-mua-attachment-check' is added
124 to `notmuch-mua-send-hook'."
126 :group 'notmuch-send)
128 ;;; Various functions
130 (defun notmuch-mua-attachment-check ()
131 "Signal an error if the message text indicates that an
132 attachment is expected but no MML referencing an attachment is
135 Typically this is added to `notmuch-mua-send-hook'."
137 ;; When the message mentions attachment...
140 ;; Limit search from reaching other possible parts of the message
141 (let ((search-limit (search-forward "\n<#" nil t)))
143 (cl-loop while (re-search-forward notmuch-mua-attachment-regexp
145 ;; For every instance of the "attachment" string
146 ;; found, examine the text properties. If the text
147 ;; has either a `face' or `syntax-table' property
148 ;; then it is quoted text and should *not* cause the
149 ;; user to be asked about a missing attachment.
150 if (let ((props (text-properties-at (match-beginning 0))))
151 (not (or (memq 'syntax-table props)
152 (memq 'face props))))
154 finally return nil)))
155 ;; ...but doesn't have a part with a filename...
158 (not (re-search-forward "^<#part [^>]*filename=" nil t)))
159 ;; ...and that's not okay...
160 (not (y-or-n-p "Attachment mentioned, but no attachment - is that okay?")))
161 ;; ...signal an error.
162 (error "Missing attachment")))
164 (defun notmuch-mua-get-switch-function ()
165 "Get a switch function according to `notmuch-mua-compose-in'."
166 (cond ((eq notmuch-mua-compose-in 'current-window)
168 ((eq notmuch-mua-compose-in 'new-window)
169 'switch-to-buffer-other-window)
170 ((eq notmuch-mua-compose-in 'new-frame)
171 'switch-to-buffer-other-frame)
172 (t (error "Invalid value for `notmuch-mua-compose-in'"))))
174 (defun notmuch-mua-maybe-set-window-dedicated ()
175 "Set the selected window as dedicated according to `notmuch-mua-compose-in'."
176 (when (or (eq notmuch-mua-compose-in 'new-frame)
177 (eq notmuch-mua-compose-in 'new-window))
178 (set-window-dedicated-p (selected-window) t)))
180 (defun notmuch-mua-user-agent-full ()
181 "Generate a `User-Agent:' string suitable for notmuch."
182 (concat (notmuch-mua-user-agent-notmuch)
184 (notmuch-mua-user-agent-emacs)))
186 (defun notmuch-mua-user-agent-notmuch ()
187 "Generate a `User-Agent:' string suitable for notmuch."
188 (let ((notmuch-version (if (string= notmuch-emacs-version "unknown")
189 (notmuch-cli-version)
190 notmuch-emacs-version)))
191 (concat "Notmuch/" notmuch-version " (https://notmuchmail.org)")))
193 (defun notmuch-mua-user-agent-emacs ()
194 "Generate a `User-Agent:' string suitable for notmuch."
195 (concat "Emacs/" emacs-version " (" system-configuration ")"))
197 (defun notmuch-mua-add-more-hidden-headers ()
198 "Add some headers to the list that are hidden by default."
199 (mapc (lambda (header)
200 (unless (member header message-hidden-headers)
201 (push header message-hidden-headers)))
202 notmuch-mua-hidden-headers))
204 (defun notmuch-mua-reply-crypto (parts)
205 "Add mml sign-encrypt flag if any part of original message is encrypted."
206 (cl-loop for part in parts
207 if (notmuch-match-content-type (plist-get part :content-type)
208 "multipart/encrypted")
209 do (mml-secure-message-sign-encrypt)
210 else if (notmuch-match-content-type (plist-get part :content-type)
212 do (notmuch-mua-reply-crypto (plist-get part :content))))
214 ;; There is a bug in Emacs' message.el that results in a newline
215 ;; not being inserted after the References header, so the next header
216 ;; is concatenated to the end of it. This function fixes the problem,
217 ;; while guarding against the possibility that some current or future
218 ;; version of emacs has the bug fixed.
219 (defun notmuch-mua-insert-references (original-func header references)
220 (funcall original-func header references)
221 (unless (bolp) (insert "\n")))
225 (defun notmuch-mua-reply (query-string &optional sender reply-all)
226 (let ((args '("reply" "--format=sexp" "--format-version=4"))
227 (process-crypto notmuch-show-process-crypto)
231 (setq args (append args '("--decrypt=true"))))
233 (setq args (append args '("--reply-to=all")))
234 (setq args (append args '("--reply-to=sender"))))
235 (setq args (append args (list query-string)))
236 ;; Get the reply object as SEXP, and parse it into an elisp object.
237 (setq reply (apply #'notmuch-call-notmuch-sexp args))
238 ;; Extract the original message to simplify the following code.
239 (setq original (plist-get reply :original))
240 ;; Extract the headers of both the reply and the original message.
241 (let* ((original-headers (plist-get original :headers))
242 (reply-headers (plist-get reply :reply-headers)))
243 ;; If sender is non-nil, set the From: header to its value.
245 (plist-put reply-headers :From sender))
247 ;; Overlay the composition window on that being used to read
248 ;; the original message.
249 ((same-window-regexps '("\\*mail .*")))
250 ;; We modify message-header-format-alist to get around
251 ;; a bug in message.el. See the comment above on
252 ;; notmuch-mua-insert-references.
253 (let ((message-header-format-alist
254 (cl-loop for pair in message-header-format-alist
255 if (eq (car pair) 'References)
256 collect (cons 'References
258 'notmuch-mua-insert-references
262 (notmuch-mua-mail (plist-get reply-headers :To)
263 (notmuch-sanitize (plist-get reply-headers :Subject))
264 (notmuch-headers-plist-to-alist reply-headers)
265 nil (notmuch-mua-get-switch-function))))
266 ;; Create a buffer-local queue for tag changes triggered when
267 ;; sending the reply.
268 (when notmuch-message-replied-tags
269 (setq-local notmuch-message-queued-tag-changes
270 (list (cons query-string notmuch-message-replied-tags))))
271 ;; Insert the message body - but put it in front of the signature
272 ;; if one is present, and after any other content
273 ;; message*setup-hooks may have added to the message body already.
276 (narrow-to-region (point) (point-max))
277 (goto-char (point-max))
278 (if (re-search-backward message-signature-separator nil t)
279 (when message-signature-insert-empty-line
281 (goto-char (point-max))))
282 (let ((from (plist-get original-headers :From))
283 (date (plist-get original-headers :Date))
285 ;; notmuch-mua-cite-function constructs a citation line based
286 ;; on the From and Date headers of the original message, which
287 ;; are assumed to be in the buffer.
288 (insert "From: " from "\n")
289 (insert "Date: " date "\n\n")
293 ;; Don't attempt to clean up messages, excerpt
294 ;; citations, etc. in the original message before
296 ((notmuch-show-insert-text/plain-hook nil)
297 ;; Don't omit long parts.
298 (notmuch-show-max-text-part-size 0)
299 ;; Insert headers for parts as appropriate for replying.
300 (notmuch-show-insert-header-p-function
301 notmuch-mua-reply-insert-header-p-function)
302 ;; Ensure that any encrypted parts are
303 ;; decrypted during the generation of the reply
305 (notmuch-show-process-crypto process-crypto)
306 ;; Don't indent multipart sub-parts.
307 (notmuch-show-indent-multipart nil))
308 ;; We don't want sigstatus buttons (an information leak and usually wrong anyway).
309 (cl-letf (((symbol-function 'notmuch-crypto-insert-sigstatus-button) #'ignore)
310 ((symbol-function 'notmuch-crypto-insert-encstatus-button) #'ignore))
311 (notmuch-show-insert-body original (plist-get original :body) 0)
312 (buffer-substring-no-properties (point-min) (point-max))))))
315 ;; Quote the original message according to the user's configured style.
316 (funcall notmuch-mua-cite-function)))
317 ;; Crypto processing based crypto content of the original message
319 (notmuch-mua-reply-crypto (plist-get original :body))))
320 ;; Push mark right before signature, if any.
321 (message-goto-signature)
326 (set-buffer-modified-p nil))
330 (defvar notmuch-message-mode-map
331 (let ((map (make-sparse-keymap)))
332 (define-key map (kbd "C-c C-c") #'notmuch-mua-send-and-exit)
333 (define-key map (kbd "C-c C-s") #'notmuch-mua-send)
334 (define-key map (kbd "C-c C-p") #'notmuch-draft-postpone)
335 (define-key map (kbd "C-x C-s") #'notmuch-draft-save)
337 "Keymap for `notmuch-message-mode'.")
339 (define-derived-mode notmuch-message-mode message-mode "Message[Notmuch]"
340 "Notmuch message composition mode. Mostly like `message-mode'."
341 (notmuch-address-setup))
343 (put 'notmuch-message-mode 'flyspell-mode-predicate 'mail-mode-flyspell-verify)
347 (defun notmuch-mua-pop-to-buffer (name switch-function)
348 "Pop to buffer NAME, and warn if it already exists and is modified.
349 Like `message-pop-to-buffer' but enable `notmuch-message-mode'
350 instead of `message-mode' and SWITCH-FUNCTION is mandatory."
351 (let ((buffer (get-buffer name)))
353 (buffer-name buffer))
354 (let ((window (get-buffer-window buffer 0)))
356 ;; Raise the frame already displaying the message buffer.
358 (select-frame-set-input-focus (window-frame window))
359 (select-window window))
360 (funcall switch-function buffer)
362 (when (and (buffer-modified-p)
365 "Message already being composed; erase? ")
367 (error "Message being composed")))
368 (funcall switch-function name)
371 (notmuch-message-mode)))
373 (defun notmuch-mua-mail (&optional to subject other-headers continue
374 switch-function yank-action send-actions
375 return-action &rest ignored)
376 "Invoke the notmuch mail composition window."
378 (when notmuch-mua-user-agent-function
379 (let ((user-agent (funcall notmuch-mua-user-agent-function)))
380 (unless (string= "" user-agent)
381 (push (cons 'User-Agent user-agent) other-headers))))
382 (unless (assq 'From other-headers)
383 (push (cons 'From (message-make-from
385 (notmuch-user-primary-email)))
387 (notmuch-mua-pop-to-buffer (message-buffer-name "mail" to)
389 (notmuch-mua-get-switch-function)))
392 ;; The following is copied from `message-mail'
393 `((To . ,(or to "")) (Subject . ,(or subject "")))
394 ;; C-h f compose-mail says that headers should be specified as
395 ;; (string . value); however all the rest of message expects
396 ;; headers to be symbols, not strings (eg message-header-format-alist).
397 ;; https://lists.gnu.org/archive/html/emacs-devel/2011-01/msg00337.html
398 ;; We need to convert any string input, eg from rmail-start-mail.
399 (dolist (h other-headers other-headers)
400 (when (stringp (car h))
401 (setcar h (intern (capitalize (car h))))))))
402 ;; Cause `message-setup-1' to do things relevant for mail,
403 ;; such as observe `message-default-mail-headers'.
404 (message-this-is-mail t))
405 (message-setup-1 headers yank-action send-actions return-action))
406 (notmuch-fcc-header-setup)
407 (message-sort-headers)
408 (message-hide-headers)
409 (set-buffer-modified-p nil)
410 (notmuch-mua-maybe-set-window-dedicated)
413 (defcustom notmuch-identities nil
414 "Identities that can be used as the From: address when composing a new message.
416 If this variable is left unset, then a list will be constructed from the
417 name and addresses configured in the notmuch configuration file."
418 :type '(repeat string)
419 :group 'notmuch-send)
421 (defcustom notmuch-always-prompt-for-sender nil
422 "Always prompt for the From: address when composing or forwarding a message.
424 This is not taken into account when replying to a message, because in that case
425 the From: header is already filled in by notmuch."
427 :group 'notmuch-send)
429 (defvar notmuch-mua-sender-history nil)
431 (defun notmuch-mua-prompt-for-sender ()
432 "Prompt for a sender from the user's configured identities."
433 (if notmuch-identities
434 (ido-completing-read "Send mail from: " notmuch-identities
435 nil nil nil 'notmuch-mua-sender-history
436 (car notmuch-identities))
437 (let* ((name (notmuch-user-name))
438 (addrs (cons (notmuch-user-primary-email)
439 (notmuch-user-other-email)))
441 (ido-completing-read (concat "Sender address for " name ": ") addrs
442 nil nil nil 'notmuch-mua-sender-history
444 (message-make-from name address))))
446 (put 'notmuch-mua-new-mail 'notmuch-prefix-doc "... and prompt for sender")
447 (defun notmuch-mua-new-mail (&optional prompt-for-sender)
450 If PROMPT-FOR-SENDER is non-nil, the user will be prompted for
451 the From: address first."
454 (and (or prompt-for-sender notmuch-always-prompt-for-sender)
455 (list (cons 'From (notmuch-mua-prompt-for-sender))))))
456 (notmuch-mua-mail nil nil other-headers nil (notmuch-mua-get-switch-function))))
458 (defun notmuch-mua-new-forward-messages (messages &optional prompt-for-sender)
459 "Compose a new message forwarding MESSAGES.
461 If PROMPT-FOR-SENDER is non-nil, the user will be prompteed for
463 (let* ((other-headers
464 (and (or prompt-for-sender notmuch-always-prompt-for-sender)
465 (list (cons 'From (notmuch-mua-prompt-for-sender)))))
466 ;; Comes from the first message and is applied later.
468 ;; List of accumulated message-references of forwarded messages.
470 ;; List of corresponding message-query.
472 ;; Generate the template for the outgoing message.
473 (notmuch-mua-mail nil "" other-headers nil (notmuch-mua-get-switch-function))
475 ;; Insert all of the forwarded messages.
477 (let ((temp-buffer (get-buffer-create
478 (concat "*notmuch-fwd-raw-" id "*"))))
479 ;; Get the raw version of this message in the buffer.
480 (with-current-buffer temp-buffer
482 (let ((coding-system-for-read 'no-conversion))
483 (call-process notmuch-command nil t nil
484 "show" "--format=raw" id))
485 ;; Because we process the messages in reverse order,
486 ;; always generate a forwarded subject, then use the
487 ;; last (i.e. first) one.
488 (setq forward-subject (message-make-forward-subject))
489 (push (message-fetch-field "Message-ID") forward-references)
490 (push id forward-queries))
491 ;; Make a copy ready to be forwarded in the
492 ;; composition buffer.
493 (message-forward-make-body temp-buffer)
494 ;; Kill the temporary buffer.
495 (kill-buffer temp-buffer)))
496 ;; `message-forward-make-body' always puts the message at
497 ;; the top, so do them in reverse order.
499 ;; Add in the appropriate subject.
501 (message-narrow-to-headers)
502 (message-remove-header "Subject")
503 (message-add-header (concat "Subject: " forward-subject))
504 (message-remove-header "References")
505 (message-add-header (concat "References: "
506 (mapconcat 'identity forward-references " "))))
507 ;; Create a buffer-local queue for tag changes triggered when
508 ;; sending the message.
509 (when notmuch-message-forwarded-tags
510 (setq-local notmuch-message-queued-tag-changes
511 (cl-loop for id in forward-queries
513 (cons id notmuch-message-forwarded-tags))))
514 ;; `message-forward-make-body' shows the User-agent header. Hide
516 (message-hide-headers)
517 (set-buffer-modified-p nil))))
519 (defun notmuch-mua-new-reply (query-string &optional prompt-for-sender reply-all)
520 "Compose a reply to the message identified by QUERY-STRING.
522 If PROMPT-FOR-SENDER is non-nil, the user will be prompted for
523 the From: address first. If REPLY-ALL is non-nil, the message
524 will be addressed to all recipients of the source message."
525 ;; `select-active-regions' is t by default. The reply insertion code
526 ;; sets the region to the quoted message to make it easy to delete
527 ;; (kill-region or C-w). These two things combine to put the quoted
528 ;; message in the primary selection.
530 ;; This is not what the user wanted and is a privacy risk (accidental
531 ;; pasting of the quoted message). We can avoid some of the problems
532 ;; by let-binding select-active-regions to nil. This fixes if the
533 ;; primary selection was previously in a non-emacs window but not if
534 ;; it was in an emacs window. To avoid the problem in the latter case
535 ;; we deactivate mark.
536 (let ((sender (and prompt-for-sender
537 (notmuch-mua-prompt-for-sender)))
538 (select-active-regions nil))
539 (notmuch-mua-reply query-string sender reply-all)
544 (defun notmuch-mua-check-no-misplaced-secure-tag ()
545 "Query user if there is a misplaced secure mml tag.
547 Emacs message-send will (probably) ignore a secure mml tag unless
548 it is at the start of the body. Returns t if there is no such
549 tag, or the user confirms they mean it."
551 (let ((body-start (progn (message-goto-body) (point))))
552 (goto-char (point-max))
554 ;; We are always fine if there is no secure tag.
555 (not (search-backward "<#secure" nil t))
556 ;; There is a secure tag, so it must be at the start of the
557 ;; body, with no secure tag earlier (i.e., in the headers).
558 (and (= (point) body-start)
559 (not (search-backward "<#secure" nil t)))
560 ;; The user confirms they means it.
562 There is a <#secure> tag not at the start of the body. It is
563 likely that the message will be sent unsigned and unencrypted.
566 (defun notmuch-mua-check-secure-tag-has-newline ()
567 "Query if the secure mml tag has a newline following it.
569 Emacs message-send will (probably) ignore a correctly placed
570 secure mml tag unless it is followed by a newline. Returns t if
571 any secure tag is followed by a newline, or the user confirms
576 ;; There is no (correctly placed) secure tag.
577 (not (looking-at "<#secure"))
578 ;; The secure tag is followed by a newline.
579 (looking-at "<#secure[^\n>]*>\n")
580 ;; The user confirms they means it.
582 The <#secure> tag at the start of the body is not followed by a
583 newline. It is likely that the message will be sent unsigned and
584 unencrypted. Really send? "))))
586 ;;; Finishing commands
588 (defun notmuch-mua-send-common (arg &optional exit)
590 (run-hooks 'notmuch-mua-send-hook)
591 (when (and (notmuch-mua-check-no-misplaced-secure-tag)
592 (notmuch-mua-check-secure-tag-has-newline))
593 (cl-letf (((symbol-function 'message-do-fcc)
594 #'notmuch-maildir-message-do-fcc))
596 (message-send-and-exit arg)
597 (message-send arg)))))
599 (defun notmuch-mua-send-and-exit (&optional arg)
601 (notmuch-mua-send-common arg t))
603 (defun notmuch-mua-send (&optional arg)
605 (notmuch-mua-send-common arg))
607 (defun notmuch-mua-kill-buffer ()
609 (message-kill-buffer))
613 (define-mail-user-agent 'notmuch-user-agent
614 'notmuch-mua-mail 'notmuch-mua-send-and-exit
615 'notmuch-mua-kill-buffer 'notmuch-mua-send-hook)
617 ;; Add some more headers to the list that `message-mode' hides when
618 ;; composing a message.
619 (notmuch-mua-add-more-hidden-headers)
621 (provide 'notmuch-mua)
623 ;;; notmuch-mua.el ends here