1 ;;; notmuch-mua.el --- emacs style mail-user-agent
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" ())
43 (defcustom notmuch-mua-send-hook nil
44 "Hook run before sending messages."
47 :group 'notmuch-hooks)
49 (defcustom notmuch-mua-compose-in 'current-window
50 "Where to create the mail buffer used to compose a new message.
51 Possible values are `current-window' (default), `new-window' and
52 `new-frame'. If set to `current-window', the mail buffer will be
53 displayed in the current window, so the old buffer will be
54 restored when the mail buffer is killed. If set to `new-window'
55 or `new-frame', the mail buffer will be displayed in a new
56 window/frame that will be destroyed when the buffer is killed.
57 You may want to customize `message-kill-buffer-on-exit'
60 :type '(choice (const :tag "Compose in the current window" current-window)
61 (const :tag "Compose mail in a new window" new-window)
62 (const :tag "Compose mail in a new frame" new-frame)))
64 (defcustom notmuch-mua-user-agent-function nil
65 "Function used to generate a `User-Agent:' string.
66 If this is `nil' then no `User-Agent:' will be generated."
67 :type '(choice (const :tag "No user agent string" nil)
68 (const :tag "Full" notmuch-mua-user-agent-full)
69 (const :tag "Notmuch" notmuch-mua-user-agent-notmuch)
70 (const :tag "Emacs" notmuch-mua-user-agent-emacs)
71 (function :tag "Custom user agent function"
72 :value notmuch-mua-user-agent-full))
75 (defcustom notmuch-mua-hidden-headers nil
76 "Headers that are added to the `message-mode' hidden headers list."
77 :type '(repeat string)
80 (defgroup notmuch-reply nil
81 "Replying to messages in notmuch"
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)
96 (defcustom notmuch-mua-reply-insert-header-p-function
97 'notmuch-show-reply-insert-header-p-never
98 "Function to decide which parts get a header when replying.
100 This function specifies which parts of a mime message with
101 multiple parts get a header."
102 :type '(radio (const :tag "No part headers"
103 notmuch-show-reply-insert-header-p-never)
104 (const :tag "All except multipart/* and hidden parts"
105 notmuch-show-reply-insert-header-p-trimmed)
106 (const :tag "Only for included text parts"
107 notmuch-show-reply-insert-header-p-minimal)
108 (const :tag "Exactly as in show view"
109 notmuch-show-insert-header-p)
110 (function :tag "Other"))
111 :group 'notmuch-reply)
113 (defcustom notmuch-mua-attachment-regexp
114 "\\b\\(attache\?ment\\|attached\\|attach\\|pi[èe]ce\s+jointe?\\)\\b"
115 "Message body text indicating that an attachment is expected.
117 This is not used unless `notmuch-mua-attachment-check' is added
118 to `notmuch-mua-send-hook'."
120 :group 'notmuch-send)
124 (defun notmuch-mua-attachment-check ()
125 "Signal an error if the message text indicates that an
126 attachment is expected but no MML referencing an attachment is
129 Typically this is added to `notmuch-mua-send-hook'."
131 ;; When the message mentions attachment...
134 ;; Limit search from reaching other possible parts of the message
135 (let ((search-limit (search-forward "\n<#" nil t)))
137 (cl-loop while (re-search-forward notmuch-mua-attachment-regexp
139 ;; For every instance of the "attachment" string
140 ;; found, examine the text properties. If the text
141 ;; has either a `face' or `syntax-table' property
142 ;; then it is quoted text and should *not* cause the
143 ;; user to be asked about a missing attachment.
144 if (let ((props (text-properties-at (match-beginning 0))))
145 (not (or (memq 'syntax-table props)
146 (memq 'face props))))
148 finally return nil)))
149 ;; ...but doesn't have a part with a filename...
152 (not (re-search-forward "^<#part [^>]*filename=" nil t)))
153 ;; ...and that's not okay...
154 (not (y-or-n-p "Attachment mentioned, but no attachment - is that okay?")))
155 ;; ...signal an error.
156 (error "Missing attachment")))
158 (defun notmuch-mua-get-switch-function ()
159 "Get a switch function according to `notmuch-mua-compose-in'."
160 (cond ((eq notmuch-mua-compose-in 'current-window)
162 ((eq notmuch-mua-compose-in 'new-window)
163 'switch-to-buffer-other-window)
164 ((eq notmuch-mua-compose-in 'new-frame)
165 'switch-to-buffer-other-frame)
166 (t (error "Invalid value for `notmuch-mua-compose-in'"))))
168 (defun notmuch-mua-maybe-set-window-dedicated ()
169 "Set the selected window as dedicated according to `notmuch-mua-compose-in'."
170 (when (or (eq notmuch-mua-compose-in 'new-frame)
171 (eq notmuch-mua-compose-in 'new-window))
172 (set-window-dedicated-p (selected-window) t)))
174 (defun notmuch-mua-user-agent-full ()
175 "Generate a `User-Agent:' string suitable for notmuch."
176 (concat (notmuch-mua-user-agent-notmuch)
178 (notmuch-mua-user-agent-emacs)))
180 (defun notmuch-mua-user-agent-notmuch ()
181 "Generate a `User-Agent:' string suitable for notmuch."
182 (let ((notmuch-version (if (string= notmuch-emacs-version "unknown")
183 (notmuch-cli-version)
184 notmuch-emacs-version)))
185 (concat "Notmuch/" notmuch-version " (https://notmuchmail.org)")))
187 (defun notmuch-mua-user-agent-emacs ()
188 "Generate a `User-Agent:' string suitable for notmuch."
189 (concat "Emacs/" emacs-version " (" system-configuration ")"))
191 (defun notmuch-mua-add-more-hidden-headers ()
192 "Add some headers to the list that are hidden by default."
193 (mapc (lambda (header)
194 (unless (member header message-hidden-headers)
195 (push header message-hidden-headers)))
196 notmuch-mua-hidden-headers))
198 (defun notmuch-mua-reply-crypto (parts)
199 "Add mml sign-encrypt flag if any part of original message is encrypted."
200 (cl-loop for part in parts
201 if (notmuch-match-content-type (plist-get part :content-type)
202 "multipart/encrypted")
203 do (mml-secure-message-sign-encrypt)
204 else if (notmuch-match-content-type (plist-get part :content-type)
206 do (notmuch-mua-reply-crypto (plist-get part :content))))
208 ;; There is a bug in Emacs' message.el that results in a newline
209 ;; not being inserted after the References header, so the next header
210 ;; is concatenated to the end of it. This function fixes the problem,
211 ;; while guarding against the possibility that some current or future
212 ;; version of emacs has the bug fixed.
213 (defun notmuch-mua-insert-references (original-func header references)
214 (funcall original-func header references)
215 (unless (bolp) (insert "\n")))
217 (defun notmuch-mua-reply (query-string &optional sender reply-all)
218 (let ((args '("reply" "--format=sexp" "--format-version=4"))
219 (process-crypto notmuch-show-process-crypto)
223 (setq args (append args '("--decrypt=true"))))
225 (setq args (append args '("--reply-to=all")))
226 (setq args (append args '("--reply-to=sender"))))
227 (setq args (append args (list query-string)))
228 ;; Get the reply object as SEXP, and parse it into an elisp object.
229 (setq reply (apply #'notmuch-call-notmuch-sexp args))
230 ;; Extract the original message to simplify the following code.
231 (setq original (plist-get reply :original))
232 ;; Extract the headers of both the reply and the original message.
233 (let* ((original-headers (plist-get original :headers))
234 (reply-headers (plist-get reply :reply-headers)))
235 ;; If sender is non-nil, set the From: header to its value.
237 (plist-put reply-headers :From sender))
239 ;; Overlay the composition window on that being used to read
240 ;; the original message.
241 ((same-window-regexps '("\\*mail .*")))
242 ;; We modify message-header-format-alist to get around
243 ;; a bug in message.el. See the comment above on
244 ;; notmuch-mua-insert-references.
245 (let ((message-header-format-alist
246 (cl-loop for pair in message-header-format-alist
247 if (eq (car pair) 'References)
248 collect (cons 'References
250 'notmuch-mua-insert-references
254 (notmuch-mua-mail (plist-get reply-headers :To)
255 (notmuch-sanitize (plist-get reply-headers :Subject))
256 (notmuch-headers-plist-to-alist reply-headers)
257 nil (notmuch-mua-get-switch-function))))
258 ;; Create a buffer-local queue for tag changes triggered when
259 ;; sending the reply.
260 (when notmuch-message-replied-tags
261 (setq-local notmuch-message-queued-tag-changes
262 (list (cons query-string notmuch-message-replied-tags))))
263 ;; Insert the message body - but put it in front of the signature
264 ;; if one is present, and after any other content
265 ;; message*setup-hooks may have added to the message body already.
268 (narrow-to-region (point) (point-max))
269 (goto-char (point-max))
270 (if (re-search-backward message-signature-separator nil t)
271 (when message-signature-insert-empty-line
273 (goto-char (point-max))))
274 (let ((from (plist-get original-headers :From))
275 (date (plist-get original-headers :Date))
277 ;; notmuch-mua-cite-function constructs a citation line based
278 ;; on the From and Date headers of the original message, which
279 ;; are assumed to be in the buffer.
280 (insert "From: " from "\n")
281 (insert "Date: " date "\n\n")
285 ;; Don't attempt to clean up messages, excerpt
286 ;; citations, etc. in the original message before
288 ((notmuch-show-insert-text/plain-hook nil)
289 ;; Don't omit long parts.
290 (notmuch-show-max-text-part-size 0)
291 ;; Insert headers for parts as appropriate for replying.
292 (notmuch-show-insert-header-p-function
293 notmuch-mua-reply-insert-header-p-function)
294 ;; Ensure that any encrypted parts are
295 ;; decrypted during the generation of the reply
297 (notmuch-show-process-crypto process-crypto)
298 ;; Don't indent multipart sub-parts.
299 (notmuch-show-indent-multipart nil))
300 ;; We don't want sigstatus buttons (an information leak and usually wrong anyway).
301 (cl-letf (((symbol-function 'notmuch-crypto-insert-sigstatus-button) #'ignore)
302 ((symbol-function 'notmuch-crypto-insert-encstatus-button) #'ignore))
303 (notmuch-show-insert-body original (plist-get original :body) 0)
304 (buffer-substring-no-properties (point-min) (point-max))))))
307 ;; Quote the original message according to the user's configured style.
308 (funcall notmuch-mua-cite-function)))
309 ;; Crypto processing based crypto content of the original message
311 (notmuch-mua-reply-crypto (plist-get original :body))))
312 ;; Push mark right before signature, if any.
313 (message-goto-signature)
318 (set-buffer-modified-p nil))
320 (defvar notmuch-message-mode-map
321 (let ((map (make-sparse-keymap)))
322 (define-key map (kbd "C-c C-c") #'notmuch-mua-send-and-exit)
323 (define-key map (kbd "C-c C-s") #'notmuch-mua-send)
324 (define-key map (kbd "C-c C-p") #'notmuch-draft-postpone)
325 (define-key map (kbd "C-x C-s") #'notmuch-draft-save)
327 "Keymap for `notmuch-message-mode'.")
329 (define-derived-mode notmuch-message-mode message-mode "Message[Notmuch]"
330 "Notmuch message composition mode. Mostly like `message-mode'."
331 (notmuch-address-setup))
333 (put 'notmuch-message-mode 'flyspell-mode-predicate 'mail-mode-flyspell-verify)
335 (defun notmuch-mua-pop-to-buffer (name switch-function)
336 "Pop to buffer NAME, and warn if it already exists and is modified.
337 Like `message-pop-to-buffer' but enable `notmuch-message-mode'
338 instead of `message-mode' and SWITCH-FUNCTION is mandatory."
339 (let ((buffer (get-buffer name)))
341 (buffer-name buffer))
342 (let ((window (get-buffer-window buffer 0)))
344 ;; Raise the frame already displaying the message buffer.
346 (select-frame-set-input-focus (window-frame window))
347 (select-window window))
348 (funcall switch-function buffer)
350 (when (and (buffer-modified-p)
353 "Message already being composed; erase? ")
355 (error "Message being composed")))
356 (funcall switch-function name)
359 (notmuch-message-mode)))
361 (defun notmuch-mua-mail (&optional to subject other-headers continue
362 switch-function yank-action send-actions
363 return-action &rest ignored)
364 "Invoke the notmuch mail composition window."
366 (when notmuch-mua-user-agent-function
367 (let ((user-agent (funcall notmuch-mua-user-agent-function)))
368 (unless (string= "" user-agent)
369 (push (cons 'User-Agent user-agent) other-headers))))
370 (unless (assq 'From other-headers)
371 (push (cons 'From (message-make-from
373 (notmuch-user-primary-email)))
375 (notmuch-mua-pop-to-buffer (message-buffer-name "mail" to)
377 (notmuch-mua-get-switch-function)))
380 ;; The following is copied from `message-mail'
381 `((To . ,(or to "")) (Subject . ,(or subject "")))
382 ;; C-h f compose-mail says that headers should be specified as
383 ;; (string . value); however all the rest of message expects
384 ;; headers to be symbols, not strings (eg message-header-format-alist).
385 ;; https://lists.gnu.org/archive/html/emacs-devel/2011-01/msg00337.html
386 ;; We need to convert any string input, eg from rmail-start-mail.
387 (dolist (h other-headers other-headers)
388 (when (stringp (car h))
389 (setcar h (intern (capitalize (car h))))))))
390 ;; Cause `message-setup-1' to do things relevant for mail,
391 ;; such as observe `message-default-mail-headers'.
392 (message-this-is-mail t))
393 (message-setup-1 headers yank-action send-actions return-action))
394 (notmuch-fcc-header-setup)
395 (message-sort-headers)
396 (message-hide-headers)
397 (set-buffer-modified-p nil)
398 (notmuch-mua-maybe-set-window-dedicated)
401 (defcustom notmuch-identities nil
402 "Identities that can be used as the From: address when composing a new message.
404 If this variable is left unset, then a list will be constructed from the
405 name and addresses configured in the notmuch configuration file."
406 :type '(repeat string)
407 :group 'notmuch-send)
409 (defcustom notmuch-always-prompt-for-sender nil
410 "Always prompt for the From: address when composing or forwarding a message.
412 This is not taken into account when replying to a message, because in that case
413 the From: header is already filled in by notmuch."
415 :group 'notmuch-send)
417 (defvar notmuch-mua-sender-history nil)
419 (defun notmuch-mua-prompt-for-sender ()
420 "Prompt for a sender from the user's configured identities."
421 (if notmuch-identities
422 (ido-completing-read "Send mail from: " notmuch-identities
423 nil nil nil 'notmuch-mua-sender-history
424 (car notmuch-identities))
425 (let* ((name (notmuch-user-name))
426 (addrs (cons (notmuch-user-primary-email)
427 (notmuch-user-other-email)))
429 (ido-completing-read (concat "Sender address for " name ": ") addrs
430 nil nil nil 'notmuch-mua-sender-history
432 (message-make-from name address))))
434 (put 'notmuch-mua-new-mail 'notmuch-prefix-doc "... and prompt for sender")
435 (defun notmuch-mua-new-mail (&optional prompt-for-sender)
438 If PROMPT-FOR-SENDER is non-nil, the user will be prompted for
439 the From: address first."
442 (and (or prompt-for-sender notmuch-always-prompt-for-sender)
443 (list (cons 'From (notmuch-mua-prompt-for-sender))))))
444 (notmuch-mua-mail nil nil other-headers nil (notmuch-mua-get-switch-function))))
446 (defun notmuch-mua-new-forward-messages (messages &optional prompt-for-sender)
447 "Compose a new message forwarding MESSAGES.
449 If PROMPT-FOR-SENDER is non-nil, the user will be prompteed for
451 (let* ((other-headers
452 (and (or prompt-for-sender notmuch-always-prompt-for-sender)
453 (list (cons 'From (notmuch-mua-prompt-for-sender)))))
454 ;; Comes from the first message and is applied later.
456 ;; List of accumulated message-references of forwarded messages.
458 ;; List of corresponding message-query.
460 ;; Generate the template for the outgoing message.
461 (notmuch-mua-mail nil "" other-headers nil (notmuch-mua-get-switch-function))
463 ;; Insert all of the forwarded messages.
465 (let ((temp-buffer (get-buffer-create
466 (concat "*notmuch-fwd-raw-" id "*"))))
467 ;; Get the raw version of this message in the buffer.
468 (with-current-buffer temp-buffer
470 (let ((coding-system-for-read 'no-conversion))
471 (call-process notmuch-command nil t nil
472 "show" "--format=raw" id))
473 ;; Because we process the messages in reverse order,
474 ;; always generate a forwarded subject, then use the
475 ;; last (i.e. first) one.
476 (setq forward-subject (message-make-forward-subject))
477 (push (message-fetch-field "Message-ID") forward-references)
478 (push id forward-queries))
479 ;; Make a copy ready to be forwarded in the
480 ;; composition buffer.
481 (message-forward-make-body temp-buffer)
482 ;; Kill the temporary buffer.
483 (kill-buffer temp-buffer)))
484 ;; `message-forward-make-body' always puts the message at
485 ;; the top, so do them in reverse order.
487 ;; Add in the appropriate subject.
489 (message-narrow-to-headers)
490 (message-remove-header "Subject")
491 (message-add-header (concat "Subject: " forward-subject))
492 (message-remove-header "References")
493 (message-add-header (concat "References: "
494 (mapconcat 'identity forward-references " "))))
495 ;; Create a buffer-local queue for tag changes triggered when
496 ;; sending the message.
497 (when notmuch-message-forwarded-tags
498 (setq-local notmuch-message-queued-tag-changes
499 (cl-loop for id in forward-queries
501 (cons id notmuch-message-forwarded-tags))))
502 ;; `message-forward-make-body' shows the User-agent header. Hide
504 (message-hide-headers)
505 (set-buffer-modified-p nil))))
507 (defun notmuch-mua-new-reply (query-string &optional prompt-for-sender reply-all)
508 "Compose a reply to the message identified by QUERY-STRING.
510 If PROMPT-FOR-SENDER is non-nil, the user will be prompted for
511 the From: address first. If REPLY-ALL is non-nil, the message
512 will be addressed to all recipients of the source message."
513 ;; `select-active-regions' is t by default. The reply insertion code
514 ;; sets the region to the quoted message to make it easy to delete
515 ;; (kill-region or C-w). These two things combine to put the quoted
516 ;; message in the primary selection.
518 ;; This is not what the user wanted and is a privacy risk (accidental
519 ;; pasting of the quoted message). We can avoid some of the problems
520 ;; by let-binding select-active-regions to nil. This fixes if the
521 ;; primary selection was previously in a non-emacs window but not if
522 ;; it was in an emacs window. To avoid the problem in the latter case
523 ;; we deactivate mark.
524 (let ((sender (and prompt-for-sender
525 (notmuch-mua-prompt-for-sender)))
526 (select-active-regions nil))
527 (notmuch-mua-reply query-string sender reply-all)
530 (defun notmuch-mua-check-no-misplaced-secure-tag ()
531 "Query user if there is a misplaced secure mml tag.
533 Emacs message-send will (probably) ignore a secure mml tag unless
534 it is at the start of the body. Returns t if there is no such
535 tag, or the user confirms they mean it."
537 (let ((body-start (progn (message-goto-body) (point))))
538 (goto-char (point-max))
540 ;; We are always fine if there is no secure tag.
541 (not (search-backward "<#secure" nil 't))
542 ;; There is a secure tag, so it must be at the start of the
543 ;; body, with no secure tag earlier (i.e., in the headers).
544 (and (= (point) body-start)
545 (not (search-backward "<#secure" nil 't)))
546 ;; The user confirms they means it.
548 There is a <#secure> tag not at the start of the body. It is
549 likely that the message will be sent unsigned and unencrypted.
552 (defun notmuch-mua-check-secure-tag-has-newline ()
553 "Query if the secure mml tag has a newline following it.
555 Emacs message-send will (probably) ignore a correctly placed
556 secure mml tag unless it is followed by a newline. Returns t if
557 any secure tag is followed by a newline, or the user confirms
562 ;; There is no (correctly placed) secure tag.
563 (not (looking-at "<#secure"))
564 ;; The secure tag is followed by a newline.
565 (looking-at "<#secure[^\n>]*>\n")
566 ;; The user confirms they means it.
568 The <#secure> tag at the start of the body is not followed by a
569 newline. It is likely that the message will be sent unsigned and
570 unencrypted. Really send? "))))
572 (defun notmuch-mua-send-common (arg &optional exit)
574 (run-hooks 'notmuch-mua-send-hook)
575 (when (and (notmuch-mua-check-no-misplaced-secure-tag)
576 (notmuch-mua-check-secure-tag-has-newline))
577 (cl-letf (((symbol-function 'message-do-fcc)
578 #'notmuch-maildir-message-do-fcc))
580 (message-send-and-exit arg)
581 (message-send arg)))))
583 (defun notmuch-mua-send-and-exit (&optional arg)
585 (notmuch-mua-send-common arg 't))
587 (defun notmuch-mua-send (&optional arg)
589 (notmuch-mua-send-common arg))
591 (defun notmuch-mua-kill-buffer ()
593 (message-kill-buffer))
597 (define-mail-user-agent 'notmuch-user-agent
598 'notmuch-mua-mail 'notmuch-mua-send-and-exit
599 'notmuch-mua-kill-buffer 'notmuch-mua-send-hook)
601 ;; Add some more headers to the list that `message-mode' hides when
602 ;; composing a message.
603 (notmuch-mua-add-more-hidden-headers)
607 (provide 'notmuch-mua)
609 ;;; notmuch-mua.el ends here