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