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