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" tag-changes)
36 (declare-function notmuch-show-tag "notmuch-show" tag-changes)
37 (declare-function notmuch-tree-tag "notmuch-tree" tag-changes)
39 (autoload 'notmuch-jump "notmuch-jump")
41 (define-widget 'notmuch-tag-key-type 'list
42 "A single key tagging binding."
44 :args '((list :inline t
46 (key-sequence :tag "Key")
47 (radio :tag "Tag operations"
48 (repeat :tag "Tag list"
49 (string :format "%v" :tag "change"))
50 (variable :tag "Tag variable"))
51 (string :tag "Name"))))
53 (defcustom notmuch-tagging-keys
54 `((,(kbd "a") notmuch-archive-tags "Archive")
55 (,(kbd "u") notmuch-show-mark-read-tags "Mark read")
56 (,(kbd "f") ("+flagged") "Flag")
57 (,(kbd "s") ("+spam" "-inbox") "Mark as spam")
58 (,(kbd "d") ("+deleted" "-inbox") "Delete"))
59 "A list of keys and corresponding tagging operations.
61 For each key (or key sequence) you can specify a sequence of
62 tagging operations to apply, or a variable which contains a list
63 of tagging operations such as `notmuch-archive-tags'. The final
64 element is a name for this tagging operation. If the name is
65 omitted or empty then the list of tag changes, or the variable
66 name is used as the name.
68 The key `notmuch-tag-jump-reverse-key' (k by default) should not
69 be used (either as a key, or as the start of a key sequence) as
70 it is already bound: it switches the menu to a menu of the
71 reverse tagging operations. The reverse of a tagging operation is
72 the same list of individual tag-ops but with `+tag` replaced by
73 `-tag` and vice versa.
75 If setting this variable outside of customize then it should be a
76 list of triples (lists of three elements). Each triple should be
77 of the form (key-binding tagging-operations name). KEY-BINDING
78 can be a single character or a key sequence; TAGGING-OPERATIONS
79 should either be a list of individual tag operations each of the
80 form `+tag` or `-tag`, or the variable name of a variable that is
81 a list of tagging operations; NAME should be a name for the
82 tagging operation, if omitted or empty than then name is taken
83 from TAGGING-OPERATIONS."
84 :tag "List of tagging bindings"
85 :type '(repeat notmuch-tag-key-type)
88 (define-widget 'notmuch-tag-format-type 'lazy
89 "Customize widget for notmuch-tag-format and friends."
90 :type '(alist :key-type (regexp :tag "Tag")
94 (const :tag "Hidden" nil)
96 (string :tag "Display as")
97 (list :tag "Face" :extra-offset -4
98 (const :format "" :inline t
99 (notmuch-apply-face tag))
101 (const :format "" quote)
103 (list :format "%v" :extra-offset -4
104 (const :format "" :inline t
105 (notmuch-tag-format-image-data tag))
108 (notmuch-tag-star-icon))
109 (const :tag "Empty star"
110 (notmuch-tag-star-empty-icon))
112 (notmuch-tag-tag-icon))
113 (string :tag "Custom")))
114 (sexp :tag "Custom")))))
116 (defface notmuch-tag-unread
117 '((t :foreground "red"))
118 "Default face used for the unread tag.
120 Used in the default value of `notmuch-tag-formats`."
121 :group 'notmuch-faces)
123 (defface notmuch-tag-flagged
126 (:foreground "LightBlue1"))
129 (:foreground "blue")))
130 "Face used for the flagged tag.
132 Used in the default value of `notmuch-tag-formats`."
133 :group 'notmuch-faces)
135 (defcustom notmuch-tag-formats
136 '(("unread" (propertize tag 'face 'notmuch-tag-unread))
137 ("flagged" (propertize tag 'face 'notmuch-tag-flagged)
138 (notmuch-tag-format-image-data tag (notmuch-tag-star-icon))))
139 "Custom formats for individual tags.
141 This is an association list that maps from tag name regexps to
142 lists of formatting expressions. The first entry whose car
143 regexp-matches a tag will be used to format that tag. The regexp
144 is implicitly anchored, so to match a literal tag name, just use
145 that tag name (if it contains special regexp characters like
146 \".\" or \"*\", these have to be escaped). The cdr of the
147 matching entry gives a list of Elisp expressions that modify the
148 tag. If the list is empty, the tag will simply be hidden.
149 Otherwise, each expression will be evaluated in order: for the
150 first expression, the variable `tag' will be bound to the tag
151 name; for each later expression, the variable `tag' will be bound
152 to the result of the previous expression. In this way, each
153 expression can build on the formatting performed by the previous
154 expression. The result of the last expression will displayed in
157 For example, to replace a tag with another string, simply use
158 that string as a formatting expression. To change the foreground
159 of a tag to red, use the expression
160 (propertize tag 'face '(:foreground \"red\"))
162 See also `notmuch-tag-format-image', which can help replace tags
164 :group 'notmuch-search
166 :group 'notmuch-faces
167 :type 'notmuch-tag-format-type)
169 (defface notmuch-tag-deleted
170 '((((class color) (supports :strike-through "red")) :strike-through "red")
171 (t :inverse-video t))
172 "Face used to display deleted tags.
174 Used in the default value of `notmuch-tag-deleted-formats`."
175 :group 'notmuch-faces)
177 (defcustom notmuch-tag-deleted-formats
178 '(("unread" (notmuch-apply-face bare-tag `notmuch-tag-deleted))
179 (".*" (notmuch-apply-face tag `notmuch-tag-deleted)))
180 "Custom formats for tags when deleted.
182 For deleted tags the formats in `notmuch-tag-formats` are applied
183 first and then these formats are applied on top; that is `tag'
184 passed to the function is the tag with all these previous
185 formattings applied. The formatted can access the original
186 unformatted tag as `bare-tag'.
188 By default this shows deleted tags with strike-through in red,
189 unless strike-through is not available (e.g., emacs is running in
190 a terminal) in which case it uses inverse video. To hide deleted
191 tags completely set this to
194 See `notmuch-tag-formats' for full documentation."
196 :group 'notmuch-faces
197 :type 'notmuch-tag-format-type)
199 (defface notmuch-tag-added
200 '((t :underline "green"))
201 "Default face used for added tags.
203 Used in the default value for `notmuch-tag-added-formats`."
204 :group 'notmuch-faces)
206 (defcustom notmuch-tag-added-formats
207 '((".*" (notmuch-apply-face tag 'notmuch-tag-added)))
208 "Custom formats for tags when added.
210 For added tags the formats in `notmuch-tag-formats` are applied
211 first and then these formats are applied on top.
213 To disable special formatting of added tags, set this variable to
216 See `notmuch-tag-formats' for full documentation."
218 :group 'notmuch-faces
219 :type 'notmuch-tag-format-type)
221 (defun notmuch-tag-format-image-data (tag data)
222 "Replace TAG with image DATA, if available.
224 This function returns a propertized string that will display image
225 DATA in place of TAG.This is designed for use in
226 `notmuch-tag-formats'.
228 DATA is the content of an SVG picture (e.g., as returned by
229 `notmuch-tag-star-icon')."
230 (propertize tag 'display
236 (defun notmuch-tag-star-icon ()
237 "Return SVG data representing a star icon.
238 This can be used with `notmuch-tag-format-image-data'."
239 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>
240 <svg version=\"1.1\" width=\"16\" height=\"16\">
241 <g transform=\"translate(-242.81601,-315.59635)\">
243 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\"
244 transform=\"matrix(0.2484147,-0.02623394,0.02623394,0.2484147,174.63605,255.37691)\"
245 style=\"fill:#ffff00;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1\" />
249 (defun notmuch-tag-star-empty-icon ()
250 "Return SVG data representing an empty star icon.
251 This can be used with `notmuch-tag-format-image-data'."
252 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>
253 <svg version=\"1.1\" width=\"16\" height=\"16\">
254 <g transform=\"translate(-242.81601,-315.59635)\">
256 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\"
257 transform=\"matrix(0.2484147,-0.02623394,0.02623394,0.2484147,174.63605,255.37691)\"
258 style=\"fill:#d6d6d1;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1\" />
262 (defun notmuch-tag-tag-icon ()
263 "Return SVG data representing a tag icon.
264 This can be used with `notmuch-tag-format-image-data'."
265 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>
266 <svg version=\"1.1\" width=\"16\" height=\"16\">
267 <g transform=\"translate(0,-1036.3622)\">
269 d=\"m 0.44642857,1040.9336 12.50000043,0 2.700893,3.6161 -2.700893,3.616 -12.50000043,0 z\"
270 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\" />
274 (defvar notmuch-tag--format-cache (make-hash-table :test 'equal)
275 "Cache of tag format lookup. Internal to `notmuch-tag-format-tag'.")
277 (defun notmuch-tag-clear-cache ()
278 "Clear the internal cache of tag formats."
279 (clrhash notmuch-tag--format-cache))
281 (defun notmuch-tag--get-formats (tag format-alist)
282 "Find the first item whose car regexp-matches TAG."
284 ;; Don't use assoc-default since there's no way to distinguish a
285 ;; missing key from a present key with a null cdr.
286 (cl-assoc tag format-alist
287 :test (lambda (tag key)
288 (and (eq (string-match key tag) 0)
289 (= (match-end 0) (length tag)))))))
291 (defun notmuch-tag--do-format (tag formatted-tag formats)
292 "Apply a tag-formats entry to TAG."
293 (cond ((null formats) ;; - Tag not in `formats',
294 formatted-tag) ;; the format is the tag itself.
295 ((null (cdr formats)) ;; - Tag was deliberately hidden,
296 nil) ;; no format must be returned
298 ;; Tag was found and has formats, we must apply all the
299 ;; formats. TAG may be null so treat that as a special case.
301 (tag (copy-sequence (or formatted-tag ""))))
302 (dolist (format (cdr formats))
303 (setq tag (eval format)))
304 (if (and (null formatted-tag) (equal tag ""))
308 (defun notmuch-tag-format-tag (tags orig-tags tag)
309 "Format TAG according to `notmuch-tag-formats'.
311 TAGS and ORIG-TAGS are lists of the current tags and the original
312 tags; tags which have been deleted (i.e., are in ORIG-TAGS but
313 are not in TAGS) are shown using formats from
314 `notmuch-tag-deleted-formats'; tags which have been added (i.e.,
315 are in TAGS but are not in ORIG-TAGS) are shown using formats
316 from `notmuch-tag-added-formats' and tags which have not been
317 changed (the normal case) are shown using formats from
318 `notmuch-tag-formats'."
319 (let* ((tag-state (cond ((not (member tag tags)) 'deleted)
320 ((not (member tag orig-tags)) 'added)))
321 (formatted-tag (gethash (cons tag tag-state)
322 notmuch-tag--format-cache
324 (when (eq formatted-tag 'missing)
325 (let ((base (notmuch-tag--get-formats tag notmuch-tag-formats))
326 (over (cl-case tag-state
327 (deleted (notmuch-tag--get-formats
328 tag notmuch-tag-deleted-formats))
329 (added (notmuch-tag--get-formats
330 tag notmuch-tag-added-formats))
332 (setq formatted-tag (notmuch-tag--do-format tag tag base))
333 (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."
361 :options '(notmuch-hl-line-mode)
362 :group 'notmuch-hooks)
364 (defcustom notmuch-after-tag-hook nil
365 "Hooks that are run after tags of a message are modified.
367 'tag-changes' will contain the tags that were added or removed as
368 a list of strings of the form \"+TAG\" or \"-TAG\".
369 'query' will be a string containing the search query that determines
370 the messages that were tagged."
372 :options '(notmuch-hl-line-mode)
373 :group 'notmuch-hooks)
375 (defvar notmuch-select-tag-history nil
376 "Variable to store minibuffer history for
377 `notmuch-select-tag-with-completion' function.")
379 (defvar notmuch-read-tag-changes-history nil
380 "Variable to store minibuffer history for
381 `notmuch-read-tag-changes' function.")
383 (defun notmuch-tag-completions (&rest search-terms)
384 "Return a list of tags for messages matching SEARCH-TERMS.
386 Returns all tags if no search terms are given."
387 (if (null search-terms)
388 (setq search-terms (list "*")))
390 (with-output-to-string
391 (with-current-buffer standard-output
392 (apply 'call-process notmuch-command nil t
393 nil "search" "--output=tags" "--exclude=false" search-terms)))
396 (defun notmuch-select-tag-with-completion (prompt &rest search-terms)
397 (let ((tag-list (apply #'notmuch-tag-completions search-terms)))
398 (completing-read prompt tag-list nil nil nil 'notmuch-select-tag-history)))
400 (defun notmuch-read-tag-changes (current-tags &optional prompt initial-input)
401 "Prompt for tag changes in the minibuffer.
403 CURRENT-TAGS is a list of tags that are present on the message or
404 messages to be changed. These are offered as tag removal
405 completions. CURRENT-TAGS may contain duplicates. PROMPT, if
406 non-nil, is the query string to present in the minibuffer. It
407 defaults to \"Tags\". INITIAL-INPUT, if non-nil, will be the
408 initial input in the minibuffer."
410 (let* ((all-tag-list (notmuch-tag-completions))
411 (add-tag-list (mapcar (apply-partially 'concat "+") all-tag-list))
412 (remove-tag-list (mapcar (apply-partially 'concat "-") current-tags))
413 (tag-list (append add-tag-list remove-tag-list))
414 (prompt (concat (or prompt "Tags") " (+add -drop): "))
416 ;; By default, space is bound to "complete word" function.
417 ;; Re-bind it to insert a space instead. Note that <tab>
418 ;; still does the completion.
419 (crm-local-completion-map
420 (let ((map (make-sparse-keymap)))
421 (set-keymap-parent map crm-local-completion-map)
422 (define-key map " " 'self-insert-command)
424 (delete "" (completing-read-multiple
426 ;; Append the separator to each completion so when the
427 ;; user completes a tag they can immediately begin
428 ;; entering another. `completing-read-multiple'
429 ;; ultimately splits the input on crm-separator, so we
430 ;; don't need to strip this back off (we just need to
431 ;; delete "empty" entries caused by trailing spaces).
432 (mapcar (lambda (tag-op) (concat tag-op crm-separator)) tag-list)
433 nil nil initial-input
434 'notmuch-read-tag-changes-history))))
436 (defun notmuch-update-tags (tags tag-changes)
437 "Return a copy of TAGS with additions and removals from TAG-CHANGES.
439 TAG-CHANGES must be a list of tags names, each prefixed with
440 either a \"+\" to indicate the tag should be added to TAGS if not
441 present or a \"-\" to indicate that the tag should be removed
442 from TAGS if present."
443 (let ((result-tags (copy-sequence tags)))
444 (dolist (tag-change tag-changes)
445 (let ((op (string-to-char tag-change))
446 (tag (unless (string= tag-change "") (substring tag-change 1))))
448 (?+ (unless (member tag result-tags)
449 (push tag result-tags)))
450 (?- (setq result-tags (delete tag result-tags)))
452 (error "Changed tag must be of the form `+this_tag' or `-that_tag'")))))
453 (sort result-tags 'string<)))
455 (defconst notmuch-tag-argument-limit 1000
456 "Use batch tagging if the tagging query is longer than this.
458 This limits the length of arguments passed to the notmuch CLI to
459 avoid system argument length limits and performance problems.")
461 (defun notmuch-tag (query tag-changes)
462 "Add/remove tags in TAG-CHANGES to messages matching QUERY.
464 QUERY should be a string containing the search-terms.
465 TAG-CHANGES is a list of strings of the form \"+tag\" or
466 \"-tag\" to add or remove tags, respectively.
468 Note: Other code should always use this function to alter tags of
469 messages instead of running (notmuch-call-notmuch-process \"tag\" ..)
470 directly, so that hooks specified in notmuch-before-tag-hook and
471 notmuch-after-tag-hook will be run."
472 ;; Perform some validation
473 (mapc (lambda (tag-change)
474 (unless (string-match-p "^[-+]\\S-+$" tag-change)
475 (error "Tag must be of the form `+this_tag' or `-that_tag'")))
478 (error "Nothing to tag!"))
479 (unless (null tag-changes)
480 (run-hooks 'notmuch-before-tag-hook)
481 (if (<= (length query) notmuch-tag-argument-limit)
482 (apply 'notmuch-call-notmuch-process "tag"
483 (append tag-changes (list "--" query)))
484 ;; Use batch tag mode to avoid argument length limitations
485 (let ((batch-op (concat (mapconcat #'notmuch-hex-encode tag-changes " ")
487 (notmuch-call-notmuch-process :stdin-string batch-op "tag" "--batch")))
488 (run-hooks 'notmuch-after-tag-hook)))
490 (defun notmuch-tag-change-list (tags &optional reverse)
491 "Convert TAGS into a list of tag changes.
493 Add a \"+\" prefix to any tag in TAGS list that doesn't already
494 begin with a \"+\" or a \"-\". If REVERSE is non-nil, replace all
495 \"+\" prefixes with \"-\" and vice versa in the result."
496 (mapcar (lambda (str)
497 (let ((s (if (string-match "^[+-]" str) str (concat "+" str))))
499 (concat (if (= (string-to-char s) ?-) "+" "-")
504 (defvar notmuch-tag-jump-reverse-key "k"
505 "The key in tag-jump to switch to the reverse tag changes.")
507 (defun notmuch-tag-jump (reverse)
508 "Create a jump menu for tagging operations.
510 Creates and displays a jump menu for the tagging operations
511 specified in `notmuch-tagging-keys'. If REVERSE is set then it
512 offers a menu of the reverses of the operations specified in
513 `notmuch-tagging-keys'; i.e. each `+tag` is replaced by `-tag`
515 ;; In principle this function is simple, but it has to deal with
516 ;; lots of cases: different modes (search/show/tree), whether a name
517 ;; is specified, whether the tagging operations is a list of
518 ;; tag-ops, or a symbol that evaluates to such a list, and whether
519 ;; REVERSE is specified.
522 (pcase-dolist (`(,key ,tag ,name) notmuch-tagging-keys)
523 (let* ((tag-function (cl-case major-mode
524 (notmuch-search-mode #'notmuch-search-tag)
525 (notmuch-show-mode #'notmuch-show-tag)
526 (notmuch-tree-mode #'notmuch-tree-tag)))
527 (tag (if (symbolp tag)
530 (tag-change (if reverse
531 (notmuch-tag-change-list tag 't)
533 (name (or (and (not (string= name ""))
536 (symbol-name name))))
537 (name-string (if name
538 (if reverse (concat "Reverse " name)
540 (mapconcat #'identity tag-change " "))))
541 (push (list key name-string
542 `(lambda () (,tag-function ',tag-change)))
544 (push (list notmuch-tag-jump-reverse-key
546 "Forward tag changes "
547 "Reverse tag changes")
548 (apply-partially 'notmuch-tag-jump (not reverse)))
550 (setq action-map (nreverse action-map))
551 (notmuch-jump action-map "Tag: ")))
555 (provide 'notmuch-tag)