]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-mua.el
bf62b65691810f491cb9f98d04e0acc760a4a3ad
[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 duplicate)
241   (let* ((duparg (and duplicate (list (format "--duplicate=%d" duplicate))))
242          (args `("reply" "--format=sexp" "--format-version=5" ,@duparg))
243          (process-crypto notmuch-show-process-crypto)
244          reply
245          original)
246     (when process-crypto
247       (setq args (append args '("--decrypt=true"))))
248     (if reply-all
249         (setq args (append args '("--reply-to=all")))
250       (setq args (append args '("--reply-to=sender"))))
251     (setq args (append args (list query-string)))
252     ;; Get the reply object as SEXP, and parse it into an elisp object.
253     (setq reply (apply #'notmuch-call-notmuch-sexp args))
254     ;; Extract the original message to simplify the following code.
255     (setq original (plist-get reply :original))
256     ;; Extract the headers of both the reply and the original message.
257     (let* ((original-headers (plist-get original :headers))
258            (reply-headers (plist-get reply :reply-headers)))
259       ;; If sender is non-nil, set the From: header to its value.
260       (when sender
261         (plist-put reply-headers :From sender))
262       (let
263           ;; Overlay the composition window on that being used to read
264           ;; the original message.
265           ((same-window-regexps '("\\*mail .*")))
266         ;; We modify message-header-format-alist to get around
267         ;; a bug in message.el.  See the comment above on
268         ;; notmuch-mua-insert-references.
269         (let ((message-header-format-alist
270                (cl-loop for pair in message-header-format-alist
271                         if (eq (car pair) 'References)
272                         collect (cons 'References
273                                       (apply-partially
274                                        'notmuch-mua-insert-references
275                                        (cdr pair)))
276                         else
277                         collect pair)))
278           (notmuch-mua-mail (plist-get reply-headers :To)
279                             (notmuch-sanitize (plist-get reply-headers :Subject))
280                             (notmuch-headers-plist-to-alist reply-headers)
281                             nil (notmuch-mua-get-switch-function))))
282       ;; Create a buffer-local queue for tag changes triggered when
283       ;; sending the reply.
284       (when notmuch-message-replied-tags
285         (setq notmuch-message-queued-tag-changes
286               (list (cons query-string notmuch-message-replied-tags))))
287       ;; Insert the message body - but put it in front of the signature
288       ;; if one is present, and after any other content
289       ;; message*setup-hooks may have added to the message body already.
290       (save-restriction
291         (message-goto-body)
292         (narrow-to-region (point) (point-max))
293         (goto-char (point-max))
294         (if (re-search-backward message-signature-separator nil t)
295             (when message-signature-insert-empty-line
296               (forward-line -1))
297           (goto-char (point-max))))
298       (let ((from (plist-get original-headers :From))
299             (date (plist-get original-headers :Date))
300             (start (point)))
301         ;; notmuch-mua-cite-function constructs a citation line based
302         ;; on the From and Date headers of the original message, which
303         ;; are assumed to be in the buffer.
304         (insert "From: " from "\n")
305         (insert "Date: " date "\n\n")
306         (insert
307          (with-temp-buffer
308            (let
309                ;; Don't attempt to clean up messages, excerpt
310                ;; citations, etc. in the original message before
311                ;; quoting.
312                ((notmuch-show-insert-text/plain-hook nil)
313                 ;; Don't omit long parts.
314                 (notmuch-show-max-text-part-size 0)
315                 ;; Insert headers for parts as appropriate for replying.
316                 (notmuch-show-insert-header-p-function
317                  notmuch-mua-reply-insert-header-p-function)
318                 ;; Ensure that any encrypted parts are
319                 ;; decrypted during the generation of the reply
320                 ;; text.
321                 (notmuch-show-process-crypto process-crypto)
322                 ;; Don't indent multipart sub-parts.
323                 (notmuch-show-indent-multipart nil)
324                 ;; Stop certain mime types from being inlined
325                 (mm-inline-override-types (notmuch--inline-override-types)))
326              ;; We don't want sigstatus buttons (an information leak and usually wrong anyway).
327              (cl-letf (((symbol-function 'notmuch-crypto-insert-sigstatus-button) #'ignore)
328                        ((symbol-function 'notmuch-crypto-insert-encstatus-button) #'ignore))
329                (notmuch-show-insert-body original (plist-get original :body) 0)
330                (buffer-substring-no-properties (point-min) (point-max))))))
331         (set-mark (point))
332         (goto-char start)
333         ;; Quote the original message according to the user's configured style.
334         (funcall notmuch-mua-cite-function)))
335     ;; Crypto processing based crypto content of the original message
336     (when process-crypto
337       (notmuch-mua-reply-crypto (plist-get original :body))))
338   ;; Push mark right before signature, if any.
339   (message-goto-signature)
340   (unless (eobp)
341     (end-of-line -1))
342   (push-mark)
343   (message-goto-body)
344   (set-buffer-modified-p nil))
345
346 ;;; Mode and keymap
347
348 (defvar notmuch-message-mode-map
349   (let ((map (make-sparse-keymap)))
350     (define-key map [remap message-send-and-exit] #'notmuch-mua-send-and-exit)
351     (define-key map [remap message-send] #'notmuch-mua-send)
352     (define-key map (kbd "C-c C-p") #'notmuch-draft-postpone)
353     (define-key map (kbd "C-x C-s") #'notmuch-draft-save)
354     map)
355   "Keymap for `notmuch-message-mode'.")
356
357 (define-derived-mode notmuch-message-mode message-mode "Message[Notmuch]"
358   "Notmuch message composition mode. Mostly like `message-mode'."
359   (notmuch-address-setup))
360
361 (put 'notmuch-message-mode 'flyspell-mode-predicate 'mail-mode-flyspell-verify)
362
363 ;;; New messages
364
365 (defun notmuch-mua-pop-to-buffer (name switch-function)
366   "Pop to buffer NAME, and warn if it already exists and is modified.
367 Like `message-pop-to-buffer' but enable `notmuch-message-mode'
368 instead of `message-mode' and SWITCH-FUNCTION is mandatory."
369   (let ((buffer (get-buffer name)))
370     (if (and buffer
371              (buffer-name buffer))
372         (let ((window (get-buffer-window buffer 0)))
373           (if window
374               ;; Raise the frame already displaying the message buffer.
375               (progn
376                 (select-frame-set-input-focus (window-frame window))
377                 (select-window window))
378             (funcall switch-function buffer)
379             (set-buffer buffer))
380           (when (buffer-modified-p)
381             (if (y-or-n-p "Message already being composed; erase? ")
382                 (message nil)
383               (error "Message being composed"))))
384       (funcall switch-function name)
385       (set-buffer name))
386     (erase-buffer)
387     (notmuch-message-mode)))
388
389 (defun notmuch-mua--remove-dont-reply-to-names ()
390   (when-let* ((nr (if (functionp message-dont-reply-to-names)
391                       message-dont-reply-to-names
392                     (gmm-regexp-concat message-dont-reply-to-names)))
393               (nr-filter
394                (if (functionp nr)
395                    (lambda (mail) (and (not (funcall nr mail)) mail))
396                  (lambda (mail) (and (not (string-match-p nr mail)) mail)))))
397     (dolist (header '("To" "Cc"))
398       (when-let ((v (message-fetch-field header)))
399         (let* ((tokens (mapcar #'string-trim (message-tokenize-header v)))
400                (good-tokens (delq nil (mapcar nr-filter tokens)))
401                (addr (and good-tokens (mapconcat #'identity good-tokens ", "))))
402           (message-replace-header header addr))))))
403
404 ;;;#autoload
405 (defun notmuch-mua-mail (&optional to subject other-headers _continue
406                                    switch-function yank-action send-actions
407                                    return-action &rest _ignored)
408   "Invoke the notmuch mail composition window.
409
410 The position of point when the function returns differs depending
411 on the values of TO and SUBJECT.  If both are non-nil, point is
412 moved to the message's body.  If SUBJECT is nil but TO isn't,
413 point is moved to the \"Subject:\" header.  Otherwise, point is
414 moved to the \"To:\" header."
415   (interactive)
416   (when notmuch-mua-user-agent-function
417     (let ((user-agent (funcall notmuch-mua-user-agent-function)))
418       (unless (string-empty-p user-agent)
419         (push (cons 'User-Agent user-agent) other-headers))))
420   (notmuch-mua-pop-to-buffer (message-buffer-name "mail" to)
421                              (or switch-function
422                                  (notmuch-mua-get-switch-function)))
423   (let ((headers
424          (append
425           ;; The following is copied from `message-mail'
426           `((To . ,(or to "")) (Subject . ,(or subject "")))
427           ;; C-h f compose-mail says that headers should be specified as
428           ;; (string . value); however all the rest of message expects
429           ;; headers to be symbols, not strings (eg message-header-format-alist).
430           ;; https://lists.gnu.org/archive/html/emacs-devel/2011-01/msg00337.html
431           ;; We need to convert any string input, eg from rmail-start-mail.
432           (dolist (h other-headers other-headers)
433             (when (stringp (car h))
434               (setcar h (intern (capitalize (car h))))))))
435         ;; Cause `message-setup-1' to do things relevant for mail,
436         ;; such as observe `message-default-mail-headers'.
437         (message-this-is-mail t))
438     (unless (assq 'From headers)
439       (push (cons 'From (message-make-from
440                          (notmuch-user-name)
441                          (notmuch-user-primary-email)))
442             headers))
443     (message-setup-1 headers yank-action send-actions return-action))
444   (notmuch-fcc-header-setup)
445   (notmuch-mua--remove-dont-reply-to-names)
446   (message-sort-headers)
447   (message-hide-headers)
448   (set-buffer-modified-p nil)
449   (notmuch-mua-maybe-set-window-dedicated)
450   (cond
451    ((and to subject) (message-goto-body))
452    (to (message-goto-subject))
453    (t (message-goto-to))))
454
455 (defvar notmuch-mua-sender-history nil)
456
457 (defun notmuch-mua-prompt-for-sender ()
458   "Prompt for a sender from the user's configured identities."
459   (if notmuch-identities
460       (completing-read "Send mail from: " notmuch-identities
461                        nil nil nil 'notmuch-mua-sender-history
462                        (car notmuch-identities))
463     (let* ((name (notmuch-user-name))
464            (addrs (cons (notmuch-user-primary-email)
465                         (notmuch-user-other-email)))
466            (address
467             (completing-read (concat "Sender address for " name ": ") addrs
468                              nil nil nil 'notmuch-mua-sender-history
469                              (car addrs))))
470       (message-make-from name address))))
471
472 (put 'notmuch-mua-new-mail 'notmuch-prefix-doc "... and prompt for sender")
473 (defun notmuch-mua-new-mail (&optional prompt-for-sender)
474   "Compose new mail.
475
476 If PROMPT-FOR-SENDER is non-nil, the user will be prompted for
477 the From: address first."
478   (interactive "P")
479   (let ((other-headers
480          (and (or prompt-for-sender notmuch-always-prompt-for-sender)
481               (list (cons 'From (notmuch-mua-prompt-for-sender))))))
482     (notmuch-mua-mail nil nil other-headers nil (notmuch-mua-get-switch-function))))
483
484 (defun notmuch-mua-new-forward-messages (messages &optional prompt-for-sender)
485   "Compose a new message forwarding MESSAGES.
486
487 If PROMPT-FOR-SENDER is non-nil, the user will be prompteed for
488 the From: address."
489   (let* ((other-headers
490           (and (or prompt-for-sender notmuch-always-prompt-for-sender)
491                (list (cons 'From (notmuch-mua-prompt-for-sender)))))
492          ;; Comes from the first message and is applied later.
493          forward-subject
494          ;; List of accumulated message-references of forwarded messages.
495          forward-references
496          ;; List of corresponding message-query.
497          forward-queries)
498     ;; Generate the template for the outgoing message.
499     (notmuch-mua-mail nil "" other-headers nil (notmuch-mua-get-switch-function))
500     (save-excursion
501       ;; Insert all of the forwarded messages.
502       (mapc (lambda (id)
503               (let ((temp-buffer (get-buffer-create
504                                   (concat "*notmuch-fwd-raw-" id "*"))))
505                 ;; Get the raw version of this message in the buffer.
506                 (with-current-buffer temp-buffer
507                   (erase-buffer)
508                   (let ((coding-system-for-read 'no-conversion))
509                     (notmuch--call-process notmuch-command nil t nil
510                                   "show" "--format=raw" id))
511                   ;; Because we process the messages in reverse order,
512                   ;; always generate a forwarded subject, then use the
513                   ;; last (i.e. first) one.
514                   (setq forward-subject (message-make-forward-subject))
515                   (push (message-fetch-field "Message-ID") forward-references)
516                   (push id forward-queries))
517                 ;; Make a copy ready to be forwarded in the
518                 ;; composition buffer.
519                 (message-forward-make-body temp-buffer)
520                 ;; Kill the temporary buffer.
521                 (kill-buffer temp-buffer)))
522             ;; `message-forward-make-body' always puts the message at
523             ;; the top, so do them in reverse order.
524             (reverse messages))
525       ;; Add in the appropriate subject.
526       (save-restriction
527         (message-narrow-to-headers)
528         (message-remove-header "Subject")
529         (message-add-header (concat "Subject: " forward-subject))
530         (message-remove-header "References")
531         (message-add-header (concat "References: "
532                                     (mapconcat 'identity forward-references " "))))
533       ;; Create a buffer-local queue for tag changes triggered when
534       ;; sending the message.
535       (when notmuch-message-forwarded-tags
536         (setq notmuch-message-queued-tag-changes
537               (cl-loop for id in forward-queries
538                        collect
539                        (cons id notmuch-message-forwarded-tags))))
540       ;; `message-forward-make-body' shows the User-agent header.  Hide
541       ;; it again.
542       (message-hide-headers)
543       (set-buffer-modified-p nil))))
544
545 (defun notmuch-mua-new-reply (query-string &optional prompt-for-sender reply-all duplicate)
546   "Compose a reply to the message identified by QUERY-STRING.
547
548 If PROMPT-FOR-SENDER is non-nil, the user will be prompted for
549 the From: address first.  If REPLY-ALL is non-nil, the message
550 will be addressed to all recipients of the source message.  If
551 DUPLICATE is non-nil, based the reply on that duplicate file"
552   ;; `select-active-regions' is t by default. The reply insertion code
553   ;; sets the region to the quoted message to make it easy to delete
554   ;; (kill-region or C-w). These two things combine to put the quoted
555   ;; message in the primary selection.
556   ;;
557   ;; This is not what the user wanted and is a privacy risk (accidental
558   ;; pasting of the quoted message). We can avoid some of the problems
559   ;; by let-binding select-active-regions to nil. This fixes if the
560   ;; primary selection was previously in a non-emacs window but not if
561   ;; it was in an emacs window. To avoid the problem in the latter case
562   ;; we deactivate mark.
563   (let ((sender (and prompt-for-sender
564                      (notmuch-mua-prompt-for-sender)))
565         (select-active-regions nil))
566     (notmuch-mua-reply query-string sender reply-all duplicate)
567     (deactivate-mark)))
568
569 ;;; Checks
570
571 (defun notmuch-mua-check-no-misplaced-secure-tag ()
572   "Query user if there is a misplaced secure mml tag.
573
574 Emacs message-send will (probably) ignore a secure mml tag unless
575 it is at the start of the body. Returns t if there is no such
576 tag, or the user confirms they mean it."
577   (save-excursion
578     (let ((body-start (progn (message-goto-body) (point))))
579       (goto-char (point-max))
580       (or
581        ;; We are always fine if there is no secure tag.
582        (not (search-backward "<#secure" nil t))
583        ;; There is a secure tag, so it must be at the start of the
584        ;; body, with no secure tag earlier (i.e., in the headers).
585        (and (= (point) body-start)
586             (not (search-backward "<#secure" nil t)))
587        ;; The user confirms they means it.
588        (yes-or-no-p "\
589 There is a <#secure> tag not at the start of the body. It is
590 likely that the message will be sent unsigned and unencrypted.
591 Really send? ")))))
592
593 (defun notmuch-mua-check-secure-tag-has-newline ()
594   "Query if the secure mml tag has a newline following it.
595
596 Emacs message-send will (probably) ignore a correctly placed
597 secure mml tag unless it is followed by a newline. Returns t if
598 any secure tag is followed by a newline, or the user confirms
599 they mean it."
600   (save-excursion
601     (message-goto-body)
602     (or
603      ;; There is no (correctly placed) secure tag.
604      (not (looking-at "<#secure"))
605      ;; The secure tag is followed by a newline.
606      (looking-at "<#secure[^\n>]*>\n")
607      ;; The user confirms they means it.
608      (yes-or-no-p "\
609 The <#secure> tag at the start of the body is not followed by a
610 newline. It is likely that the message will be sent unsigned and
611 unencrypted.  Really send? "))))
612
613 ;;; Finishing commands
614
615 (defun notmuch-mua-send-common (arg &optional exit)
616   (interactive "P")
617   (run-hooks 'notmuch-mua-send-hook)
618   (when (and (notmuch-mua-check-no-misplaced-secure-tag)
619              (notmuch-mua-check-secure-tag-has-newline))
620     (cl-letf (((symbol-function 'message-do-fcc)
621                #'notmuch-maildir-message-do-fcc))
622       (if exit
623           (message-send-and-exit arg)
624         (message-send arg)))))
625
626 ;;;#autoload
627 (defun notmuch-mua-send-and-exit (&optional arg)
628   (interactive "P")
629   (notmuch-mua-send-common arg t))
630
631 ;;;#autoload
632 (defun notmuch-mua-send (&optional arg)
633   (interactive "P")
634   (notmuch-mua-send-common arg))
635
636 ;;;#autoload
637 (defun notmuch-mua-kill-buffer ()
638   (interactive)
639   (message-kill-buffer))
640
641 ;;; _
642
643 ;;;#autoload
644 (define-mail-user-agent 'notmuch-user-agent
645   'notmuch-mua-mail
646   'notmuch-mua-send-and-exit
647   'notmuch-mua-kill-buffer
648   'notmuch-mua-send-hook)
649
650 ;; Add some more headers to the list that `message-mode' hides when
651 ;; composing a message.
652 (notmuch-mua-add-more-hidden-headers)
653
654 (provide 'notmuch-mua)
655
656 ;;; notmuch-mua.el ends here