]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch.el
emacs: Re-work the implementation of highlighting in notmuch-search-mode.
[notmuch] / emacs / notmuch.el
1 ; notmuch.el --- run notmuch within emacs
2 ;
3 ; Copyright © Carl Worth
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 <http://www.gnu.org/licenses/>.
19 ;
20 ; Authors: Carl Worth <cworth@cworth.org>
21
22 ; This is an emacs-based interface to the notmuch mail system.
23 ;
24 ; You will first need to have the notmuch program installed and have a
25 ; notmuch database built in order to use this. See
26 ; http://notmuchmail.org for details.
27 ;
28 ; To install this software, copy it to a directory that is on the
29 ; `load-path' variable within emacs (a good candidate is
30 ; /usr/local/share/emacs/site-lisp). If you are viewing this from the
31 ; notmuch source distribution then you can simply run:
32 ;
33 ;       sudo make install-emacs
34 ;
35 ; to install it.
36 ;
37 ; Then, to actually run it, add:
38 ;
39 ;       (require 'notmuch)
40 ;
41 ; to your ~/.emacs file, and then run "M-x notmuch" from within emacs,
42 ; or run:
43 ;
44 ;       emacs -f notmuch
45 ;
46 ; Have fun, and let us know if you have any comment, questions, or
47 ; kudos: Notmuch list <notmuch@notmuchmail.org> (subscription is not
48 ; required, but is available from http://notmuchmail.org).
49
50 (eval-when-compile (require 'cl))
51 (require 'mm-view)
52 (require 'message)
53
54 (require 'notmuch-lib)
55 (require 'notmuch-show)
56 (require 'notmuch-mua)
57 (require 'notmuch-hello)
58 (require 'notmuch-maildir-fcc)
59 (require 'notmuch-message)
60
61 (defcustom notmuch-search-result-format
62   `(("date" . "%s ")
63     ("count" . "%-7s ")
64     ("authors" . "%-20s ")
65     ("subject" . "%s ")
66     ("tags" . "(%s)"))
67   "Search result formating. Supported fields are:
68         date, count, authors, subject, tags
69 For example:
70         (setq notmuch-search-result-format \(\(\"authors\" . \"%-40s\"\)
71                                              \(\"subject\" . \"%s\"\)\)\)"
72   :type '(alist :key-type (string) :value-type (string))
73   :group 'notmuch)
74
75 (defun notmuch-select-tag-with-completion (prompt &rest search-terms)
76   (let ((tag-list
77          (with-output-to-string
78            (with-current-buffer standard-output
79              (apply 'call-process notmuch-command nil t nil "search-tags" search-terms)))))
80     (completing-read prompt (split-string tag-list "\n+" t) nil nil nil)))
81
82 (defun notmuch-foreach-mime-part (function mm-handle)
83   (cond ((stringp (car mm-handle))
84          (dolist (part (cdr mm-handle))
85            (notmuch-foreach-mime-part function part)))
86         ((bufferp (car mm-handle))
87          (funcall function mm-handle))
88         (t (dolist (part mm-handle)
89              (notmuch-foreach-mime-part function part)))))
90
91 (defun notmuch-count-attachments (mm-handle)
92   (let ((count 0))
93     (notmuch-foreach-mime-part
94      (lambda (p)
95        (let ((disposition (mm-handle-disposition p)))
96          (and (listp disposition)
97               (or (equal (car disposition) "attachment")
98                   (and (equal (car disposition) "inline")
99                        (assq 'filename disposition)))
100               (incf count))))
101      mm-handle)
102     count))
103
104 (defun notmuch-save-attachments (mm-handle &optional queryp)
105   (notmuch-foreach-mime-part
106    (lambda (p)
107      (let ((disposition (mm-handle-disposition p)))
108        (and (listp disposition)
109             (or (equal (car disposition) "attachment")
110                 (and (equal (car disposition) "inline")
111                      (assq 'filename disposition)))
112             (or (not queryp)
113                 (y-or-n-p
114                  (concat "Save '" (cdr (assq 'filename disposition)) "' ")))
115             (mm-save-part p))))
116    mm-handle))
117
118 (defun notmuch-documentation-first-line (symbol)
119   "Return the first line of the documentation string for SYMBOL."
120   (let ((doc (documentation symbol)))
121     (if doc
122         (with-temp-buffer
123           (insert (documentation symbol t))
124           (goto-char (point-min))
125           (let ((beg (point)))
126             (end-of-line)
127             (buffer-substring beg (point))))
128       "")))
129
130 (defun notmuch-prefix-key-description (key)
131   "Given a prefix key code, return a human-readable string representation.
132
133 This is basically just `format-kbd-macro' but we also convert ESC to M-."
134   (let ((desc (format-kbd-macro (vector key))))
135     (if (string= desc "ESC")
136         "M-"
137       (concat desc " "))))
138
139 ; I would think that emacs would have code handy for walking a keymap
140 ; and generating strings for each key, and I would prefer to just call
141 ; that. But I couldn't find any (could be all implemented in C I
142 ; suppose), so I wrote my own here.
143 (defun notmuch-substitute-one-command-key-with-prefix (prefix binding)
144   "For a key binding, return a string showing a human-readable
145 representation of the prefixed key as well as the first line of
146 documentation from the bound function.
147
148 For a mouse binding, return nil."
149   (let ((key (car binding))
150         (action (cdr binding)))
151     (if (mouse-event-p key)
152         nil
153       (if (keymapp action)
154           (let ((substitute (apply-partially 'notmuch-substitute-one-command-key-with-prefix (notmuch-prefix-key-description key)))
155                 (as-list))
156             (map-keymap (lambda (a b)
157                           (push (cons a b) as-list))
158                         action)
159             (mapconcat substitute as-list "\n"))
160         (concat prefix (format-kbd-macro (vector key))
161                 "\t"
162                 (notmuch-documentation-first-line action))))))
163
164 (defalias 'notmuch-substitute-one-command-key
165   (apply-partially 'notmuch-substitute-one-command-key-with-prefix nil))
166
167 (defun notmuch-substitute-command-keys (doc)
168   "Like `substitute-command-keys' but with documentation, not function names."
169   (let ((beg 0))
170     (while (string-match "\\\\{\\([^}[:space:]]*\\)}" doc beg)
171       (let ((map (substring doc (match-beginning 1) (match-end 1))))
172         (setq doc (replace-match (mapconcat 'notmuch-substitute-one-command-key
173                                             (cdr (symbol-value (intern map))) "\n") 1 1 doc)))
174       (setq beg (match-end 0)))
175     doc))
176
177 (defun notmuch-help ()
178   "Display help for the current notmuch mode."
179   (interactive)
180   (let* ((mode major-mode)
181          (doc (substitute-command-keys (notmuch-substitute-command-keys (documentation mode t)))))
182     (with-current-buffer (generate-new-buffer "*notmuch-help*")
183       (insert doc)
184       (goto-char (point-min))
185       (set-buffer-modified-p nil)
186       (view-buffer (current-buffer) 'kill-buffer-if-not-modified))))
187
188 (defcustom notmuch-search-hook '(hl-line-mode)
189   "List of functions to call when notmuch displays the search results."
190   :type 'hook
191   :options '(hl-line-mode)
192   :group 'notmuch)
193
194 (defvar notmuch-search-mode-map
195   (let ((map (make-sparse-keymap)))
196     (define-key map "?" 'notmuch-help)
197     (define-key map "q" 'notmuch-search-quit)
198     (define-key map "x" 'notmuch-search-quit)
199     (define-key map (kbd "<DEL>") 'notmuch-search-scroll-down)
200     (define-key map "b" 'notmuch-search-scroll-down)
201     (define-key map " " 'notmuch-search-scroll-up)
202     (define-key map "<" 'notmuch-search-first-thread)
203     (define-key map ">" 'notmuch-search-last-thread)
204     (define-key map "p" 'notmuch-search-previous-thread)
205     (define-key map "n" 'notmuch-search-next-thread)
206     (define-key map "r" 'notmuch-search-reply-to-thread)
207     (define-key map "m" 'notmuch-mua-mail)
208     (define-key map "s" 'notmuch-search)
209     (define-key map "o" 'notmuch-search-toggle-order)
210     (define-key map "=" 'notmuch-search-refresh-view)
211     (define-key map "G" 'notmuch-search-poll-and-refresh-view)
212     (define-key map "t" 'notmuch-search-filter-by-tag)
213     (define-key map "f" 'notmuch-search-filter)
214     (define-key map [mouse-1] 'notmuch-search-show-thread)
215     (define-key map "*" 'notmuch-search-operate-all)
216     (define-key map "a" 'notmuch-search-archive-thread)
217     (define-key map "-" 'notmuch-search-remove-tag)
218     (define-key map "+" 'notmuch-search-add-tag)
219     (define-key map (kbd "RET") 'notmuch-search-show-thread)
220     map)
221   "Keymap for \"notmuch search\" buffers.")
222 (fset 'notmuch-search-mode-map notmuch-search-mode-map)
223
224 (defvar notmuch-search-query-string)
225 (defvar notmuch-search-target-thread)
226 (defvar notmuch-search-target-line)
227 (defvar notmuch-search-continuation)
228
229 (defvar notmuch-search-disjunctive-regexp      "\\<[oO][rR]\\>")
230
231 (defun notmuch-search-quit ()
232   "Exit the search buffer, calling any defined continuation function."
233   (interactive)
234   (let ((continuation notmuch-search-continuation))
235     (kill-this-buffer)
236     (when continuation
237       (funcall continuation))))
238
239 (defun notmuch-search-scroll-up ()
240   "Move forward through search results by one window's worth."
241   (interactive)
242   (condition-case nil
243       (scroll-up nil)
244     ((end-of-buffer) (notmuch-search-last-thread))))
245
246 (defun notmuch-search-scroll-down ()
247   "Move backward through the search results by one window's worth."
248   (interactive)
249   ; I don't know why scroll-down doesn't signal beginning-of-buffer
250   ; the way that scroll-up signals end-of-buffer, but c'est la vie.
251   ;
252   ; So instead of trapping a signal we instead check whether the
253   ; window begins on the first line of the buffer and if so, move
254   ; directly to that position. (We have to count lines since the
255   ; window-start position is not the same as point-min due to the
256   ; invisible thread-ID characters on the first line.
257   (if (equal (count-lines (point-min) (window-start)) 0)
258       (goto-char (point-min))
259     (scroll-down nil)))
260
261 (defun notmuch-search-next-thread ()
262   "Select the next thread in the search results."
263   (interactive)
264   (forward-line 1))
265
266 (defun notmuch-search-previous-thread ()
267   "Select the previous thread in the search results."
268   (interactive)
269   (forward-line -1))
270
271 (defun notmuch-search-last-thread ()
272   "Select the last thread in the search results."
273   (interactive)
274   (goto-char (point-max))
275   (forward-line -2))
276
277 (defun notmuch-search-first-thread ()
278   "Select the first thread in the search results."
279   (interactive)
280   (goto-char (point-min)))
281
282 (defface notmuch-message-summary-face
283  '((((class color) (background light)) (:background "#f0f0f0"))
284    (((class color) (background dark)) (:background "#303030")))
285  "Face for the single-line message summary in notmuch-show-mode."
286  :group 'notmuch)
287
288 (defface notmuch-search-date
289   '((t :inherit default))
290   "Face used in search mode for dates."
291   :group 'notmuch)
292
293 (defface notmuch-search-count
294   '((t :inherit default))
295   "Face used in search mode for the count matching the query."
296   :group 'notmuch)
297
298 (defface notmuch-search-subject
299   '((t :inherit default))
300   "Face used in search mode for subjects."
301   :group 'notmuch)
302
303 (defface notmuch-search-matching-authors
304   '((t :inherit default))
305   "Face used in search mode for authors matching the query."
306   :group 'notmuch)
307
308 (defface notmuch-search-non-matching-authors
309   '((((class color)
310       (background dark))
311      (:foreground "grey30"))
312     (((class color)
313       (background light))
314      (:foreground "grey60"))
315     (t
316      (:italic t)))
317   "Face used in search mode for authors not matching the query."
318   :group 'notmuch)
319
320 (defface notmuch-tag-face
321   '((((class color)
322       (background dark))
323      (:foreground "OliveDrab1"))
324     (((class color)
325       (background light))
326      (:foreground "navy blue" :bold t))
327     (t
328      (:bold t)))
329   "Face used in search mode face for tags."
330   :group 'notmuch)
331
332 (defun notmuch-search-mode ()
333   "Major mode displaying results of a notmuch search.
334
335 This buffer contains the results of a \"notmuch search\" of your
336 email archives. Each line in the buffer represents a single
337 thread giving a summary of the thread (a relative date, the
338 number of matched messages and total messages in the thread,
339 participants in the thread, a representative subject line, and
340 any tags).
341
342 Pressing \\[notmuch-search-show-thread] on any line displays that thread. The '\\[notmuch-search-add-tag]' and '\\[notmuch-search-remove-tag]'
343 keys can be used to add or remove tags from a thread. The '\\[notmuch-search-archive-thread]' key
344 is a convenience for archiving a thread (removing the \"inbox\"
345 tag). The '\\[notmuch-search-operate-all]' key can be used to add or remove a tag from all
346 threads in the current buffer.
347
348 Other useful commands are '\\[notmuch-search-filter]' for filtering the current search
349 based on an additional query string, '\\[notmuch-search-filter-by-tag]' for filtering to include
350 only messages with a given tag, and '\\[notmuch-search]' to execute a new, global
351 search.
352
353 Complete list of currently available key bindings:
354
355 \\{notmuch-search-mode-map}"
356   (interactive)
357   (kill-all-local-variables)
358   (make-local-variable 'notmuch-search-query-string)
359   (make-local-variable 'notmuch-search-oldest-first)
360   (make-local-variable 'notmuch-search-target-thread)
361   (make-local-variable 'notmuch-search-target-line)
362   (set (make-local-variable 'notmuch-search-continuation) nil)
363   (set (make-local-variable 'scroll-preserve-screen-position) t)
364   (add-to-invisibility-spec 'notmuch-search)
365   (use-local-map notmuch-search-mode-map)
366   (setq truncate-lines t)
367   (setq major-mode 'notmuch-search-mode
368         mode-name "notmuch-search")
369   (setq buffer-read-only t))
370
371 (defun notmuch-search-properties-in-region (property beg end)
372   (save-excursion
373     (let ((output nil)
374           (last-line (line-number-at-pos end))
375           (max-line (- (line-number-at-pos (point-max)) 2)))
376       (goto-char beg)
377       (beginning-of-line)
378       (while (<= (line-number-at-pos) (min last-line max-line))
379         (setq output (cons (get-text-property (point) property) output))
380         (forward-line 1))
381       output)))
382
383 (defun notmuch-search-find-thread-id ()
384   "Return the thread for the current thread"
385   (get-text-property (point) 'notmuch-search-thread-id))
386
387 (defun notmuch-search-find-thread-id-region (beg end)
388   "Return a list of threads for the current region"
389   (notmuch-search-properties-in-region 'notmuch-search-thread-id beg end))
390
391 (defun notmuch-search-find-authors ()
392   "Return the authors for the current thread"
393   (get-text-property (point) 'notmuch-search-authors))
394
395 (defun notmuch-search-find-authors-region (beg end)
396   "Return a list of authors for the current region"
397   (notmuch-search-properties-in-region 'notmuch-search-authors beg end))
398
399 (defun notmuch-search-find-subject ()
400   "Return the subject for the current thread"
401   (get-text-property (point) 'notmuch-search-subject))
402
403 (defun notmuch-search-find-subject-region (beg end)
404   "Return a list of authors for the current region"
405   (notmuch-search-properties-in-region 'notmuch-search-subject beg end))
406
407 (defun notmuch-search-show-thread ()
408   "Display the currently selected thread."
409   (interactive)
410   (let ((thread-id (notmuch-search-find-thread-id))
411         (subject (notmuch-search-find-subject)))
412     (if (> (length thread-id) 0)
413         (notmuch-show thread-id
414                       (current-buffer)
415                       notmuch-search-query-string
416                       ;; name the buffer based on notmuch-search-find-subject
417                       (if (string-match "^[ \t]*$" subject)
418                           "[No Subject]"
419                         (truncate-string-to-width
420                          (concat "*"
421                                  (truncate-string-to-width subject 32 nil nil t)
422                                  "*")
423                          32 nil nil t)))
424       (error "End of search results"))))
425
426 (defun notmuch-search-reply-to-thread ()
427   "Begin composing a reply to the entire current thread in a new buffer."
428   (interactive)
429   (let ((message-id (notmuch-search-find-thread-id)))
430     (notmuch-mua-reply message-id)))
431
432 (defun notmuch-call-notmuch-process (&rest args)
433   "Synchronously invoke \"notmuch\" with the given list of arguments.
434
435 Output from the process will be presented to the user as an error
436 and will also appear in a buffer named \"*Notmuch errors*\"."
437   (let ((error-buffer (get-buffer-create "*Notmuch errors*")))
438     (with-current-buffer error-buffer
439         (erase-buffer))
440     (if (eq (apply 'call-process notmuch-command nil error-buffer nil args) 0)
441         (point)
442       (progn
443         (with-current-buffer error-buffer
444           (let ((beg (point-min))
445                 (end (- (point-max) 1)))
446             (error (buffer-substring beg end))
447             ))))))
448
449 (defun notmuch-search-set-tags (tags)
450   (save-excursion
451     (end-of-line)
452     (re-search-backward "(")
453     (forward-char)
454     (let ((beg (point))
455           (inhibit-read-only t))
456       (re-search-forward ")")
457       (backward-char)
458       (let ((end (point)))
459         (delete-region beg end)
460         (insert (propertize (mapconcat  'identity tags " ")
461                             'face 'notmuch-tag-face))))))
462
463 (defun notmuch-search-get-tags ()
464   (save-excursion
465     (end-of-line)
466     (re-search-backward "(")
467     (let ((beg (+ (point) 1)))
468       (re-search-forward ")")
469       (let ((end (- (point) 1)))
470         (split-string (buffer-substring beg end))))))
471
472 (defun notmuch-search-get-tags-region (beg end)
473   (save-excursion
474     (let ((output nil)
475           (last-line (line-number-at-pos end))
476           (max-line (- (line-number-at-pos (point-max)) 2)))
477       (goto-char beg)
478       (while (<= (line-number-at-pos) (min last-line max-line))
479         (setq output (append output (notmuch-search-get-tags)))
480         (forward-line 1))
481       output)))
482
483 (defun notmuch-search-add-tag-thread (tag)
484   (notmuch-search-add-tag-region tag (point) (point)))
485
486 (defun notmuch-search-add-tag-region (tag beg end)
487   (let ((search-id-string (mapconcat 'identity (notmuch-search-find-thread-id-region beg end) " or ")))
488     (notmuch-call-notmuch-process "tag" (concat "+" tag) search-id-string)
489     (save-excursion
490       (let ((last-line (line-number-at-pos end))
491             (max-line (- (line-number-at-pos (point-max)) 2)))
492         (goto-char beg)
493         (while (<= (line-number-at-pos) (min last-line max-line))
494           (notmuch-search-set-tags (delete-dups (sort (cons tag (notmuch-search-get-tags)) 'string<)))
495           (forward-line))))))
496
497 (defun notmuch-search-remove-tag-thread (tag)
498   (notmuch-search-remove-tag-region tag (point) (point)))
499
500 (defun notmuch-search-remove-tag-region (tag beg end)
501   (let ((search-id-string (mapconcat 'identity (notmuch-search-find-thread-id-region beg end) " or ")))
502     (notmuch-call-notmuch-process "tag" (concat "-" tag) search-id-string)
503     (save-excursion
504       (let ((last-line (line-number-at-pos end))
505             (max-line (- (line-number-at-pos (point-max)) 2)))
506         (goto-char beg)
507         (while (<= (line-number-at-pos) (min last-line max-line))
508           (notmuch-search-set-tags (delete tag (notmuch-search-get-tags)))
509           (forward-line))))))
510
511 (defun notmuch-search-add-tag (tag)
512   "Add a tag to the currently selected thread or region.
513
514 The tag is added to all messages in the currently selected thread
515 or threads in the current region."
516   (interactive
517    (list (notmuch-select-tag-with-completion "Tag to add: ")))
518   (save-excursion
519     (if (region-active-p)
520         (let* ((beg (region-beginning))
521                (end (region-end)))
522           (notmuch-search-add-tag-region tag beg end))
523       (notmuch-search-add-tag-thread tag))))
524
525 (defun notmuch-search-remove-tag (tag)
526   "Remove a tag from the currently selected thread or region.
527
528 The tag is removed from all messages in the currently selected
529 thread or threads in the current region."
530   (interactive
531    (list (notmuch-select-tag-with-completion
532           "Tag to remove: "
533           (if (region-active-p)
534               (mapconcat 'identity
535                          (notmuch-search-find-thread-id-region (region-beginning) (region-end))
536                          " ")
537             (notmuch-search-find-thread-id)))))
538   (save-excursion
539     (if (region-active-p)
540         (let* ((beg (region-beginning))
541                (end (region-end)))
542           (notmuch-search-remove-tag-region tag beg end))
543       (notmuch-search-remove-tag-thread tag))))
544
545 (defun notmuch-search-archive-thread ()
546   "Archive the currently selected thread (remove its \"inbox\" tag).
547
548 This function advances the next thread when finished."
549   (interactive)
550   (notmuch-search-remove-tag-thread "inbox")
551   (forward-line))
552
553 (defun notmuch-search-process-sentinel (proc msg)
554   "Add a message to let user know when \"notmuch search\" exits"
555   (let ((buffer (process-buffer proc))
556         (status (process-status proc))
557         (exit-status (process-exit-status proc))
558         (never-found-target-thread nil))
559     (if (memq status '(exit signal))
560         (if (buffer-live-p buffer)
561             (with-current-buffer buffer
562               (save-excursion
563                 (let ((inhibit-read-only t)
564                       (atbob (bobp)))
565                   (goto-char (point-max))
566                   (if (eq status 'signal)
567                       (insert "Incomplete search results (search process was killed).\n"))
568                   (if (eq status 'exit)
569                       (progn
570                         (insert "End of search results.")
571                         (if (not (= exit-status 0))
572                             (insert (format " (process returned %d)" exit-status)))
573                         (insert "\n")
574                         (if (and atbob
575                                  (not (string= notmuch-search-target-thread "found")))
576                             (set 'never-found-target-thread t))))))
577               (when (and never-found-target-thread
578                        notmuch-search-target-line)
579                   (goto-char (point-min))
580                   (forward-line (1- notmuch-search-target-line))))))))
581
582 (defcustom notmuch-search-line-faces nil
583   "Tag/face mapping for line highlighting in notmuch-search.
584
585 Here is an example of how to color search results based on tags.
586  (the following text would be placed in your ~/.emacs file):
587
588  (setq notmuch-search-line-faces '((\"delete\" . '(:foreground \"red\"
589                                                    :background \"blue\"))
590                                    (\"unread\" . '(:foreground \"green\"))))
591
592 The attributes defined for matching tags are merged, with later
593 attributes overriding earlier. A message having both \"delete\"
594 and \"unread\" tags with the above settings would have a green
595 foreground and blue background."
596   :type '(alist :key-type (string) :value-type (list))
597   :group 'notmuch)
598
599 (defun notmuch-search-color-line (start end line-tag-list)
600   "Colorize lines in `notmuch-show' based on tags."
601   ;; Create the overlay only if the message has tags which match one
602   ;; of those specified in `notmuch-search-line-faces'.
603   (let (overlay)
604     (mapc '(lambda (elem)
605              (let ((tag (car elem))
606                    (attributes (cdr elem)))
607                (when (member tag line-tag-list)
608                  (when (not overlay)
609                    (setq overlay (make-overlay start end)))
610                  ;; Merge the specified properties with any already
611                  ;; applied from an earlier match.
612                  (overlay-put overlay 'face
613                               (append (overlay-get overlay 'face) attributes)))))
614           notmuch-search-line-faces)))
615
616 (defun notmuch-search-isearch-authors-show (overlay)
617   (remove-from-invisibility-spec (cons (overlay-get overlay 'invisible) t)))
618
619 (defun notmuch-search-insert-authors (format-string authors)
620   (let* ((propertized-authors
621           ;; Need to save the match data to avoid interfering with
622           ;; `notmuch-search-process-filter'.
623           (save-match-data
624             ;; Authors that don't match the search query are shown in a
625             ;; different font.
626             (if (string-match "\\(.*\\)|\\(..*\\)" authors)
627                 (concat (propertize (concat (match-string 1 authors) ",")
628                                     'face 'notmuch-search-matching-authors)
629                         (propertize (match-string 2 authors)
630                                     'face 'notmuch-search-non-matching-authors))
631               (propertize authors 'face 'notmuch-search-matching-authors))))
632
633          (formatted-sample (format format-string ""))
634          (formatted-authors (format format-string propertized-authors))
635          visible-string invisible-string)
636
637     ;; Determine the part of the authors that will be visible by
638     ;; default.
639     (if (> (length formatted-authors)
640            (length formatted-sample))
641         ;; 4 is `(length "... ")'.
642         (let ((visible-length (- (length formatted-sample) 4)))
643           (setq visible-string (substring propertized-authors 0 visible-length)
644                 invisible-string (substring propertized-authors visible-length)))
645       (setq visible-string formatted-authors
646             invisible-string nil))
647
648     ;; Insert both the visible and invisible author strings.
649     (insert visible-string)
650     (when invisible-string
651       (let ((start (point))
652             (invis-spec (make-symbol "notmuch-search-authors"))
653             overlay)
654         (insert invisible-string)
655         ;; Using a cons-cell here causes an ellipsis to be inserted
656         ;; instead of the invisible text.
657         (add-to-invisibility-spec (cons invis-spec t))
658         (setq overlay (make-overlay start (point)))
659         (overlay-put overlay 'invisible invis-spec)
660         (overlay-put overlay 'isearch-open-invisible #'notmuch-search-isearch-authors-show)
661         (insert " ")))))
662
663 (defun notmuch-search-insert-field (field date count authors subject tags)
664   (cond
665    ((string-equal field "date")
666     (insert (propertize (format (cdr (assoc field notmuch-search-result-format)) date)
667                         'face 'notmuch-search-date)))
668    ((string-equal field "count")
669     (insert (propertize (format (cdr (assoc field notmuch-search-result-format)) count)
670                         'face 'notmuch-search-count)))
671    ((string-equal field "subject")
672     (insert (propertize (format (cdr (assoc field notmuch-search-result-format)) subject)
673                         'face 'notmuch-search-subject)))
674
675    ((string-equal field "authors")
676     (notmuch-search-insert-authors (cdr (assoc field notmuch-search-result-format)) authors))
677
678    ((string-equal field "tags")
679     (insert (concat "(" (propertize tags 'font-lock-face 'notmuch-tag-face) ")")))))
680
681 (defun notmuch-search-show-result (date count authors subject tags)
682   (let ((fields) (field))
683     (setq fields (mapcar 'car notmuch-search-result-format))
684     (loop for field in fields
685           do (notmuch-search-insert-field field date count authors subject tags)))
686   (insert "\n"))
687
688 (defun notmuch-search-process-filter (proc string)
689   "Process and filter the output of \"notmuch search\""
690   (let ((buffer (process-buffer proc))
691         (found-target nil))
692     (if (buffer-live-p buffer)
693         (with-current-buffer buffer
694           (save-excursion
695             (let ((line 0)
696                   (more t)
697                   (inhibit-read-only t))
698               (while more
699                 (if (string-match "^\\(thread:[0-9A-Fa-f]*\\) \\([^][]*\\) \\(\\[[0-9/]*\\]\\) \\([^;]*\\); \\(.*\\) (\\([^()]*\\))$" string line)
700                     (let* ((thread-id (match-string 1 string))
701                            (date (match-string 2 string))
702                            (count (match-string 3 string))
703                            (authors (match-string 4 string))
704                            (subject (match-string 5 string))
705                            (tags (match-string 6 string))
706                            (tag-list (if tags (save-match-data (split-string tags)))))
707                       (goto-char (point-max))
708                       (let ((beg (point-marker)))
709                         (notmuch-search-show-result date count authors subject tags)
710                         (notmuch-search-color-line beg (point-marker) tag-list)
711                         (put-text-property beg (point-marker) 'notmuch-search-thread-id thread-id)
712                         (put-text-property beg (point-marker) 'notmuch-search-authors authors)
713                         (put-text-property beg (point-marker) 'notmuch-search-subject subject)
714                         (if (string= thread-id notmuch-search-target-thread)
715                             (progn
716                               (set 'found-target beg)
717                               (set 'notmuch-search-target-thread "found"))))
718                       (set 'line (match-end 0)))
719                   (set 'more nil)))))
720           (if found-target
721               (goto-char found-target)))
722       (delete-process proc))))
723
724 (defun notmuch-search-operate-all (action)
725   "Add/remove tags from all matching messages.
726
727 Tis command adds or removes tags from all messages matching the
728 current search terms. When called interactively, this command
729 will prompt for tags to be added or removed. Tags prefixed with
730 '+' will be added and tags prefixed with '-' will be removed.
731
732 Each character of the tag name may consist of alphanumeric
733 characters as well as `_.+-'.
734 "
735   (interactive "sOperation (+add -drop): notmuch tag ")
736   (let ((action-split (split-string action " +")))
737     ;; Perform some validation
738     (let ((words action-split))
739       (when (null words) (error "No operation given"))
740       (while words
741         (unless (string-match-p "^[-+][-+_.[:word:]]+$" (car words))
742           (error "Action must be of the form `+thistag -that_tag'"))
743         (setq words (cdr words))))
744     (apply 'notmuch-call-notmuch-process "tag"
745            (append action-split (list notmuch-search-query-string) nil))))
746
747 (defun notmuch-search-buffer-title (query)
748   "Returns the title for a buffer with notmuch search results."
749   (let* ((saved-search
750           (let (longest
751                 (longest-length 0))
752             (loop for tuple in notmuch-saved-searches
753                   if (let ((quoted-query (regexp-quote (cdr tuple))))
754                        (and (string-match (concat "^" quoted-query) query)
755                             (> (length (match-string 0 query))
756                                longest-length)))
757                   do (setq longest tuple))
758             longest))
759          (saved-search-name (car saved-search))
760          (saved-search-query (cdr saved-search)))
761     (cond ((and saved-search (equal saved-search-query query))
762            ;; Query is the same as saved search (ignoring case)
763            (concat "*notmuch-saved-search-" saved-search-name "*"))
764           (saved-search
765            (concat "*notmuch-search-"
766                    (replace-regexp-in-string (concat "^" (regexp-quote saved-search-query))
767                                              (concat "[ " saved-search-name " ]")
768                                              query)
769                    "*"))
770           (t
771            (concat "*notmuch-search-" query "*"))
772           )))
773
774 ;;;###autoload
775 (defun notmuch-search (query &optional oldest-first target-thread target-line continuation)
776   "Run \"notmuch search\" with the given query string and display results.
777
778 The optional parameters are used as follows:
779
780   oldest-first: A Boolean controlling the sort order of returned threads
781   target-thread: A thread ID (with the thread: prefix) that will be made
782                  current if it appears in the search results.
783   target-line: The line number to move to if the target thread does not
784                appear in the search results."
785   (interactive "sNotmuch search: ")
786   (let ((buffer (get-buffer-create (notmuch-search-buffer-title query))))
787     (switch-to-buffer buffer)
788     (notmuch-search-mode)
789     (set 'notmuch-search-query-string query)
790     (set 'notmuch-search-oldest-first oldest-first)
791     (set 'notmuch-search-target-thread target-thread)
792     (set 'notmuch-search-target-line target-line)
793     (set 'notmuch-search-continuation continuation)
794     (let ((proc (get-buffer-process (current-buffer)))
795           (inhibit-read-only t))
796       (if proc
797           (error "notmuch search process already running for query `%s'" query)
798         )
799       (erase-buffer)
800       (goto-char (point-min))
801       (save-excursion
802         (let ((proc (start-process
803                      "notmuch-search" buffer
804                      notmuch-command "search"
805                      (if oldest-first
806                          "--sort=oldest-first"
807                        "--sort=newest-first")
808                      query)))
809           (set-process-sentinel proc 'notmuch-search-process-sentinel)
810           (set-process-filter proc 'notmuch-search-process-filter))))
811     (run-hooks 'notmuch-search-hook)))
812
813 (defun notmuch-search-refresh-view ()
814   "Refresh the current view.
815
816 Kills the current buffer and runs a new search with the same
817 query string as the current search. If the current thread is in
818 the new search results, then point will be placed on the same
819 thread. Otherwise, point will be moved to attempt to be in the
820 same relative position within the new buffer."
821   (interactive)
822   (let ((target-line (line-number-at-pos))
823         (oldest-first notmuch-search-oldest-first)
824         (target-thread (notmuch-search-find-thread-id))
825         (query notmuch-search-query-string)
826         (continuation notmuch-search-continuation))
827     (kill-this-buffer)
828     (notmuch-search query oldest-first target-thread target-line continuation)
829     (goto-char (point-min))))
830
831 (defcustom notmuch-poll-script ""
832   "An external script to incorporate new mail into the notmuch database.
833
834 If this variable is non empty, then it should name a script to be
835 invoked by `notmuch-search-poll-and-refresh-view' and
836 `notmuch-hello-poll-and-update' (each have a default keybinding
837 of 'G'). The script could do any of the following depending on
838 the user's needs:
839
840 1. Invoke a program to transfer mail to the local mail store
841 2. Invoke \"notmuch new\" to incorporate the new mail
842 3. Invoke one or more \"notmuch tag\" commands to classify the mail"
843   :type 'string
844   :group 'notmuch)
845
846 (defun notmuch-poll ()
847   "Run external script to import mail.
848
849 Invokes `notmuch-poll-script' if it is not set to an empty string."
850   (interactive)
851   (if (not (string= notmuch-poll-script ""))
852       (call-process notmuch-poll-script nil nil)))
853
854 (defun notmuch-search-poll-and-refresh-view ()
855   "Invoke `notmuch-poll' to import mail, then refresh the current view."
856   (interactive)
857   (notmuch-poll)
858   (notmuch-search-refresh-view))
859
860 (defun notmuch-search-toggle-order ()
861   "Toggle the current search order.
862
863 By default, the \"inbox\" view created by `notmuch' is displayed
864 in chronological order (oldest thread at the beginning of the
865 buffer), while any global searches created by `notmuch-search'
866 are displayed in reverse-chronological order (newest thread at
867 the beginning of the buffer).
868
869 This command toggles the sort order for the current search.
870
871 Note that any filtered searches created by
872 `notmuch-search-filter' retain the search order of the parent
873 search."
874   (interactive)
875   (set 'notmuch-search-oldest-first (not notmuch-search-oldest-first))
876   (notmuch-search-refresh-view))
877
878 (defun notmuch-search-filter (query)
879   "Filter the current search results based on an additional query string.
880
881 Runs a new search matching only messages that match both the
882 current search results AND the additional query string provided."
883   (interactive "sFilter search: ")
884   (let ((grouped-query (if (string-match-p notmuch-search-disjunctive-regexp query)
885                            (concat "( " query " )")
886                          query)))
887     (notmuch-search (if (string= notmuch-search-query-string "*")
888                         grouped-query
889                       (concat notmuch-search-query-string " and " grouped-query)) notmuch-search-oldest-first)))
890
891 (defun notmuch-search-filter-by-tag (tag)
892   "Filter the current search results based on a single tag.
893
894 Runs a new search matching only messages that match both the
895 current search results AND that are tagged with the given tag."
896   (interactive
897    (list (notmuch-select-tag-with-completion "Filter by tag: ")))
898   (notmuch-search (concat notmuch-search-query-string " and tag:" tag) notmuch-search-oldest-first))
899
900 ;;;###autoload
901 (defun notmuch ()
902   "Run notmuch and display saved searches, known tags, etc."
903   (interactive)
904   (notmuch-hello))
905
906 (setq mail-user-agent 'notmuch-user-agent)
907
908 (provide 'notmuch)