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