- "Can be added to message-send-hook and will set the FCC header
- based on the values of notmuch-fcc-directories (see the
- variable customization there for examples). It uses the
- first entry as default fallback if no From address
- matches."
- ; only do something if notmuch-fcc-dirs is set
- (if notmuch-fcc-dirs
- (let ((subdir
- (cdr (assoc-string (message-fetch-field "from") notmuch-fcc-dirs t))))
- (if (eq subdir nil) (setq subdir (car (car notmuch-fcc-dirs))))
- (unless (message-fetch-field "fcc")
- (message-add-header (concat "Fcc: " message-directory subdir)))
- (let ((fcc-header (message-fetch-field "fcc")))
- (unless (notmuch-maildir-fcc-dir-is-maildir-p fcc-header)
- (cond ((not (file-writable-p fcc-header))
- (error (format "%s is not a maildir, but you don't have permission to create one." fcc-header)))
- ((y-or-n-p (format "%s is not a maildir. Create it? "
- fcc-header))
- (notmuch-maildir-fcc-create-maildir fcc-header))
- (t
- (error "Not sending message."))))))))
-
+ "Add an Fcc header to the current message buffer.
+
+Can be added to `message-send-hook' and will set the Fcc header
+based on the values of `notmuch-fcc-dirs'. An existing Fcc header
+will NOT be removed or replaced."
+
+ (let ((subdir
+ (cond
+ ((or (not notmuch-fcc-dirs)
+ (message-field-value "Fcc"))
+ ;; Nothing set or an existing header.
+ nil)
+
+ ((stringp notmuch-fcc-dirs)
+ notmuch-fcc-dirs)
+
+ ((and (listp notmuch-fcc-dirs)
+ (stringp (car notmuch-fcc-dirs)))
+ ;; Old style - no longer works.
+ (error "Invalid `notmuch-fcc-dirs' setting (old style)"))
+
+ ((listp notmuch-fcc-dirs)
+ (let* ((from (message-field-value "From"))
+ (match
+ (catch 'first-match
+ (dolist (re-folder notmuch-fcc-dirs)
+ (when (string-match-p (car re-folder) from)
+ (throw 'first-match re-folder))))))
+ (if match
+ (cdr match)
+ (message "No Fcc header added.")
+ nil)))
+
+ (t
+ (error "Invalid `notmuch-fcc-dirs' setting (neither string nor list)")))))
+
+ (when subdir
+ (message-add-header
+ (concat "Fcc: "
+ (file-truename
+ ;; If the resulting directory is not an absolute path,
+ ;; prepend the standard notmuch database path.
+ (if (= (elt subdir 0) ?/)
+ subdir
+ (concat (notmuch-database-path) "/" subdir)))))
+
+ ;; finally test if fcc points to a valid maildir
+ (let ((fcc-header (message-field-value "Fcc")))
+ (unless (notmuch-maildir-fcc-dir-is-maildir-p fcc-header)
+ (cond ((not (file-writable-p fcc-header))
+ (error (format "No permission to create %s, which does not exist"
+ fcc-header)))
+ ((y-or-n-p (format "%s is not a maildir. Create it? "
+ fcc-header))
+ (notmuch-maildir-fcc-create-maildir fcc-header))
+ (t
+ (error "Message not sent"))))))))
+