config

Personal configuration.
git clone git://code.dwrz.net/config
Log | Files | Refs

notmuch-mua.el (25830B)


      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 (defun notmuch-mua-mail (&optional to subject other-headers _continue
    405 				   switch-function yank-action send-actions
    406 				   return-action &rest _ignored)
    407   "Invoke the notmuch mail composition window.
    408 
    409 The position of point when the function returns differs depending
    410 on the values of TO and SUBJECT.  If both are non-nil, point is
    411 moved to the message's body.  If SUBJECT is nil but TO isn't,
    412 point is moved to the \"Subject:\" header.  Otherwise, point is
    413 moved to the \"To:\" header."
    414   (interactive)
    415   (when notmuch-mua-user-agent-function
    416     (let ((user-agent (funcall notmuch-mua-user-agent-function)))
    417       (unless (string-empty-p user-agent)
    418 	(push (cons 'User-Agent user-agent) other-headers))))
    419   (notmuch-mua-pop-to-buffer (message-buffer-name "mail" to)
    420 			     (or switch-function
    421 				 (notmuch-mua-get-switch-function)))
    422   (let ((headers
    423 	 (append
    424 	  ;; The following is copied from `message-mail'
    425 	  `((To . ,(or to "")) (Subject . ,(or subject "")))
    426 	  ;; C-h f compose-mail says that headers should be specified as
    427 	  ;; (string . value); however all the rest of message expects
    428 	  ;; headers to be symbols, not strings (eg message-header-format-alist).
    429 	  ;; https://lists.gnu.org/archive/html/emacs-devel/2011-01/msg00337.html
    430 	  ;; We need to convert any string input, eg from rmail-start-mail.
    431 	  (dolist (h other-headers other-headers)
    432 	    (when (stringp (car h))
    433 	      (setcar h (intern (capitalize (car h))))))))
    434 	;; Cause `message-setup-1' to do things relevant for mail,
    435 	;; such as observe `message-default-mail-headers'.
    436 	(message-this-is-mail t))
    437     (unless (assq 'From headers)
    438       (push (cons 'From (message-make-from
    439 			 (notmuch-user-name)
    440 			 (notmuch-user-primary-email)))
    441 	    headers))
    442     (message-setup-1 headers yank-action send-actions return-action))
    443   (notmuch-fcc-header-setup)
    444   (notmuch-mua--remove-dont-reply-to-names)
    445   (message-sort-headers)
    446   (message-hide-headers)
    447   (set-buffer-modified-p nil)
    448   (notmuch-mua-maybe-set-window-dedicated)
    449   (cond
    450    ((and to subject) (message-goto-body))
    451    (to (message-goto-subject))
    452    (t (message-goto-to))))
    453 
    454 (defvar notmuch-mua-sender-history nil)
    455 
    456 (defun notmuch-mua-prompt-for-sender ()
    457   "Prompt for a sender from the user's configured identities."
    458   (if notmuch-identities
    459       (completing-read "Send mail from: " notmuch-identities
    460 		       nil nil nil 'notmuch-mua-sender-history
    461 		       (car notmuch-identities))
    462     (let* ((name (notmuch-user-name))
    463 	   (addrs (cons (notmuch-user-primary-email)
    464 			(notmuch-user-other-email)))
    465 	   (address
    466 	    (completing-read (concat "Sender address for " name ": ") addrs
    467 			     nil nil nil 'notmuch-mua-sender-history
    468 			     (car addrs))))
    469       (message-make-from name address))))
    470 
    471 (put 'notmuch-mua-new-mail 'notmuch-prefix-doc "... and prompt for sender")
    472 (defun notmuch-mua-new-mail (&optional prompt-for-sender)
    473   "Compose new mail.
    474 
    475 If PROMPT-FOR-SENDER is non-nil, the user will be prompted for
    476 the From: address first."
    477   (interactive "P")
    478   (let ((other-headers
    479 	 (and (or prompt-for-sender notmuch-always-prompt-for-sender)
    480 	      (list (cons 'From (notmuch-mua-prompt-for-sender))))))
    481     (notmuch-mua-mail nil nil other-headers nil (notmuch-mua-get-switch-function))))
    482 
    483 (defun notmuch-mua-new-forward-messages (messages &optional prompt-for-sender)
    484   "Compose a new message forwarding MESSAGES.
    485 
    486 If PROMPT-FOR-SENDER is non-nil, the user will be prompteed for
    487 the From: address."
    488   (let* ((other-headers
    489 	  (and (or prompt-for-sender notmuch-always-prompt-for-sender)
    490 	       (list (cons 'From (notmuch-mua-prompt-for-sender)))))
    491 	 ;; Comes from the first message and is applied later.
    492 	 forward-subject
    493 	 ;; List of accumulated message-references of forwarded messages.
    494 	 forward-references
    495 	 ;; List of corresponding message-query.
    496 	 forward-queries)
    497     ;; Generate the template for the outgoing message.
    498     (notmuch-mua-mail nil "" other-headers nil (notmuch-mua-get-switch-function))
    499     (save-excursion
    500       ;; Insert all of the forwarded messages.
    501       (mapc (lambda (id)
    502 	      (let ((temp-buffer (get-buffer-create
    503 				  (concat "*notmuch-fwd-raw-" id "*"))))
    504 		;; Get the raw version of this message in the buffer.
    505 		(with-current-buffer temp-buffer
    506 		  (erase-buffer)
    507 		  (let ((coding-system-for-read 'no-conversion))
    508 		    (notmuch--call-process notmuch-command nil t nil
    509 				  "show" "--format=raw" id))
    510 		  ;; Because we process the messages in reverse order,
    511 		  ;; always generate a forwarded subject, then use the
    512 		  ;; last (i.e. first) one.
    513 		  (setq forward-subject (message-make-forward-subject))
    514 		  (push (message-fetch-field "Message-ID") forward-references)
    515 		  (push id forward-queries))
    516 		;; Make a copy ready to be forwarded in the
    517 		;; composition buffer.
    518 		(message-forward-make-body temp-buffer)
    519 		;; Kill the temporary buffer.
    520 		(kill-buffer temp-buffer)))
    521 	    ;; `message-forward-make-body' always puts the message at
    522 	    ;; the top, so do them in reverse order.
    523 	    (reverse messages))
    524       ;; Add in the appropriate subject.
    525       (save-restriction
    526 	(message-narrow-to-headers)
    527 	(message-remove-header "Subject")
    528 	(message-add-header (concat "Subject: " forward-subject))
    529 	(message-remove-header "References")
    530 	(message-add-header (concat "References: "
    531 				    (mapconcat 'identity forward-references " "))))
    532       ;; Create a buffer-local queue for tag changes triggered when
    533       ;; sending the message.
    534       (when notmuch-message-forwarded-tags
    535 	(setq notmuch-message-queued-tag-changes
    536 	      (cl-loop for id in forward-queries
    537 		       collect
    538 		       (cons id notmuch-message-forwarded-tags))))
    539       ;; `message-forward-make-body' shows the User-agent header.  Hide
    540       ;; it again.
    541       (message-hide-headers)
    542       (set-buffer-modified-p nil))))
    543 
    544 (defun notmuch-mua-new-reply (query-string &optional prompt-for-sender reply-all duplicate)
    545   "Compose a reply to the message identified by QUERY-STRING.
    546 
    547 If PROMPT-FOR-SENDER is non-nil, the user will be prompted for
    548 the From: address first.  If REPLY-ALL is non-nil, the message
    549 will be addressed to all recipients of the source message.  If
    550 DUPLICATE is non-nil, based the reply on that duplicate file"
    551   ;; `select-active-regions' is t by default. The reply insertion code
    552   ;; sets the region to the quoted message to make it easy to delete
    553   ;; (kill-region or C-w). These two things combine to put the quoted
    554   ;; message in the primary selection.
    555   ;;
    556   ;; This is not what the user wanted and is a privacy risk (accidental
    557   ;; pasting of the quoted message). We can avoid some of the problems
    558   ;; by let-binding select-active-regions to nil. This fixes if the
    559   ;; primary selection was previously in a non-emacs window but not if
    560   ;; it was in an emacs window. To avoid the problem in the latter case
    561   ;; we deactivate mark.
    562   (let ((sender (and prompt-for-sender
    563 		     (notmuch-mua-prompt-for-sender)))
    564 	(select-active-regions nil))
    565     (notmuch-mua-reply query-string sender reply-all duplicate)
    566     (deactivate-mark)))
    567 
    568 ;;; Checks
    569 
    570 (defun notmuch-mua-check-no-misplaced-secure-tag ()
    571   "Query user if there is a misplaced secure mml tag.
    572 
    573 Emacs message-send will (probably) ignore a secure mml tag unless
    574 it is at the start of the body. Returns t if there is no such
    575 tag, or the user confirms they mean it."
    576   (save-excursion
    577     (let ((body-start (progn (message-goto-body) (point))))
    578       (goto-char (point-max))
    579       (or
    580        ;; We are always fine if there is no secure tag.
    581        (not (search-backward "<#secure" nil t))
    582        ;; There is a secure tag, so it must be at the start of the
    583        ;; body, with no secure tag earlier (i.e., in the headers).
    584        (and (= (point) body-start)
    585 	    (not (search-backward "<#secure" nil t)))
    586        ;; The user confirms they means it.
    587        (yes-or-no-p "\
    588 There is a <#secure> tag not at the start of the body. It is
    589 likely that the message will be sent unsigned and unencrypted.
    590 Really send? ")))))
    591 
    592 (defun notmuch-mua-check-secure-tag-has-newline ()
    593   "Query if the secure mml tag has a newline following it.
    594 
    595 Emacs message-send will (probably) ignore a correctly placed
    596 secure mml tag unless it is followed by a newline. Returns t if
    597 any secure tag is followed by a newline, or the user confirms
    598 they mean it."
    599   (save-excursion
    600     (message-goto-body)
    601     (or
    602      ;; There is no (correctly placed) secure tag.
    603      (not (looking-at "<#secure"))
    604      ;; The secure tag is followed by a newline.
    605      (looking-at "<#secure[^\n>]*>\n")
    606      ;; The user confirms they means it.
    607      (yes-or-no-p "\
    608 The <#secure> tag at the start of the body is not followed by a
    609 newline. It is likely that the message will be sent unsigned and
    610 unencrypted.  Really send? "))))
    611 
    612 ;;; Finishing commands
    613 
    614 (defun notmuch-mua-send-common (arg &optional exit)
    615   (interactive "P")
    616   (run-hooks 'notmuch-mua-send-hook)
    617   (when (and (notmuch-mua-check-no-misplaced-secure-tag)
    618 	     (notmuch-mua-check-secure-tag-has-newline))
    619     (cl-letf (((symbol-function 'message-do-fcc)
    620 	       #'notmuch-maildir-message-do-fcc))
    621       (if exit
    622 	  (message-send-and-exit arg)
    623 	(message-send arg)))))
    624 
    625 (defun notmuch-mua-send-and-exit (&optional arg)
    626   (interactive "P")
    627   (notmuch-mua-send-common arg t))
    628 
    629 (defun notmuch-mua-send (&optional arg)
    630   (interactive "P")
    631   (notmuch-mua-send-common arg))
    632 
    633 (defun notmuch-mua-kill-buffer ()
    634   (interactive)
    635   (message-kill-buffer))
    636 
    637 ;;; _
    638 
    639 (define-mail-user-agent 'notmuch-user-agent
    640   'notmuch-mua-mail
    641   'notmuch-mua-send-and-exit
    642   'notmuch-mua-kill-buffer
    643   'notmuch-mua-send-hook)
    644 
    645 ;; Add some more headers to the list that `message-mode' hides when
    646 ;; composing a message.
    647 (notmuch-mua-add-more-hidden-headers)
    648 
    649 (provide 'notmuch-mua)
    650 
    651 ;;; notmuch-mua.el ends here