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