]> 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 ---
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     (mail-encode-encoded-word-buffer))
173   (goto-char (point-min))
174   (when (re-search-forward
175          (concat "^" (regexp-quote mail-header-separator) "$")
176          nil t)
177     (replace-match "" t t )))
178
179 (defun notmuch-maildir-message-do-fcc ()
180   "Process Fcc headers in the current buffer.
181
182 This is a rearranged version of message mode's message-do-fcc."
183   (let (list file)
184     (save-excursion
185       (save-restriction
186         (message-narrow-to-headers)
187         (setq file (message-fetch-field "fcc" t)))
188       (when file
189         (with-temporary-notmuch-message-buffer
190          (save-restriction
191            (message-narrow-to-headers)
192            (while (setq file (message-fetch-field "fcc" t))
193              (push file list)
194              (message-remove-header "fcc" nil t)))
195          (notmuch-maildir-setup-message-for-saving)
196          ;; Process FCC operations.
197          (while list
198            (setq file (pop list))
199            (notmuch-fcc-handler file))
200          (kill-buffer (current-buffer)))))))
201
202 (defun notmuch-fcc-handler (fcc-header)
203   "Store message with notmuch insert or normal (file) fcc.
204
205 If `notmuch-maildir-use-notmuch-insert` is set then store the
206 message using notmuch insert. Otherwise store the message using
207 normal fcc."
208   (message "Doing Fcc...")
209   (if notmuch-maildir-use-notmuch-insert
210       (notmuch-maildir-fcc-with-notmuch-insert fcc-header)
211     (notmuch-maildir-fcc-file-fcc fcc-header)))
212
213 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
214 ;; Functions for saving a message using notmuch insert.
215
216 (defun notmuch-maildir-notmuch-insert-current-buffer (folder &optional create tags)
217   "Use notmuch insert to put the current buffer in the database.
218
219 This inserts the current buffer as a message into the notmuch
220 database in folder FOLDER. If CREATE is non-nil it will supply
221 the --create-folder flag to create the folder if necessary. TAGS
222 should be a list of tag changes to apply to the inserted message."
223   (let* ((args (append (when create (list "--create-folder"))
224                        (list (concat "--folder=" folder))
225                        tags)))
226     (apply 'notmuch-call-notmuch-process
227            :stdin-string (buffer-string) "insert" args)))
228
229 (defun notmuch-maildir-fcc-with-notmuch-insert (fcc-header &optional create)
230   "Store message with notmuch insert.
231
232 The fcc-header should be of the form \"folder +tag1 -tag2\" where
233 folder is the folder (relative to the notmuch mailstore) to store
234 the message in, and tag1 and tag2 are tag changes to apply to the
235 stored message. This string is split using `split-string-and-unquote',
236 so a folder name containing spaces can be specified by
237 quoting each space with an immediately preceding backslash
238 or surrounding the entire folder name in double quotes.
239
240 If CREATE is non-nil then create the folder if necessary."
241   (let* ((args (split-string-and-unquote fcc-header))
242          (folder (car args))
243          (tags (cdr args)))
244     (condition-case nil
245         (notmuch-maildir-notmuch-insert-current-buffer folder create tags)
246       ;; Since there are many reasons notmuch insert could fail, e.g.,
247       ;; locked database, non-existent folder (which could be due to a
248       ;; typo, or just the user want a new folder, let the user decide
249       ;; how to deal with it.
250       (error
251        (let ((response (notmuch-read-char-choice
252                         "Insert failed: (r)etry, (c)reate folder, (i)gnore, or (e)dit the header? "
253                         '(?r ?c ?i ?e))))
254          (case response
255                (?r (notmuch-maildir-fcc-with-notmuch-insert fcc-header))
256                (?c (notmuch-maildir-fcc-with-notmuch-insert fcc-header 't))
257                (?i 't)
258                (?e (notmuch-maildir-fcc-with-notmuch-insert
259                     (read-from-minibuffer "Fcc header: " fcc-header)))))))))
260
261
262 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
263 ;; Functions for saving a message using file fcc.
264
265 (defun notmuch-maildir-fcc-host-fixer (hostname)
266   (replace-regexp-in-string "/\\|:"
267                             (lambda (s)
268                               (cond ((string-equal s "/") "\\057")
269                                     ((string-equal s ":") "\\072")
270                                     (t s)))
271                             hostname
272                             t
273                             t))
274
275 (defun notmuch-maildir-fcc-make-uniq-maildir-id ()
276    (let* ((ftime (float-time))
277           (microseconds (mod (* 1000000 ftime) 1000000))
278           (hostname (notmuch-maildir-fcc-host-fixer (system-name))))
279      (setq notmuch-maildir-fcc-count (+ notmuch-maildir-fcc-count 1))
280      (format "%d.%d_%d_%d.%s"
281              ftime
282              (emacs-pid)
283              microseconds
284              notmuch-maildir-fcc-count
285              hostname)))
286
287 (defun notmuch-maildir-fcc-dir-is-maildir-p (dir)
288   (and (file-exists-p (concat dir "/cur/"))
289        (file-exists-p (concat dir "/new/"))
290        (file-exists-p (concat dir "/tmp/"))))
291
292 (defun notmuch-maildir-fcc-create-maildir (path)
293   (cond ((or (not (file-exists-p path)) (file-directory-p path))
294          (make-directory (concat path "/cur/") t)
295          (make-directory (concat path "/new/") t)
296          (make-directory (concat path "/tmp/") t))
297         ((file-regular-p path)
298          (error "%s is a file. Can't create maildir." path))
299         (t
300          (error "I don't know how to create a maildir here"))))
301
302 (defun notmuch-maildir-fcc-save-buffer-to-tmp (destdir)
303   "Returns the msg id of the message written to the temp directory
304 if successful, nil if not."
305   (let ((msg-id (notmuch-maildir-fcc-make-uniq-maildir-id)))
306     (while (file-exists-p (concat destdir "/tmp/" msg-id))
307       (setq msg-id (notmuch-maildir-fcc-make-uniq-maildir-id)))
308     (cond ((notmuch-maildir-fcc-dir-is-maildir-p destdir)
309            (write-file (concat destdir "/tmp/" msg-id))
310            msg-id)
311           (t
312            (error (format "Can't write to %s. Not a maildir."
313                           destdir))
314            nil))))
315
316 (defun notmuch-maildir-fcc-move-tmp-to-new (destdir msg-id)
317   (add-name-to-file
318    (concat destdir "/tmp/" msg-id)
319    (concat destdir "/new/" msg-id ":2,")))
320
321 (defun notmuch-maildir-fcc-move-tmp-to-cur (destdir msg-id &optional mark-seen)
322   (add-name-to-file
323    (concat destdir "/tmp/" msg-id)
324    (concat destdir "/cur/" msg-id ":2," (when mark-seen "S"))))
325
326 (defun notmuch-maildir-fcc-file-fcc (fcc-header)
327   "Write the message to the file specified by FCC-HEADER.
328
329 It offers the user a chance to correct the header, or filesystem,
330 if needed."
331   (if (notmuch-maildir-fcc-dir-is-maildir-p fcc-header)
332       (notmuch-maildir-fcc-write-buffer-to-maildir fcc-header 't)
333     ;; The fcc-header is not a valid maildir see if the user wants to
334     ;; fix it in some way.
335     (let* ((prompt (format "Fcc %s is not a maildir: (r)etry, (c)reate folder, (i)gnore, or  (e)dit the header? "
336                            fcc-header))
337             (response (notmuch-read-char-choice prompt '(?r ?c ?i ?e))))
338          (case response
339                (?r (notmuch-maildir-fcc-file-fcc fcc-header))
340                (?c (if (file-writable-p fcc-header)
341                        (notmuch-maildir-fcc-create-maildir fcc-header)
342                      (message "No permission to create %s." fcc-header)
343                      (sit-for 2))
344                    (notmuch-maildir-fcc-file-fcc fcc-header))
345                (?i 't)
346                (?e (notmuch-maildir-fcc-file-fcc
347                     (read-from-minibuffer "Fcc header: " fcc-header)))))))
348
349 (defun notmuch-maildir-fcc-write-buffer-to-maildir (destdir &optional mark-seen)
350   "Writes the current buffer to maildir destdir. If mark-seen is
351 non-nil, it will write it to cur/, and mark it as read. It should
352 return t if successful, and nil otherwise."
353   (let ((orig-buffer (buffer-name)))
354     (with-temp-buffer
355       (insert-buffer-substring orig-buffer)
356       (catch 'link-error
357         (let ((msg-id (notmuch-maildir-fcc-save-buffer-to-tmp destdir)))
358           (when msg-id
359             (cond (mark-seen
360                    (condition-case err
361                        (notmuch-maildir-fcc-move-tmp-to-cur destdir msg-id t)
362                      (file-already-exists
363                       (throw 'link-error nil))))
364                   (t
365                    (condition-case err
366                        (notmuch-maildir-fcc-move-tmp-to-new destdir msg-id)
367                      (file-already-exists
368                       (throw 'link-error nil))))))
369           (delete-file (concat destdir "/tmp/" msg-id))))
370       t)))
371
372 (provide 'notmuch-maildir-fcc)
373
374 ;;; notmuch-maildir-fcc.el ends here