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 (defcustom notmuch-identities nil
86 "Identities that can be used as the From: address when composing a new message.
88 If this variable is left unset, then a list will be constructed from the
89 name and addresses configured in the notmuch configuration file."
90 :type '(repeat string)
93 (defcustom notmuch-always-prompt-for-sender nil
94 "Always prompt for the From: address when composing or forwarding a message.
96 This is not taken into account when replying to a message, because in that case
97 the From: header is already filled in by notmuch."
101 (defgroup notmuch-reply nil
102 "Replying to messages in notmuch"
105 (defcustom notmuch-mua-cite-function 'message-cite-original
106 "Function for citing an original message.
108 Predefined functions include `message-cite-original' and
109 `message-cite-original-without-signature'. Note that these
110 functions use `mail-citation-hook' if that is non-nil."
111 :type '(radio (function-item message-cite-original)
112 (function-item message-cite-original-without-signature)
113 (function-item sc-cite-original)
114 (function :tag "Other"))
115 :link '(custom-manual "(message)Insertion Variables")
116 :group 'notmuch-reply)
118 (defcustom notmuch-mua-reply-insert-header-p-function
119 'notmuch-show-reply-insert-header-p-never
120 "Function to decide which parts get a header when replying.
122 This function specifies which parts of a mime message with
123 multiple parts get a header."
124 :type '(radio (const :tag "No part headers"
125 notmuch-show-reply-insert-header-p-never)
126 (const :tag "All except multipart/* and hidden parts"
127 notmuch-show-reply-insert-header-p-trimmed)
128 (const :tag "Only for included text parts"
129 notmuch-show-reply-insert-header-p-minimal)
130 (const :tag "Exactly as in show view"
131 notmuch-show-insert-header-p)
132 (function :tag "Other"))
133 :group 'notmuch-reply)
135 (defcustom notmuch-mua-attachment-regexp
136 "\\b\\(attache\?ment\\|attached\\|attach\\|pi[èe]ce\s+jointe?\\)\\b"
137 "Message body text indicating that an attachment is expected.
139 This is not used unless `notmuch-mua-attachment-check' is added
140 to `notmuch-mua-send-hook'."
142 :group 'notmuch-send)
144 ;;; Various functions
146 (defun notmuch-mua-attachment-check ()
147 "Signal an error if the message text indicates that an
148 attachment is expected but no MML referencing an attachment is
151 Typically this is added to `notmuch-mua-send-hook'."
153 ;; When the message mentions attachment...
156 ;; Limit search from reaching other possible parts of the message
157 (let ((search-limit (search-forward "\n<#" nil t)))
159 (cl-loop while (re-search-forward notmuch-mua-attachment-regexp
161 ;; For every instance of the "attachment" string
162 ;; found, examine the text properties. If the text
163 ;; has either a `face' or `syntax-table' property
164 ;; then it is quoted text and should *not* cause the
165 ;; user to be asked about a missing attachment.
166 if (let ((props (text-properties-at (match-beginning 0))))
167 (not (or (memq 'syntax-table props)
168 (memq 'face props))))
170 finally return nil)))
171 ;; ...but doesn't have a part with a filename...
174 (not (re-search-forward "^<#part [^>]*filename=" nil t)))
175 ;; ...and that's not okay...
176 (not (y-or-n-p "Attachment mentioned, but no attachment - is that okay?")))
177 ;; ...signal an error.
178 (error "Missing attachment")))
180 (defun notmuch-mua-get-switch-function ()
181 "Get a switch function according to `notmuch-mua-compose-in'."
182 (pcase notmuch-mua-compose-in
183 ('current-window 'switch-to-buffer)
184 ('new-window 'switch-to-buffer-other-window)
185 ('new-frame 'switch-to-buffer-other-frame)
186 (_ (error "Invalid value for `notmuch-mua-compose-in'"))))
188 (defun notmuch-mua-maybe-set-window-dedicated ()
189 "Set the selected window as dedicated according to `notmuch-mua-compose-in'."
190 (when (or (eq notmuch-mua-compose-in 'new-frame)
191 (eq notmuch-mua-compose-in 'new-window))
192 (set-window-dedicated-p (selected-window) t)))
194 (defun notmuch-mua-user-agent-full ()
195 "Generate a `User-Agent:' string suitable for notmuch."
196 (concat (notmuch-mua-user-agent-notmuch)
198 (notmuch-mua-user-agent-emacs)))
200 (defun notmuch-mua-user-agent-notmuch ()
201 "Generate a `User-Agent:' string suitable for notmuch."
202 (let ((notmuch-version (if (string= notmuch-emacs-version "unknown")
203 (notmuch-cli-version)
204 notmuch-emacs-version)))
205 (concat "Notmuch/" notmuch-version " (https://notmuchmail.org)")))
207 (defun notmuch-mua-user-agent-emacs ()
208 "Generate a `User-Agent:' string suitable for notmuch."
209 (concat "Emacs/" emacs-version " (" system-configuration ")"))
211 (defun notmuch-mua-add-more-hidden-headers ()
212 "Add some headers to the list that are hidden by default."
213 (mapc (lambda (header)
214 (unless (member header message-hidden-headers)
215 (push header message-hidden-headers)))
216 notmuch-mua-hidden-headers))
218 (defun notmuch-mua-reply-crypto (parts)
219 "Add mml sign-encrypt flag if any part of original message is encrypted."
220 (cl-loop for part in parts
221 if (notmuch-match-content-type (plist-get part :content-type)
222 "multipart/encrypted")
223 do (mml-secure-message-sign-encrypt)
224 else if (notmuch-match-content-type (plist-get part :content-type)
226 do (notmuch-mua-reply-crypto (plist-get part :content))))
228 ;; There is a bug in Emacs' message.el that results in a newline
229 ;; not being inserted after the References header, so the next header
230 ;; is concatenated to the end of it. This function fixes the problem,
231 ;; while guarding against the possibility that some current or future
232 ;; version of emacs has the bug fixed.
233 (defun notmuch-mua-insert-references (original-func header references)
234 (funcall original-func header references)
235 (unless (bolp) (insert "\n")))
239 (defun notmuch-mua-reply (query-string &optional sender reply-all)
240 (let ((args '("reply" "--format=sexp" "--format-version=4"))
241 (process-crypto notmuch-show-process-crypto)
245 (setq args (append args '("--decrypt=true"))))
247 (setq args (append args '("--reply-to=all")))
248 (setq args (append args '("--reply-to=sender"))))
249 (setq args (append args (list query-string)))
250 ;; Get the reply object as SEXP, and parse it into an elisp object.
251 (setq reply (apply #'notmuch-call-notmuch-sexp args))
252 ;; Extract the original message to simplify the following code.
253 (setq original (plist-get reply :original))
254 ;; Extract the headers of both the reply and the original message.
255 (let* ((original-headers (plist-get original :headers))
256 (reply-headers (plist-get reply :reply-headers)))
257 ;; If sender is non-nil, set the From: header to its value.
259 (plist-put reply-headers :From sender))
261 ;; Overlay the composition window on that being used to read
262 ;; the original message.
263 ((same-window-regexps '("\\*mail .*")))
264 ;; We modify message-header-format-alist to get around
265 ;; a bug in message.el. See the comment above on
266 ;; notmuch-mua-insert-references.
267 (let ((message-header-format-alist
268 (cl-loop for pair in message-header-format-alist
269 if (eq (car pair) 'References)
270 collect (cons 'References
272 'notmuch-mua-insert-references
276 (notmuch-mua-mail (plist-get reply-headers :To)
277 (notmuch-sanitize (plist-get reply-headers :Subject))
278 (notmuch-headers-plist-to-alist reply-headers)
279 nil (notmuch-mua-get-switch-function))))
280 ;; Create a buffer-local queue for tag changes triggered when
281 ;; sending the reply.
282 (when notmuch-message-replied-tags
283 (setq notmuch-message-queued-tag-changes
284 (list (cons query-string notmuch-message-replied-tags))))
285 ;; Insert the message body - but put it in front of the signature
286 ;; if one is present, and after any other content
287 ;; message*setup-hooks may have added to the message body already.
290 (narrow-to-region (point) (point-max))
291 (goto-char (point-max))
292 (if (re-search-backward message-signature-separator nil t)
293 (when message-signature-insert-empty-line
295 (goto-char (point-max))))
296 (let ((from (plist-get original-headers :From))
297 (date (plist-get original-headers :Date))
299 ;; notmuch-mua-cite-function constructs a citation line based
300 ;; on the From and Date headers of the original message, which
301 ;; are assumed to be in the buffer.
302 (insert "From: " from "\n")
303 (insert "Date: " date "\n\n")
307 ;; Don't attempt to clean up messages, excerpt
308 ;; citations, etc. in the original message before
310 ((notmuch-show-insert-text/plain-hook nil)
311 ;; Don't omit long parts.
312 (notmuch-show-max-text-part-size 0)
313 ;; Insert headers for parts as appropriate for replying.
314 (notmuch-show-insert-header-p-function
315 notmuch-mua-reply-insert-header-p-function)
316 ;; Ensure that any encrypted parts are
317 ;; decrypted during the generation of the reply
319 (notmuch-show-process-crypto process-crypto)
320 ;; Don't indent multipart sub-parts.
321 (notmuch-show-indent-multipart nil))
322 ;; We don't want sigstatus buttons (an information leak and usually wrong anyway).
323 (cl-letf (((symbol-function 'notmuch-crypto-insert-sigstatus-button) #'ignore)
324 ((symbol-function 'notmuch-crypto-insert-encstatus-button) #'ignore))
325 (notmuch-show-insert-body original (plist-get original :body) 0)
326 (buffer-substring-no-properties (point-min) (point-max))))))
329 ;; Quote the original message according to the user's configured style.
330 (funcall notmuch-mua-cite-function)))
331 ;; Crypto processing based crypto content of the original message
333 (notmuch-mua-reply-crypto (plist-get original :body))))
334 ;; Push mark right before signature, if any.
335 (message-goto-signature)
340 (set-buffer-modified-p nil))
344 (defvar notmuch-message-mode-map
345 (let ((map (make-sparse-keymap)))
346 (define-key map (kbd "C-c C-c") #'notmuch-mua-send-and-exit)
347 (define-key map (kbd "C-c C-s") #'notmuch-mua-send)
348 (define-key map (kbd "C-c C-p") #'notmuch-draft-postpone)
349 (define-key map (kbd "C-x C-s") #'notmuch-draft-save)
351 "Keymap for `notmuch-message-mode'.")
353 (define-derived-mode notmuch-message-mode message-mode "Message[Notmuch]"
354 "Notmuch message composition mode. Mostly like `message-mode'."
355 (notmuch-address-setup))
357 (put 'notmuch-message-mode 'flyspell-mode-predicate 'mail-mode-flyspell-verify)
361 (defun notmuch-mua-pop-to-buffer (name switch-function)
362 "Pop to buffer NAME, and warn if it already exists and is modified.
363 Like `message-pop-to-buffer' but enable `notmuch-message-mode'
364 instead of `message-mode' and SWITCH-FUNCTION is mandatory."
365 (let ((buffer (get-buffer name)))
367 (buffer-name buffer))
368 (let ((window (get-buffer-window buffer 0)))
370 ;; Raise the frame already displaying the message buffer.
372 (select-frame-set-input-focus (window-frame window))
373 (select-window window))
374 (funcall switch-function buffer)
376 (when (buffer-modified-p)
377 (if (y-or-n-p "Message already being composed; erase? ")
379 (error "Message being composed"))))
380 (funcall switch-function name)
383 (notmuch-message-mode)))
385 (defun notmuch-mua-mail (&optional to subject other-headers _continue
386 switch-function yank-action send-actions
387 return-action &rest ignored)
388 "Invoke the notmuch mail composition window."
390 (when notmuch-mua-user-agent-function
391 (let ((user-agent (funcall notmuch-mua-user-agent-function)))
392 (unless (string= "" user-agent)
393 (push (cons 'User-Agent user-agent) other-headers))))
394 (unless (assq 'From other-headers)
395 (push (cons 'From (message-make-from
397 (notmuch-user-primary-email)))
399 (notmuch-mua-pop-to-buffer (message-buffer-name "mail" to)
401 (notmuch-mua-get-switch-function)))
404 ;; The following is copied from `message-mail'
405 `((To . ,(or to "")) (Subject . ,(or subject "")))
406 ;; C-h f compose-mail says that headers should be specified as
407 ;; (string . value); however all the rest of message expects
408 ;; headers to be symbols, not strings (eg message-header-format-alist).
409 ;; https://lists.gnu.org/archive/html/emacs-devel/2011-01/msg00337.html
410 ;; We need to convert any string input, eg from rmail-start-mail.
411 (dolist (h other-headers other-headers)
412 (when (stringp (car h))
413 (setcar h (intern (capitalize (car h))))))))
414 ;; Cause `message-setup-1' to do things relevant for mail,
415 ;; such as observe `message-default-mail-headers'.
416 (message-this-is-mail t))
417 (message-setup-1 headers yank-action send-actions return-action))
418 (notmuch-fcc-header-setup)
419 (message-sort-headers)
420 (message-hide-headers)
421 (set-buffer-modified-p nil)
422 (notmuch-mua-maybe-set-window-dedicated)
425 (defvar notmuch-mua-sender-history nil)
427 (defun notmuch-mua-prompt-for-sender ()
428 "Prompt for a sender from the user's configured identities."
429 (if notmuch-identities
430 (completing-read "Send mail from: " notmuch-identities
431 nil nil nil 'notmuch-mua-sender-history
432 (car notmuch-identities))
433 (let* ((name (notmuch-user-name))
434 (addrs (cons (notmuch-user-primary-email)
435 (notmuch-user-other-email)))
437 (completing-read (concat "Sender address for " name ": ") addrs
438 nil nil nil 'notmuch-mua-sender-history
440 (message-make-from name address))))
442 (put 'notmuch-mua-new-mail 'notmuch-prefix-doc "... and prompt for sender")
443 (defun notmuch-mua-new-mail (&optional prompt-for-sender)
446 If PROMPT-FOR-SENDER is non-nil, the user will be prompted for
447 the From: address first."
450 (and (or prompt-for-sender notmuch-always-prompt-for-sender)
451 (list (cons 'From (notmuch-mua-prompt-for-sender))))))
452 (notmuch-mua-mail nil nil other-headers nil (notmuch-mua-get-switch-function))))
454 (defun notmuch-mua-new-forward-messages (messages &optional prompt-for-sender)
455 "Compose a new message forwarding MESSAGES.
457 If PROMPT-FOR-SENDER is non-nil, the user will be prompteed for
459 (let* ((other-headers
460 (and (or prompt-for-sender notmuch-always-prompt-for-sender)
461 (list (cons 'From (notmuch-mua-prompt-for-sender)))))
462 ;; Comes from the first message and is applied later.
464 ;; List of accumulated message-references of forwarded messages.
466 ;; List of corresponding message-query.
468 ;; Generate the template for the outgoing message.
469 (notmuch-mua-mail nil "" other-headers nil (notmuch-mua-get-switch-function))
471 ;; Insert all of the forwarded messages.
473 (let ((temp-buffer (get-buffer-create
474 (concat "*notmuch-fwd-raw-" id "*"))))
475 ;; Get the raw version of this message in the buffer.
476 (with-current-buffer temp-buffer
478 (let ((coding-system-for-read 'no-conversion))
479 (call-process notmuch-command nil t nil
480 "show" "--format=raw" id))
481 ;; Because we process the messages in reverse order,
482 ;; always generate a forwarded subject, then use the
483 ;; last (i.e. first) one.
484 (setq forward-subject (message-make-forward-subject))
485 (push (message-fetch-field "Message-ID") forward-references)
486 (push id forward-queries))
487 ;; Make a copy ready to be forwarded in the
488 ;; composition buffer.
489 (message-forward-make-body temp-buffer)
490 ;; Kill the temporary buffer.
491 (kill-buffer temp-buffer)))
492 ;; `message-forward-make-body' always puts the message at
493 ;; the top, so do them in reverse order.
495 ;; Add in the appropriate subject.
497 (message-narrow-to-headers)
498 (message-remove-header "Subject")
499 (message-add-header (concat "Subject: " forward-subject))
500 (message-remove-header "References")
501 (message-add-header (concat "References: "
502 (mapconcat 'identity forward-references " "))))
503 ;; Create a buffer-local queue for tag changes triggered when
504 ;; sending the message.
505 (when notmuch-message-forwarded-tags
506 (setq notmuch-message-queued-tag-changes
507 (cl-loop for id in forward-queries
509 (cons id notmuch-message-forwarded-tags))))
510 ;; `message-forward-make-body' shows the User-agent header. Hide
512 (message-hide-headers)
513 (set-buffer-modified-p nil))))
515 (defun notmuch-mua-new-reply (query-string &optional prompt-for-sender reply-all)
516 "Compose a reply to the message identified by QUERY-STRING.
518 If PROMPT-FOR-SENDER is non-nil, the user will be prompted for
519 the From: address first. If REPLY-ALL is non-nil, the message
520 will be addressed to all recipients of the source message."
521 ;; `select-active-regions' is t by default. The reply insertion code
522 ;; sets the region to the quoted message to make it easy to delete
523 ;; (kill-region or C-w). These two things combine to put the quoted
524 ;; message in the primary selection.
526 ;; This is not what the user wanted and is a privacy risk (accidental
527 ;; pasting of the quoted message). We can avoid some of the problems
528 ;; by let-binding select-active-regions to nil. This fixes if the
529 ;; primary selection was previously in a non-emacs window but not if
530 ;; it was in an emacs window. To avoid the problem in the latter case
531 ;; we deactivate mark.
532 (let ((sender (and prompt-for-sender
533 (notmuch-mua-prompt-for-sender)))
534 (select-active-regions nil))
535 (notmuch-mua-reply query-string sender reply-all)
540 (defun notmuch-mua-check-no-misplaced-secure-tag ()
541 "Query user if there is a misplaced secure mml tag.
543 Emacs message-send will (probably) ignore a secure mml tag unless
544 it is at the start of the body. Returns t if there is no such
545 tag, or the user confirms they mean it."
547 (let ((body-start (progn (message-goto-body) (point))))
548 (goto-char (point-max))
550 ;; We are always fine if there is no secure tag.
551 (not (search-backward "<#secure" nil t))
552 ;; There is a secure tag, so it must be at the start of the
553 ;; body, with no secure tag earlier (i.e., in the headers).
554 (and (= (point) body-start)
555 (not (search-backward "<#secure" nil t)))
556 ;; The user confirms they means it.
558 There is a <#secure> tag not at the start of the body. It is
559 likely that the message will be sent unsigned and unencrypted.
562 (defun notmuch-mua-check-secure-tag-has-newline ()
563 "Query if the secure mml tag has a newline following it.
565 Emacs message-send will (probably) ignore a correctly placed
566 secure mml tag unless it is followed by a newline. Returns t if
567 any secure tag is followed by a newline, or the user confirms
572 ;; There is no (correctly placed) secure tag.
573 (not (looking-at "<#secure"))
574 ;; The secure tag is followed by a newline.
575 (looking-at "<#secure[^\n>]*>\n")
576 ;; The user confirms they means it.
578 The <#secure> tag at the start of the body is not followed by a
579 newline. It is likely that the message will be sent unsigned and
580 unencrypted. Really send? "))))
582 ;;; Finishing commands
584 (defun notmuch-mua-send-common (arg &optional exit)
586 (run-hooks 'notmuch-mua-send-hook)
587 (when (and (notmuch-mua-check-no-misplaced-secure-tag)
588 (notmuch-mua-check-secure-tag-has-newline))
589 (cl-letf (((symbol-function 'message-do-fcc)
590 #'notmuch-maildir-message-do-fcc))
592 (message-send-and-exit arg)
593 (message-send arg)))))
595 (defun notmuch-mua-send-and-exit (&optional arg)
597 (notmuch-mua-send-common arg t))
599 (defun notmuch-mua-send (&optional arg)
601 (notmuch-mua-send-common arg))
603 (defun notmuch-mua-kill-buffer ()
605 (message-kill-buffer))
609 (define-mail-user-agent 'notmuch-user-agent
611 'notmuch-mua-send-and-exit
612 'notmuch-mua-kill-buffer
613 'notmuch-mua-send-hook)
615 ;; Add some more headers to the list that `message-mode' hides when
616 ;; composing a message.
617 (notmuch-mua-add-more-hidden-headers)
619 (provide 'notmuch-mua)
621 ;;; notmuch-mua.el ends here