]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-mua.el
emacs: Add new option notmuch-search-hide-excluded
[notmuch] / emacs / notmuch-mua.el
1 ;;; notmuch-mua.el --- emacs style mail-user-agent  -*- lexical-binding: t -*-
2 ;;
3 ;; Copyright © David Edmondson
4 ;;
5 ;; This file is part of Notmuch.
6 ;;
7 ;; Notmuch is free software: you can redistribute it and/or modify it
8 ;; under the terms of the GNU General Public License as published by
9 ;; the Free Software Foundation, either version 3 of the License, or
10 ;; (at your option) any later version.
11 ;;
12 ;; Notmuch is distributed in the hope that it will be useful, but
13 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 ;; General Public License for more details.
16 ;;
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with Notmuch.  If not, see <https://www.gnu.org/licenses/>.
19 ;;
20 ;; Authors: David Edmondson <dme@dme.org>
21
22 ;;; Code:
23
24 (eval-when-compile (require 'subr-x))
25
26 (require 'message)
27 (require 'gmm-utils)
28 (require 'mm-view)
29 (require 'format-spec)
30
31 (require 'notmuch-lib)
32 (require 'notmuch-address)
33 (require 'notmuch-draft)
34 (require 'notmuch-message)
35
36 (declare-function notmuch-show-insert-body "notmuch-show" (msg body depth))
37 (declare-function notmuch-fcc-header-setup "notmuch-maildir-fcc" ())
38 (declare-function notmuch-maildir-message-do-fcc "notmuch-maildir-fcc" ())
39 (declare-function notmuch-draft-postpone "notmuch-draft" ())
40 (declare-function notmuch-draft-save "notmuch-draft" ())
41
42 (defvar notmuch-show-indent-multipart)
43 (defvar notmuch-show-insert-header-p-function)
44 (defvar notmuch-show-max-text-part-size)
45 (defvar notmuch-show-insert-text/plain-hook)
46
47 ;;; Options
48
49 (defcustom notmuch-mua-send-hook nil
50   "Hook run before sending messages."
51   :type 'hook
52   :group 'notmuch-send
53   :group 'notmuch-hooks)
54
55 (defcustom notmuch-mua-compose-in 'current-window
56   "Where to create the mail buffer used to compose a new message.
57 Possible values are `current-window' (default), `new-window' and
58 `new-frame'. If set to `current-window', the mail buffer will be
59 displayed in the current window, so the old buffer will be
60 restored when the mail buffer is killed. If set to `new-window'
61 or `new-frame', the mail buffer will be displayed in a new
62 window/frame that will be destroyed when the buffer is killed.
63 You may want to customize `message-kill-buffer-on-exit'
64 accordingly."
65   :group 'notmuch-send
66   :type '(choice (const :tag "Compose in the current window" current-window)
67                  (const :tag "Compose mail in a new window"  new-window)
68                  (const :tag "Compose mail in a new frame"   new-frame)))
69
70 (defcustom notmuch-mua-user-agent-function nil
71   "Function used to generate a `User-Agent:' string.
72 If this is `nil' then no `User-Agent:' will be generated."
73   :type '(choice (const :tag "No user agent string" nil)
74                  (const :tag "Full" notmuch-mua-user-agent-full)
75                  (const :tag "Notmuch" notmuch-mua-user-agent-notmuch)
76                  (const :tag "Emacs" notmuch-mua-user-agent-emacs)
77                  (function :tag "Custom user agent function"
78                            :value notmuch-mua-user-agent-full))
79   :group 'notmuch-send)
80
81 (defcustom notmuch-mua-hidden-headers nil
82   "Headers that are added to the `message-mode' hidden headers list."
83   :type '(repeat string)
84   :group 'notmuch-send)
85
86 (defcustom notmuch-identities nil
87   "Identities that can be used as the From: address when composing a new message.
88
89 If this variable is left unset, then a list will be constructed from the
90 name and addresses configured in the notmuch configuration file."
91   :type '(repeat string)
92   :group 'notmuch-send)
93
94 (defcustom notmuch-always-prompt-for-sender nil
95   "Always prompt for the From: address when composing or forwarding a message.
96
97 This is not taken into account when replying to a message, because in that case
98 the From: header is already filled in by notmuch."
99   :type 'boolean
100   :group 'notmuch-send)
101
102 (defgroup notmuch-reply nil
103   "Replying to messages in notmuch."
104   :group 'notmuch)
105
106 (defcustom notmuch-mua-cite-function 'message-cite-original
107   "Function for citing an original message.
108
109 Predefined functions include `message-cite-original' and
110 `message-cite-original-without-signature'.  Note that these
111 functions use `mail-citation-hook' if that is non-nil."
112   :type '(radio (function-item message-cite-original)
113                 (function-item message-cite-original-without-signature)
114                 (function-item sc-cite-original)
115                 (function :tag "Other"))
116   :link '(custom-manual "(message)Insertion Variables")
117   :group 'notmuch-reply)
118
119 (defcustom notmuch-mua-reply-insert-header-p-function
120   'notmuch-show-reply-insert-header-p-never
121   "Function to decide which parts get a header when replying.
122
123 This function specifies which parts of a mime message with
124 multiple parts get a header."
125   :type '(radio (const :tag "No part headers"
126                        notmuch-show-reply-insert-header-p-never)
127                 (const :tag "All except multipart/* and hidden parts"
128                        notmuch-show-reply-insert-header-p-trimmed)
129                 (const :tag "Only for included text parts"
130                        notmuch-show-reply-insert-header-p-minimal)
131                 (const :tag "Exactly as in show view"
132                        notmuch-show-insert-header-p)
133                 (function :tag "Other"))
134   :group 'notmuch-reply)
135
136 (defcustom notmuch-mua-attachment-regexp
137   "\\b\\(attache\?ment\\|attached\\|attach\\|pi[èe]ce\s+jointe?\\)\\b"
138   "Message body text indicating that an attachment is expected.
139
140 This is not used unless `notmuch-mua-attachment-check' is added
141 to `notmuch-mua-send-hook'."
142   :type 'regexp
143   :group 'notmuch-send)
144
145 ;;; Various functions
146
147 (defun notmuch-mua-attachment-check ()
148   "Signal an error an attachement is expected but missing.
149
150 Signal an error if the message text indicates that an attachment
151 is expected but no MML referencing an attachment is found.
152
153 Typically this is added to `notmuch-mua-send-hook'."
154   (when (and
155          ;; When the message mentions attachment...
156          (save-excursion
157            (message-goto-body)
158            ;; Limit search from reaching other possible parts of the message
159            (let ((search-limit (search-forward "\n<#" nil t)))
160              (message-goto-body)
161              (cl-loop while (re-search-forward notmuch-mua-attachment-regexp
162                                                search-limit t)
163                       ;; For every instance of the "attachment" string
164                       ;; found, examine the text properties. If the text
165                       ;; has either a `face' or `syntax-table' property
166                       ;; then it is quoted text and should *not* cause the
167                       ;; user to be asked about a missing attachment.
168                       if (let ((props (text-properties-at (match-beginning 0))))
169                            (not (or (memq 'syntax-table props)
170                                     (memq 'face props))))
171                       return t
172                       finally return nil)))
173          ;; ...but doesn't have a part with a filename...
174          (save-excursion
175            (message-goto-body)
176            (not (re-search-forward "^<#part [^>]*filename=" nil t)))
177          ;; ...and that's not okay...
178          (not (y-or-n-p "Attachment mentioned, but no attachment - is that okay?")))
179     ;; ...signal an error.
180     (error "Missing attachment")))
181
182 (defun notmuch-mua-get-switch-function ()
183   "Get a switch function according to `notmuch-mua-compose-in'."
184   (pcase notmuch-mua-compose-in
185     ('current-window 'switch-to-buffer)
186     ('new-window     'switch-to-buffer-other-window)
187     ('new-frame      'switch-to-buffer-other-frame)
188     (_ (error "Invalid value for `notmuch-mua-compose-in'"))))
189
190 (defun notmuch-mua-maybe-set-window-dedicated ()
191   "Set the selected window as dedicated according to `notmuch-mua-compose-in'."
192   (when (or (eq notmuch-mua-compose-in 'new-frame)
193             (eq notmuch-mua-compose-in 'new-window))
194     (set-window-dedicated-p (selected-window) t)))
195
196 (defun notmuch-mua-user-agent-full ()
197   "Generate a `User-Agent:' string suitable for notmuch."
198   (concat (notmuch-mua-user-agent-notmuch)
199           " "
200           (notmuch-mua-user-agent-emacs)))
201
202 (defun notmuch-mua-user-agent-notmuch ()
203   "Generate a `User-Agent:' string suitable for notmuch."
204   (let ((notmuch-version (if (string= notmuch-emacs-version "unknown")
205                              (notmuch-cli-version)
206                            notmuch-emacs-version)))
207     (concat "Notmuch/" notmuch-version " (https://notmuchmail.org)")))
208
209 (defun notmuch-mua-user-agent-emacs ()
210   "Generate a `User-Agent:' string suitable for notmuch."
211   (concat "Emacs/" emacs-version " (" system-configuration ")"))
212
213 (defun notmuch-mua-add-more-hidden-headers ()
214   "Add some headers to the list that are hidden by default."
215   (mapc (lambda (header)
216           (unless (member header message-hidden-headers)
217             (push header message-hidden-headers)))
218         notmuch-mua-hidden-headers))
219
220 (defun notmuch-mua-reply-crypto (parts)
221   "Add mml sign-encrypt flag if any part of original message is encrypted."
222   (cl-loop for part in parts
223            for type = (plist-get part :content-type)
224            if (notmuch-match-content-type type "multipart/encrypted")
225            do (mml-secure-message-sign-encrypt)
226            else if (notmuch-match-content-type type "multipart/*")
227            do (notmuch-mua-reply-crypto (plist-get part :content))))
228
229 ;; There is a bug in Emacs' message.el that results in a newline
230 ;; not being inserted after the References header, so the next header
231 ;; is concatenated to the end of it. This function fixes the problem,
232 ;; while guarding against the possibility that some current or future
233 ;; version of emacs has the bug fixed.
234 (defun notmuch-mua-insert-references (original-func header references)
235   (funcall original-func header references)
236   (unless (bolp) (insert "\n")))
237
238 ;;; Mua reply
239
240 (defun notmuch-mua-reply (query-string &optional sender reply-all)
241   (let ((args '("reply" "--format=sexp" "--format-version=5"))
242         (process-crypto notmuch-show-process-crypto)
243         reply
244         original)
245     (when process-crypto
246       (setq args (append args '("--decrypt=true"))))
247     (if reply-all
248         (setq args (append args '("--reply-to=all")))
249       (setq args (append args '("--reply-to=sender"))))
250     (setq args (append args (list query-string)))
251     ;; Get the reply object as SEXP, and parse it into an elisp object.
252     (setq reply (apply #'notmuch-call-notmuch-sexp args))
253     ;; Extract the original message to simplify the following code.
254     (setq original (plist-get reply :original))
255     ;; Extract the headers of both the reply and the original message.
256     (let* ((original-headers (plist-get original :headers))
257            (reply-headers (plist-get reply :reply-headers)))
258       ;; If sender is non-nil, set the From: header to its value.
259       (when sender
260         (plist-put reply-headers :From sender))
261       (let
262           ;; Overlay the composition window on that being used to read
263           ;; the original message.
264           ((same-window-regexps '("\\*mail .*")))
265         ;; We modify message-header-format-alist to get around
266         ;; a bug in message.el.  See the comment above on
267         ;; notmuch-mua-insert-references.
268         (let ((message-header-format-alist
269                (cl-loop for pair in message-header-format-alist
270                         if (eq (car pair) 'References)
271                         collect (cons 'References
272                                       (apply-partially
273                                        'notmuch-mua-insert-references
274                                        (cdr pair)))
275                         else
276                         collect pair)))
277           (notmuch-mua-mail (plist-get reply-headers :To)
278                             (notmuch-sanitize (plist-get reply-headers :Subject))
279                             (notmuch-headers-plist-to-alist reply-headers)
280                             nil (notmuch-mua-get-switch-function))))
281       ;; Create a buffer-local queue for tag changes triggered when
282       ;; sending the reply.
283       (when notmuch-message-replied-tags
284         (setq notmuch-message-queued-tag-changes
285               (list (cons query-string notmuch-message-replied-tags))))
286       ;; Insert the message body - but put it in front of the signature
287       ;; if one is present, and after any other content
288       ;; message*setup-hooks may have added to the message body already.
289       (save-restriction
290         (message-goto-body)
291         (narrow-to-region (point) (point-max))
292         (goto-char (point-max))
293         (if (re-search-backward message-signature-separator nil t)
294             (when message-signature-insert-empty-line
295               (forward-line -1))
296           (goto-char (point-max))))
297       (let ((from (plist-get original-headers :From))
298             (date (plist-get original-headers :Date))
299             (start (point)))
300         ;; notmuch-mua-cite-function constructs a citation line based
301         ;; on the From and Date headers of the original message, which
302         ;; are assumed to be in the buffer.
303         (insert "From: " from "\n")
304         (insert "Date: " date "\n\n")
305         (insert
306          (with-temp-buffer
307            (let
308                ;; Don't attempt to clean up messages, excerpt
309                ;; citations, etc. in the original message before
310                ;; quoting.
311                ((notmuch-show-insert-text/plain-hook nil)
312                 ;; Don't omit long parts.
313                 (notmuch-show-max-text-part-size 0)
314                 ;; Insert headers for parts as appropriate for replying.
315                 (notmuch-show-insert-header-p-function
316                  notmuch-mua-reply-insert-header-p-function)
317                 ;; Ensure that any encrypted parts are
318                 ;; decrypted during the generation of the reply
319                 ;; text.
320                 (notmuch-show-process-crypto process-crypto)
321                 ;; Don't indent multipart sub-parts.
322                 (notmuch-show-indent-multipart nil)
323                 ;; Stop certain mime types from being inlined
324                 (mm-inline-override-types (notmuch--inline-override-types)))
325              ;; We don't want sigstatus buttons (an information leak and usually wrong anyway).
326              (cl-letf (((symbol-function 'notmuch-crypto-insert-sigstatus-button) #'ignore)
327                        ((symbol-function 'notmuch-crypto-insert-encstatus-button) #'ignore))
328                (notmuch-show-insert-body original (plist-get original :body) 0)
329                (buffer-substring-no-properties (point-min) (point-max))))))
330         (set-mark (point))
331         (goto-char start)
332         ;; Quote the original message according to the user's configured style.
333         (funcall notmuch-mua-cite-function)))
334     ;; Crypto processing based crypto content of the original message
335     (when process-crypto
336       (notmuch-mua-reply-crypto (plist-get original :body))))
337   ;; Push mark right before signature, if any.
338   (message-goto-signature)
339   (unless (eobp)
340     (end-of-line -1))
341   (push-mark)
342   (message-goto-body)
343   (set-buffer-modified-p nil))
344
345 ;;; Mode and keymap
346
347 (defvar notmuch-message-mode-map
348   (let ((map (make-sparse-keymap)))
349     (define-key map [remap message-send-and-exit] #'notmuch-mua-send-and-exit)
350     (define-key map [remap message-send] #'notmuch-mua-send)
351     (define-key map (kbd "C-c C-p") #'notmuch-draft-postpone)
352     (define-key map (kbd "C-x C-s") #'notmuch-draft-save)
353     map)
354   "Keymap for `notmuch-message-mode'.")
355
356 (define-derived-mode notmuch-message-mode message-mode "Message[Notmuch]"
357   "Notmuch message composition mode. Mostly like `message-mode'."
358   (notmuch-address-setup))
359
360 (put 'notmuch-message-mode 'flyspell-mode-predicate 'mail-mode-flyspell-verify)
361
362 ;;; New messages
363
364 (defun notmuch-mua-pop-to-buffer (name switch-function)
365   "Pop to buffer NAME, and warn if it already exists and is modified.
366 Like `message-pop-to-buffer' but enable `notmuch-message-mode'
367 instead of `message-mode' and SWITCH-FUNCTION is mandatory."
368   (let ((buffer (get-buffer name)))
369     (if (and buffer
370              (buffer-name buffer))
371         (let ((window (get-buffer-window buffer 0)))
372           (if window
373               ;; Raise the frame already displaying the message buffer.
374               (progn
375                 (select-frame-set-input-focus (window-frame window))
376                 (select-window window))
377             (funcall switch-function buffer)
378             (set-buffer buffer))
379           (when (buffer-modified-p)
380             (if (y-or-n-p "Message already being composed; erase? ")
381                 (message nil)
382               (error "Message being composed"))))
383       (funcall switch-function name)
384       (set-buffer name))
385     (erase-buffer)
386     (notmuch-message-mode)))
387
388 (defun notmuch-mua--remove-dont-reply-to-names ()
389   (when-let* ((nr (if (functionp message-dont-reply-to-names)
390                       message-dont-reply-to-names
391                     (gmm-regexp-concat message-dont-reply-to-names)))
392               (nr-filter
393                (if (functionp nr)
394                    (lambda (mail) (and (not (funcall nr mail)) mail))
395                  (lambda (mail) (and (not (string-match-p nr mail)) mail)))))
396     (dolist (header '("To" "Cc"))
397       (when-let ((v (message-fetch-field header)))
398         (let* ((tokens (mapcar #'string-trim (message-tokenize-header v)))
399                (good-tokens (delq nil (mapcar nr-filter tokens)))
400                (addr (and good-tokens (mapconcat #'identity good-tokens ", "))))
401           (message-replace-header header addr))))))
402
403 (defun notmuch-mua-mail (&optional to subject other-headers _continue
404                                    switch-function yank-action send-actions
405                                    return-action &rest ignored)
406   "Invoke the notmuch mail composition window.
407
408 The position of point when the function returns differs depending
409 on the values of TO and SUBJECT.  If both are non-nil, point is
410 moved to the message's body.  If SUBJECT is nil but TO isn't,
411 point is moved to the \"Subject:\" header.  Otherwise, point is
412 moved to the \"To:\" header."
413   (interactive)
414   (when notmuch-mua-user-agent-function
415     (let ((user-agent (funcall notmuch-mua-user-agent-function)))
416       (unless (string-empty-p user-agent)
417         (push (cons 'User-Agent user-agent) other-headers))))
418   (unless (assq 'From other-headers)
419     (push (cons 'From (message-make-from
420                        (notmuch-user-name)
421                        (notmuch-user-primary-email)))
422           other-headers))
423   (notmuch-mua-pop-to-buffer (message-buffer-name "mail" to)
424                              (or switch-function
425                                  (notmuch-mua-get-switch-function)))
426   (let ((headers
427          (append
428           ;; The following is copied from `message-mail'
429           `((To . ,(or to "")) (Subject . ,(or subject "")))
430           ;; C-h f compose-mail says that headers should be specified as
431           ;; (string . value); however all the rest of message expects
432           ;; headers to be symbols, not strings (eg message-header-format-alist).
433           ;; https://lists.gnu.org/archive/html/emacs-devel/2011-01/msg00337.html
434           ;; We need to convert any string input, eg from rmail-start-mail.
435           (dolist (h other-headers other-headers)
436             (when (stringp (car h))
437               (setcar h (intern (capitalize (car h))))))))
438         ;; Cause `message-setup-1' to do things relevant for mail,
439         ;; such as observe `message-default-mail-headers'.
440         (message-this-is-mail t))
441     (message-setup-1 headers yank-action send-actions return-action))
442   (notmuch-fcc-header-setup)
443   (notmuch-mua--remove-dont-reply-to-names)
444   (message-sort-headers)
445   (message-hide-headers)
446   (set-buffer-modified-p nil)
447   (notmuch-mua-maybe-set-window-dedicated)
448   (cond
449    ((and to subject) (message-goto-body))
450    (to (message-goto-subject))
451    (t (message-goto-to))))
452
453 (defvar notmuch-mua-sender-history nil)
454
455 (defun notmuch-mua-prompt-for-sender ()
456   "Prompt for a sender from the user's configured identities."
457   (if notmuch-identities
458       (completing-read "Send mail from: " notmuch-identities
459                        nil nil nil 'notmuch-mua-sender-history
460                        (car notmuch-identities))
461     (let* ((name (notmuch-user-name))
462            (addrs (cons (notmuch-user-primary-email)
463                         (notmuch-user-other-email)))
464            (address
465             (completing-read (concat "Sender address for " name ": ") addrs
466                              nil nil nil 'notmuch-mua-sender-history
467                              (car addrs))))
468       (message-make-from name address))))
469
470 (put 'notmuch-mua-new-mail 'notmuch-prefix-doc "... and prompt for sender")
471 (defun notmuch-mua-new-mail (&optional prompt-for-sender)
472   "Compose new mail.
473
474 If PROMPT-FOR-SENDER is non-nil, the user will be prompted for
475 the From: address first."
476   (interactive "P")
477   (let ((other-headers
478          (and (or prompt-for-sender notmuch-always-prompt-for-sender)
479               (list (cons 'From (notmuch-mua-prompt-for-sender))))))
480     (notmuch-mua-mail nil nil other-headers nil (notmuch-mua-get-switch-function))))
481
482 (defun notmuch-mua-new-forward-messages (messages &optional prompt-for-sender)
483   "Compose a new message forwarding MESSAGES.
484
485 If PROMPT-FOR-SENDER is non-nil, the user will be prompteed for
486 the From: address."
487   (let* ((other-headers
488           (and (or prompt-for-sender notmuch-always-prompt-for-sender)
489                (list (cons 'From (notmuch-mua-prompt-for-sender)))))
490          ;; Comes from the first message and is applied later.
491          forward-subject
492          ;; List of accumulated message-references of forwarded messages.
493          forward-references
494          ;; List of corresponding message-query.
495          forward-queries)
496     ;; Generate the template for the outgoing message.
497     (notmuch-mua-mail nil "" other-headers nil (notmuch-mua-get-switch-function))
498     (save-excursion
499       ;; Insert all of the forwarded messages.
500       (mapc (lambda (id)
501               (let ((temp-buffer (get-buffer-create
502                                   (concat "*notmuch-fwd-raw-" id "*"))))
503                 ;; Get the raw version of this message in the buffer.
504                 (with-current-buffer temp-buffer
505                   (erase-buffer)
506                   (let ((coding-system-for-read 'no-conversion))
507                     (notmuch--call-process notmuch-command nil t nil
508                                   "show" "--format=raw" id))
509                   ;; Because we process the messages in reverse order,
510                   ;; always generate a forwarded subject, then use the
511                   ;; last (i.e. first) one.
512                   (setq forward-subject (message-make-forward-subject))
513                   (push (message-fetch-field "Message-ID") forward-references)
514                   (push id forward-queries))
515                 ;; Make a copy ready to be forwarded in the
516                 ;; composition buffer.
517                 (message-forward-make-body temp-buffer)
518                 ;; Kill the temporary buffer.
519                 (kill-buffer temp-buffer)))
520             ;; `message-forward-make-body' always puts the message at
521             ;; the top, so do them in reverse order.
522             (reverse messages))
523       ;; Add in the appropriate subject.
524       (save-restriction
525         (message-narrow-to-headers)
526         (message-remove-header "Subject")
527         (message-add-header (concat "Subject: " forward-subject))
528         (message-remove-header "References")
529         (message-add-header (concat "References: "
530                                     (mapconcat 'identity forward-references " "))))
531       ;; Create a buffer-local queue for tag changes triggered when
532       ;; sending the message.
533       (when notmuch-message-forwarded-tags
534         (setq notmuch-message-queued-tag-changes
535               (cl-loop for id in forward-queries
536                        collect
537                        (cons id notmuch-message-forwarded-tags))))
538       ;; `message-forward-make-body' shows the User-agent header.  Hide
539       ;; it again.
540       (message-hide-headers)
541       (set-buffer-modified-p nil))))
542
543 (defun notmuch-mua-new-reply (query-string &optional prompt-for-sender reply-all)
544   "Compose a reply to the message identified by QUERY-STRING.
545
546 If PROMPT-FOR-SENDER is non-nil, the user will be prompted for
547 the From: address first.  If REPLY-ALL is non-nil, the message
548 will be addressed to all recipients of the source message."
549   ;; `select-active-regions' is t by default. The reply insertion code
550   ;; sets the region to the quoted message to make it easy to delete
551   ;; (kill-region or C-w). These two things combine to put the quoted
552   ;; message in the primary selection.
553   ;;
554   ;; This is not what the user wanted and is a privacy risk (accidental
555   ;; pasting of the quoted message). We can avoid some of the problems
556   ;; by let-binding select-active-regions to nil. This fixes if the
557   ;; primary selection was previously in a non-emacs window but not if
558   ;; it was in an emacs window. To avoid the problem in the latter case
559   ;; we deactivate mark.
560   (let ((sender (and prompt-for-sender
561                      (notmuch-mua-prompt-for-sender)))
562         (select-active-regions nil))
563     (notmuch-mua-reply query-string sender reply-all)
564     (deactivate-mark)))
565
566 ;;; Checks
567
568 (defun notmuch-mua-check-no-misplaced-secure-tag ()
569   "Query user if there is a misplaced secure mml tag.
570
571 Emacs message-send will (probably) ignore a secure mml tag unless
572 it is at the start of the body. Returns t if there is no such
573 tag, or the user confirms they mean it."
574   (save-excursion
575     (let ((body-start (progn (message-goto-body) (point))))
576       (goto-char (point-max))
577       (or
578        ;; We are always fine if there is no secure tag.
579        (not (search-backward "<#secure" nil t))
580        ;; There is a secure tag, so it must be at the start of the
581        ;; body, with no secure tag earlier (i.e., in the headers).
582        (and (= (point) body-start)
583             (not (search-backward "<#secure" nil t)))
584        ;; The user confirms they means it.
585        (yes-or-no-p "\
586 There is a <#secure> tag not at the start of the body. It is
587 likely that the message will be sent unsigned and unencrypted.
588 Really send? ")))))
589
590 (defun notmuch-mua-check-secure-tag-has-newline ()
591   "Query if the secure mml tag has a newline following it.
592
593 Emacs message-send will (probably) ignore a correctly placed
594 secure mml tag unless it is followed by a newline. Returns t if
595 any secure tag is followed by a newline, or the user confirms
596 they mean it."
597   (save-excursion
598     (message-goto-body)
599     (or
600      ;; There is no (correctly placed) secure tag.
601      (not (looking-at "<#secure"))
602      ;; The secure tag is followed by a newline.
603      (looking-at "<#secure[^\n>]*>\n")
604      ;; The user confirms they means it.
605      (yes-or-no-p "\
606 The <#secure> tag at the start of the body is not followed by a
607 newline. It is likely that the message will be sent unsigned and
608 unencrypted.  Really send? "))))
609
610 ;;; Finishing commands
611
612 (defun notmuch-mua-send-common (arg &optional exit)
613   (interactive "P")
614   (run-hooks 'notmuch-mua-send-hook)
615   (when (and (notmuch-mua-check-no-misplaced-secure-tag)
616              (notmuch-mua-check-secure-tag-has-newline))
617     (cl-letf (((symbol-function 'message-do-fcc)
618                #'notmuch-maildir-message-do-fcc))
619       (if exit
620           (message-send-and-exit arg)
621         (message-send arg)))))
622
623 (defun notmuch-mua-send-and-exit (&optional arg)
624   (interactive "P")
625   (notmuch-mua-send-common arg t))
626
627 (defun notmuch-mua-send (&optional arg)
628   (interactive "P")
629   (notmuch-mua-send-common arg))
630
631 (defun notmuch-mua-kill-buffer ()
632   (interactive)
633   (message-kill-buffer))
634
635 ;;; _
636
637 (define-mail-user-agent 'notmuch-user-agent
638   'notmuch-mua-mail
639   'notmuch-mua-send-and-exit
640   'notmuch-mua-kill-buffer
641   'notmuch-mua-send-hook)
642
643 ;; Add some more headers to the list that `message-mode' hides when
644 ;; composing a message.
645 (notmuch-mua-add-more-hidden-headers)
646
647 (provide 'notmuch-mua)
648
649 ;;; notmuch-mua.el ends here