]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-mua.el
94fa19d778e7f7f9c85436ae62cc00c4c1182535
[notmuch] / emacs / notmuch-mua.el
1 ;;; notmuch-mua.el --- emacs style mail-user-agent
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 (require 'message)
25 (require 'mm-view)
26 (require 'format-spec)
27
28 (require 'notmuch-lib)
29 (require 'notmuch-address)
30 (require 'notmuch-draft)
31 (require 'notmuch-message)
32
33 (eval-when-compile (require 'cl))
34
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" ())
40
41 ;;
42
43 (defcustom notmuch-mua-send-hook '(notmuch-mua-message-send-hook)
44   "Hook run before sending messages."
45   :type 'hook
46   :group 'notmuch-send
47   :group 'notmuch-hooks)
48
49 (defcustom notmuch-mua-compose-in 'current-window
50   (concat
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'
59 accordingly."
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."))
64   :group 'notmuch-send
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)))
68
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))
78   :group 'notmuch-send)
79
80 (defcustom notmuch-mua-hidden-headers nil
81   "Headers that are added to the `message-mode' hidden headers
82 list."
83   :type '(repeat string)
84   :group 'notmuch-send)
85
86 (defgroup notmuch-reply nil
87   "Replying to messages in notmuch"
88   :group 'notmuch)
89
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)
101
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.
105
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)
118
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.
122
123 This is not used unless `notmuch-mua-attachment-check' is added
124 to `notmuch-mua-send-hook'.")
125
126 ;;
127
128 (defun notmuch-mua-attachment-check ()
129   "Signal an error if the message text indicates that an
130 attachment is expected but no MML referencing an attachment is
131 found.
132
133 Typically this is added to `notmuch-mua-send-hook'."
134   (when (and
135          ;; When the message mentions attachment...
136          (save-excursion
137            (message-goto-body)
138            (loop while (re-search-forward notmuch-mua-attachment-regexp (point-max) t)
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))))
147                  return t
148                  finally return nil))
149          ;; ...but doesn't have a part with a filename...
150          (save-excursion
151            (message-goto-body)
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")))
157
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)
161          'switch-to-buffer)
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'"))))
167
168 (defun notmuch-mua-maybe-set-window-dedicated ()
169   "Set the selected window as dedicated according to
170 `notmuch-mua-compose-in'."
171   (when (or (eq notmuch-mua-compose-in 'new-frame)
172             (eq notmuch-mua-compose-in 'new-window))
173     (set-window-dedicated-p (selected-window) t)))
174
175 (defun notmuch-mua-user-agent-full ()
176   "Generate a `User-Agent:' string suitable for notmuch."
177   (concat (notmuch-mua-user-agent-notmuch)
178           " "
179           (notmuch-mua-user-agent-emacs)))
180
181 (defun notmuch-mua-user-agent-notmuch ()
182   "Generate a `User-Agent:' string suitable for notmuch."
183   (let ((notmuch-version (if (string= notmuch-emacs-version "unknown")
184                              (notmuch-cli-version)
185                            notmuch-emacs-version)))
186     (concat "Notmuch/" notmuch-version " (https://notmuchmail.org)")))
187
188 (defun notmuch-mua-user-agent-emacs ()
189   "Generate a `User-Agent:' string suitable for notmuch."
190   (concat "Emacs/" emacs-version " (" system-configuration ")"))
191
192 (defun notmuch-mua-add-more-hidden-headers ()
193   "Add some headers to the list that are hidden by default."
194   (mapc (lambda (header)
195           (when (not (member header message-hidden-headers))
196             (push header message-hidden-headers)))
197         notmuch-mua-hidden-headers))
198
199 (defun notmuch-mua-reply-crypto (parts)
200   "Add mml sign-encrypt flag if any part of original message is encrypted."
201   (loop for part in parts
202         if (notmuch-match-content-type (plist-get part :content-type) "multipart/encrypted")
203           do (mml-secure-message-sign-encrypt)
204         else if (notmuch-match-content-type (plist-get part :content-type) "multipart/*")
205           do (notmuch-mua-reply-crypto (plist-get part :content))))
206
207 ;; There is a bug in emacs 23's message.el that results in a newline
208 ;; not being inserted after the References header, so the next header
209 ;; is concatenated to the end of it. This function fixes the problem,
210 ;; while guarding against the possibility that some current or future
211 ;; version of emacs has the bug fixed.
212 (defun notmuch-mua-insert-references (original-func header references)
213   (funcall original-func header references)
214   (unless (bolp) (insert "\n")))
215
216 (defun notmuch-mua-reply (query-string &optional sender reply-all)
217   (let ((args '("reply" "--format=sexp" "--format-version=4"))
218         (process-crypto notmuch-show-process-crypto)
219         reply
220         original)
221     (when process-crypto
222       (setq args (append args '("--decrypt=true"))))
223
224     (if reply-all
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
229     ;; Get the reply object as SEXP, and parse it into an elisp object.
230     (setq reply (apply #'notmuch-call-notmuch-sexp args))
231
232     ;; Extract the original message to simplify the following code.
233     (setq original (plist-get reply :original))
234
235     ;; Extract the headers of both the reply and the original message.
236     (let* ((original-headers (plist-get original :headers))
237            (reply-headers (plist-get reply :reply-headers)))
238
239       ;; If sender is non-nil, set the From: header to its value.
240       (when sender
241         (plist-put reply-headers :From sender))
242       (let
243           ;; Overlay the composition window on that being used to read
244           ;; the original message.
245           ((same-window-regexps '("\\*mail .*")))
246
247         ;; We modify message-header-format-alist to get around a bug in message.el.
248         ;; See the comment above on notmuch-mua-insert-references.
249         (let ((message-header-format-alist
250                (loop for pair in message-header-format-alist
251                      if (eq (car pair) 'References)
252                      collect (cons 'References
253                                    (apply-partially
254                                     'notmuch-mua-insert-references
255                                     (cdr pair)))
256                      else
257                      collect pair)))
258           (notmuch-mua-mail (plist-get reply-headers :To)
259                             (notmuch-sanitize (plist-get reply-headers :Subject))
260                             (notmuch-headers-plist-to-alist reply-headers)
261                             nil (notmuch-mua-get-switch-function))))
262
263       ;; Create a buffer-local queue for tag changes triggered when sending the reply
264       (when notmuch-message-replied-tags
265         (setq-local notmuch-message-queued-tag-changes
266                     (list (cons query-string notmuch-message-replied-tags))))
267
268       ;; Insert the message body - but put it in front of the signature
269       ;; if one is present, and after any other content
270       ;; message*setup-hooks may have added to the message body already.
271       (save-restriction
272         (message-goto-body)
273         (narrow-to-region (point) (point-max))
274         (goto-char (point-max))
275         (if (re-search-backward message-signature-separator nil t)
276             (if message-signature-insert-empty-line
277                 (forward-line -1))
278           (goto-char (point-max))))
279
280       (let ((from (plist-get original-headers :From))
281             (date (plist-get original-headers :Date))
282             (start (point)))
283
284         ;; notmuch-mua-cite-function constructs a citation line based
285         ;; on the From and Date headers of the original message, which
286         ;; are assumed to be in the buffer.
287         (insert "From: " from "\n")
288         (insert "Date: " date "\n\n")
289
290         (insert (with-temp-buffer
291                   (let
292                       ;; Don't attempt to clean up messages, excerpt
293                       ;; citations, etc. in the original message before
294                       ;; quoting.
295                       ((notmuch-show-insert-text/plain-hook nil)
296                        ;; Don't omit long parts.
297                        (notmuch-show-max-text-part-size 0)
298                        ;; Insert headers for parts as appropriate for replying.
299                        (notmuch-show-insert-header-p-function notmuch-mua-reply-insert-header-p-function)
300                        ;; Ensure that any encrypted parts are
301                        ;; decrypted during the generation of the reply
302                        ;; text.
303                        (notmuch-show-process-crypto process-crypto)
304                        ;; Don't indent multipart sub-parts.
305                        (notmuch-show-indent-multipart nil))
306                     ;; We don't want sigstatus buttons (an information leak and usually wrong anyway).
307                     (letf (((symbol-function 'notmuch-crypto-insert-sigstatus-button) #'ignore)
308                            ((symbol-function 'notmuch-crypto-insert-encstatus-button) #'ignore))
309                           (notmuch-show-insert-body original (plist-get original :body) 0)
310                           (buffer-substring-no-properties (point-min) (point-max))))))
311
312         (set-mark (point))
313         (goto-char start)
314         ;; Quote the original message according to the user's configured style.
315         (funcall notmuch-mua-cite-function)))
316
317     ;; Crypto processing based crypto content of the original message
318     (when process-crypto
319       (notmuch-mua-reply-crypto (plist-get original :body))))
320
321   ;; Push mark right before signature, if any.
322   (message-goto-signature)
323   (unless (eobp)
324     (end-of-line -1))
325   (push-mark)
326
327   (message-goto-body)
328   (set-buffer-modified-p nil))
329
330 (define-derived-mode notmuch-message-mode message-mode "Message[Notmuch]"
331   "Notmuch message composition mode. Mostly like `message-mode'"
332   (notmuch-address-setup))
333
334 (put 'notmuch-message-mode 'flyspell-mode-predicate 'mail-mode-flyspell-verify)
335
336 (define-key notmuch-message-mode-map (kbd "C-c C-c") #'notmuch-mua-send-and-exit)
337 (define-key notmuch-message-mode-map (kbd "C-c C-s") #'notmuch-mua-send)
338 (define-key notmuch-message-mode-map (kbd "C-c C-p") #'notmuch-draft-postpone)
339 (define-key notmuch-message-mode-map (kbd "C-x C-s") #'notmuch-draft-save)
340
341 (defun notmuch-mua-pop-to-buffer (name switch-function)
342   "Pop to buffer NAME, and warn if it already exists and is
343 modified. This function is notmuch addaptation of
344 `message-pop-to-buffer'."
345   (let ((buffer (get-buffer name)))
346     (if (and buffer
347              (buffer-name buffer))
348         (let ((window (get-buffer-window buffer 0)))
349           (if window
350               ;; Raise the frame already displaying the message buffer.
351               (progn
352                 (select-frame-set-input-focus (window-frame window))
353                 (select-window window))
354             (funcall switch-function buffer)
355             (set-buffer buffer))
356           (when (and (buffer-modified-p)
357                      (not (prog1
358                               (y-or-n-p
359                                "Message already being composed; erase? ")
360                             (message nil))))
361             (error "Message being composed")))
362       (funcall switch-function name)
363       (set-buffer name))
364     (erase-buffer)
365     (notmuch-message-mode)))
366
367 (defun notmuch-mua-mail (&optional to subject other-headers continue
368                                    switch-function yank-action send-actions
369                                    return-action &rest ignored)
370   "Invoke the notmuch mail composition window."
371   (interactive)
372
373   (when notmuch-mua-user-agent-function
374     (let ((user-agent (funcall notmuch-mua-user-agent-function)))
375       (when (not (string= "" user-agent))
376         (push (cons 'User-Agent user-agent) other-headers))))
377
378   (unless (assq 'From other-headers)
379     (push (cons 'From (message-make-from
380                        (notmuch-user-name) (notmuch-user-primary-email))) other-headers))
381
382   (notmuch-mua-pop-to-buffer (message-buffer-name "mail" to)
383                              (or switch-function (notmuch-mua-get-switch-function)))
384   (let ((headers
385          (append
386           ;; The following is copied from `message-mail'
387           `((To . ,(or to "")) (Subject . ,(or subject "")))
388           ;; C-h f compose-mail says that headers should be specified as
389           ;; (string . value); however all the rest of message expects
390           ;; headers to be symbols, not strings (eg message-header-format-alist).
391           ;; https://lists.gnu.org/archive/html/emacs-devel/2011-01/msg00337.html
392           ;; We need to convert any string input, eg from rmail-start-mail.
393           (dolist (h other-headers other-headers)
394             (if (stringp (car h)) (setcar h (intern (capitalize (car h))))))))
395         (args (list yank-action send-actions))
396         ;; Cause `message-setup-1' to do things relevant for mail,
397         ;; such as observe `message-default-mail-headers'.
398         (message-this-is-mail t))
399     ;; message-setup-1 in Emacs 23 does not accept return-action
400     ;; argument. Pass it only if it is supplied by the caller. This
401     ;; will never be the case when we're called by `compose-mail' in
402     ;; Emacs 23.
403     (when return-action (nconc args '(return-action)))
404     (apply 'message-setup-1 headers args))
405   (notmuch-fcc-header-setup)
406   (message-sort-headers)
407   (message-hide-headers)
408   (set-buffer-modified-p nil)
409   (notmuch-mua-maybe-set-window-dedicated)
410
411   (message-goto-to))
412
413 (defcustom notmuch-identities nil
414   "Identities that can be used as the From: address when composing a new message.
415
416 If this variable is left unset, then a list will be constructed from the
417 name and addresses configured in the notmuch configuration file."
418   :type '(repeat string)
419   :group 'notmuch-send)
420
421 (defcustom notmuch-always-prompt-for-sender nil
422   "Always prompt for the From: address when composing or forwarding a message.
423
424 This is not taken into account when replying to a message, because in that case
425 the From: header is already filled in by notmuch."
426   :type 'boolean
427   :group 'notmuch-send)
428
429 (defvar notmuch-mua-sender-history nil)
430
431 ;; Workaround: Running `ido-completing-read' in emacs 23.1, 23.2 and 23.3
432 ;; without some explicit initialization fill freeze the operation.
433 ;; Hence, we advice `ido-completing-read' to ensure required initialization
434 ;; is done.
435 (if (and (= emacs-major-version 23) (< emacs-minor-version 4))
436     (defadvice ido-completing-read (before notmuch-ido-mode-init activate)
437       (ido-init-completion-maps)
438       (add-hook 'minibuffer-setup-hook 'ido-minibuffer-setup)
439       (add-hook 'choose-completion-string-functions
440                 'ido-choose-completion-string)
441       (ad-disable-advice 'ido-completing-read 'before 'notmuch-ido-mode-init)
442       (ad-activate 'ido-completing-read)))
443
444 (defun notmuch-mua-prompt-for-sender ()
445   "Prompt for a sender from the user's configured identities."
446   (if notmuch-identities
447       (ido-completing-read "Send mail from: " notmuch-identities
448                            nil nil nil 'notmuch-mua-sender-history
449                            (car notmuch-identities))
450     (let* ((name (notmuch-user-name))
451            (addrs (cons (notmuch-user-primary-email)
452                         (notmuch-user-other-email)))
453            (address
454             (ido-completing-read (concat "Sender address for " name ": ") addrs
455                                  nil nil nil 'notmuch-mua-sender-history
456                                  (car addrs))))
457       (message-make-from name address))))
458
459 (put 'notmuch-mua-new-mail 'notmuch-prefix-doc "... and prompt for sender")
460 (defun notmuch-mua-new-mail (&optional prompt-for-sender)
461   "Compose new mail.
462
463 If PROMPT-FOR-SENDER is non-nil, the user will be prompted for
464 the From: address first."
465   (interactive "P")
466   (let ((other-headers
467          (when (or prompt-for-sender notmuch-always-prompt-for-sender)
468            (list (cons 'From (notmuch-mua-prompt-for-sender))))))
469     (notmuch-mua-mail nil nil other-headers nil (notmuch-mua-get-switch-function))))
470
471 (defun notmuch-mua-new-forward-messages (messages &optional prompt-for-sender)
472   "Compose a new message forwarding MESSAGES.
473
474 If PROMPT-FOR-SENDER is non-nil, the user will be prompteed for
475 the From: address."
476   (let* ((other-headers
477           (when (or prompt-for-sender notmuch-always-prompt-for-sender)
478             (list (cons 'From (notmuch-mua-prompt-for-sender)))))
479          forward-subject  ;; Comes from the first message and is
480                           ;; applied later.
481          forward-references ;; List of accumulated message-references of forwarded messages
482          forward-queries) ;; List of corresponding message-query
483
484     ;; Generate the template for the outgoing message.
485     (notmuch-mua-mail nil "" other-headers nil (notmuch-mua-get-switch-function))
486
487     (save-excursion
488       ;; Insert all of the forwarded messages.
489       (mapc (lambda (id)
490               (let ((temp-buffer (get-buffer-create
491                                   (concat "*notmuch-fwd-raw-" id "*"))))
492                 ;; Get the raw version of this message in the buffer.
493                 (with-current-buffer temp-buffer
494                   (erase-buffer)
495                   (let ((coding-system-for-read 'no-conversion))
496                     (call-process notmuch-command nil t nil "show" "--format=raw" id))
497                   ;; Because we process the messages in reverse order,
498                   ;; always generate a forwarded subject, then use the
499                   ;; last (i.e. first) one.
500                   (setq forward-subject (message-make-forward-subject))
501                   (push (message-fetch-field "Message-ID") forward-references)
502                   (push id forward-queries))
503                 ;; Make a copy ready to be forwarded in the
504                 ;; composition buffer.
505                 (message-forward-make-body temp-buffer)
506                 ;; Kill the temporary buffer.
507                 (kill-buffer temp-buffer)))
508             ;; `message-forward-make-body' always puts the message at
509             ;; the top, so do them in reverse order.
510             (reverse messages))
511
512       ;; Add in the appropriate subject.
513       (save-restriction
514         (message-narrow-to-headers)
515         (message-remove-header "Subject")
516         (message-add-header (concat "Subject: " forward-subject))
517         (message-remove-header "References")
518         (message-add-header (concat "References: "
519                                     (mapconcat 'identity forward-references " "))))
520
521       ;; Create a buffer-local queue for tag changes triggered when sending the message
522       (when notmuch-message-forwarded-tags
523         (setq-local notmuch-message-queued-tag-changes
524                     (loop for id in forward-queries
525                           collect
526                           (cons id
527                                 notmuch-message-forwarded-tags))))
528
529       ;; `message-forward-make-body' shows the User-agent header.  Hide
530       ;; it again.
531       (message-hide-headers)
532       (set-buffer-modified-p nil))))
533
534 (defun notmuch-mua-new-reply (query-string &optional prompt-for-sender reply-all)
535   "Compose a reply to the message identified by QUERY-STRING.
536
537 If PROMPT-FOR-SENDER is non-nil, the user will be prompted for
538 the From: address first.  If REPLY-ALL is non-nil, the message
539 will be addressed to all recipients of the source message."
540
541 ;; In current emacs (24.3) select-active-regions is set to t by
542 ;; default. The reply insertion code sets the region to the quoted
543 ;; message to make it easy to delete (kill-region or C-w). These two
544 ;; things combine to put the quoted message in the primary selection.
545 ;;
546 ;; This is not what the user wanted and is a privacy risk (accidental
547 ;; pasting of the quoted message). We can avoid some of the problems
548 ;; by let-binding select-active-regions to nil. This fixes if the
549 ;; primary selection was previously in a non-emacs window but not if
550 ;; it was in an emacs window. To avoid the problem in the latter case
551 ;; we deactivate mark.
552
553   (let ((sender
554          (when prompt-for-sender
555            (notmuch-mua-prompt-for-sender)))
556         (select-active-regions nil))
557     (notmuch-mua-reply query-string sender reply-all)
558     (deactivate-mark)))
559
560 (defun notmuch-mua-check-no-misplaced-secure-tag ()
561   "Query user if there is a misplaced secure mml tag.
562
563 Emacs message-send will (probably) ignore a secure mml tag unless
564 it is at the start of the body. Returns t if there is no such
565 tag, or the user confirms they mean it."
566   (save-excursion
567     (let ((body-start (progn (message-goto-body) (point))))
568       (goto-char (point-max))
569       (or
570        ;; We are always fine if there is no secure tag.
571        (not (search-backward "<#secure" nil 't))
572        ;; There is a secure tag, so it must be at the start of the
573        ;; body, with no secure tag earlier (i.e., in the headers).
574        (and (= (point) body-start)
575             (not (search-backward "<#secure" nil 't)))
576        ;; The user confirms they means it.
577        (yes-or-no-p "\
578 There is a <#secure> tag not at the start of the body. It is
579 likely that the message will be sent unsigned and unencrypted.
580 Really send? ")))))
581
582 (defun notmuch-mua-check-secure-tag-has-newline ()
583   "Query if the secure mml tag has a newline following it.
584
585 Emacs message-send will (probably) ignore a correctly placed
586 secure mml tag unless it is followed by a newline. Returns t if
587 any secure tag is followed by a newline, or the user confirms
588 they mean it."
589   (save-excursion
590     (message-goto-body)
591     (or
592      ;; There is no (correctly placed) secure tag.
593      (not (looking-at "<#secure"))
594      ;; The secure tag is followed by a newline.
595      (looking-at "<#secure[^\n>]*>\n")
596      ;; The user confirms they means it.
597      (yes-or-no-p "\
598 The <#secure> tag at the start of the body is not followed by a
599 newline. It is likely that the message will be sent unsigned and
600 unencrypted.  Really send? "))))
601
602 (defun notmuch-mua-send-common (arg &optional exit)
603   (interactive "P")
604   (run-hooks 'notmuch-mua-send-hook)
605   (when (and (notmuch-mua-check-no-misplaced-secure-tag)
606              (notmuch-mua-check-secure-tag-has-newline))
607     (letf (((symbol-function 'message-do-fcc) #'notmuch-maildir-message-do-fcc))
608           (if exit
609               (message-send-and-exit arg)
610             (message-send arg)))))
611
612 (defun notmuch-mua-send-and-exit (&optional arg)
613   (interactive "P")
614   (notmuch-mua-send-common arg 't))
615
616 (defun notmuch-mua-send (&optional arg)
617   (interactive "P")
618   (notmuch-mua-send-common arg))
619
620 (defun notmuch-mua-kill-buffer ()
621   (interactive)
622   (message-kill-buffer))
623
624 (defun notmuch-mua-message-send-hook ()
625   "The default function used for `notmuch-mua-send-hook', this
626 simply runs the corresponding `message-mode' hook functions."
627   (run-hooks 'message-send-hook))
628
629 ;;
630
631 (define-mail-user-agent 'notmuch-user-agent
632   'notmuch-mua-mail 'notmuch-mua-send-and-exit
633   'notmuch-mua-kill-buffer 'notmuch-mua-send-hook)
634
635 ;; Add some more headers to the list that `message-mode' hides when
636 ;; composing a message.
637 (notmuch-mua-add-more-hidden-headers)
638
639 ;;
640
641 (provide 'notmuch-mua)
642
643 ;;; notmuch-mua.el ends here