]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-mua.el
Use https instead of http where possible
[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
31 (eval-when-compile (require 'cl))
32
33 (declare-function notmuch-show-insert-body "notmuch-show" (msg body depth))
34 (declare-function notmuch-fcc-header-setup "notmuch-maildir-fcc" ())
35 (declare-function notmuch-fcc-handler "notmuch-maildir-fcc" (destdir))
36
37 ;;
38
39 (defcustom notmuch-mua-send-hook '(notmuch-mua-message-send-hook)
40   "Hook run before sending messages."
41   :type 'hook
42   :group 'notmuch-send
43   :group 'notmuch-hooks)
44
45 (defcustom notmuch-mua-compose-in 'current-window
46   (concat
47    "Where to create the mail buffer used to compose a new message.
48 Possible values are `current-window' (default), `new-window' and
49 `new-frame'. If set to `current-window', the mail buffer will be
50 displayed in the current window, so the old buffer will be
51 restored when the mail buffer is killed. If set to `new-window'
52 or `new-frame', the mail buffer will be displayed in a new
53 window/frame that will be destroyed when the buffer is killed.
54 You may want to customize `message-kill-buffer-on-exit'
55 accordingly."
56    (when (< emacs-major-version 24)
57            " Due to a known bug in Emacs 23, you should not set
58 this to `new-window' if `message-kill-buffer-on-exit' is
59 disabled: this would result in an incorrect behavior."))
60   :group 'notmuch-send
61   :type '(choice (const :tag "Compose in the current window" current-window)
62                  (const :tag "Compose mail in a new window"  new-window)
63                  (const :tag "Compose mail in a new frame"   new-frame)))
64
65 (defcustom notmuch-mua-user-agent-function 'notmuch-mua-user-agent-full
66   "Function used to generate a `User-Agent:' string. If this is
67 `nil' then no `User-Agent:' will be generated."
68   :type '(choice (const :tag "No user agent string" nil)
69                  (const :tag "Full" notmuch-mua-user-agent-full)
70                  (const :tag "Notmuch" notmuch-mua-user-agent-notmuch)
71                  (const :tag "Emacs" notmuch-mua-user-agent-emacs)
72                  (function :tag "Custom user agent function"
73                            :value notmuch-mua-user-agent-full))
74   :group 'notmuch-send)
75
76 (defcustom notmuch-mua-hidden-headers '("^User-Agent:")
77   "Headers that are added to the `message-mode' hidden headers
78 list."
79   :type '(repeat string)
80   :group 'notmuch-send)
81
82 (defgroup notmuch-reply nil
83   "Replying to messages in notmuch"
84   :group 'notmuch)
85
86 (defcustom notmuch-mua-cite-function 'message-cite-original
87   "*Function for citing an original message.
88 Predefined functions include `message-cite-original' and
89 `message-cite-original-without-signature'.
90 Note that these functions use `mail-citation-hook' if that is non-nil."
91   :type '(radio (function-item message-cite-original)
92                 (function-item message-cite-original-without-signature)
93                 (function-item sc-cite-original)
94                 (function :tag "Other"))
95   :link '(custom-manual "(message)Insertion Variables")
96   :group 'notmuch-reply)
97
98 (defcustom notmuch-mua-reply-insert-header-p-function
99   'notmuch-show-reply-insert-header-p-never
100   "Function to decide which parts get a header when replying.
101
102 This function specifies which parts of a mime message with
103 mutiple parts get a header."
104   :type '(radio (const :tag "No part headers"
105                                notmuch-show-reply-insert-header-p-never)
106                 (const :tag "All except multipart/* and hidden parts"
107                                notmuch-show-reply-insert-header-p-trimmed)
108                 (const :tag "Only for included text parts"
109                                notmuch-show-reply-insert-header-p-minimal)
110                 (const :tag "Exactly as in show view"
111                                notmuch-show-insert-header-p)
112                 (function :tag "Other"))
113   :group 'notmuch-reply)
114
115 ;;
116
117 (defun notmuch-mua-get-switch-function ()
118   "Get a switch function according to `notmuch-mua-compose-in'."
119   (cond ((eq notmuch-mua-compose-in 'current-window)
120          'switch-to-buffer)
121         ((eq notmuch-mua-compose-in 'new-window)
122          'switch-to-buffer-other-window)
123         ((eq notmuch-mua-compose-in 'new-frame)
124          'switch-to-buffer-other-frame)
125         (t (error "Invalid value for `notmuch-mua-compose-in'"))))
126
127 (defun notmuch-mua-maybe-set-window-dedicated ()
128   "Set the selected window as dedicated according to
129 `notmuch-mua-compose-in'."
130   (when (or (eq notmuch-mua-compose-in 'new-frame)
131             (eq notmuch-mua-compose-in 'new-window))
132     (set-window-dedicated-p (selected-window) t)))
133
134 (defun notmuch-mua-user-agent-full ()
135   "Generate a `User-Agent:' string suitable for notmuch."
136   (concat (notmuch-mua-user-agent-notmuch)
137           " "
138           (notmuch-mua-user-agent-emacs)))
139
140 (defun notmuch-mua-user-agent-notmuch ()
141   "Generate a `User-Agent:' string suitable for notmuch."
142   (let ((notmuch-version (if (string= notmuch-emacs-version "unknown")
143                              (notmuch-cli-version)
144                            notmuch-emacs-version)))
145     (concat "Notmuch/" notmuch-version " (https://notmuchmail.org)")))
146
147 (defun notmuch-mua-user-agent-emacs ()
148   "Generate a `User-Agent:' string suitable for notmuch."
149   (concat "Emacs/" emacs-version " (" system-configuration ")"))
150
151 (defun notmuch-mua-add-more-hidden-headers ()
152   "Add some headers to the list that are hidden by default."
153   (mapc (lambda (header)
154           (when (not (member header message-hidden-headers))
155             (push header message-hidden-headers)))
156         notmuch-mua-hidden-headers))
157
158 (defun notmuch-mua-reply-crypto (parts)
159   "Add mml sign-encrypt flag if any part of original message is encrypted."
160   (loop for part in parts
161         if (notmuch-match-content-type (plist-get part :content-type) "multipart/encrypted")
162           do (mml-secure-message-sign-encrypt)
163         else if (notmuch-match-content-type (plist-get part :content-type) "multipart/*")
164           do (notmuch-mua-reply-crypto (plist-get part :content))))
165
166 ;; There is a bug in emacs 23's message.el that results in a newline
167 ;; not being inserted after the References header, so the next header
168 ;; is concatenated to the end of it. This function fixes the problem,
169 ;; while guarding against the possibility that some current or future
170 ;; version of emacs has the bug fixed.
171 (defun notmuch-mua-insert-references (original-func header references)
172   (funcall original-func header references)
173   (unless (bolp) (insert "\n")))
174
175 (defun notmuch-mua-reply (query-string &optional sender reply-all)
176   (let ((args '("reply" "--format=sexp" "--format-version=1"))
177         (process-crypto notmuch-show-process-crypto)
178         reply
179         original)
180     (when process-crypto
181       (setq args (append args '("--decrypt"))))
182
183     (if reply-all
184         (setq args (append args '("--reply-to=all")))
185       (setq args (append args '("--reply-to=sender"))))
186     (setq args (append args (list query-string)))
187
188     ;; Get the reply object as SEXP, and parse it into an elisp object.
189     (setq reply (apply #'notmuch-call-notmuch-sexp args))
190
191     ;; Extract the original message to simplify the following code.
192     (setq original (plist-get reply :original))
193
194     ;; Extract the headers of both the reply and the original message.
195     (let* ((original-headers (plist-get original :headers))
196            (reply-headers (plist-get reply :reply-headers)))
197
198       ;; If sender is non-nil, set the From: header to its value.
199       (when sender
200         (plist-put reply-headers :From sender))
201       (let
202           ;; Overlay the composition window on that being used to read
203           ;; the original message.
204           ((same-window-regexps '("\\*mail .*")))
205
206         ;; We modify message-header-format-alist to get around a bug in message.el.
207         ;; See the comment above on notmuch-mua-insert-references.
208         (let ((message-header-format-alist
209                (loop for pair in message-header-format-alist
210                      if (eq (car pair) 'References)
211                      collect (cons 'References
212                                    (apply-partially
213                                     'notmuch-mua-insert-references
214                                     (cdr pair)))
215                      else
216                      collect pair)))
217           (notmuch-mua-mail (plist-get reply-headers :To)
218                             (plist-get reply-headers :Subject)
219                             (notmuch-headers-plist-to-alist reply-headers)
220                             nil (notmuch-mua-get-switch-function))))
221
222       ;; Insert the message body - but put it in front of the signature
223       ;; if one is present, and after any other content
224       ;; message*setup-hooks may have added to the message body already.
225       (save-restriction
226         (message-goto-body)
227         (narrow-to-region (point) (point-max))
228         (goto-char (point-max))
229         (if (re-search-backward message-signature-separator nil t)
230             (if message-signature-insert-empty-line
231                 (forward-line -1))
232           (goto-char (point-max))))
233
234       (let ((from (plist-get original-headers :From))
235             (date (plist-get original-headers :Date))
236             (start (point)))
237
238         ;; notmuch-mua-cite-function constructs a citation line based
239         ;; on the From and Date headers of the original message, which
240         ;; are assumed to be in the buffer.
241         (insert "From: " from "\n")
242         (insert "Date: " date "\n\n")
243
244         (insert (with-temp-buffer
245                   (let
246                       ;; Don't attempt to clean up messages, excerpt
247                       ;; citations, etc. in the original message before
248                       ;; quoting.
249                       ((notmuch-show-insert-text/plain-hook nil)
250                        ;; Don't omit long parts.
251                        (notmuch-show-max-text-part-size 0)
252                        ;; Insert headers for parts as appropriate for replying.
253                        (notmuch-show-insert-header-p-function notmuch-mua-reply-insert-header-p-function)
254                        ;; Don't indent multipart sub-parts.
255                        (notmuch-show-indent-multipart nil))
256                     (notmuch-show-insert-body original (plist-get original :body) 0)
257                     (buffer-substring-no-properties (point-min) (point-max)))))
258
259         (set-mark (point))
260         (goto-char start)
261         ;; Quote the original message according to the user's configured style.
262         (funcall notmuch-mua-cite-function)))
263
264     ;; Crypto processing based crypto content of the original message
265     (when process-crypto
266       (notmuch-mua-reply-crypto (plist-get original :body))))
267
268   ;; Push mark right before signature, if any.
269   (message-goto-signature)
270   (unless (eobp)
271     (end-of-line -1))
272   (push-mark)
273
274   (message-goto-body)
275   (set-buffer-modified-p nil))
276
277 (define-derived-mode notmuch-message-mode message-mode "Message[Notmuch]"
278   "Notmuch message composition mode. Mostly like `message-mode'"
279   (when notmuch-address-command
280     (notmuch-address-setup)))
281
282 (put 'notmuch-message-mode 'flyspell-mode-predicate 'mail-mode-flyspell-verify)
283
284 (define-key notmuch-message-mode-map (kbd "C-c C-c") #'notmuch-mua-send-and-exit)
285 (define-key notmuch-message-mode-map (kbd "C-c C-s") #'notmuch-mua-send)
286
287 (defun notmuch-mua-pop-to-buffer (name switch-function)
288   "Pop to buffer NAME, and warn if it already exists and is
289 modified. This function is notmuch addaptation of
290 `message-pop-to-buffer'."
291   (let ((buffer (get-buffer name)))
292     (if (and buffer
293              (buffer-name buffer))
294         (let ((window (get-buffer-window buffer 0)))
295           (if window
296               ;; Raise the frame already displaying the message buffer.
297               (progn
298                 (gnus-select-frame-set-input-focus (window-frame window))
299                 (select-window window))
300             (funcall switch-function buffer)
301             (set-buffer buffer))
302           (when (and (buffer-modified-p)
303                      (not (prog1
304                               (y-or-n-p
305                                "Message already being composed; erase? ")
306                             (message nil))))
307             (error "Message being composed")))
308       (funcall switch-function name)
309       (set-buffer name))
310     (erase-buffer)
311     (notmuch-message-mode)))
312
313 (defun notmuch-mua-mail (&optional to subject other-headers continue
314                                    switch-function yank-action send-actions
315                                    return-action &rest ignored)
316   "Invoke the notmuch mail composition window."
317   (interactive)
318
319   (when notmuch-mua-user-agent-function
320     (let ((user-agent (funcall notmuch-mua-user-agent-function)))
321       (when (not (string= "" user-agent))
322         (push (cons 'User-Agent user-agent) other-headers))))
323
324   (unless (assq 'From other-headers)
325     (push (cons 'From (message-make-from
326                        (notmuch-user-name) (notmuch-user-primary-email))) other-headers))
327
328   (notmuch-mua-pop-to-buffer (message-buffer-name "mail" to)
329                              (or switch-function (notmuch-mua-get-switch-function)))
330   (let ((headers
331          (append
332           ;; The following is copied from `message-mail'
333           `((To . ,(or to "")) (Subject . ,(or subject "")))
334           ;; C-h f compose-mail says that headers should be specified as
335           ;; (string . value); however all the rest of message expects
336           ;; headers to be symbols, not strings (eg message-header-format-alist).
337           ;; https://lists.gnu.org/archive/html/emacs-devel/2011-01/msg00337.html
338           ;; We need to convert any string input, eg from rmail-start-mail.
339           (dolist (h other-headers other-headers)
340             (if (stringp (car h)) (setcar h (intern (capitalize (car h))))))))
341         (args (list yank-action send-actions))
342         ;; Cause `message-setup-1' to do things relevant for mail,
343         ;; such as observe `message-default-mail-headers'.
344         (message-this-is-mail t))
345     ;; message-setup-1 in Emacs 23 does not accept return-action
346     ;; argument. Pass it only if it is supplied by the caller. This
347     ;; will never be the case when we're called by `compose-mail' in
348     ;; Emacs 23.
349     (when return-action (nconc args '(return-action)))
350     (apply 'message-setup-1 headers args))
351   (notmuch-fcc-header-setup)
352   (message-sort-headers)
353   (message-hide-headers)
354   (set-buffer-modified-p nil)
355   (notmuch-mua-maybe-set-window-dedicated)
356
357   (message-goto-to))
358
359 (defcustom notmuch-identities nil
360   "Identities that can be used as the From: address when composing a new message.
361
362 If this variable is left unset, then a list will be constructed from the
363 name and addresses configured in the notmuch configuration file."
364   :type '(repeat string)
365   :group 'notmuch-send)
366
367 (defcustom notmuch-always-prompt-for-sender nil
368   "Always prompt for the From: address when composing or forwarding a message.
369
370 This is not taken into account when replying to a message, because in that case
371 the From: header is already filled in by notmuch."
372   :type 'boolean
373   :group 'notmuch-send)
374
375 (defvar notmuch-mua-sender-history nil)
376
377 ;; Workaround: Running `ido-completing-read' in emacs 23.1, 23.2 and 23.3
378 ;; without some explicit initialization fill freeze the operation.
379 ;; Hence, we advice `ido-completing-read' to ensure required initialization
380 ;; is done.
381 (if (and (= emacs-major-version 23) (< emacs-minor-version 4))
382     (defadvice ido-completing-read (before notmuch-ido-mode-init activate)
383       (ido-init-completion-maps)
384       (add-hook 'minibuffer-setup-hook 'ido-minibuffer-setup)
385       (add-hook 'choose-completion-string-functions
386                 'ido-choose-completion-string)
387       (ad-disable-advice 'ido-completing-read 'before 'notmuch-ido-mode-init)
388       (ad-activate 'ido-completing-read)))
389
390 (defun notmuch-mua-prompt-for-sender ()
391   "Prompt for a sender from the user's configured identities."
392   (if notmuch-identities
393       (ido-completing-read "Send mail from: " notmuch-identities
394                            nil nil nil 'notmuch-mua-sender-history
395                            (car notmuch-identities))
396     (let* ((name (notmuch-user-name))
397            (addrs (cons (notmuch-user-primary-email)
398                         (notmuch-user-other-email)))
399            (address
400             (ido-completing-read (concat "Sender address for " name ": ") addrs
401                                  nil nil nil 'notmuch-mua-sender-history
402                                  (car addrs))))
403       (message-make-from name address))))
404
405 (put 'notmuch-mua-new-mail 'notmuch-prefix-doc "... and prompt for sender")
406 (defun notmuch-mua-new-mail (&optional prompt-for-sender)
407   "Compose new mail.
408
409 If PROMPT-FOR-SENDER is non-nil, the user will be prompted for
410 the From: address first."
411   (interactive "P")
412   (let ((other-headers
413          (when (or prompt-for-sender notmuch-always-prompt-for-sender)
414            (list (cons 'From (notmuch-mua-prompt-for-sender))))))
415     (notmuch-mua-mail nil nil other-headers nil (notmuch-mua-get-switch-function))))
416
417 (defun notmuch-mua-new-forward-messages (messages &optional prompt-for-sender)
418   "Compose a new message forwarding MESSAGES.
419
420 If PROMPT-FOR-SENDER is non-nil, the user will be prompteed for
421 the From: address."
422   (let* ((other-headers
423           (when (or prompt-for-sender notmuch-always-prompt-for-sender)
424             (list (cons 'From (notmuch-mua-prompt-for-sender)))))
425          forward-subject) ;; Comes from the first message and is
426                           ;; applied later.
427
428     ;; Generate the template for the outgoing message.
429     (notmuch-mua-mail nil "" other-headers nil (notmuch-mua-get-switch-function))
430
431     (save-excursion
432       ;; Insert all of the forwarded messages.
433       (mapc (lambda (id)
434               (let ((temp-buffer (get-buffer-create
435                                   (concat "*notmuch-fwd-raw-" id "*"))))
436                 ;; Get the raw version of this message in the buffer.
437                 (with-current-buffer temp-buffer
438                   (erase-buffer)
439                   (let ((coding-system-for-read 'no-conversion))
440                     (call-process notmuch-command nil t nil "show" "--format=raw" id))
441                   ;; Because we process the messages in reverse order,
442                   ;; always generate a forwarded subject, then use the
443                   ;; last (i.e. first) one.
444                   (setq forward-subject (message-make-forward-subject)))
445                 ;; Make a copy ready to be forwarded in the
446                 ;; composition buffer.
447                 (message-forward-make-body temp-buffer)
448                 ;; Kill the temporary buffer.
449                 (kill-buffer temp-buffer)))
450             ;; `message-forward-make-body' always puts the message at
451             ;; the top, so do them in reverse order.
452             (reverse messages))
453
454       ;; Add in the appropriate subject.
455       (save-restriction
456         (message-narrow-to-headers)
457         (message-remove-header "Subject")
458         (message-add-header (concat "Subject: " forward-subject)))
459
460       ;; `message-forward-make-body' shows the User-agent header.  Hide
461       ;; it again.
462       (message-hide-headers)
463       (set-buffer-modified-p nil))))
464
465 (defun notmuch-mua-new-reply (query-string &optional prompt-for-sender reply-all)
466   "Compose a reply to the message identified by QUERY-STRING.
467
468 If PROMPT-FOR-SENDER is non-nil, the user will be prompted for
469 the From: address first.  If REPLY-ALL is non-nil, the message
470 will be addressed to all recipients of the source message."
471
472 ;; In current emacs (24.3) select-active-regions is set to t by
473 ;; default. The reply insertion code sets the region to the quoted
474 ;; message to make it easy to delete (kill-region or C-w). These two
475 ;; things combine to put the quoted message in the primary selection.
476 ;;
477 ;; This is not what the user wanted and is a privacy risk (accidental
478 ;; pasting of the quoted message). We can avoid some of the problems
479 ;; by let-binding select-active-regions to nil. This fixes if the
480 ;; primary selection was previously in a non-emacs window but not if
481 ;; it was in an emacs window. To avoid the problem in the latter case
482 ;; we deactivate mark.
483
484   (let ((sender
485          (when prompt-for-sender
486            (notmuch-mua-prompt-for-sender)))
487         (select-active-regions nil))
488     (notmuch-mua-reply query-string sender reply-all)
489     (deactivate-mark)))
490
491 (defun notmuch-mua-send-and-exit (&optional arg)
492   (interactive "P")
493   (let ((message-fcc-handler-function #'notmuch-fcc-handler))
494     (message-send-and-exit arg)))
495
496 (defun notmuch-mua-send (&optional arg)
497   (interactive "P")
498   (let ((message-fcc-handler-function #'notmuch-fcc-handler))
499     (message-send arg)))
500
501 (defun notmuch-mua-kill-buffer ()
502   (interactive)
503   (message-kill-buffer))
504
505 (defun notmuch-mua-message-send-hook ()
506   "The default function used for `notmuch-mua-send-hook', this
507 simply runs the corresponding `message-mode' hook functions."
508   (run-hooks 'message-send-hook))
509
510 ;;
511
512 (define-mail-user-agent 'notmuch-user-agent
513   'notmuch-mua-mail 'notmuch-mua-send-and-exit
514   'notmuch-mua-kill-buffer 'notmuch-mua-send-hook)
515
516 ;; Add some more headers to the list that `message-mode' hides when
517 ;; composing a message.
518 (notmuch-mua-add-more-hidden-headers)
519
520 ;;
521
522 (provide 'notmuch-mua)
523
524 ;;; notmuch-mua.el ends here