]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-maildir-fcc.el
emacs: always use elisp quoting style in doc-strings
[notmuch] / emacs / notmuch-maildir-fcc.el
1 ;;; notmuch-maildir-fcc.el --- inserting using a fcc handler
2
3 ;; Copyright © Jesse Rosenthal
4 ;;
5 ;; This file is part of Notmuch.
6 ;;
7 ;; Notmuch is free software: you can redistribute it and/or modify it
8 ;; under the terms of the GNU General Public License as published by
9 ;; the Free Software Foundation, either version 3 of the License, or
10 ;; (at your option) any later version.
11 ;;
12 ;; Notmuch is distributed in the hope that it will be useful, but
13 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 ;; General Public License for more details.
16 ;;
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with Notmuch.  If not, see <https://www.gnu.org/licenses/>.
19 ;;
20 ;; Authors: Jesse Rosenthal <jrosenthal@jhu.edu>
21
22 ;;; Code:
23
24 (eval-when-compile (require 'cl-lib))
25
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   (let ((subdir
97          (cond
98           ((or (not notmuch-fcc-dirs)
99                (message-field-value "Fcc"))
100            ;; Nothing set or an existing header.
101            nil)
102           ((stringp notmuch-fcc-dirs)
103            notmuch-fcc-dirs)
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           ((listp notmuch-fcc-dirs)
109            (let* ((from (message-field-value "From"))
110                   (match
111                    (catch 'first-match
112                      (dolist (re-folder notmuch-fcc-dirs)
113                        (when (string-match-p (car re-folder) from)
114                          (throw 'first-match re-folder))))))
115              (if match
116                  (cdr match)
117                (message "No Fcc header added.")
118                nil)))
119           (t
120            (error "Invalid `notmuch-fcc-dirs' setting (neither string nor list)")))))
121     (when subdir
122       (if notmuch-maildir-use-notmuch-insert
123           (notmuch-maildir-add-notmuch-insert-style-fcc-header subdir)
124         (notmuch-maildir-add-file-style-fcc-header subdir)))))
125
126 (defun notmuch-maildir-add-notmuch-insert-style-fcc-header (subdir)
127   ;; Notmuch insert does not accept absolute paths, so check the user
128   ;; really want this header inserted.
129   (when (or (not (= (elt subdir 0) ?/))
130             (y-or-n-p
131              (format "Fcc header %s is an absolute path and notmuch insert is requested.
132 Insert header anyway? " subdir)))
133     (message-add-header (concat "Fcc: " subdir))))
134
135 (defun notmuch-maildir-add-file-style-fcc-header (subdir)
136   (message-add-header
137    (concat "Fcc: "
138            (file-truename
139             ;; If the resulting directory is not an absolute path,
140             ;; prepend the standard notmuch database path.
141             (if (= (elt subdir 0) ?/)
142                 subdir
143               (concat (notmuch-database-path) "/" subdir))))))
144
145 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
146 ;; Functions for saving a message either using notmuch insert or file
147 ;; fcc. First functions common to the two cases.
148
149 (defmacro with-temporary-notmuch-message-buffer (&rest body)
150   "Set-up a temporary copy of the current message-mode buffer."
151   `(let ((case-fold-search t)
152          (buf (current-buffer))
153          (mml-externalize-attachments message-fcc-externalize-attachments))
154      (with-current-buffer (get-buffer-create " *message temp*")
155        (erase-buffer)
156        (insert-buffer-substring buf)
157        ,@body)))
158
159 (defun notmuch-maildir-setup-message-for-saving ()
160   "Setup message for saving. Should be called on a temporary copy.
161
162 This is taken from the function message-do-fcc."
163   (message-encode-message-body)
164   (save-restriction
165     (message-narrow-to-headers)
166     (mail-encode-encoded-word-buffer))
167   (goto-char (point-min))
168   (when (re-search-forward
169          (concat "^" (regexp-quote mail-header-separator) "$")
170          nil t)
171     (replace-match "" t t )))
172
173 (defun notmuch-maildir-message-do-fcc ()
174   "Process Fcc headers in the current buffer.
175
176 This is a rearranged version of message mode's message-do-fcc."
177   (let (list file)
178     (save-excursion
179       (save-restriction
180         (message-narrow-to-headers)
181         (setq file (message-fetch-field "fcc" t)))
182       (when file
183         (with-temporary-notmuch-message-buffer
184          (save-restriction
185            (message-narrow-to-headers)
186            (while (setq file (message-fetch-field "fcc" t))
187              (push file list)
188              (message-remove-header "fcc" nil t)))
189          (notmuch-maildir-setup-message-for-saving)
190          ;; Process FCC operations.
191          (while list
192            (setq file (pop list))
193            (notmuch-fcc-handler file))
194          (kill-buffer (current-buffer)))))))
195
196 (defun notmuch-fcc-handler (fcc-header)
197   "Store message with notmuch insert or normal (file) fcc.
198
199 If `notmuch-maildir-use-notmuch-insert' is set then store the
200 message using notmuch insert. Otherwise store the message using
201 normal fcc."
202   (message "Doing Fcc...")
203   (if notmuch-maildir-use-notmuch-insert
204       (notmuch-maildir-fcc-with-notmuch-insert fcc-header)
205     (notmuch-maildir-fcc-file-fcc fcc-header)))
206
207 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
208 ;; Functions for saving a message using notmuch insert.
209
210 (defun notmuch-maildir-notmuch-insert-current-buffer (folder &optional create tags)
211   "Use notmuch insert to put the current buffer in the database.
212
213 This inserts the current buffer as a message into the notmuch
214 database in folder FOLDER. If CREATE is non-nil it will supply
215 the --create-folder flag to create the folder if necessary. TAGS
216 should be a list of tag changes to apply to the inserted message."
217   (let* ((args (append (and create (list "--create-folder"))
218                        (list (concat "--folder=" folder))
219                        tags)))
220     (apply 'notmuch-call-notmuch-process
221            :stdin-string (buffer-string) "insert" args)))
222
223 (defun notmuch-maildir-fcc-with-notmuch-insert (fcc-header &optional create)
224   "Store message with notmuch insert.
225
226 The fcc-header should be of the form \"folder +tag1 -tag2\" where
227 folder is the folder (relative to the notmuch mailstore) to store
228 the message in, and tag1 and tag2 are tag changes to apply to the
229 stored message. This string is split using `split-string-and-unquote',
230 so a folder name containing spaces can be specified by
231 quoting each space with an immediately preceding backslash
232 or surrounding the entire folder name in double quotes.
233
234 If CREATE is non-nil then create the folder if 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 "Insert failed: \
246 \(r)etry, (c)reate folder, (i)gnore, or (e)dit the header? " '(?r ?c ?i ?e))))
247          (cl-case response
248            (?r (notmuch-maildir-fcc-with-notmuch-insert fcc-header))
249            (?c (notmuch-maildir-fcc-with-notmuch-insert fcc-header 't))
250            (?i 't)
251            (?e (notmuch-maildir-fcc-with-notmuch-insert
252                 (read-from-minibuffer "Fcc header: " fcc-header)))))))))
253
254
255 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
256 ;; Functions for saving a message using file fcc.
257
258 (defun notmuch-maildir-fcc-host-fixer (hostname)
259   (replace-regexp-in-string "/\\|:"
260                             (lambda (s)
261                               (cond ((string-equal s "/") "\\057")
262                                     ((string-equal s ":") "\\072")
263                                     (t s)))
264                             hostname
265                             t
266                             t))
267
268 (defun notmuch-maildir-fcc-make-uniq-maildir-id ()
269   (let* ((ftime (float-time))
270          (microseconds (mod (* 1000000 ftime) 1000000))
271          (hostname (notmuch-maildir-fcc-host-fixer (system-name))))
272     (setq notmuch-maildir-fcc-count (+ notmuch-maildir-fcc-count 1))
273     (format "%d.%d_%d_%d.%s"
274             ftime
275             (emacs-pid)
276             microseconds
277             notmuch-maildir-fcc-count
278             hostname)))
279
280 (defun notmuch-maildir-fcc-dir-is-maildir-p (dir)
281   (and (file-exists-p (concat dir "/cur/"))
282        (file-exists-p (concat dir "/new/"))
283        (file-exists-p (concat dir "/tmp/"))))
284
285 (defun notmuch-maildir-fcc-create-maildir (path)
286   (cond ((or (not (file-exists-p path)) (file-directory-p path))
287          (make-directory (concat path "/cur/") t)
288          (make-directory (concat path "/new/") t)
289          (make-directory (concat path "/tmp/") t))
290         ((file-regular-p path)
291          (error "%s is a file. Can't create maildir." path))
292         (t
293          (error "I don't know how to create a maildir here"))))
294
295 (defun notmuch-maildir-fcc-save-buffer-to-tmp (destdir)
296   "Returns the msg id of the message written to the temp directory
297 if successful, nil if not."
298   (let ((msg-id (notmuch-maildir-fcc-make-uniq-maildir-id)))
299     (while (file-exists-p (concat destdir "/tmp/" msg-id))
300       (setq msg-id (notmuch-maildir-fcc-make-uniq-maildir-id)))
301     (cond ((notmuch-maildir-fcc-dir-is-maildir-p destdir)
302            (write-file (concat destdir "/tmp/" msg-id))
303            msg-id)
304           (t
305            (error (format "Can't write to %s. Not a maildir."
306                           destdir))
307            nil))))
308
309 (defun notmuch-maildir-fcc-move-tmp-to-new (destdir msg-id)
310   (add-name-to-file
311    (concat destdir "/tmp/" msg-id)
312    (concat destdir "/new/" msg-id ":2,")))
313
314 (defun notmuch-maildir-fcc-move-tmp-to-cur (destdir msg-id &optional mark-seen)
315   (add-name-to-file
316    (concat destdir "/tmp/" msg-id)
317    (concat destdir "/cur/" msg-id ":2," (and mark-seen "S"))))
318
319 (defun notmuch-maildir-fcc-file-fcc (fcc-header)
320   "Write the message to the file specified by FCC-HEADER.
321
322 It offers the user a chance to correct the header, or filesystem,
323 if needed."
324   (if (notmuch-maildir-fcc-dir-is-maildir-p fcc-header)
325       (notmuch-maildir-fcc-write-buffer-to-maildir fcc-header 't)
326     ;; The fcc-header is not a valid maildir see if the user wants to
327     ;; fix it in some way.
328     (let* ((prompt (format "Fcc %s is not a maildir: \
329 \(r)etry, (c)reate folder, (i)gnore, or (e)dit the header? " fcc-header))
330            (response (read-char-choice prompt '(?r ?c ?i ?e))))
331       (cl-case response
332         (?r (notmuch-maildir-fcc-file-fcc fcc-header))
333         (?c (if (file-writable-p fcc-header)
334                 (notmuch-maildir-fcc-create-maildir fcc-header)
335               (message "No permission to create %s." fcc-header)
336               (sit-for 2))
337             (notmuch-maildir-fcc-file-fcc fcc-header))
338         (?i 't)
339         (?e (notmuch-maildir-fcc-file-fcc
340              (read-from-minibuffer "Fcc header: " fcc-header)))))))
341
342 (defun notmuch-maildir-fcc-write-buffer-to-maildir (destdir &optional mark-seen)
343   "Writes the current buffer to maildir destdir. If mark-seen is
344 non-nil, it will write it to cur/, and mark it as read. It should
345 return t if successful, and nil otherwise."
346   (let ((orig-buffer (buffer-name)))
347     (with-temp-buffer
348       (insert-buffer-substring orig-buffer)
349       (catch 'link-error
350         (let ((msg-id (notmuch-maildir-fcc-save-buffer-to-tmp destdir)))
351           (when msg-id
352             (cond (mark-seen
353                    (condition-case err
354                        (notmuch-maildir-fcc-move-tmp-to-cur destdir msg-id t)
355                      (file-already-exists
356                       (throw 'link-error nil))))
357                   (t
358                    (condition-case err
359                        (notmuch-maildir-fcc-move-tmp-to-new destdir msg-id)
360                      (file-already-exists
361                       (throw 'link-error nil))))))
362           (delete-file (concat destdir "/tmp/" msg-id))))
363       t)))
364
365 (provide 'notmuch-maildir-fcc)
366
367 ;;; notmuch-maildir-fcc.el ends here