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>
29 (require 'notmuch-lib)
31 (declare-function notmuch-search-tag "notmuch" tag-changes)
32 (declare-function notmuch-show-tag "notmuch-show" tag-changes)
33 (declare-function notmuch-tree-tag "notmuch-tree" tag-changes)
35 (autoload 'notmuch-jump "notmuch-jump")
37 (define-widget 'notmuch-tag-key-type 'list
38 "A single key tagging binding."
40 :args '((list :inline t
42 (key-sequence :tag "Key")
43 (radio :tag "Tag operations" (repeat :tag "Tag list" (string :format "%v" :tag "change"))
44 (variable :tag "Tag variable"))
45 (string :tag "Name"))))
47 (defcustom notmuch-tagging-keys
48 `((,(kbd "a") notmuch-archive-tags "Archive")
49 (,(kbd "u") notmuch-show-mark-read-tags "Mark read")
50 (,(kbd "f") ("+flagged") "Flag")
51 (,(kbd "s") ("+spam" "-inbox") "Mark as spam")
52 (,(kbd "d") ("+deleted" "-inbox") "Delete"))
53 "A list of keys and corresponding tagging operations.
55 For each key (or key sequence) you can specify a sequence of
56 tagging operations to apply, or a variable which contains a list
57 of tagging operations such as `notmuch-archive-tags'. The final
58 element is a name for this tagging operation. If the name is
59 omitted or empty then the list of tag changes, or the variable
60 name is used as the name.
62 The key `notmuch-tag-jump-reverse-key' (k by default) should not
63 be used (either as a key, or as the start of a key sequence) as
64 it is already bound: it switches the menu to a menu of the
65 reverse tagging operations. The reverse of a tagging operation is
66 the same list of individual tag-ops but with `+tag` replaced by
67 `-tag` and vice versa.
69 If setting this variable outside of customize then it should be a
70 list of triples (lists of three elements). Each triple should be
71 of the form (key-binding tagging-operations name). KEY-BINDING
72 can be a single character or a key sequence; TAGGING-OPERATIONS
73 should either be a list of individual tag operations each of the
74 form `+tag` or `-tag`, or the variable name of a variable that is
75 a list of tagging operations; NAME should be a name for the
76 tagging operation, if omitted or empty than then name is taken
77 from TAGGING-OPERATIONS."
78 :tag "List of tagging bindings"
79 :type '(repeat notmuch-tag-key-type)
82 (define-widget 'notmuch-tag-format-type 'lazy
83 "Customize widget for notmuch-tag-format and friends"
84 :type '(alist :key-type (regexp :tag "Tag")
88 (const :tag "Hidden" nil)
90 (string :tag "Display as")
91 (list :tag "Face" :extra-offset -4
92 (const :format "" :inline t
93 (notmuch-apply-face tag))
95 (const :format "" quote)
97 (list :format "%v" :extra-offset -4
98 (const :format "" :inline t
99 (notmuch-tag-format-image-data tag))
102 (notmuch-tag-star-icon))
103 (const :tag "Empty star"
104 (notmuch-tag-star-empty-icon))
106 (notmuch-tag-tag-icon))
107 (string :tag "Custom")))
108 (sexp :tag "Custom")))))
110 (defface notmuch-tag-unread
111 '((t :foreground "red"))
112 "Default face used for the unread tag.
114 Used in the default value of `notmuch-tag-formats`."
115 :group 'notmuch-faces)
117 (defface notmuch-tag-flagged
120 (:foreground "LightBlue1"))
123 (:foreground "blue")))
124 "Face used for the flagged tag.
126 Used in the default value of `notmuch-tag-formats`."
127 :group 'notmuch-faces)
129 (defcustom notmuch-tag-formats
130 '(("unread" (propertize tag 'face 'notmuch-tag-unread))
131 ("flagged" (propertize tag 'face 'notmuch-tag-flagged)
132 (notmuch-tag-format-image-data tag (notmuch-tag-star-icon))))
133 "Custom formats for individual tags.
135 This is an association list that maps from tag name regexps to
136 lists of formatting expressions. The first entry whose car
137 regexp-matches a tag will be used to format that tag. The regexp
138 is implicitly anchored, so to match a literal tag name, just use
139 that tag name (if it contains special regexp characters like
140 \".\" or \"*\", these have to be escaped). The cdr of the
141 matching entry gives a list of Elisp expressions that modify the
142 tag. If the list is empty, the tag will simply be hidden.
143 Otherwise, each expression will be evaluated in order: for the
144 first expression, the variable `tag' will be bound to the tag
145 name; for each later expression, the variable `tag' will be bound
146 to the result of the previous expression. In this way, each
147 expression can build on the formatting performed by the previous
148 expression. The result of the last expression will displayed in
151 For example, to replace a tag with another string, simply use
152 that string as a formatting expression. To change the foreground
153 of a tag to red, use the expression
154 (propertize tag 'face '(:foreground \"red\"))
156 See also `notmuch-tag-format-image', which can help replace tags
158 :group 'notmuch-search
160 :group 'notmuch-faces
161 :type 'notmuch-tag-format-type)
163 (defface notmuch-tag-deleted
164 '((((class color) (supports :strike-through "red")) :strike-through "red")
165 (t :inverse-video t))
166 "Face used to display deleted tags.
168 Used in the default value of `notmuch-tag-deleted-formats`."
169 :group 'notmuch-faces)
171 (defcustom notmuch-tag-deleted-formats
172 '(("unread" (notmuch-apply-face bare-tag `notmuch-tag-deleted))
173 (".*" (notmuch-apply-face tag `notmuch-tag-deleted)))
174 "Custom formats for tags when deleted.
176 For deleted tags the formats in `notmuch-tag-formats` are applied
177 first and then these formats are applied on top; that is `tag'
178 passed to the function is the tag with all these previous
179 formattings applied. The formatted can access the original
180 unformatted tag as `bare-tag'.
182 By default this shows deleted tags with strike-through in red,
183 unless strike-through is not available (e.g., emacs is running in
184 a terminal) in which case it uses inverse video. To hide deleted
185 tags completely set this to
188 See `notmuch-tag-formats' for full documentation."
190 :group 'notmuch-faces
191 :type 'notmuch-tag-format-type)
193 (defface notmuch-tag-added
194 '((t :underline "green"))
195 "Default face used for added tags.
197 Used in the default value for `notmuch-tag-added-formats`."
198 :group 'notmuch-faces)
200 (defcustom notmuch-tag-added-formats
201 '((".*" (notmuch-apply-face tag 'notmuch-tag-added)))
202 "Custom formats for tags when added.
204 For added tags the formats in `notmuch-tag-formats` are applied
205 first and then these formats are applied on top.
207 To disable special formatting of added tags, set this variable to
210 See `notmuch-tag-formats' for full documentation."
212 :group 'notmuch-faces
213 :type 'notmuch-tag-format-type)
215 (defun notmuch-tag-format-image-data (tag data)
216 "Replace TAG with image DATA, if available.
218 This function returns a propertized string that will display image
219 DATA in place of TAG.This is designed for use in
220 `notmuch-tag-formats'.
222 DATA is the content of an SVG picture (e.g., as returned by
223 `notmuch-tag-star-icon')."
224 (propertize tag 'display
230 (defun notmuch-tag-star-icon ()
231 "Return SVG data representing a star icon.
232 This can be used with `notmuch-tag-format-image-data'."
233 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>
234 <svg version=\"1.1\" width=\"16\" height=\"16\">
235 <g transform=\"translate(-242.81601,-315.59635)\">
237 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\"
238 transform=\"matrix(0.2484147,-0.02623394,0.02623394,0.2484147,174.63605,255.37691)\"
239 style=\"fill:#ffff00;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1\" />
243 (defun notmuch-tag-star-empty-icon ()
244 "Return SVG data representing an empty star icon.
245 This can be used with `notmuch-tag-format-image-data'."
246 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>
247 <svg version=\"1.1\" width=\"16\" height=\"16\">
248 <g transform=\"translate(-242.81601,-315.59635)\">
250 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\"
251 transform=\"matrix(0.2484147,-0.02623394,0.02623394,0.2484147,174.63605,255.37691)\"
252 style=\"fill:#d6d6d1;fill-opacity:1;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1\" />
256 (defun notmuch-tag-tag-icon ()
257 "Return SVG data representing a tag icon.
258 This can be used with `notmuch-tag-format-image-data'."
259 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>
260 <svg version=\"1.1\" width=\"16\" height=\"16\">
261 <g transform=\"translate(0,-1036.3622)\">
263 d=\"m 0.44642857,1040.9336 12.50000043,0 2.700893,3.6161 -2.700893,3.616 -12.50000043,0 z\"
264 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\" />
268 (defvar notmuch-tag--format-cache (make-hash-table :test 'equal)
269 "Cache of tag format lookup. Internal to `notmuch-tag-format-tag'.")
271 (defun notmuch-tag-clear-cache ()
272 "Clear the internal cache of tag formats."
273 (clrhash notmuch-tag--format-cache))
275 (defun notmuch-tag--get-formats (tag format-alist)
276 "Find the first item whose car regexp-matches TAG."
278 ;; Don't use assoc-default since there's no way to distinguish a
279 ;; missing key from a present key with a null cdr.
280 (assoc* tag format-alist
281 :test (lambda (tag key)
282 (and (eq (string-match key tag) 0)
283 (= (match-end 0) (length tag)))))))
285 (defun notmuch-tag--do-format (tag formatted-tag formats)
286 "Apply a tag-formats entry to TAG."
287 (cond ((null formats) ;; - Tag not in `formats',
288 formatted-tag) ;; the format is the tag itself.
289 ((null (cdr formats)) ;; - Tag was deliberately hidden,
290 nil) ;; no format must be returned
292 ;; Tag was found and has formats, we must apply all the
293 ;; formats. TAG may be null so treat that as a special case.
295 (tag (copy-sequence (or formatted-tag ""))))
296 (dolist (format (cdr formats))
297 (setq tag (eval format)))
298 (if (and (null formatted-tag) (equal tag ""))
302 (defun notmuch-tag-format-tag (tags orig-tags tag)
303 "Format TAG according to `notmuch-tag-formats'.
305 TAGS and ORIG-TAGS are lists of the current tags and the original
306 tags; tags which have been deleted (i.e., are in ORIG-TAGS but
307 are not in TAGS) are shown using formats from
308 `notmuch-tag-deleted-formats'; tags which have been added (i.e.,
309 are in TAGS but are not in ORIG-TAGS) are shown using formats
310 from `notmuch-tag-added-formats' and tags which have not been
311 changed (the normal case) are shown using formats from
312 `notmuch-tag-formats'"
313 (let* ((tag-state (cond ((not (member tag tags)) 'deleted)
314 ((not (member tag orig-tags)) 'added)))
315 (formatted-tag (gethash (cons tag tag-state) notmuch-tag--format-cache 'missing)))
316 (when (eq formatted-tag 'missing)
317 (let ((base (notmuch-tag--get-formats tag notmuch-tag-formats))
318 (over (case tag-state
319 (deleted (notmuch-tag--get-formats
320 tag notmuch-tag-deleted-formats))
321 (added (notmuch-tag--get-formats
322 tag notmuch-tag-added-formats))
324 (setq formatted-tag (notmuch-tag--do-format tag tag base))
325 (setq formatted-tag (notmuch-tag--do-format tag formatted-tag over))
327 (puthash (cons tag tag-state) formatted-tag notmuch-tag--format-cache)))
330 (defun notmuch-tag-format-tags (tags orig-tags &optional face)
331 "Return a string representing formatted TAGS."
332 (let ((face (or face 'notmuch-tag-face))
333 (all-tags (sort (delete-dups (append tags orig-tags nil)) #'string<)))
335 (mapconcat #'identity
336 ;; nil indicated that the tag was deliberately hidden
338 (apply-partially #'notmuch-tag-format-tag tags orig-tags)
344 (defcustom notmuch-before-tag-hook nil
345 "Hooks that are run before tags of a message are modified.
347 'tag-changes' will contain the tags that are about to be added or removed as
348 a list of strings of the form \"+TAG\" or \"-TAG\".
349 'query' will be a string containing the search query that determines
350 the messages that are about to be tagged"
353 :options '(notmuch-hl-line-mode)
354 :group 'notmuch-hooks)
356 (defcustom notmuch-after-tag-hook nil
357 "Hooks that are run after tags of a message are modified.
359 'tag-changes' will contain the tags that were added or removed as
360 a list of strings of the form \"+TAG\" or \"-TAG\".
361 'query' will be a string containing the search query that determines
362 the messages that were tagged"
364 :options '(notmuch-hl-line-mode)
365 :group 'notmuch-hooks)
367 (defvar notmuch-select-tag-history nil
368 "Variable to store minibuffer history for
369 `notmuch-select-tag-with-completion' function.")
371 (defvar notmuch-read-tag-changes-history nil
372 "Variable to store minibuffer history for
373 `notmuch-read-tag-changes' function.")
375 (defun notmuch-tag-completions (&rest search-terms)
376 "Return a list of tags for messages matching SEARCH-TERMS.
378 Returns all tags if no search terms are given."
379 (if (null search-terms)
380 (setq search-terms (list "*")))
382 (with-output-to-string
383 (with-current-buffer standard-output
384 (apply 'call-process notmuch-command nil t
385 nil "search" "--output=tags" "--exclude=false" search-terms)))
388 (defun notmuch-select-tag-with-completion (prompt &rest search-terms)
389 (let ((tag-list (apply #'notmuch-tag-completions search-terms)))
390 (completing-read prompt tag-list nil nil nil 'notmuch-select-tag-history)))
392 (defun notmuch-read-tag-changes (current-tags &optional prompt initial-input)
393 "Prompt for tag changes in the minibuffer.
395 CURRENT-TAGS is a list of tags that are present on the message or
396 messages to be changed. These are offered as tag removal
397 completions. CURRENT-TAGS may contain duplicates. PROMPT, if
398 non-nil, is the query string to present in the minibuffer. It
399 defaults to \"Tags\". INITIAL-INPUT, if non-nil, will be the
400 initial input in the minibuffer."
402 (let* ((all-tag-list (notmuch-tag-completions))
403 (add-tag-list (mapcar (apply-partially 'concat "+") all-tag-list))
404 (remove-tag-list (mapcar (apply-partially 'concat "-") current-tags))
405 (tag-list (append add-tag-list remove-tag-list))
406 (prompt (concat (or prompt "Tags") " (+add -drop): "))
408 ;; By default, space is bound to "complete word" function.
409 ;; Re-bind it to insert a space instead. Note that <tab>
410 ;; still does the completion.
411 (crm-local-completion-map
412 (let ((map (make-sparse-keymap)))
413 (set-keymap-parent map crm-local-completion-map)
414 (define-key map " " 'self-insert-command)
416 (delete "" (completing-read-multiple
418 ;; Append the separator to each completion so when the
419 ;; user completes a tag they can immediately begin
420 ;; entering another. `completing-read-multiple'
421 ;; ultimately splits the input on crm-separator, so we
422 ;; don't need to strip this back off (we just need to
423 ;; delete "empty" entries caused by trailing spaces).
424 (mapcar (lambda (tag-op) (concat tag-op crm-separator)) tag-list)
425 nil nil initial-input
426 'notmuch-read-tag-changes-history))))
428 (defun notmuch-update-tags (tags tag-changes)
429 "Return a copy of TAGS with additions and removals from TAG-CHANGES.
431 TAG-CHANGES must be a list of tags names, each prefixed with
432 either a \"+\" to indicate the tag should be added to TAGS if not
433 present or a \"-\" to indicate that the tag should be removed
434 from TAGS if present."
435 (let ((result-tags (copy-sequence tags)))
436 (dolist (tag-change tag-changes)
437 (let ((op (string-to-char tag-change))
438 (tag (unless (string= tag-change "") (substring tag-change 1))))
440 (?+ (unless (member tag result-tags)
441 (push tag result-tags)))
442 (?- (setq result-tags (delete tag result-tags)))
444 (error "Changed tag must be of the form `+this_tag' or `-that_tag'")))))
445 (sort result-tags 'string<)))
447 (defconst notmuch-tag-argument-limit 1000
448 "Use batch tagging if the tagging query is longer than this.
450 This limits the length of arguments passed to the notmuch CLI to
451 avoid system argument length limits and performance problems.")
453 (defun notmuch-tag (query tag-changes)
454 "Add/remove tags in TAG-CHANGES to messages matching QUERY.
456 QUERY should be a string containing the search-terms.
457 TAG-CHANGES is a list of strings of the form \"+tag\" or
458 \"-tag\" to add or remove tags, respectively.
460 Note: Other code should always use this function to alter tags of
461 messages instead of running (notmuch-call-notmuch-process \"tag\" ..)
462 directly, so that hooks specified in notmuch-before-tag-hook and
463 notmuch-after-tag-hook will be run."
464 ;; Perform some validation
465 (mapc (lambda (tag-change)
466 (unless (string-match-p "^[-+]\\S-+$" tag-change)
467 (error "Tag must be of the form `+this_tag' or `-that_tag'")))
470 (error "Nothing to tag!"))
471 (unless (null tag-changes)
472 (run-hooks 'notmuch-before-tag-hook)
473 (if (<= (length query) notmuch-tag-argument-limit)
474 (apply 'notmuch-call-notmuch-process "tag"
475 (append tag-changes (list "--" query)))
476 ;; Use batch tag mode to avoid argument length limitations
477 (let ((batch-op (concat (mapconcat #'notmuch-hex-encode tag-changes " ")
479 (notmuch-call-notmuch-process :stdin-string batch-op "tag" "--batch")))
480 (run-hooks 'notmuch-after-tag-hook)))
482 (defun notmuch-tag-change-list (tags &optional reverse)
483 "Convert TAGS into a list of tag changes.
485 Add a \"+\" prefix to any tag in TAGS list that doesn't already
486 begin with a \"+\" or a \"-\". If REVERSE is non-nil, replace all
487 \"+\" prefixes with \"-\" and vice versa in the result."
488 (mapcar (lambda (str)
489 (let ((s (if (string-match "^[+-]" str) str (concat "+" str))))
491 (concat (if (= (string-to-char s) ?-) "+" "-")
496 (defvar notmuch-tag-jump-reverse-key "k"
497 "The key in tag-jump to switch to the reverse tag changes.")
499 (defun notmuch-tag-jump (reverse)
500 "Create a jump menu for tagging operations.
502 Creates and displays a jump menu for the tagging operations
503 specified in `notmuch-tagging-keys'. If REVERSE is set then it
504 offers a menu of the reverses of the operations specified in
505 `notmuch-tagging-keys'; i.e. each `+tag` is replaced by `-tag`
507 ;; In principle this function is simple, but it has to deal with
508 ;; lots of cases: different modes (search/show/tree), whether a name
509 ;; is specified, whether the tagging operations is a list of
510 ;; tag-ops, or a symbol that evaluates to such a list, and whether
511 ;; REVERSE is specified.
514 (dolist (binding notmuch-tagging-keys)
515 (let* ((tag-function (case major-mode
516 (notmuch-search-mode #'notmuch-search-tag)
517 (notmuch-show-mode #'notmuch-show-tag)
518 (notmuch-tree-mode #'notmuch-tree-tag)))
519 (key (first binding))
520 (forward-tag-change (if (symbolp (second binding))
521 (symbol-value (second binding))
523 (tag-change (if reverse
524 (notmuch-tag-change-list forward-tag-change 't)
526 (name (or (and (not (string= (third binding) ""))
528 (and (symbolp (second binding))
529 (symbol-name (second binding)))))
530 (name-string (if name
531 (if reverse (concat "Reverse " name)
533 (mapconcat #'identity tag-change " "))))
534 (push (list key name-string
535 `(lambda () (,tag-function ',tag-change)))
537 (push (list notmuch-tag-jump-reverse-key
539 "Forward tag changes "
540 "Reverse tag changes")
541 (apply-partially 'notmuch-tag-jump (not reverse)))
543 (setq action-map (nreverse action-map))
544 (notmuch-jump action-map "Tag: ")))
548 (provide 'notmuch-tag)
551 ;; byte-compile-warnings: (not cl-functions)