]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-maildir-fcc.el
95e565033c050d9e436cbcaaf3cccb6038506219
[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))
26 (require 'message)
27
28 (require 'notmuch-lib)
29
30 (defvar notmuch-maildir-fcc-count 0)
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.
58
59 If `notmuch-maildir-use-notmuch-insert' is nil then the Fcc
60 header should be the directory where the message should be
61 saved. A relative directory will be understood to specify a
62 directory within the notmuch mail store, (as set by the
63 database.path option in the notmuch configuration file).
64
65 In all cases you will be prompted to create the folder or
66 directory if it does not exist yet when sending a mail."
67
68  :type '(choice
69          (const :tag "No FCC header" nil)
70          (string :tag "A single folder")
71          (repeat :tag "A folder based on the From header"
72                  (cons regexp (string :tag "Folder"))))
73  :require 'notmuch-fcc-initialization
74  :group 'notmuch-send)
75
76 (defcustom notmuch-maildir-use-notmuch-insert 't
77   "Should fcc use notmuch insert instead of simple fcc"
78   :type '(choice :tag "Fcc Method"
79                  (const :tag "Use notmuch insert" t)
80                  (const :tag "Use simple fcc" nil))
81   :group 'notmuch-send)
82
83 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
84 ;; Functions which set up the fcc header in the message buffer.
85
86 (defun notmuch-fcc-header-setup ()
87   "Add an Fcc header to the current message buffer.
88
89 Sets the Fcc header based on the values of `notmuch-fcc-dirs'.
90
91 Originally intended to be use a hook function, but now called directly
92 by notmuch-mua-mail"
93
94   (let ((subdir
95          (cond
96           ((or (not notmuch-fcc-dirs)
97                (message-field-value "Fcc"))
98            ;; Nothing set or an existing header.
99            nil)
100
101           ((stringp notmuch-fcc-dirs)
102            notmuch-fcc-dirs)
103
104           ((and (listp notmuch-fcc-dirs)
105                 (stringp (car notmuch-fcc-dirs)))
106            ;; Old style - no longer works.
107            (error "Invalid `notmuch-fcc-dirs' setting (old style)"))
108
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
121           (t
122            (error "Invalid `notmuch-fcc-dirs' setting (neither string nor list)")))))
123
124     (when subdir
125       (if notmuch-maildir-use-notmuch-insert
126           (notmuch-maildir-add-notmuch-insert-style-fcc-header subdir)
127         (notmuch-maildir-add-file-style-fcc-header subdir)))))
128
129 (defun notmuch-maildir-add-notmuch-insert-style-fcc-header (subdir)
130   ;; Notmuch insert does not accept absolute paths, so check the user
131   ;; really want this header inserted.
132
133   (when (or (not (= (elt subdir 0) ?/))
134             (y-or-n-p (format "Fcc header %s is an absolute path and notmuch insert is requested.\nInsert header anyway? "
135                               subdir)))
136     (message-add-header (concat "Fcc: " subdir))))
137
138 (defun notmuch-maildir-add-file-style-fcc-header (subdir)
139   (message-add-header
140    (concat "Fcc: "
141            (file-truename
142             ;; If the resulting directory is not an absolute path,
143             ;; prepend the standard notmuch database path.
144             (if (= (elt subdir 0) ?/)
145                 subdir
146               (concat (notmuch-database-path) "/" subdir))))))
147
148 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
149 ;; Functions for saving a message either using notmuch insert or file
150 ;; fcc. First functions common to the two cases.
151
152 (defmacro with-temporary-notmuch-message-buffer (&rest body)
153   "Set-up a temporary copy of the current message-mode buffer."
154   `(let ((case-fold-search t)
155          (buf (current-buffer))
156          (mml-externalize-attachments message-fcc-externalize-attachments))
157      (with-current-buffer (get-buffer-create " *message temp*")
158        (erase-buffer)
159        (insert-buffer-substring buf)
160        ,@body)))
161
162 (defun notmuch-maildir-setup-message-for-saving ()
163   "Setup message for saving. Should be called on a temporary copy.
164
165 This is taken from the function message-do-fcc."
166   (message-encode-message-body)
167   (save-restriction
168     (message-narrow-to-headers)
169     (let ((mail-parse-charset message-default-charset))
170       (mail-encode-encoded-word-buffer)))
171   (goto-char (point-min))
172   (when (re-search-forward
173          (concat "^" (regexp-quote mail-header-separator) "$")
174          nil t)
175     (replace-match "" t t )))
176
177 (defun notmuch-maildir-message-do-fcc ()
178   "Process Fcc headers in the current buffer.
179
180 This is a rearranged version of message mode's message-do-fcc."
181   (let (list file)
182     (save-excursion
183       (save-restriction
184         (message-narrow-to-headers)
185         (setq file (message-fetch-field "fcc" t)))
186       (when file
187         (with-temporary-notmuch-message-buffer
188          (save-restriction
189            (message-narrow-to-headers)
190            (while (setq file (message-fetch-field "fcc" t))
191              (push file list)
192              (message-remove-header "fcc" nil t)))
193          (notmuch-maildir-setup-message-for-saving)
194          ;; Process FCC operations.
195          (while list
196            (setq file (pop list))
197            (notmuch-fcc-handler file))
198          (kill-buffer (current-buffer)))))))
199
200 (defun notmuch-fcc-handler (fcc-header)
201   "Store message with notmuch insert or normal (file) fcc.
202
203 If `notmuch-maildir-use-notmuch-insert` is set then store the
204 message using notmuch insert. Otherwise store the message using
205 normal fcc."
206   (message "Doing Fcc...")
207   (if notmuch-maildir-use-notmuch-insert
208       (notmuch-maildir-fcc-with-notmuch-insert fcc-header)
209     (notmuch-maildir-fcc-file-fcc fcc-header)))
210
211 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
212 ;; Functions for saving a message using notmuch insert.
213
214 (defun notmuch-maildir-notmuch-insert-current-buffer (folder &optional create tags)
215   "Use notmuch insert to put the current buffer in the database.
216
217 This inserts the current buffer as a message into the notmuch
218 database in folder FOLDER. If CREATE is non-nil it will supply
219 the --create-folder flag to create the folder if necessary. TAGS
220 should be a list of tag changes to apply to the inserted message."
221   (let* ((args (append (when create (list "--create-folder"))
222                        (list (concat "--folder=" folder))
223                        tags)))
224     (apply 'notmuch-call-notmuch-process
225            :stdin-string (buffer-string) "insert" args)))
226
227 (defun notmuch-maildir-fcc-with-notmuch-insert (fcc-header &optional create)
228   "Store message with notmuch insert.
229
230 The fcc-header should be of the form \"folder +tag1 -tag2\" where
231 folder is the folder (relative to the notmuch mailstore) to store
232 the message in, and tag1 and tag2 are tag changes to apply to the
233 stored message. If CREATE is non-nil then create the folder if
234 necessary."
235   (let* ((args (split-string-and-unquote fcc-header))
236          (folder (car args))
237          (tags (cdr args)))
238     (condition-case nil
239         (notmuch-maildir-notmuch-insert-current-buffer folder create tags)
240       ;; Since there are many reasons notmuch insert could fail, e.g.,
241       ;; locked database, non-existent folder (which could be due to a
242       ;; typo, or just the user want a new folder, let the user decide
243       ;; how to deal with it.
244       (error
245        (let ((response (read-char-choice
246                         "Insert failed: (r)etry, (c)reate folder, (i)gnore, or  (e)dit the header? "
247                         '(?r ?c ?i ?e))))
248          (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: (r)etry, (c)reate folder, (i)gnore, or  (e)dit the header? "
330                            fcc-header))
331             (response (read-char-choice prompt '(?r ?c ?i ?e))))
332          (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