]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch.el
c22add7aa97f4a001100bc289c9fbfca6e13e4cb
[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-new-mail)
208     (define-key map "s" 'notmuch-search)
209     (define-key map "o" 'notmuch-search-toggle-order)
210     (define-key map "c" 'notmuch-search-stash-map)
211     (define-key map "=" 'notmuch-search-refresh-view)
212     (define-key map "G" 'notmuch-search-poll-and-refresh-view)
213     (define-key map "t" 'notmuch-search-filter-by-tag)
214     (define-key map "f" 'notmuch-search-filter)
215     (define-key map [mouse-1] 'notmuch-search-show-thread)
216     (define-key map "*" 'notmuch-search-operate-all)
217     (define-key map "a" 'notmuch-search-archive-thread)
218     (define-key map "-" 'notmuch-search-remove-tag)
219     (define-key map "+" 'notmuch-search-add-tag)
220     (define-key map (kbd "RET") 'notmuch-search-show-thread)
221     map)
222   "Keymap for \"notmuch search\" buffers.")
223 (fset 'notmuch-search-mode-map notmuch-search-mode-map)
224
225 (defvar notmuch-search-stash-map
226   (let ((map (make-sparse-keymap)))
227     (define-key map "i" 'notmuch-search-stash-thread-id)
228     map)
229   "Submap for stash commands")
230 (fset 'notmuch-search-stash-map notmuch-search-stash-map)
231
232 (defun notmuch-search-stash-thread-id ()
233   "Copy thread ID of current thread to kill-ring."
234   (interactive)
235   (notmuch-common-do-stash (notmuch-search-find-thread-id)))
236
237 (defvar notmuch-search-query-string)
238 (defvar notmuch-search-target-thread)
239 (defvar notmuch-search-target-line)
240 (defvar notmuch-search-continuation)
241
242 (defvar notmuch-search-disjunctive-regexp      "\\<[oO][rR]\\>")
243
244 (defun notmuch-search-quit ()
245   "Exit the search buffer, calling any defined continuation function."
246   (interactive)
247   (let ((continuation notmuch-search-continuation))
248     (notmuch-kill-this-buffer)
249     (when continuation
250       (funcall continuation))))
251
252 (defun notmuch-search-scroll-up ()
253   "Move forward through search results by one window's worth."
254   (interactive)
255   (condition-case nil
256       (scroll-up nil)
257     ((end-of-buffer) (notmuch-search-last-thread))))
258
259 (defun notmuch-search-scroll-down ()
260   "Move backward through the search results by one window's worth."
261   (interactive)
262   ; I don't know why scroll-down doesn't signal beginning-of-buffer
263   ; the way that scroll-up signals end-of-buffer, but c'est la vie.
264   ;
265   ; So instead of trapping a signal we instead check whether the
266   ; window begins on the first line of the buffer and if so, move
267   ; directly to that position. (We have to count lines since the
268   ; window-start position is not the same as point-min due to the
269   ; invisible thread-ID characters on the first line.
270   (if (equal (count-lines (point-min) (window-start)) 0)
271       (goto-char (point-min))
272     (scroll-down nil)))
273
274 (defun notmuch-search-next-thread ()
275   "Select the next thread in the search results."
276   (interactive)
277   (forward-line 1))
278
279 (defun notmuch-search-previous-thread ()
280   "Select the previous thread in the search results."
281   (interactive)
282   (forward-line -1))
283
284 (defun notmuch-search-last-thread ()
285   "Select the last thread in the search results."
286   (interactive)
287   (goto-char (point-max))
288   (forward-line -2))
289
290 (defun notmuch-search-first-thread ()
291   "Select the first thread in the search results."
292   (interactive)
293   (goto-char (point-min)))
294
295 (defface notmuch-message-summary-face
296  '((((class color) (background light)) (:background "#f0f0f0"))
297    (((class color) (background dark)) (:background "#303030")))
298  "Face for the single-line message summary in notmuch-show-mode."
299  :group 'notmuch)
300
301 (defface notmuch-search-date
302   '((t :inherit default))
303   "Face used in search mode for dates."
304   :group 'notmuch)
305
306 (defface notmuch-search-count
307   '((t :inherit default))
308   "Face used in search mode for the count matching the query."
309   :group 'notmuch)
310
311 (defface notmuch-search-subject
312   '((t :inherit default))
313   "Face used in search mode for subjects."
314   :group 'notmuch)
315
316 (defface notmuch-search-matching-authors
317   '((t :inherit default))
318   "Face used in search mode for authors matching the query."
319   :group 'notmuch)
320
321 (defface notmuch-search-non-matching-authors
322   '((((class color)
323       (background dark))
324      (:foreground "grey30"))
325     (((class color)
326       (background light))
327      (:foreground "grey60"))
328     (t
329      (:italic t)))
330   "Face used in search mode for authors not matching the query."
331   :group 'notmuch)
332
333 (defface notmuch-tag-face
334   '((((class color)
335       (background dark))
336      (:foreground "OliveDrab1"))
337     (((class color)
338       (background light))
339      (:foreground "navy blue" :bold t))
340     (t
341      (:bold t)))
342   "Face used in search mode face for tags."
343   :group 'notmuch)
344
345 (defun notmuch-search-mode ()
346   "Major mode displaying results of a notmuch search.
347
348 This buffer contains the results of a \"notmuch search\" of your
349 email archives. Each line in the buffer represents a single
350 thread giving a summary of the thread (a relative date, the
351 number of matched messages and total messages in the thread,
352 participants in the thread, a representative subject line, and
353 any tags).
354
355 Pressing \\[notmuch-search-show-thread] on any line displays that thread. The '\\[notmuch-search-add-tag]' and '\\[notmuch-search-remove-tag]'
356 keys can be used to add or remove tags from a thread. The '\\[notmuch-search-archive-thread]' key
357 is a convenience for archiving a thread (removing the \"inbox\"
358 tag). The '\\[notmuch-search-operate-all]' key can be used to add or remove a tag from all
359 threads in the current buffer.
360
361 Other useful commands are '\\[notmuch-search-filter]' for filtering the current search
362 based on an additional query string, '\\[notmuch-search-filter-by-tag]' for filtering to include
363 only messages with a given tag, and '\\[notmuch-search]' to execute a new, global
364 search.
365
366 Complete list of currently available key bindings:
367
368 \\{notmuch-search-mode-map}"
369   (interactive)
370   (kill-all-local-variables)
371   (make-local-variable 'notmuch-search-query-string)
372   (make-local-variable 'notmuch-search-oldest-first)
373   (make-local-variable 'notmuch-search-target-thread)
374   (make-local-variable 'notmuch-search-target-line)
375   (set (make-local-variable 'notmuch-search-continuation) nil)
376   (set (make-local-variable 'scroll-preserve-screen-position) t)
377   (add-to-invisibility-spec 'notmuch-search)
378   (use-local-map notmuch-search-mode-map)
379   (setq truncate-lines t)
380   (setq major-mode 'notmuch-search-mode
381         mode-name "notmuch-search")
382   (setq buffer-read-only t))
383
384 (defun notmuch-search-properties-in-region (property beg end)
385   (save-excursion
386     (let ((output nil)
387           (last-line (line-number-at-pos end))
388           (max-line (- (line-number-at-pos (point-max)) 2)))
389       (goto-char beg)
390       (beginning-of-line)
391       (while (<= (line-number-at-pos) (min last-line max-line))
392         (setq output (cons (get-text-property (point) property) output))
393         (forward-line 1))
394       output)))
395
396 (defun notmuch-search-find-thread-id ()
397   "Return the thread for the current thread"
398   (get-text-property (point) 'notmuch-search-thread-id))
399
400 (defun notmuch-search-find-thread-id-region (beg end)
401   "Return a list of threads for the current region"
402   (notmuch-search-properties-in-region 'notmuch-search-thread-id beg end))
403
404 (defun notmuch-search-find-authors ()
405   "Return the authors for the current thread"
406   (get-text-property (point) 'notmuch-search-authors))
407
408 (defun notmuch-search-find-authors-region (beg end)
409   "Return a list of authors for the current region"
410   (notmuch-search-properties-in-region 'notmuch-search-authors beg end))
411
412 (defun notmuch-search-find-subject ()
413   "Return the subject for the current thread"
414   (get-text-property (point) 'notmuch-search-subject))
415
416 (defun notmuch-search-find-subject-region (beg end)
417   "Return a list of authors for the current region"
418   (notmuch-search-properties-in-region 'notmuch-search-subject beg end))
419
420 (defun notmuch-search-show-thread ()
421   "Display the currently selected thread."
422   (interactive)
423   (let ((thread-id (notmuch-search-find-thread-id))
424         (subject (notmuch-search-find-subject)))
425     (if (> (length thread-id) 0)
426         (notmuch-show thread-id
427                       (current-buffer)
428                       notmuch-search-query-string
429                       ;; name the buffer based on notmuch-search-find-subject
430                       (if (string-match "^[ \t]*$" subject)
431                           "[No Subject]"
432                         (truncate-string-to-width
433                          (concat "*"
434                                  (truncate-string-to-width subject 32 nil nil t)
435                                  "*")
436                          32 nil nil t)))
437       (error "End of search results"))))
438
439 (defun notmuch-search-reply-to-thread (&optional prompt-for-sender)
440   "Begin composing a reply to the entire current thread in a new buffer."
441   (interactive "P")
442   (let ((message-id (notmuch-search-find-thread-id)))
443     (notmuch-mua-new-reply message-id prompt-for-sender)))
444
445 (defun notmuch-call-notmuch-process (&rest args)
446   "Synchronously invoke \"notmuch\" with the given list of arguments.
447
448 Output from the process will be presented to the user as an error
449 and will also appear in a buffer named \"*Notmuch errors*\"."
450   (let ((error-buffer (get-buffer-create "*Notmuch errors*")))
451     (with-current-buffer error-buffer
452         (erase-buffer))
453     (if (eq (apply 'call-process notmuch-command nil error-buffer nil args) 0)
454         (point)
455       (progn
456         (with-current-buffer error-buffer
457           (let ((beg (point-min))
458                 (end (- (point-max) 1)))
459             (error (buffer-substring beg end))
460             ))))))
461
462 (defun notmuch-tag (query &rest tags)
463   "Add/remove tags in TAGS to messages matching QUERY.
464
465 TAGS should be a list of strings of the form \"+TAG\" or \"-TAG\" and
466 QUERY should be a string containing the search-query.
467
468 Note: Other code should always use this function 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   (run-hooks 'notmuch-before-tag-hook)
473   (apply 'notmuch-call-notmuch-process
474          (append (list "tag") tags (list "--" query)))
475   (run-hooks 'notmuch-after-tag-hook))
476
477 (defcustom notmuch-before-tag-hook nil
478   "Hooks that are run before tags of a message are modified.
479
480 'tags' will contain the tags that are about to be added or removed as
481 a list of strings of the form \"+TAG\" or \"-TAG\".
482 'query' will be a string containing the search query that determines
483 the messages that are about to be tagged"
484
485   :type 'hook
486   :options '(hl-line-mode)
487   :group 'notmuch)
488
489 (defcustom notmuch-after-tag-hook nil
490   "Hooks that are run before tags of a message are modified.
491
492 'tags' will contain the tags that were added or removed as
493 a list of strings of the form \"+TAG\" or \"-TAG\".
494 'query' will be a string containing the search query that determines
495 the messages that were tagged"
496   :type 'hook
497   :options '(hl-line-mode)
498   :group 'notmuch)
499
500 (defun notmuch-search-set-tags (tags)
501   (save-excursion
502     (end-of-line)
503     (re-search-backward "(")
504     (forward-char)
505     (let ((beg (point))
506           (inhibit-read-only t))
507       (re-search-forward ")")
508       (backward-char)
509       (let ((end (point)))
510         (delete-region beg end)
511         (insert (propertize (mapconcat  'identity tags " ")
512                             'face 'notmuch-tag-face))))))
513
514 (defun notmuch-search-get-tags ()
515   (save-excursion
516     (end-of-line)
517     (re-search-backward "(")
518     (let ((beg (+ (point) 1)))
519       (re-search-forward ")")
520       (let ((end (- (point) 1)))
521         (split-string (buffer-substring beg end))))))
522
523 (defun notmuch-search-get-tags-region (beg end)
524   (save-excursion
525     (let ((output nil)
526           (last-line (line-number-at-pos end))
527           (max-line (- (line-number-at-pos (point-max)) 2)))
528       (goto-char beg)
529       (while (<= (line-number-at-pos) (min last-line max-line))
530         (setq output (append output (notmuch-search-get-tags)))
531         (forward-line 1))
532       output)))
533
534 (defun notmuch-search-add-tag-thread (tag)
535   (notmuch-search-add-tag-region tag (point) (point)))
536
537 (defun notmuch-search-add-tag-region (tag beg end)
538   (let ((search-id-string (mapconcat 'identity (notmuch-search-find-thread-id-region beg end) " or ")))
539     (notmuch-tag search-id-string (concat "+" tag))
540     (save-excursion
541       (let ((last-line (line-number-at-pos end))
542             (max-line (- (line-number-at-pos (point-max)) 2)))
543         (goto-char beg)
544         (while (<= (line-number-at-pos) (min last-line max-line))
545           (notmuch-search-set-tags (delete-dups (sort (cons tag (notmuch-search-get-tags)) 'string<)))
546           (forward-line))))))
547
548 (defun notmuch-search-remove-tag-thread (tag)
549   (notmuch-search-remove-tag-region tag (point) (point)))
550
551 (defun notmuch-search-remove-tag-region (tag beg end)
552   (let ((search-id-string (mapconcat 'identity (notmuch-search-find-thread-id-region beg end) " or ")))
553     (notmuch-tag search-id-string (concat "-" tag))
554     (save-excursion
555       (let ((last-line (line-number-at-pos end))
556             (max-line (- (line-number-at-pos (point-max)) 2)))
557         (goto-char beg)
558         (while (<= (line-number-at-pos) (min last-line max-line))
559           (notmuch-search-set-tags (delete tag (notmuch-search-get-tags)))
560           (forward-line))))))
561
562 (defun notmuch-search-add-tag (tag)
563   "Add a tag to the currently selected thread or region.
564
565 The tag is added to all messages in the currently selected thread
566 or threads in the current region."
567   (interactive
568    (list (notmuch-select-tag-with-completion "Tag to add: ")))
569   (save-excursion
570     (if (region-active-p)
571         (let* ((beg (region-beginning))
572                (end (region-end)))
573           (notmuch-search-add-tag-region tag beg end))
574       (notmuch-search-add-tag-thread tag))))
575
576 (defun notmuch-search-remove-tag (tag)
577   "Remove a tag from the currently selected thread or region.
578
579 The tag is removed from all messages in the currently selected
580 thread or threads in the current region."
581   (interactive
582    (list (notmuch-select-tag-with-completion
583           "Tag to remove: "
584           (if (region-active-p)
585               (mapconcat 'identity
586                          (notmuch-search-find-thread-id-region (region-beginning) (region-end))
587                          " ")
588             (notmuch-search-find-thread-id)))))
589   (save-excursion
590     (if (region-active-p)
591         (let* ((beg (region-beginning))
592                (end (region-end)))
593           (notmuch-search-remove-tag-region tag beg end))
594       (notmuch-search-remove-tag-thread tag))))
595
596 (defun notmuch-search-archive-thread ()
597   "Archive the currently selected thread (remove its \"inbox\" tag).
598
599 This function advances the next thread when finished."
600   (interactive)
601   (notmuch-search-remove-tag-thread "inbox")
602   (forward-line))
603
604 (defvar notmuch-search-process-filter-data nil
605   "Data that has not yet been processed.")
606 (make-variable-buffer-local 'notmuch-search-process-filter-data)
607
608 (defun notmuch-search-process-sentinel (proc msg)
609   "Add a message to let user know when \"notmuch search\" exits"
610   (let ((buffer (process-buffer proc))
611         (status (process-status proc))
612         (exit-status (process-exit-status proc))
613         (never-found-target-thread nil))
614     (if (memq status '(exit signal))
615         (if (buffer-live-p buffer)
616             (with-current-buffer buffer
617               (save-excursion
618                 (let ((inhibit-read-only t)
619                       (atbob (bobp)))
620                   (goto-char (point-max))
621                   (if (eq status 'signal)
622                       (insert "Incomplete search results (search process was killed).\n"))
623                   (if (eq status 'exit)
624                       (progn
625                         (if notmuch-search-process-filter-data
626                             (insert (concat "Error: Unexpected output from notmuch search:\n" notmuch-search-process-filter-data)))
627                         (insert "End of search results.")
628                         (if (not (= exit-status 0))
629                             (insert (format " (process returned %d)" exit-status)))
630                         (insert "\n")
631                         (if (and atbob
632                                  (not (string= notmuch-search-target-thread "found")))
633                             (set 'never-found-target-thread t))))))
634               (when (and never-found-target-thread
635                        notmuch-search-target-line)
636                   (goto-char (point-min))
637                   (forward-line (1- notmuch-search-target-line))))))))
638
639 (defcustom notmuch-search-line-faces nil
640   "Tag/face mapping for line highlighting in notmuch-search.
641
642 Here is an example of how to color search results based on tags.
643  (the following text would be placed in your ~/.emacs file):
644
645  (setq notmuch-search-line-faces '((\"delete\" . '(:foreground \"red\"
646                                                    :background \"blue\"))
647                                    (\"unread\" . '(:foreground \"green\"))))
648
649 The attributes defined for matching tags are merged, with later
650 attributes overriding earlier. A message having both \"delete\"
651 and \"unread\" tags with the above settings would have a green
652 foreground and blue background."
653   :type '(alist :key-type (string) :value-type (custom-face-edit))
654   :group 'notmuch)
655
656 (defun notmuch-search-color-line (start end line-tag-list)
657   "Colorize lines in `notmuch-show' based on tags."
658   ;; Create the overlay only if the message has tags which match one
659   ;; of those specified in `notmuch-search-line-faces'.
660   (let (overlay)
661     (mapc '(lambda (elem)
662              (let ((tag (car elem))
663                    (attributes (cdr elem)))
664                (when (member tag line-tag-list)
665                  (when (not overlay)
666                    (setq overlay (make-overlay start end)))
667                  ;; Merge the specified properties with any already
668                  ;; applied from an earlier match.
669                  (overlay-put overlay 'face
670                               (append (overlay-get overlay 'face) attributes)))))
671           notmuch-search-line-faces)))
672
673 (defun notmuch-search-isearch-authors-show (overlay)
674   (remove-from-invisibility-spec (cons (overlay-get overlay 'invisible) t)))
675
676 (defun notmuch-search-author-propertize (authors)
677   "Split `authors' into matching and non-matching authors and
678 propertize appropriately. If no boundary between authors and
679 non-authors is found, assume that all of the authors match."
680   (if (string-match "\\(.*\\)|\\(.*\\)" authors)
681       (concat (propertize (concat (match-string 1 authors) ",")
682                           'face 'notmuch-search-matching-authors)
683               (propertize (match-string 2 authors)
684                           'face 'notmuch-search-non-matching-authors))
685     (propertize authors 'face 'notmuch-search-matching-authors)))
686
687 (defun notmuch-search-insert-authors (format-string authors)
688   ;; Save the match data to avoid interfering with
689   ;; `notmuch-search-process-filter'.
690   (save-match-data
691     (let* ((formatted-authors (format format-string authors))
692            (formatted-sample (format format-string ""))
693            (visible-string formatted-authors)
694            (invisible-string "")
695            (padding ""))
696
697       ;; Truncate the author string to fit the specification.
698       (if (> (length formatted-authors)
699              (length formatted-sample))
700           (let ((visible-length (- (length formatted-sample)
701                                    (length "... "))))
702             ;; Truncate the visible string according to the width of
703             ;; the display string.
704             (setq visible-string (substring formatted-authors 0 visible-length)
705                   invisible-string (substring formatted-authors visible-length))
706             ;; If possible, truncate the visible string at a natural
707             ;; break (comma or pipe), as incremental search doesn't
708             ;; match across the visible/invisible border.
709             (when (string-match "\\(.*\\)\\([,|] \\)\\([^,|]*\\)" visible-string)
710               ;; Second clause is destructive on `visible-string', so
711               ;; order is important.
712               (setq invisible-string (concat (match-string 3 visible-string)
713                                              invisible-string)
714                     visible-string (concat (match-string 1 visible-string)
715                                            (match-string 2 visible-string))))
716             ;; `visible-string' may be shorter than the space allowed
717             ;; by `format-string'. If so we must insert some padding
718             ;; after `invisible-string'.
719             (setq padding (make-string (- (length formatted-sample)
720                                           (length visible-string)
721                                           (length "..."))
722                                        ? ))))
723
724       ;; Use different faces to show matching and non-matching authors.
725       (if (string-match "\\(.*\\)|\\(.*\\)" visible-string)
726           ;; The visible string contains both matching and
727           ;; non-matching authors.
728           (setq visible-string (notmuch-search-author-propertize visible-string)
729                 ;; The invisible string must contain only non-matching
730                 ;; authors, as the visible-string contains both.
731                 invisible-string (propertize invisible-string
732                                              'face 'notmuch-search-non-matching-authors))
733         ;; The visible string contains only matching authors.
734         (setq visible-string (propertize visible-string
735                                          'face 'notmuch-search-matching-authors)
736               ;; The invisible string may contain both matching and
737               ;; non-matching authors.
738               invisible-string (notmuch-search-author-propertize invisible-string)))
739
740       ;; If there is any invisible text, add it as a tooltip to the
741       ;; visible text.
742       (when (not (string= invisible-string ""))
743         (setq visible-string (propertize visible-string 'help-echo (concat "..." invisible-string))))
744
745       ;; Insert the visible and, if present, invisible author strings.
746       (insert visible-string)
747       (when (not (string= invisible-string ""))
748         (let ((start (point))
749               (invis-spec (make-symbol "notmuch-search-authors"))
750               overlay)
751           (insert invisible-string)
752           (add-to-invisibility-spec (cons invis-spec t))
753           (setq overlay (make-overlay start (point)))
754           (overlay-put overlay 'invisible invis-spec)
755           (overlay-put overlay 'isearch-open-invisible #'notmuch-search-isearch-authors-show)))
756       (insert padding))))
757
758 (defun notmuch-search-insert-field (field date count authors subject tags)
759   (cond
760    ((string-equal field "date")
761     (insert (propertize (format (cdr (assoc field notmuch-search-result-format)) date)
762                         'face 'notmuch-search-date)))
763    ((string-equal field "count")
764     (insert (propertize (format (cdr (assoc field notmuch-search-result-format)) count)
765                         'face 'notmuch-search-count)))
766    ((string-equal field "subject")
767     (insert (propertize (format (cdr (assoc field notmuch-search-result-format)) subject)
768                         'face 'notmuch-search-subject)))
769
770    ((string-equal field "authors")
771     (notmuch-search-insert-authors (cdr (assoc field notmuch-search-result-format)) authors))
772
773    ((string-equal field "tags")
774     (insert (concat "(" (propertize tags 'font-lock-face 'notmuch-tag-face) ")")))))
775
776 (defun notmuch-search-show-result (date count authors subject tags)
777   (let ((fields) (field))
778     (setq fields (mapcar 'car notmuch-search-result-format))
779     (loop for field in fields
780           do (notmuch-search-insert-field field date count authors subject tags)))
781   (insert "\n"))
782
783 (defun notmuch-search-process-filter (proc string)
784   "Process and filter the output of \"notmuch search\""
785   (let ((buffer (process-buffer proc))
786         (found-target nil))
787     (if (buffer-live-p buffer)
788         (with-current-buffer buffer
789           (save-excursion
790             (let ((line 0)
791                   (more t)
792                   (inhibit-read-only t)
793                   (string (concat notmuch-search-process-filter-data string)))
794               (setq notmuch-search-process-filter-data nil)
795               (while more
796                 (while (and (< line (length string)) (= (elt string line) ?\n))
797                   (setq line (1+ line)))
798                 (if (string-match "^\\(thread:[0-9A-Fa-f]*\\) \\([^][]*\\) \\(\\[[0-9/]*\\]\\) \\([^;]*\\); \\(.*\\) (\\([^()]*\\))$" string line)
799                     (let* ((thread-id (match-string 1 string))
800                            (date (match-string 2 string))
801                            (count (match-string 3 string))
802                            (authors (match-string 4 string))
803                            (subject (match-string 5 string))
804                            (tags (match-string 6 string))
805                            (tag-list (if tags (save-match-data (split-string tags)))))
806                       (goto-char (point-max))
807                       (if (/= (match-beginning 1) line)
808                           (insert (concat "Error: Unexpected output from notmuch search:\n" (substring string line (match-beginning 1)) "\n")))
809                       (let ((beg (point-marker)))
810                         (notmuch-search-show-result date count authors subject tags)
811                         (notmuch-search-color-line beg (point-marker) tag-list)
812                         (put-text-property beg (point-marker) 'notmuch-search-thread-id thread-id)
813                         (put-text-property beg (point-marker) 'notmuch-search-authors authors)
814                         (put-text-property beg (point-marker) 'notmuch-search-subject subject)
815                         (if (string= thread-id notmuch-search-target-thread)
816                             (progn
817                               (set 'found-target beg)
818                               (set 'notmuch-search-target-thread "found"))))
819                       (set 'line (match-end 0)))
820                   (set 'more nil)
821                   (while (and (< line (length string)) (= (elt string line) ?\n))
822                     (setq line (1+ line)))
823                   (if (< line (length string))
824                       (setq notmuch-search-process-filter-data (substring string line)))
825                   ))))
826           (if found-target
827               (goto-char found-target)))
828       (delete-process proc))))
829
830 (defun notmuch-search-operate-all (action)
831   "Add/remove tags from all matching messages.
832
833 Tis command adds or removes tags from all messages matching the
834 current search terms. When called interactively, this command
835 will prompt for tags to be added or removed. Tags prefixed with
836 '+' will be added and tags prefixed with '-' will be removed.
837
838 Each character of the tag name may consist of alphanumeric
839 characters as well as `_.+-'.
840 "
841   (interactive "sOperation (+add -drop): notmuch tag ")
842   (let ((action-split (split-string action " +")))
843     ;; Perform some validation
844     (let ((words action-split))
845       (when (null words) (error "No operation given"))
846       (while words
847         (unless (string-match-p "^[-+][-+_.[:word:]]+$" (car words))
848           (error "Action must be of the form `+thistag -that_tag'"))
849         (setq words (cdr words))))
850     (apply 'notmuch-tag notmuch-search-query-string action-split)))
851
852 (defun notmuch-search-buffer-title (query)
853   "Returns the title for a buffer with notmuch search results."
854   (let* ((saved-search
855           (let (longest
856                 (longest-length 0))
857             (loop for tuple in notmuch-saved-searches
858                   if (let ((quoted-query (regexp-quote (cdr tuple))))
859                        (and (string-match (concat "^" quoted-query) query)
860                             (> (length (match-string 0 query))
861                                longest-length)))
862                   do (setq longest tuple))
863             longest))
864          (saved-search-name (car saved-search))
865          (saved-search-query (cdr saved-search)))
866     (cond ((and saved-search (equal saved-search-query query))
867            ;; Query is the same as saved search (ignoring case)
868            (concat "*notmuch-saved-search-" saved-search-name "*"))
869           (saved-search
870            (concat "*notmuch-search-"
871                    (replace-regexp-in-string (concat "^" (regexp-quote saved-search-query))
872                                              (concat "[ " saved-search-name " ]")
873                                              query)
874                    "*"))
875           (t
876            (concat "*notmuch-search-" query "*"))
877           )))
878
879 ;;;###autoload
880 (defun notmuch-search (query &optional oldest-first target-thread target-line continuation)
881   "Run \"notmuch search\" with the given query string and display results.
882
883 The optional parameters are used as follows:
884
885   oldest-first: A Boolean controlling the sort order of returned threads
886   target-thread: A thread ID (with the thread: prefix) that will be made
887                  current if it appears in the search results.
888   target-line: The line number to move to if the target thread does not
889                appear in the search results."
890   (interactive "sNotmuch search: ")
891   (let ((buffer (get-buffer-create (notmuch-search-buffer-title query))))
892     (switch-to-buffer buffer)
893     (notmuch-search-mode)
894     (set 'notmuch-search-query-string query)
895     (set 'notmuch-search-oldest-first oldest-first)
896     (set 'notmuch-search-target-thread target-thread)
897     (set 'notmuch-search-target-line target-line)
898     (set 'notmuch-search-continuation continuation)
899     (let ((proc (get-buffer-process (current-buffer)))
900           (inhibit-read-only t))
901       (if proc
902           (error "notmuch search process already running for query `%s'" query)
903         )
904       (erase-buffer)
905       (goto-char (point-min))
906       (save-excursion
907         (let ((proc (start-process
908                      "notmuch-search" buffer
909                      notmuch-command "search"
910                      (if oldest-first
911                          "--sort=oldest-first"
912                        "--sort=newest-first")
913                      query)))
914           (set-process-sentinel proc 'notmuch-search-process-sentinel)
915           (set-process-filter proc 'notmuch-search-process-filter))))
916     (run-hooks 'notmuch-search-hook)))
917
918 (defun notmuch-search-refresh-view ()
919   "Refresh the current view.
920
921 Kills the current buffer and runs a new search with the same
922 query string as the current search. If the current thread is in
923 the new search results, then point will be placed on the same
924 thread. Otherwise, point will be moved to attempt to be in the
925 same relative position within the new buffer."
926   (interactive)
927   (let ((target-line (line-number-at-pos))
928         (oldest-first notmuch-search-oldest-first)
929         (target-thread (notmuch-search-find-thread-id))
930         (query notmuch-search-query-string)
931         (continuation notmuch-search-continuation))
932     (notmuch-kill-this-buffer)
933     (notmuch-search query oldest-first target-thread target-line continuation)
934     (goto-char (point-min))))
935
936 (defcustom notmuch-poll-script ""
937   "An external script to incorporate new mail into the notmuch database.
938
939 If this variable is non empty, then it should name a script to be
940 invoked by `notmuch-search-poll-and-refresh-view' and
941 `notmuch-hello-poll-and-update' (each have a default keybinding
942 of 'G'). The script could do any of the following depending on
943 the user's needs:
944
945 1. Invoke a program to transfer mail to the local mail store
946 2. Invoke \"notmuch new\" to incorporate the new mail
947 3. Invoke one or more \"notmuch tag\" commands to classify the mail"
948   :type 'string
949   :group 'notmuch)
950
951 (defun notmuch-poll ()
952   "Run external script to import mail.
953
954 Invokes `notmuch-poll-script' if it is not set to an empty string."
955   (interactive)
956   (if (not (string= notmuch-poll-script ""))
957       (call-process notmuch-poll-script nil nil)))
958
959 (defun notmuch-search-poll-and-refresh-view ()
960   "Invoke `notmuch-poll' to import mail, then refresh the current view."
961   (interactive)
962   (notmuch-poll)
963   (notmuch-search-refresh-view))
964
965 (defun notmuch-search-toggle-order ()
966   "Toggle the current search order.
967
968 By default, the \"inbox\" view created by `notmuch' is displayed
969 in chronological order (oldest thread at the beginning of the
970 buffer), while any global searches created by `notmuch-search'
971 are displayed in reverse-chronological order (newest thread at
972 the beginning of the buffer).
973
974 This command toggles the sort order for the current search.
975
976 Note that any filtered searches created by
977 `notmuch-search-filter' retain the search order of the parent
978 search."
979   (interactive)
980   (set 'notmuch-search-oldest-first (not notmuch-search-oldest-first))
981   (notmuch-search-refresh-view))
982
983 (defun notmuch-search-filter (query)
984   "Filter the current search results based on an additional query string.
985
986 Runs a new search matching only messages that match both the
987 current search results AND the additional query string provided."
988   (interactive "sFilter search: ")
989   (let ((grouped-query (if (string-match-p notmuch-search-disjunctive-regexp query)
990                            (concat "( " query " )")
991                          query)))
992     (notmuch-search (if (string= notmuch-search-query-string "*")
993                         grouped-query
994                       (concat notmuch-search-query-string " and " grouped-query)) notmuch-search-oldest-first)))
995
996 (defun notmuch-search-filter-by-tag (tag)
997   "Filter the current search results based on a single tag.
998
999 Runs a new search matching only messages that match both the
1000 current search results AND that are tagged with the given tag."
1001   (interactive
1002    (list (notmuch-select-tag-with-completion "Filter by tag: ")))
1003   (notmuch-search (concat notmuch-search-query-string " and tag:" tag) notmuch-search-oldest-first))
1004
1005 ;;;###autoload
1006 (defun notmuch ()
1007   "Run notmuch and display saved searches, known tags, etc."
1008   (interactive)
1009   (notmuch-hello))
1010
1011 (setq mail-user-agent 'notmuch-user-agent)
1012
1013 (provide 'notmuch)