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