1 ;;; notmuch-tag.el --- tag messages within emacs
3 ;; Copyright © Damien Cassou
4 ;; Copyright © Carl Worth
6 ;; This file is part of Notmuch.
8 ;; Notmuch is free software: you can redistribute it and/or modify it
9 ;; under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation, either version 3 of the License, or
11 ;; (at your option) any later version.
13 ;; Notmuch is distributed in the hope that it will be useful, but
14 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 ;; General Public License for more details.
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with Notmuch. If not, see <https://www.gnu.org/licenses/>.
21 ;; Authors: Carl Worth <cworth@cworth.org>
22 ;; Damien Cassou <damien.cassou@gmail.com>
33 (require 'notmuch-lib)
35 (declare-function notmuch-search-tag "notmuch"
36 (tag-changes &optional beg end only-matched))
37 (declare-function notmuch-show-tag "notmuch-show" (tag-changes))
38 (declare-function notmuch-tree-tag "notmuch-tree" (tag-changes))
40 (autoload 'notmuch-jump "notmuch-jump")
42 (define-widget 'notmuch-tag-key-type 'list
43 "A single key tagging binding."
45 :args '((list :inline t
47 (key-sequence :tag "Key")
48 (radio :tag "Tag operations"
49 (repeat :tag "Tag list"
50 (string :format "%v" :tag "change"))
51 (variable :tag "Tag variable"))
52 (string :tag "Name"))))
54 (defcustom notmuch-tagging-keys
55 `((,(kbd "a") notmuch-archive-tags "Archive")
56 (,(kbd "u") notmuch-show-mark-read-tags "Mark read")
57 (,(kbd "f") ("+flagged") "Flag")
58 (,(kbd "s") ("+spam" "-inbox") "Mark as spam")
59 (,(kbd "d") ("+deleted" "-inbox") "Delete"))
60 "A list of keys and corresponding tagging operations.
62 For each key (or key sequence) you can specify a sequence of
63 tagging operations to apply, or a variable which contains a list
64 of tagging operations such as `notmuch-archive-tags'. The final
65 element is a name for this tagging operation. If the name is
66 omitted or empty then the list of tag changes, or the variable
67 name is used as the name.
69 The key `notmuch-tag-jump-reverse-key' (k by default) should not
70 be used (either as a key, or as the start of a key sequence) as
71 it is already bound: it switches the menu to a menu of the
72 reverse tagging operations. The reverse of a tagging operation is
73 the same list of individual tag-ops but with `+tag` replaced by
74 `-tag` and vice versa.
76 If setting this variable outside of customize then it should be a
77 list of triples (lists of three elements). Each triple should be
78 of the form (key-binding tagging-operations name). KEY-BINDING
79 can be a single character or a key sequence; TAGGING-OPERATIONS
80 should either be a list of individual tag operations each of the
81 form `+tag` or `-tag`, or the variable name of a variable that is
82 a list of tagging operations; NAME should be a name for the
83 tagging operation, if omitted or empty than then name is taken
84 from TAGGING-OPERATIONS."
85 :tag "List of tagging bindings"
86 :type '(repeat notmuch-tag-key-type)
89 (define-widget 'notmuch-tag-format-type 'lazy
90 "Customize widget for notmuch-tag-format and friends."
91 :type '(alist :key-type (regexp :tag "Tag")
95 (const :tag "Hidden" nil)
97 (string :tag "Display as")
98 (list :tag "Face" :extra-offset -4
99 (const :format "" :inline t
100 (notmuch-apply-face tag))
102 (const :format "" quote)
104 (list :format "%v" :extra-offset -4
105 (const :format "" :inline t
106 (notmuch-tag-format-image-data tag))
109 (notmuch-tag-star-icon))
110 (const :tag "Empty star"
111 (notmuch-tag-star-empty-icon))
113 (notmuch-tag-tag-icon))
114 (string :tag "Custom")))
115 (sexp :tag "Custom")))))
117 (defface notmuch-tag-unread
118 '((t :foreground "red"))
119 "Default face used for the unread tag.
121 Used in the default value of `notmuch-tag-formats`."
122 :group 'notmuch-faces)
124 (defface notmuch-tag-flagged
127 (:foreground "LightBlue1"))
130 (:foreground "blue")))
131 "Face used for the flagged tag.
133 Used in the default value of `notmuch-tag-formats`."
134 :group 'notmuch-faces)
136 (defcustom notmuch-tag-formats
137 '(("unread" (propertize tag 'face 'notmuch-tag-unread))
138 ("flagged" (propertize tag 'face 'notmuch-tag-flagged)
139 (notmuch-tag-format-image-data tag (notmuch-tag-star-icon))))
140 "Custom formats for individual tags.
142 This is an association list that maps from tag name regexps to
143 lists of formatting expressions. The first entry whose car
144 regexp-matches a tag will be used to format that tag. The regexp
145 is implicitly anchored, so to match a literal tag name, just use
146 that tag name (if it contains special regexp characters like
147 \".\" or \"*\", these have to be escaped). The cdr of the
148 matching entry gives a list of Elisp expressions that modify the
149 tag. If the list is empty, the tag will simply be hidden.
150 Otherwise, each expression will be evaluated in order: for the
151 first expression, the variable `tag' will be bound to the tag
152 name; for each later expression, the variable `tag' will be bound
153 to the result of the previous expression. In this way, each
154 expression can build on the formatting performed by the previous
155 expression. The result of the last expression will displayed in
158 For example, to replace a tag with another string, simply use
159 that string as a formatting expression. To change the foreground
160 of a tag to red, use the expression
161 (propertize tag 'face '(:foreground \"red\"))
163 See also `notmuch-tag-format-image', which can help replace tags
165 :group 'notmuch-search
167 :group 'notmuch-faces
168 :type 'notmuch-tag-format-type)
170 (defface notmuch-tag-deleted
171 '((((class color) (supports :strike-through "red")) :strike-through "red")
172 (t :inverse-video t))
173 "Face used to display deleted tags.
175 Used in the default value of `notmuch-tag-deleted-formats`."
176 :group 'notmuch-faces)
178 (defcustom notmuch-tag-deleted-formats
179 '(("unread" (notmuch-apply-face bare-tag `notmuch-tag-deleted))
180 (".*" (notmuch-apply-face tag `notmuch-tag-deleted)))
181 "Custom formats for tags when deleted.
183 For deleted tags the formats in `notmuch-tag-formats` are applied
184 first and then these formats are applied on top; that is `tag'
185 passed to the function is the tag with all these previous
186 formattings applied. The formatted can access the original
187 unformatted tag as `bare-tag'.
189 By default this shows deleted tags with strike-through in red,
190 unless strike-through is not available (e.g., emacs is running in
191 a terminal) in which case it uses inverse video. To hide deleted
192 tags completely set this to
195 See `notmuch-tag-formats' for full documentation."
197 :group 'notmuch-faces
198 :type 'notmuch-tag-format-type)
200 (defface notmuch-tag-added
201 '((t :underline "green"))
202 "Default face used for added tags.
204 Used in the default value for `notmuch-tag-added-formats`."
205 :group 'notmuch-faces)
207 (defcustom notmuch-tag-added-formats
208 '((".*" (notmuch-apply-face tag 'notmuch-tag-added)))
209 "Custom formats for tags when added.
211 For added tags the formats in `notmuch-tag-formats` are applied
212 first and then these formats are applied on top.
214 To disable special formatting of added tags, set this variable to
217 See `notmuch-tag-formats' for full documentation."
219 :group 'notmuch-faces
220 :type 'notmuch-tag-format-type)
222 (defun notmuch-tag-format-image-data (tag data)
223 "Replace TAG with image DATA, if available.
225 This function returns a propertized string that will display image
226 DATA in place of TAG.This is designed for use in
227 `notmuch-tag-formats'.
229 DATA is the content of an SVG picture (e.g., as returned by
230 `notmuch-tag-star-icon')."
231 (propertize tag 'display
237 (defun notmuch-tag-star-icon ()
238 "Return SVG data representing a star icon.
239 This can be used with `notmuch-tag-format-image-data'."
240 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>
241 <svg version=\"1.1\" width=\"16\" height=\"16\">
242 <g transform=\"translate(-242.81601,-315.59635)\">
244 d=\"m 290.25762,334.31206 -17.64143,-11.77975 -19.70508,7.85447 5.75171,-20.41814 -13.55925,-16.31348 21.19618,-0.83936 11.325,-17.93675 7.34825,19.89939 20.55849,5.22795 -16.65471,13.13786 z\"
245 transform=\"matrix(0.2484147,-0.02623394,0.02623394,0.2484147,174.63605,255.37691)\"
246 style=\"fill:#ffff00;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1\" />
250 (defun notmuch-tag-star-empty-icon ()
251 "Return SVG data representing an empty star icon.
252 This can be used with `notmuch-tag-format-image-data'."
253 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>
254 <svg version=\"1.1\" width=\"16\" height=\"16\">
255 <g transform=\"translate(-242.81601,-315.59635)\">
257 d=\"m 290.25762,334.31206 -17.64143,-11.77975 -19.70508,7.85447 5.75171,-20.41814 -13.55925,-16.31348 21.19618,-0.83936 11.325,-17.93675 7.34825,19.89939 20.55849,5.22795 -16.65471,13.13786 z\"
258 transform=\"matrix(0.2484147,-0.02623394,0.02623394,0.2484147,174.63605,255.37691)\"
259 style=\"fill:#d6d6d1;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1\" />
263 (defun notmuch-tag-tag-icon ()
264 "Return SVG data representing a tag icon.
265 This can be used with `notmuch-tag-format-image-data'."
266 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>
267 <svg version=\"1.1\" width=\"16\" height=\"16\">
268 <g transform=\"translate(0,-1036.3622)\">
270 d=\"m 0.44642857,1040.9336 12.50000043,0 2.700893,3.6161 -2.700893,3.616 -12.50000043,0 z\"
271 style=\"fill:#ffff00;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:0.25;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1\" />
275 (defvar notmuch-tag--format-cache (make-hash-table :test 'equal)
276 "Cache of tag format lookup. Internal to `notmuch-tag-format-tag'.")
278 (defun notmuch-tag-clear-cache ()
279 "Clear the internal cache of tag formats."
280 (clrhash notmuch-tag--format-cache))
282 (defun notmuch-tag--get-formats (tag format-alist)
283 "Find the first item whose car regexp-matches TAG."
285 ;; Don't use assoc-default since there's no way to distinguish a
286 ;; missing key from a present key with a null cdr.
287 (cl-assoc tag format-alist
288 :test (lambda (tag key)
289 (and (eq (string-match key tag) 0)
290 (= (match-end 0) (length tag)))))))
292 (defun notmuch-tag--do-format (tag formatted-tag formats)
293 "Apply a tag-formats entry to TAG."
294 (cond ((null formats) ;; - Tag not in `formats',
295 formatted-tag) ;; the format is the tag itself.
296 ((null (cdr formats)) ;; - Tag was deliberately hidden,
297 nil) ;; no format must be returned
299 ;; Tag was found and has formats, we must apply all the
300 ;; formats. TAG may be null so treat that as a special case.
302 (tag (copy-sequence (or formatted-tag ""))))
303 (dolist (format (cdr formats))
304 (setq tag (eval format)))
305 (if (and (null formatted-tag) (equal tag ""))
309 (defun notmuch-tag-format-tag (tags orig-tags tag)
310 "Format TAG according to `notmuch-tag-formats'.
312 TAGS and ORIG-TAGS are lists of the current tags and the original
313 tags; tags which have been deleted (i.e., are in ORIG-TAGS but
314 are not in TAGS) are shown using formats from
315 `notmuch-tag-deleted-formats'; tags which have been added (i.e.,
316 are in TAGS but are not in ORIG-TAGS) are shown using formats
317 from `notmuch-tag-added-formats' and tags which have not been
318 changed (the normal case) are shown using formats from
319 `notmuch-tag-formats'."
320 (let* ((tag-state (cond ((not (member tag tags)) 'deleted)
321 ((not (member tag orig-tags)) 'added)))
322 (formatted-tag (gethash (cons tag tag-state)
323 notmuch-tag--format-cache
325 (when (eq formatted-tag 'missing)
326 (let ((base (notmuch-tag--get-formats tag notmuch-tag-formats))
327 (over (cl-case tag-state
328 (deleted (notmuch-tag--get-formats
329 tag notmuch-tag-deleted-formats))
330 (added (notmuch-tag--get-formats
331 tag notmuch-tag-added-formats))
333 (setq formatted-tag (notmuch-tag--do-format tag tag base))
334 (setq formatted-tag (notmuch-tag--do-format tag formatted-tag over))
335 (puthash (cons tag tag-state) formatted-tag notmuch-tag--format-cache)))
338 (defun notmuch-tag-format-tags (tags orig-tags &optional face)
339 "Return a string representing formatted TAGS."
340 (let ((face (or face 'notmuch-tag-face))
341 (all-tags (sort (delete-dups (append tags orig-tags nil)) #'string<)))
343 (mapconcat #'identity
344 ;; nil indicated that the tag was deliberately hidden
345 (delq nil (mapcar (apply-partially #'notmuch-tag-format-tag
352 (defcustom notmuch-before-tag-hook nil
353 "Hooks that are run before tags of a message are modified.
355 'tag-changes' will contain the tags that are about to be added or removed as
356 a list of strings of the form \"+TAG\" or \"-TAG\".
357 'query' will be a string containing the search query that determines
358 the messages that are about to be tagged."
360 :options '(notmuch-hl-line-mode)
361 :group 'notmuch-hooks)
363 (defcustom notmuch-after-tag-hook nil
364 "Hooks that are run after tags of a message are modified.
366 'tag-changes' will contain the tags that were added or removed as
367 a list of strings of the form \"+TAG\" or \"-TAG\".
368 'query' will be a string containing the search query that determines
369 the messages that were tagged."
371 :options '(notmuch-hl-line-mode)
372 :group 'notmuch-hooks)
374 (defvar notmuch-select-tag-history nil
375 "Variable to store minibuffer history for
376 `notmuch-select-tag-with-completion' function.")
378 (defvar notmuch-read-tag-changes-history nil
379 "Variable to store minibuffer history for
380 `notmuch-read-tag-changes' function.")
382 (defun notmuch-tag-completions (&rest search-terms)
383 "Return a list of tags for messages matching SEARCH-TERMS.
385 Returns all tags if no search terms are given."
387 (setq search-terms (list "*")))
389 (with-output-to-string
390 (with-current-buffer standard-output
391 (apply 'call-process notmuch-command nil t
392 nil "search" "--output=tags" "--exclude=false" search-terms)))
395 (defun notmuch-select-tag-with-completion (prompt &rest search-terms)
396 (let ((tag-list (apply #'notmuch-tag-completions search-terms)))
397 (completing-read prompt tag-list nil nil nil 'notmuch-select-tag-history)))
399 (defun notmuch-read-tag-changes (current-tags &optional prompt initial-input)
400 "Prompt for tag changes in the minibuffer.
402 CURRENT-TAGS is a list of tags that are present on the message or
403 messages to be changed. These are offered as tag removal
404 completions. CURRENT-TAGS may contain duplicates. PROMPT, if
405 non-nil, is the query string to present in the minibuffer. It
406 defaults to \"Tags\". INITIAL-INPUT, if non-nil, will be the
407 initial input in the minibuffer."
408 (let* ((all-tag-list (notmuch-tag-completions))
409 (add-tag-list (mapcar (apply-partially 'concat "+") all-tag-list))
410 (remove-tag-list (mapcar (apply-partially 'concat "-") current-tags))
411 (tag-list (append add-tag-list remove-tag-list))
412 (prompt (concat (or prompt "Tags") " (+add -drop): "))
414 ;; By default, space is bound to "complete word" function.
415 ;; Re-bind it to insert a space instead. Note that <tab>
416 ;; still does the completion.
417 (crm-local-completion-map
418 (let ((map (make-sparse-keymap)))
419 (set-keymap-parent map crm-local-completion-map)
420 (define-key map " " 'self-insert-command)
422 (delete "" (completing-read-multiple
424 ;; Append the separator to each completion so when the
425 ;; user completes a tag they can immediately begin
426 ;; entering another. `completing-read-multiple'
427 ;; ultimately splits the input on crm-separator, so we
428 ;; don't need to strip this back off (we just need to
429 ;; delete "empty" entries caused by trailing spaces).
430 (mapcar (lambda (tag-op) (concat tag-op crm-separator)) tag-list)
431 nil nil initial-input
432 'notmuch-read-tag-changes-history))))
434 (defun notmuch-update-tags (tags tag-changes)
435 "Return a copy of TAGS with additions and removals from TAG-CHANGES.
437 TAG-CHANGES must be a list of tags names, each prefixed with
438 either a \"+\" to indicate the tag should be added to TAGS if not
439 present or a \"-\" to indicate that the tag should be removed
440 from TAGS if present."
441 (let ((result-tags (copy-sequence tags)))
442 (dolist (tag-change tag-changes)
443 (let ((op (string-to-char tag-change))
444 (tag (unless (string= tag-change "") (substring tag-change 1))))
446 (?+ (unless (member tag result-tags)
447 (push tag result-tags)))
448 (?- (setq result-tags (delete tag result-tags)))
450 (error "Changed tag must be of the form `+this_tag' or `-that_tag'")))))
451 (sort result-tags 'string<)))
453 (defconst notmuch-tag-argument-limit 1000
454 "Use batch tagging if the tagging query is longer than this.
456 This limits the length of arguments passed to the notmuch CLI to
457 avoid system argument length limits and performance problems.")
459 (defun notmuch-tag (query tag-changes)
460 "Add/remove tags in TAG-CHANGES to messages matching QUERY.
462 QUERY should be a string containing the search-terms.
463 TAG-CHANGES is a list of strings of the form \"+tag\" or
464 \"-tag\" to add or remove tags, respectively.
466 Note: Other code should always use this function to alter tags of
467 messages instead of running (notmuch-call-notmuch-process \"tag\" ..)
468 directly, so that hooks specified in notmuch-before-tag-hook and
469 notmuch-after-tag-hook will be run."
470 ;; Perform some validation
471 (mapc (lambda (tag-change)
472 (unless (string-match-p "^[-+]\\S-+$" tag-change)
473 (error "Tag must be of the form `+this_tag' or `-that_tag'")))
476 (error "Nothing to tag!"))
477 (unless (null tag-changes)
478 (run-hooks 'notmuch-before-tag-hook)
479 (if (<= (length query) notmuch-tag-argument-limit)
480 (apply 'notmuch-call-notmuch-process "tag"
481 (append tag-changes (list "--" query)))
482 ;; Use batch tag mode to avoid argument length limitations
483 (let ((batch-op (concat (mapconcat #'notmuch-hex-encode tag-changes " ")
485 (notmuch-call-notmuch-process :stdin-string batch-op "tag" "--batch")))
486 (run-hooks 'notmuch-after-tag-hook)))
488 (defun notmuch-tag-change-list (tags &optional reverse)
489 "Convert TAGS into a list of tag changes.
491 Add a \"+\" prefix to any tag in TAGS list that doesn't already
492 begin with a \"+\" or a \"-\". If REVERSE is non-nil, replace all
493 \"+\" prefixes with \"-\" and vice versa in the result."
494 (mapcar (lambda (str)
495 (let ((s (if (string-match "^[+-]" str) str (concat "+" str))))
497 (concat (if (= (string-to-char s) ?-) "+" "-")
502 (defvar notmuch-tag-jump-reverse-key "k"
503 "The key in tag-jump to switch to the reverse tag changes.")
505 (defun notmuch-tag-jump (reverse)
506 "Create a jump menu for tagging operations.
508 Creates and displays a jump menu for the tagging operations
509 specified in `notmuch-tagging-keys'. If REVERSE is set then it
510 offers a menu of the reverses of the operations specified in
511 `notmuch-tagging-keys'; i.e. each `+tag` is replaced by `-tag`
513 ;; In principle this function is simple, but it has to deal with
514 ;; lots of cases: different modes (search/show/tree), whether a name
515 ;; is specified, whether the tagging operations is a list of
516 ;; tag-ops, or a symbol that evaluates to such a list, and whether
517 ;; REVERSE is specified.
520 (pcase-dolist (`(,key ,tag ,name) notmuch-tagging-keys)
521 (let* ((tag-function (cl-case major-mode
522 (notmuch-search-mode #'notmuch-search-tag)
523 (notmuch-show-mode #'notmuch-show-tag)
524 (notmuch-tree-mode #'notmuch-tree-tag)))
525 (tag (if (symbolp tag)
528 (tag-change (if reverse
529 (notmuch-tag-change-list tag 't)
531 (name (or (and (not (string= name ""))
534 (symbol-name name))))
535 (name-string (if name
537 (concat "Reverse " name)
539 (mapconcat #'identity tag-change " "))))
540 (push (list key name-string
541 `(lambda () (,tag-function ',tag-change)))
543 (push (list notmuch-tag-jump-reverse-key
545 "Forward tag changes "
546 "Reverse tag changes")
547 (apply-partially 'notmuch-tag-jump (not reverse)))
549 (setq action-map (nreverse action-map))
550 (notmuch-jump action-map "Tag: ")))
554 (provide 'notmuch-tag)