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