]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-maildir-fcc.el
emacs: Add new option notmuch-search-hide-excluded
[notmuch] / emacs / notmuch-maildir-fcc.el
1 ;;; notmuch-maildir-fcc.el --- inserting using a fcc handler  -*- lexical-binding: t -*-
2
3 ;; Copyright © Jesse Rosenthal
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: Jesse Rosenthal <jrosenthal@jhu.edu>
21
22 ;;; Code:
23
24 (require 'message)
25
26 (require 'notmuch-lib)
27
28 (defvar notmuch-maildir-fcc-count 0)
29
30 ;;; Options
31
32 (defcustom notmuch-fcc-dirs "sent"
33   "Determines the Fcc Header which says where to save outgoing mail.
34
35 Three types of values are permitted:
36
37 - nil: no Fcc header is added,
38
39 - a string: the value of `notmuch-fcc-dirs' is the Fcc header to
40   be used.
41
42 - a list: the folder is chosen based on the From address of the
43   current message using a list of regular expressions and
44   corresponding folders:
45
46      ((\"Sebastian@SSpaeth.de\" . \"privat\")
47       (\"spaetz@sspaeth.de\" . \"OUTBOX.OSS\")
48       (\".*\" . \"defaultinbox\"))
49
50   If none of the regular expressions match the From address, no
51   Fcc header will be added.
52
53 If `notmuch-maildir-use-notmuch-insert' is set (the default) then
54 the header should be of the form \"folder +tag1 -tag2\" where
55 folder is the folder (relative to the notmuch mailstore) to store
56 the message in, and tag1 and tag2 are tag changes to apply to the
57 stored message. This string is split using `split-string-and-unquote',
58 so a folder name containing spaces can be specified by
59 quoting each space with an immediately preceding backslash
60 or surrounding the entire folder name in double quotes.
61
62 If `notmuch-maildir-use-notmuch-insert' is nil then the Fcc
63 header should be the directory where the message should be
64 saved. A relative directory will be understood to specify a
65 directory within the notmuch mail store, (as set by the
66 database.path option in the notmuch configuration file).
67
68 In all cases you will be prompted to create the folder or
69 directory if it does not exist yet when sending a mail."
70
71   :type '(choice
72           (const :tag "No FCC header" nil)
73           (string :tag "A single folder")
74           (repeat :tag "A folder based on the From header"
75                   (cons regexp (string :tag "Folder"))))
76   :require 'notmuch-fcc-initialization
77   :group 'notmuch-send)
78
79 (defcustom notmuch-maildir-use-notmuch-insert t
80   "Should fcc use notmuch insert instead of simple fcc."
81   :type '(choice :tag "Fcc Method"
82                  (const :tag "Use notmuch insert" t)
83                  (const :tag "Use simple fcc" nil))
84   :group 'notmuch-send)
85
86 ;;; Functions which set up the fcc header in the message buffer.
87
88 (defun notmuch-fcc-header-setup ()
89   "Add an Fcc header to the current message buffer.
90
91 If the Fcc header is already set, then keep it as-is.
92 Otherwise set it according to `notmuch-fcc-dirs'."
93   (let ((subdir
94          (cond
95           ((or (not notmuch-fcc-dirs)
96                (message-field-value "Fcc"))
97            ;; Nothing set or an existing header.
98            nil)
99           ((stringp notmuch-fcc-dirs)
100            notmuch-fcc-dirs)
101           ((and (listp notmuch-fcc-dirs)
102                 (stringp (car notmuch-fcc-dirs)))
103            ;; Old style - no longer works.
104            (error "Invalid `notmuch-fcc-dirs' setting (old style)"))
105           ((listp notmuch-fcc-dirs)
106            (or (seq-some (let ((from (message-field-value "From")))
107                            (pcase-lambda (`(,regexp . ,folder))
108                              (and (string-match-p regexp from)
109                                   folder)))
110                          notmuch-fcc-dirs)
111                (progn (message "No Fcc header added.")
112                       nil)))
113           (t
114            (error "Invalid `notmuch-fcc-dirs' setting (neither string nor list)")))))
115     (when subdir
116       (if notmuch-maildir-use-notmuch-insert
117           (notmuch-maildir-add-notmuch-insert-style-fcc-header subdir)
118         (notmuch-maildir-add-file-style-fcc-header subdir)))))
119
120 (defun notmuch-maildir-add-notmuch-insert-style-fcc-header (subdir)
121   ;; Notmuch insert does not accept absolute paths, so check the user
122   ;; really want this header inserted.
123   (when (or (not (= (elt subdir 0) ?/))
124             (y-or-n-p (format "Fcc header %s is an absolute path %s %s" subdir
125                               "and notmuch insert is requested."
126                               "Insert header anyway? ")))
127     (message-add-header (concat "Fcc: " subdir))))
128
129 (defun notmuch-maildir-add-file-style-fcc-header (subdir)
130   (message-add-header
131    (concat "Fcc: "
132            (file-truename
133             ;; If the resulting directory is not an absolute path,
134             ;; prepend the standard notmuch database path.
135             (if (= (elt subdir 0) ?/)
136                 subdir
137               (concat (notmuch-database-path) "/" subdir))))))
138
139 ;;; Functions for saving a message using either method.
140
141 (defmacro with-temporary-notmuch-message-buffer (&rest body)
142   "Set-up a temporary copy of the current message-mode buffer."
143   `(let ((case-fold-search t)
144          (buf (current-buffer))
145          (mml-externalize-attachments message-fcc-externalize-attachments))
146      (with-current-buffer (get-buffer-create " *message temp*")
147        (erase-buffer)
148        (insert-buffer-substring buf)
149        ,@body)))
150
151 (defun notmuch-maildir-setup-message-for-saving ()
152   "Setup message for saving.
153
154 This should be called on a temporary copy.
155 This is taken from the function message-do-fcc."
156   (message-encode-message-body)
157   (save-restriction
158     (message-narrow-to-headers)
159     (mail-encode-encoded-word-buffer))
160   (goto-char (point-min))
161   (when (re-search-forward
162          (concat "^" (regexp-quote mail-header-separator) "$")
163          nil t)
164     (replace-match "" t t )))
165
166 (defun notmuch-maildir-message-do-fcc ()
167   "Process Fcc headers in the current buffer.
168
169 This is a rearranged version of message mode's message-do-fcc."
170   (let (files file)
171     (save-excursion
172       (save-restriction
173         (message-narrow-to-headers)
174         (setq file (message-fetch-field "fcc" t)))
175       (when file
176         (with-temporary-notmuch-message-buffer
177          (save-restriction
178            (message-narrow-to-headers)
179            (while (setq file (message-fetch-field "fcc" t))
180              (push file files)
181              (message-remove-header "fcc" nil t)))
182          (notmuch-maildir-setup-message-for-saving)
183          ;; Process FCC operations.
184          (mapc #'notmuch-fcc-handler files)
185          (kill-buffer (current-buffer)))))))
186
187 (defun notmuch-fcc-handler (fcc-header)
188   "Store message with notmuch insert or normal (file) fcc.
189
190 If `notmuch-maildir-use-notmuch-insert' is set then store the
191 message using notmuch insert. Otherwise store the message using
192 normal fcc."
193   (message "Doing Fcc...")
194   (if notmuch-maildir-use-notmuch-insert
195       (notmuch-maildir-fcc-with-notmuch-insert fcc-header)
196     (notmuch-maildir-fcc-file-fcc fcc-header))
197   (message "Doing Fcc...done"))
198
199 ;;; Functions for saving a message using notmuch insert.
200
201 (defun notmuch-maildir-notmuch-insert-current-buffer (folder &optional create tags)
202   "Use notmuch insert to put the current buffer in the database.
203
204 This inserts the current buffer as a message into the notmuch
205 database in folder FOLDER. If CREATE is non-nil it will supply
206 the --create-folder flag to create the folder if necessary. TAGS
207 should be a list of tag changes to apply to the inserted message."
208   (apply 'notmuch-call-notmuch-process
209          :stdin-string (buffer-string) "insert"
210          (append (and create (list "--create-folder"))
211                  (list (concat "--folder=" folder))
212                  tags)))
213
214 (defun notmuch-maildir-fcc-with-notmuch-insert (fcc-header &optional create)
215   "Store message with notmuch insert.
216
217 The fcc-header should be of the form \"folder +tag1 -tag2\" where
218 folder is the folder (relative to the notmuch mailstore) to store
219 the message in, and tag1 and tag2 are tag changes to apply to the
220 stored message. This string is split using `split-string-and-unquote',
221 so a folder name containing spaces can be specified by
222 quoting each space with an immediately preceding backslash
223 or surrounding the entire folder name in double quotes.
224
225 If CREATE is non-nil then create the folder if necessary."
226   (pcase-let ((`(,folder . ,tags)
227                (split-string-and-unquote fcc-header)))
228     (condition-case nil
229         (notmuch-maildir-notmuch-insert-current-buffer folder create tags)
230       ;; Since there are many reasons notmuch insert could fail, e.g.,
231       ;; locked database, non-existent folder (which could be due to a
232       ;; typo, or just the user want a new folder, let the user decide
233       ;; how to deal with it.
234       (error
235        (let ((response (read-char-choice "Insert failed: \
236 \(r)etry, (c)reate folder, (i)gnore, or (e)dit the header? " '(?r ?c ?i ?e))))
237          (cl-case response
238            (?r (notmuch-maildir-fcc-with-notmuch-insert fcc-header))
239            (?c (notmuch-maildir-fcc-with-notmuch-insert fcc-header t))
240            (?i t)
241            (?e (notmuch-maildir-fcc-with-notmuch-insert
242                 (read-from-minibuffer "Fcc header: " fcc-header)))))))))
243
244 ;;; Functions for saving a message using file fcc.
245
246 (defun notmuch-maildir-fcc-host-fixer (hostname)
247   (replace-regexp-in-string "/\\|:"
248                             (lambda (s)
249                               (cond ((string-equal s "/") "\\057")
250                                     ((string-equal s ":") "\\072")
251                                     (t s)))
252                             hostname
253                             t
254                             t))
255
256 (defun notmuch-maildir-fcc-make-uniq-maildir-id ()
257   (let* ((ftime (float-time))
258          (microseconds (mod (* 1000000 ftime) 1000000))
259          (hostname (notmuch-maildir-fcc-host-fixer (system-name))))
260     (cl-incf notmuch-maildir-fcc-count)
261     (format "%d.%d_%d_%d.%s"
262             ftime
263             (emacs-pid)
264             microseconds
265             notmuch-maildir-fcc-count
266             hostname)))
267
268 (defun notmuch-maildir-fcc-dir-is-maildir-p (dir)
269   (and (file-exists-p (concat dir "/cur/"))
270        (file-exists-p (concat dir "/new/"))
271        (file-exists-p (concat dir "/tmp/"))))
272
273 (defun notmuch-maildir-fcc-create-maildir (path)
274   (cond ((or (not (file-exists-p path)) (file-directory-p path))
275          (make-directory (concat path "/cur/") t)
276          (make-directory (concat path "/new/") t)
277          (make-directory (concat path "/tmp/") t))
278         ((file-regular-p path)
279          (error "%s is a file. Can't create maildir." path))
280         (t
281          (error "I don't know how to create a maildir here"))))
282
283 (defun notmuch-maildir-fcc-save-buffer-to-tmp (destdir)
284   "Returns the msg id of the message written to the temp directory
285 if successful, nil if not."
286   (let ((msg-id (notmuch-maildir-fcc-make-uniq-maildir-id)))
287     (while (file-exists-p (concat destdir "/tmp/" msg-id))
288       (setq msg-id (notmuch-maildir-fcc-make-uniq-maildir-id)))
289     (cond ((notmuch-maildir-fcc-dir-is-maildir-p destdir)
290            (write-file (concat destdir "/tmp/" msg-id))
291            msg-id)
292           (t
293            (error "Can't write to %s. Not a maildir." destdir)))))
294
295 (defun notmuch-maildir-fcc-move-tmp-to-new (destdir msg-id)
296   (add-name-to-file
297    (concat destdir "/tmp/" msg-id)
298    (concat destdir "/new/" msg-id ":2,")))
299
300 (defun notmuch-maildir-fcc-move-tmp-to-cur (destdir msg-id &optional mark-seen)
301   (add-name-to-file
302    (concat destdir "/tmp/" msg-id)
303    (concat destdir "/cur/" msg-id ":2," (and mark-seen "S"))))
304
305 (defun notmuch-maildir-fcc-file-fcc (fcc-header)
306   "Write the message to the file specified by FCC-HEADER.
307
308 If that fails, then offer the user a chance to correct the header
309 or filesystem."
310   (if (notmuch-maildir-fcc-dir-is-maildir-p fcc-header)
311       (notmuch-maildir-fcc-write-buffer-to-maildir fcc-header t)
312     ;; The fcc-header is not a valid maildir see if the user wants to
313     ;; fix it in some way.
314     (let* ((prompt (format "Fcc %s is not a maildir: \
315 \(r)etry, (c)reate folder, (i)gnore, or (e)dit the header? " fcc-header))
316            (response (read-char-choice prompt '(?r ?c ?i ?e))))
317       (cl-case response
318         (?r (notmuch-maildir-fcc-file-fcc fcc-header))
319         (?c (if (file-writable-p fcc-header)
320                 (notmuch-maildir-fcc-create-maildir fcc-header)
321               (message "No permission to create %s." fcc-header)
322               (sit-for 2))
323             (notmuch-maildir-fcc-file-fcc fcc-header))
324         (?i t)
325         (?e (notmuch-maildir-fcc-file-fcc
326              (read-from-minibuffer "Fcc header: " fcc-header)))))))
327
328 (defun notmuch-maildir-fcc-write-buffer-to-maildir (destdir &optional mark-seen)
329   "Write the current buffer to maildir destdir.
330
331 If mark-seen is non-nil, then write it to \"cur/\", and mark it
332 as read, otherwise write it to \"new/\". Return t if successful,
333 and nil otherwise."
334   (let ((orig-buffer (buffer-name)))
335     (with-temp-buffer
336       (insert-buffer-substring orig-buffer)
337       (catch 'link-error
338         (let ((msg-id (notmuch-maildir-fcc-save-buffer-to-tmp destdir)))
339           (when msg-id
340             (condition-case nil
341                 (if mark-seen
342                     (notmuch-maildir-fcc-move-tmp-to-cur destdir msg-id t)
343                   (notmuch-maildir-fcc-move-tmp-to-new destdir msg-id))
344               (file-already-exists
345                (throw 'link-error nil))))
346           (delete-file (concat destdir "/tmp/" msg-id))))
347       t)))
348
349 ;;; _
350
351 (provide 'notmuch-maildir-fcc)
352
353 ;;; notmuch-maildir-fcc.el ends here