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