]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-maildir-fcc.el
emacs: maildir import message-do-fcc
[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
69 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
70 ;; Functions which set up the fcc header in the message buffer.
71
72 (defun notmuch-fcc-header-setup ()
73   "Add an Fcc header to the current message buffer.
74
75 Sets the Fcc header based on the values of `notmuch-fcc-dirs'.
76
77 Originally intended to be use a hook function, but now called directly
78 by notmuch-mua-mail"
79
80   (let ((subdir
81          (cond
82           ((or (not notmuch-fcc-dirs)
83                (message-field-value "Fcc"))
84            ;; Nothing set or an existing header.
85            nil)
86
87           ((stringp notmuch-fcc-dirs)
88            notmuch-fcc-dirs)
89
90           ((and (listp notmuch-fcc-dirs)
91                 (stringp (car notmuch-fcc-dirs)))
92            ;; Old style - no longer works.
93            (error "Invalid `notmuch-fcc-dirs' setting (old style)"))
94
95           ((listp notmuch-fcc-dirs)
96            (let* ((from (message-field-value "From"))
97                   (match
98                    (catch 'first-match
99                      (dolist (re-folder notmuch-fcc-dirs)
100                        (when (string-match-p (car re-folder) from)
101                          (throw 'first-match re-folder))))))
102              (if match
103                  (cdr match)
104                (message "No Fcc header added.")
105                nil)))
106
107           (t
108            (error "Invalid `notmuch-fcc-dirs' setting (neither string nor list)")))))
109
110     (when subdir
111       (notmuch-maildir-add-file-style-fcc-header subdir))))
112
113 (defun notmuch-maildir-add-file-style-fcc-header (subdir)
114   (message-add-header
115    (concat "Fcc: "
116            (file-truename
117             ;; If the resulting directory is not an absolute path,
118             ;; prepend the standard notmuch database path.
119             (if (= (elt subdir 0) ?/)
120                 subdir
121               (concat (notmuch-database-path) "/" subdir))))))
122
123 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
124 ;; Functions for saving a message either using notmuch insert or file
125 ;; fcc. First functions common to the two cases.
126
127 (defun notmuch-maildir-message-do-fcc ()
128   "Process Fcc headers in the current buffer.
129
130 This is a direct copy from message-mode's message-do-fcc."
131   (let ((case-fold-search t)
132         (buf (current-buffer))
133         list file
134         (mml-externalize-attachments message-fcc-externalize-attachments))
135     (save-excursion
136       (save-restriction
137         (message-narrow-to-headers)
138         (setq file (message-fetch-field "fcc" t)))
139       (when file
140         (set-buffer (get-buffer-create " *message temp*"))
141         (erase-buffer)
142         (insert-buffer-substring buf)
143         (message-encode-message-body)
144         (save-restriction
145           (message-narrow-to-headers)
146           (while (setq file (message-fetch-field "fcc" t))
147             (push file list)
148             (message-remove-header "fcc" nil t))
149           (let ((mail-parse-charset message-default-charset)
150                 (rfc2047-header-encoding-alist
151                  (cons '("Newsgroups" . default)
152                        rfc2047-header-encoding-alist)))
153             (mail-encode-encoded-word-buffer)))
154         (goto-char (point-min))
155         (when (re-search-forward
156                (concat "^" (regexp-quote mail-header-separator) "$")
157                nil t)
158           (replace-match "" t t ))
159         ;; Process FCC operations.
160         (while list
161           (setq file (pop list))
162           (if (string-match "^[ \t]*|[ \t]*\\(.*\\)[ \t]*$" file)
163               ;; Pipe the article to the program in question.
164               (call-process-region (point-min) (point-max) shell-file-name
165                                    nil nil nil shell-command-switch
166                                    (match-string 1 file))
167             ;; Save the article.
168             (setq file (expand-file-name file))
169             (unless (file-exists-p (file-name-directory file))
170               (make-directory (file-name-directory file) t))
171             (if (and message-fcc-handler-function
172                      (not (eq message-fcc-handler-function 'rmail-output)))
173                 (funcall message-fcc-handler-function file)
174               ;; FIXME this option, rmail-output (also used if
175               ;; message-fcc-handler-function is nil) is not
176               ;; documented anywhere AFAICS.  It should work in Emacs
177               ;; 23; I suspect it does not work in Emacs 22.
178               ;; FIXME I don't see the need for the two different cases here.
179               ;; mail-use-rfc822 makes no difference (in Emacs 23),and
180               ;; the third argument just controls \"Wrote file\" message.
181               (if (and (file-readable-p file) (mail-file-babyl-p file))
182                   (rmail-output file 1 nil t)
183                 (let ((mail-use-rfc822 t))
184                   (rmail-output file 1 t t))))))
185         (kill-buffer (current-buffer))))))
186
187 (defun notmuch-fcc-handler (fcc-header)
188   "Store message with file fcc."
189   (notmuch-maildir-fcc-file-fcc fcc-header))
190
191 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
192 ;; Functions for saving a message using file fcc.
193
194 (defun notmuch-maildir-fcc-host-fixer (hostname)
195   (replace-regexp-in-string "/\\|:"
196                             (lambda (s)
197                               (cond ((string-equal s "/") "\\057")
198                                     ((string-equal s ":") "\\072")
199                                     (t s)))
200                             hostname
201                             t
202                             t))
203
204 (defun notmuch-maildir-fcc-make-uniq-maildir-id ()
205    (let* ((ftime (float-time))
206           (microseconds (mod (* 1000000 ftime) 1000000))
207           (hostname (notmuch-maildir-fcc-host-fixer system-name)))
208      (setq notmuch-maildir-fcc-count (+ notmuch-maildir-fcc-count 1))
209      (format "%d.%d_%d_%d.%s"
210              ftime
211              (emacs-pid)
212              microseconds
213              notmuch-maildir-fcc-count
214              hostname)))
215
216 (defun notmuch-maildir-fcc-dir-is-maildir-p (dir)
217   (and (file-exists-p (concat dir "/cur/"))
218        (file-exists-p (concat dir "/new/"))
219        (file-exists-p (concat dir "/tmp/"))))
220
221 (defun notmuch-maildir-fcc-create-maildir (path)
222   (cond ((or (not (file-exists-p path)) (file-directory-p path))
223          (make-directory (concat path "/cur/") t)
224          (make-directory (concat path "/new/") t)
225          (make-directory (concat path "/tmp/") t))
226         ((file-regular-p path)
227          (error "%s is a file. Can't create maildir." path))
228         (t
229          (error "I don't know how to create a maildir here"))))
230
231 (defun notmuch-maildir-fcc-save-buffer-to-tmp (destdir)
232   "Returns the msg id of the message written to the temp directory
233 if successful, nil if not."
234   (let ((msg-id (notmuch-maildir-fcc-make-uniq-maildir-id)))
235     (while (file-exists-p (concat destdir "/tmp/" msg-id))
236       (setq msg-id (notmuch-maildir-fcc-make-uniq-maildir-id)))
237     (cond ((notmuch-maildir-fcc-dir-is-maildir-p destdir)
238            (write-file (concat destdir "/tmp/" msg-id))
239            msg-id)
240           (t
241            (error (format "Can't write to %s. Not a maildir."
242                           destdir))
243            nil))))
244
245 (defun notmuch-maildir-fcc-move-tmp-to-new (destdir msg-id)
246   (add-name-to-file
247    (concat destdir "/tmp/" msg-id)
248    (concat destdir "/new/" msg-id ":2,")))
249
250 (defun notmuch-maildir-fcc-move-tmp-to-cur (destdir msg-id &optional mark-seen)
251   (add-name-to-file
252    (concat destdir "/tmp/" msg-id)
253    (concat destdir "/cur/" msg-id ":2," (when mark-seen "S"))))
254
255 (defun notmuch-maildir-fcc-file-fcc (fcc-header)
256   "Write the message to the file specified by FCC-HEADER.
257
258 It offers the user a chance to correct the header, or filesystem,
259 if needed."
260   (if (notmuch-maildir-fcc-dir-is-maildir-p fcc-header)
261       (notmuch-maildir-fcc-write-buffer-to-maildir fcc-header 't)
262     ;; The fcc-header is not a valid maildir see if the user wants to
263     ;; fix it in some way.
264     (let* ((prompt (format "Fcc %s is not a maildir: (r)etry, (c)reate folder, (i)gnore, or  (e)dit the header? "
265                            fcc-header))
266             (response (read-char-choice prompt '(?r ?c ?i ?e))))
267          (case response
268                (?r (notmuch-maildir-fcc-file-fcc fcc-header))
269                (?c (if (file-writable-p fcc-header)
270                        (notmuch-maildir-fcc-create-maildir fcc-header)
271                      (message "No permission to create %s." fcc-header)
272                      (sit-for 2))
273                    (notmuch-maildir-fcc-file-fcc fcc-header))
274                (?i 't)
275                (?e (notmuch-maildir-fcc-file-fcc
276                     (read-from-minibuffer "Fcc header: " fcc-header)))))))
277
278 (defun notmuch-maildir-fcc-write-buffer-to-maildir (destdir &optional mark-seen)
279   "Writes the current buffer to maildir destdir. If mark-seen is
280 non-nil, it will write it to cur/, and mark it as read. It should
281 return t if successful, and nil otherwise."
282   (let ((orig-buffer (buffer-name)))
283     (with-temp-buffer
284       (insert-buffer-substring orig-buffer)
285       (catch 'link-error
286         (let ((msg-id (notmuch-maildir-fcc-save-buffer-to-tmp destdir)))
287           (when msg-id
288             (cond (mark-seen
289                    (condition-case err
290                        (notmuch-maildir-fcc-move-tmp-to-cur destdir msg-id t)
291                      (file-already-exists
292                       (throw 'link-error nil))))
293                   (t
294                    (condition-case err
295                        (notmuch-maildir-fcc-move-tmp-to-new destdir msg-id)
296                      (file-already-exists
297                       (throw 'link-error nil))))))
298           (delete-file (concat destdir "/tmp/" msg-id))))
299       t)))
300
301 (provide 'notmuch-maildir-fcc)
302
303 ;;; notmuch-maildir-fcc.el ends here