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>
26 (require 'format-spec)
28 (require 'notmuch-lib)
29 (require 'notmuch-address)
30 (require 'notmuch-draft)
31 (require 'notmuch-message)
33 (eval-when-compile (require 'cl))
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 '(notmuch-mua-message-send-hook)
44 "Hook run before sending messages."
47 :group 'notmuch-hooks)
49 (defcustom notmuch-mua-compose-in 'current-window
51 "Where to create the mail buffer used to compose a new message.
52 Possible values are `current-window' (default), `new-window' and
53 `new-frame'. If set to `current-window', the mail buffer will be
54 displayed in the current window, so the old buffer will be
55 restored when the mail buffer is killed. If set to `new-window'
56 or `new-frame', the mail buffer will be displayed in a new
57 window/frame that will be destroyed when the buffer is killed.
58 You may want to customize `message-kill-buffer-on-exit'
60 (when (< emacs-major-version 24)
61 " Due to a known bug in Emacs 23, you should not set
62 this to `new-window' if `message-kill-buffer-on-exit' is
63 disabled: this would result in an incorrect behavior."))
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. If this is
71 `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
83 :type '(repeat string)
86 (defgroup notmuch-reply nil
87 "Replying to messages in notmuch"
90 (defcustom notmuch-mua-cite-function 'message-cite-original
91 "*Function for citing an original message.
92 Predefined functions include `message-cite-original' and
93 `message-cite-original-without-signature'.
94 Note that these 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)
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 (loop while (re-search-forward notmuch-mua-attachment-regexp search-limit t)
144 ;; For every instance of the "attachment" string
145 ;; found, examine the text properties. If the text
146 ;; has either a `face' or `syntax-table' property
147 ;; then it is quoted text and should *not* cause the
148 ;; user to be asked about a missing attachment.
149 if (let ((props (text-properties-at (match-beginning 0))))
150 (not (or (memq 'syntax-table props)
151 (memq 'face props))))
153 finally return nil)))
154 ;; ...but doesn't have a part with a filename...
157 (not (re-search-forward "^<#part [^>]*filename=" nil t)))
158 ;; ...and that's not okay...
159 (not (y-or-n-p "Attachment mentioned, but no attachment - is that okay?")))
160 ;; ...signal an error.
161 (error "Missing attachment")))
163 (defun notmuch-mua-get-switch-function ()
164 "Get a switch function according to `notmuch-mua-compose-in'."
165 (cond ((eq notmuch-mua-compose-in 'current-window)
167 ((eq notmuch-mua-compose-in 'new-window)
168 'switch-to-buffer-other-window)
169 ((eq notmuch-mua-compose-in 'new-frame)
170 'switch-to-buffer-other-frame)
171 (t (error "Invalid value for `notmuch-mua-compose-in'"))))
173 (defun notmuch-mua-maybe-set-window-dedicated ()
174 "Set the selected window as dedicated according to
175 `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 (when (not (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 (loop for part in parts
207 if (notmuch-match-content-type (plist-get part :content-type) "multipart/encrypted")
208 do (mml-secure-message-sign-encrypt)
209 else if (notmuch-match-content-type (plist-get part :content-type) "multipart/*")
210 do (notmuch-mua-reply-crypto (plist-get part :content))))
212 ;; There is a bug in emacs 23's message.el that results in a newline
213 ;; not being inserted after the References header, so the next header
214 ;; is concatenated to the end of it. This function fixes the problem,
215 ;; while guarding against the possibility that some current or future
216 ;; version of emacs has the bug fixed.
217 (defun notmuch-mua-insert-references (original-func header references)
218 (funcall original-func header references)
219 (unless (bolp) (insert "\n")))
221 (defun notmuch-mua-reply (query-string &optional sender reply-all)
222 (let ((args '("reply" "--format=sexp" "--format-version=4"))
223 (process-crypto notmuch-show-process-crypto)
227 (setq args (append args '("--decrypt=true"))))
230 (setq args (append args '("--reply-to=all")))
231 (setq args (append args '("--reply-to=sender"))))
232 (setq args (append args (list query-string)))
234 ;; Get the reply object as SEXP, and parse it into an elisp object.
235 (setq reply (apply #'notmuch-call-notmuch-sexp args))
237 ;; Extract the original message to simplify the following code.
238 (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)))
244 ;; If sender is non-nil, set the From: header to its value.
246 (plist-put reply-headers :From sender))
248 ;; Overlay the composition window on that being used to read
249 ;; the original message.
250 ((same-window-regexps '("\\*mail .*")))
252 ;; We modify message-header-format-alist to get around a bug in message.el.
253 ;; See the comment above on notmuch-mua-insert-references.
254 (let ((message-header-format-alist
255 (loop for pair in message-header-format-alist
256 if (eq (car pair) 'References)
257 collect (cons 'References
259 'notmuch-mua-insert-references
263 (notmuch-mua-mail (plist-get reply-headers :To)
264 (notmuch-sanitize (plist-get reply-headers :Subject))
265 (notmuch-headers-plist-to-alist reply-headers)
266 nil (notmuch-mua-get-switch-function))))
268 ;; Create a buffer-local queue for tag changes triggered when sending the reply
269 (when notmuch-message-replied-tags
270 (setq-local notmuch-message-queued-tag-changes
271 (list (cons query-string notmuch-message-replied-tags))))
273 ;; Insert the message body - but put it in front of the signature
274 ;; if one is present, and after any other content
275 ;; message*setup-hooks may have added to the message body already.
278 (narrow-to-region (point) (point-max))
279 (goto-char (point-max))
280 (if (re-search-backward message-signature-separator nil t)
281 (if message-signature-insert-empty-line
283 (goto-char (point-max))))
285 (let ((from (plist-get original-headers :From))
286 (date (plist-get original-headers :Date))
289 ;; notmuch-mua-cite-function constructs a citation line based
290 ;; on the From and Date headers of the original message, which
291 ;; are assumed to be in the buffer.
292 (insert "From: " from "\n")
293 (insert "Date: " date "\n\n")
295 (insert (with-temp-buffer
297 ;; Don't attempt to clean up messages, excerpt
298 ;; citations, etc. in the original message before
300 ((notmuch-show-insert-text/plain-hook nil)
301 ;; Don't omit long parts.
302 (notmuch-show-max-text-part-size 0)
303 ;; Insert headers for parts as appropriate for replying.
304 (notmuch-show-insert-header-p-function notmuch-mua-reply-insert-header-p-function)
305 ;; Ensure that any encrypted parts are
306 ;; decrypted during the generation of the reply
308 (notmuch-show-process-crypto process-crypto)
309 ;; Don't indent multipart sub-parts.
310 (notmuch-show-indent-multipart nil))
311 ;; We don't want sigstatus buttons (an information leak and usually wrong anyway).
312 (letf (((symbol-function 'notmuch-crypto-insert-sigstatus-button) #'ignore)
313 ((symbol-function 'notmuch-crypto-insert-encstatus-button) #'ignore))
314 (notmuch-show-insert-body original (plist-get original :body) 0)
315 (buffer-substring-no-properties (point-min) (point-max))))))
319 ;; Quote the original message according to the user's configured style.
320 (funcall notmuch-mua-cite-function)))
322 ;; Crypto processing based crypto content of the original message
324 (notmuch-mua-reply-crypto (plist-get original :body))))
326 ;; Push mark right before signature, if any.
327 (message-goto-signature)
333 (set-buffer-modified-p nil))
335 (define-derived-mode notmuch-message-mode message-mode "Message[Notmuch]"
336 "Notmuch message composition mode. Mostly like `message-mode'"
337 (notmuch-address-setup))
339 (put 'notmuch-message-mode 'flyspell-mode-predicate 'mail-mode-flyspell-verify)
341 (define-key notmuch-message-mode-map (kbd "C-c C-c") #'notmuch-mua-send-and-exit)
342 (define-key notmuch-message-mode-map (kbd "C-c C-s") #'notmuch-mua-send)
343 (define-key notmuch-message-mode-map (kbd "C-c C-p") #'notmuch-draft-postpone)
344 (define-key notmuch-message-mode-map (kbd "C-x C-s") #'notmuch-draft-save)
346 (defun notmuch-mua-pop-to-buffer (name switch-function)
347 "Pop to buffer NAME, and warn if it already exists and is
348 modified. This function is notmuch addaptation of
349 `message-pop-to-buffer'."
350 (let ((buffer (get-buffer name)))
352 (buffer-name buffer))
353 (let ((window (get-buffer-window buffer 0)))
355 ;; Raise the frame already displaying the message buffer.
357 (select-frame-set-input-focus (window-frame window))
358 (select-window window))
359 (funcall switch-function buffer)
361 (when (and (buffer-modified-p)
364 "Message already being composed; erase? ")
366 (error "Message being composed")))
367 (funcall switch-function name)
370 (notmuch-message-mode)))
372 (defun notmuch-mua-mail (&optional to subject other-headers continue
373 switch-function yank-action send-actions
374 return-action &rest ignored)
375 "Invoke the notmuch mail composition window."
378 (when notmuch-mua-user-agent-function
379 (let ((user-agent (funcall notmuch-mua-user-agent-function)))
380 (when (not (string= "" user-agent))
381 (push (cons 'User-Agent user-agent) other-headers))))
383 (unless (assq 'From other-headers)
384 (push (cons 'From (message-make-from
385 (notmuch-user-name) (notmuch-user-primary-email))) other-headers))
387 (notmuch-mua-pop-to-buffer (message-buffer-name "mail" to)
388 (or switch-function (notmuch-mua-get-switch-function)))
391 ;; The following is copied from `message-mail'
392 `((To . ,(or to "")) (Subject . ,(or subject "")))
393 ;; C-h f compose-mail says that headers should be specified as
394 ;; (string . value); however all the rest of message expects
395 ;; headers to be symbols, not strings (eg message-header-format-alist).
396 ;; https://lists.gnu.org/archive/html/emacs-devel/2011-01/msg00337.html
397 ;; We need to convert any string input, eg from rmail-start-mail.
398 (dolist (h other-headers other-headers)
399 (if (stringp (car h)) (setcar h (intern (capitalize (car h))))))))
400 (args (list yank-action send-actions))
401 ;; Cause `message-setup-1' to do things relevant for mail,
402 ;; such as observe `message-default-mail-headers'.
403 (message-this-is-mail t))
404 ;; message-setup-1 in Emacs 23 does not accept return-action
405 ;; argument. Pass it only if it is supplied by the caller. This
406 ;; will never be the case when we're called by `compose-mail' in
408 (when return-action (nconc args '(return-action)))
409 (apply 'message-setup-1 headers args))
410 (notmuch-fcc-header-setup)
411 (message-sort-headers)
412 (message-hide-headers)
413 (set-buffer-modified-p nil)
414 (notmuch-mua-maybe-set-window-dedicated)
418 (defcustom notmuch-identities nil
419 "Identities that can be used as the From: address when composing a new message.
421 If this variable is left unset, then a list will be constructed from the
422 name and addresses configured in the notmuch configuration file."
423 :type '(repeat string)
424 :group 'notmuch-send)
426 (defcustom notmuch-always-prompt-for-sender nil
427 "Always prompt for the From: address when composing or forwarding a message.
429 This is not taken into account when replying to a message, because in that case
430 the From: header is already filled in by notmuch."
432 :group 'notmuch-send)
434 (defvar notmuch-mua-sender-history nil)
436 ;; Workaround: Running `ido-completing-read' in emacs 23.1, 23.2 and 23.3
437 ;; without some explicit initialization fill freeze the operation.
438 ;; Hence, we advice `ido-completing-read' to ensure required initialization
440 (if (and (= emacs-major-version 23) (< emacs-minor-version 4))
441 (defadvice ido-completing-read (before notmuch-ido-mode-init activate)
442 (ido-init-completion-maps)
443 (add-hook 'minibuffer-setup-hook 'ido-minibuffer-setup)
444 (add-hook 'choose-completion-string-functions
445 'ido-choose-completion-string)
446 (ad-disable-advice 'ido-completing-read 'before 'notmuch-ido-mode-init)
447 (ad-activate 'ido-completing-read)))
449 (defun notmuch-mua-prompt-for-sender ()
450 "Prompt for a sender from the user's configured identities."
451 (if notmuch-identities
452 (ido-completing-read "Send mail from: " notmuch-identities
453 nil nil nil 'notmuch-mua-sender-history
454 (car notmuch-identities))
455 (let* ((name (notmuch-user-name))
456 (addrs (cons (notmuch-user-primary-email)
457 (notmuch-user-other-email)))
459 (ido-completing-read (concat "Sender address for " name ": ") addrs
460 nil nil nil 'notmuch-mua-sender-history
462 (message-make-from name address))))
464 (put 'notmuch-mua-new-mail 'notmuch-prefix-doc "... and prompt for sender")
465 (defun notmuch-mua-new-mail (&optional prompt-for-sender)
468 If PROMPT-FOR-SENDER is non-nil, the user will be prompted for
469 the From: address first."
472 (when (or prompt-for-sender notmuch-always-prompt-for-sender)
473 (list (cons 'From (notmuch-mua-prompt-for-sender))))))
474 (notmuch-mua-mail nil nil other-headers nil (notmuch-mua-get-switch-function))))
476 (defun notmuch-mua-new-forward-messages (messages &optional prompt-for-sender)
477 "Compose a new message forwarding MESSAGES.
479 If PROMPT-FOR-SENDER is non-nil, the user will be prompteed for
481 (let* ((other-headers
482 (when (or prompt-for-sender notmuch-always-prompt-for-sender)
483 (list (cons 'From (notmuch-mua-prompt-for-sender)))))
484 forward-subject ;; Comes from the first message and is
486 forward-references ;; List of accumulated message-references of forwarded messages
487 forward-queries) ;; List of corresponding message-query
489 ;; Generate the template for the outgoing message.
490 (notmuch-mua-mail nil "" other-headers nil (notmuch-mua-get-switch-function))
493 ;; Insert all of the forwarded messages.
495 (let ((temp-buffer (get-buffer-create
496 (concat "*notmuch-fwd-raw-" id "*"))))
497 ;; Get the raw version of this message in the buffer.
498 (with-current-buffer temp-buffer
500 (let ((coding-system-for-read 'no-conversion))
501 (call-process notmuch-command nil t nil "show" "--format=raw" id))
502 ;; Because we process the messages in reverse order,
503 ;; always generate a forwarded subject, then use the
504 ;; last (i.e. first) one.
505 (setq forward-subject (message-make-forward-subject))
506 (push (message-fetch-field "Message-ID") forward-references)
507 (push id forward-queries))
508 ;; Make a copy ready to be forwarded in the
509 ;; composition buffer.
510 (message-forward-make-body temp-buffer)
511 ;; Kill the temporary buffer.
512 (kill-buffer temp-buffer)))
513 ;; `message-forward-make-body' always puts the message at
514 ;; the top, so do them in reverse order.
517 ;; Add in the appropriate subject.
519 (message-narrow-to-headers)
520 (message-remove-header "Subject")
521 (message-add-header (concat "Subject: " forward-subject))
522 (message-remove-header "References")
523 (message-add-header (concat "References: "
524 (mapconcat 'identity forward-references " "))))
526 ;; Create a buffer-local queue for tag changes triggered when sending the message
527 (when notmuch-message-forwarded-tags
528 (setq-local notmuch-message-queued-tag-changes
529 (loop for id in forward-queries
532 notmuch-message-forwarded-tags))))
534 ;; `message-forward-make-body' shows the User-agent header. Hide
536 (message-hide-headers)
537 (set-buffer-modified-p nil))))
539 (defun notmuch-mua-new-reply (query-string &optional prompt-for-sender reply-all)
540 "Compose a reply to the message identified by QUERY-STRING.
542 If PROMPT-FOR-SENDER is non-nil, the user will be prompted for
543 the From: address first. If REPLY-ALL is non-nil, the message
544 will be addressed to all recipients of the source message."
546 ;; In current emacs (24.3) select-active-regions is set to t by
547 ;; default. The reply insertion code sets the region to the quoted
548 ;; message to make it easy to delete (kill-region or C-w). These two
549 ;; things combine to put the quoted message in the primary selection.
551 ;; This is not what the user wanted and is a privacy risk (accidental
552 ;; pasting of the quoted message). We can avoid some of the problems
553 ;; by let-binding select-active-regions to nil. This fixes if the
554 ;; primary selection was previously in a non-emacs window but not if
555 ;; it was in an emacs window. To avoid the problem in the latter case
556 ;; we deactivate mark.
559 (when prompt-for-sender
560 (notmuch-mua-prompt-for-sender)))
561 (select-active-regions nil))
562 (notmuch-mua-reply query-string sender reply-all)
565 (defun notmuch-mua-check-no-misplaced-secure-tag ()
566 "Query user if there is a misplaced secure mml tag.
568 Emacs message-send will (probably) ignore a secure mml tag unless
569 it is at the start of the body. Returns t if there is no such
570 tag, or the user confirms they mean it."
572 (let ((body-start (progn (message-goto-body) (point))))
573 (goto-char (point-max))
575 ;; We are always fine if there is no secure tag.
576 (not (search-backward "<#secure" nil 't))
577 ;; There is a secure tag, so it must be at the start of the
578 ;; body, with no secure tag earlier (i.e., in the headers).
579 (and (= (point) body-start)
580 (not (search-backward "<#secure" nil 't)))
581 ;; The user confirms they means it.
583 There is a <#secure> tag not at the start of the body. It is
584 likely that the message will be sent unsigned and unencrypted.
587 (defun notmuch-mua-check-secure-tag-has-newline ()
588 "Query if the secure mml tag has a newline following it.
590 Emacs message-send will (probably) ignore a correctly placed
591 secure mml tag unless it is followed by a newline. Returns t if
592 any secure tag is followed by a newline, or the user confirms
597 ;; There is no (correctly placed) secure tag.
598 (not (looking-at "<#secure"))
599 ;; The secure tag is followed by a newline.
600 (looking-at "<#secure[^\n>]*>\n")
601 ;; The user confirms they means it.
603 The <#secure> tag at the start of the body is not followed by a
604 newline. It is likely that the message will be sent unsigned and
605 unencrypted. Really send? "))))
607 (defun notmuch-mua-send-common (arg &optional exit)
609 (run-hooks 'notmuch-mua-send-hook)
610 (when (and (notmuch-mua-check-no-misplaced-secure-tag)
611 (notmuch-mua-check-secure-tag-has-newline))
612 (letf (((symbol-function 'message-do-fcc) #'notmuch-maildir-message-do-fcc))
614 (message-send-and-exit arg)
615 (message-send arg)))))
617 (defun notmuch-mua-send-and-exit (&optional arg)
619 (notmuch-mua-send-common arg 't))
621 (defun notmuch-mua-send (&optional arg)
623 (notmuch-mua-send-common arg))
625 (defun notmuch-mua-kill-buffer ()
627 (message-kill-buffer))
629 (defun notmuch-mua-message-send-hook ()
630 "The default function used for `notmuch-mua-send-hook', this
631 simply runs the corresponding `message-mode' hook functions."
632 (run-hooks 'message-send-hook))
636 (define-mail-user-agent 'notmuch-user-agent
637 'notmuch-mua-mail 'notmuch-mua-send-and-exit
638 'notmuch-mua-kill-buffer 'notmuch-mua-send-hook)
640 ;; Add some more headers to the list that `message-mode' hides when
641 ;; composing a message.
642 (notmuch-mua-add-more-hidden-headers)
646 (provide 'notmuch-mua)
648 ;;; notmuch-mua.el ends here