]> git.notmuchmail.org Git - notmuch/blob - notmuch.el
a6b71b777795d3c6b8b53a2dc75cf16b402c7fc6
[notmuch] / 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 (require 'cl)
51 (require 'mm-view)
52 (require 'message)
53
54 (defvar notmuch-show-mode-map
55   (let ((map (make-sparse-keymap)))
56     (define-key map "?" 'notmuch-help)
57     (define-key map "q" 'kill-this-buffer)
58     (define-key map "x" 'kill-this-buffer)
59     (define-key map (kbd "C-p") 'notmuch-show-previous-line)
60     (define-key map (kbd "C-n") 'notmuch-show-next-line)
61     (define-key map (kbd "M-TAB") 'notmuch-show-previous-button)
62     (define-key map (kbd "TAB") 'notmuch-show-next-button)
63     (define-key map "s" 'notmuch-search)
64     (define-key map "m" 'message-mail)
65     (define-key map "f" 'notmuch-show-forward-current)
66     (define-key map "r" 'notmuch-show-reply)
67     (define-key map "|" 'notmuch-show-pipe-message)
68     (define-key map "w" 'notmuch-show-save-attachments)
69     (define-key map "V" 'notmuch-show-view-raw-message)
70     (define-key map "v" 'notmuch-show-view-all-mime-parts)
71     (define-key map "-" 'notmuch-show-remove-tag)
72     (define-key map "+" 'notmuch-show-add-tag)
73     (define-key map "A" 'notmuch-show-mark-read-then-archive-thread)
74     (define-key map "a" 'notmuch-show-archive-thread)
75     (define-key map "p" 'notmuch-show-previous-message)
76     (define-key map "N" 'notmuch-show-mark-read-then-next-open-message)
77     (define-key map "n" 'notmuch-show-next-message)
78     (define-key map (kbd "DEL") 'notmuch-show-rewind)
79     (define-key map " " 'notmuch-show-advance-marking-read-and-archiving)
80     map)
81   "Keymap for \"notmuch show\" buffers.")
82 (fset 'notmuch-show-mode-map notmuch-show-mode-map)
83
84 (defvar notmuch-show-signature-regexp "\\(-- ?\\|_+\\)$"
85   "Pattern to match a line that separates content from signature.
86
87 The regexp can (and should) include $ to match the end of the
88 line, but should not include ^ to match the beginning of the
89 line. This is because notmuch may have inserted additional space
90 for indentation at the beginning of the line. But notmuch will
91 move past the indentation when testing this pattern, (so that the
92 pattern can still test against the entire line).")
93
94 (defvar notmuch-show-signature-lines-max 12
95   "Maximum length of signature that will be hidden by default.")
96
97 (defvar notmuch-command "notmuch"
98   "Command to run the notmuch binary.")
99
100 (defvar notmuch-show-message-begin-regexp    "\fmessage{")
101 (defvar notmuch-show-message-end-regexp      "\fmessage}")
102 (defvar notmuch-show-header-begin-regexp     "\fheader{")
103 (defvar notmuch-show-header-end-regexp       "\fheader}")
104 (defvar notmuch-show-body-begin-regexp       "\fbody{")
105 (defvar notmuch-show-body-end-regexp         "\fbody}")
106 (defvar notmuch-show-attachment-begin-regexp "\fattachment{")
107 (defvar notmuch-show-attachment-end-regexp   "\fattachment}")
108 (defvar notmuch-show-part-begin-regexp       "\fpart{")
109 (defvar notmuch-show-part-end-regexp         "\fpart}")
110 (defvar notmuch-show-marker-regexp "\f\\(message\\|header\\|body\\|attachment\\|part\\)[{}].*$")
111
112 (defvar notmuch-show-id-regexp "\\(id:[^ ]*\\)")
113 (defvar notmuch-show-depth-regexp " depth:\\([0-9]*\\) ")
114 (defvar notmuch-show-filename-regexp "filename:\\(.*\\)$")
115 (defvar notmuch-show-tags-regexp "(\\([^)]*\\))$")
116
117 (defvar notmuch-show-parent-buffer nil)
118 (defvar notmuch-show-body-read-visible nil)
119 (defvar notmuch-show-citations-visible nil)
120 (defvar notmuch-show-signatures-visible nil)
121 (defvar notmuch-show-headers-visible nil)
122
123 ; XXX: This should be a generic function in emacs somewhere, not here
124 (defun point-invisible-p ()
125   "Return whether the character at point is invisible.
126
127 Here visibility is determined by `buffer-invisibility-spec' and
128 the invisible property of any overlays for point. It doesn't have
129 anything to do with whether point is currently being displayed
130 within the current window."
131   (let ((prop (get-char-property (point) 'invisible)))
132     (if (eq buffer-invisibility-spec t)
133         prop
134       (or (memq prop buffer-invisibility-spec)
135           (assq prop buffer-invisibility-spec)))))
136
137 (defun notmuch-select-tag-with-completion (prompt &rest search-terms)
138   (let ((tag-list
139          (with-output-to-string
140            (with-current-buffer standard-output
141              (apply 'call-process notmuch-command nil t nil "search-tags" search-terms)))))
142     (completing-read prompt (split-string tag-list "\n+" t) nil nil nil)))
143
144 (defun notmuch-show-next-line ()
145   "Like builtin `next-line' but ensuring we end on a visible character.
146
147 By advancing forward until reaching a visible character.
148
149 Unlike builtin `next-line' this version accepts no arguments."
150   (interactive)
151   (set 'this-command 'next-line)
152   (call-interactively 'next-line)
153   (while (point-invisible-p)
154     (forward-char)))
155
156 (defun notmuch-show-previous-line ()
157   "Like builtin `previous-line' but ensuring we end on a visible character.
158
159 By advancing forward until reaching a visible character.
160
161 Unlike builtin `next-line' this version accepts no arguments."
162   (interactive)
163   (set 'this-command 'previous-line)
164   (call-interactively 'previous-line)
165   (while (point-invisible-p)
166     (forward-char)))
167
168 (defun notmuch-show-get-message-id ()
169   (save-excursion
170     (beginning-of-line)
171     (if (not (looking-at notmuch-show-message-begin-regexp))
172         (re-search-backward notmuch-show-message-begin-regexp))
173     (re-search-forward notmuch-show-id-regexp)
174     (buffer-substring-no-properties (match-beginning 1) (match-end 1))))
175
176 (defun notmuch-show-get-filename ()
177   (save-excursion
178     (beginning-of-line)
179     (if (not (looking-at notmuch-show-message-begin-regexp))
180         (re-search-backward notmuch-show-message-begin-regexp))
181     (re-search-forward notmuch-show-filename-regexp)
182     (buffer-substring-no-properties (match-beginning 1) (match-end 1))))
183
184 (defun notmuch-show-set-tags (tags)
185   (save-excursion
186     (beginning-of-line)
187     (if (not (looking-at notmuch-show-message-begin-regexp))
188         (re-search-backward notmuch-show-message-begin-regexp))
189     (re-search-forward notmuch-show-tags-regexp)
190     (let ((inhibit-read-only t)
191           (beg (match-beginning 1))
192           (end (match-end 1)))
193       (delete-region beg end)
194       (goto-char beg)
195       (insert (mapconcat 'identity tags " ")))))
196
197 (defun notmuch-show-get-tags ()
198   (save-excursion
199     (beginning-of-line)
200     (if (not (looking-at notmuch-show-message-begin-regexp))
201         (re-search-backward notmuch-show-message-begin-regexp))
202     (re-search-forward notmuch-show-tags-regexp)
203     (split-string (buffer-substring (match-beginning 1) (match-end 1)))))
204
205 (defun notmuch-show-add-tag (&rest toadd)
206   "Add a tag to the current message."
207   (interactive
208    (list (notmuch-select-tag-with-completion "Tag to add: ")))
209   (apply 'notmuch-call-notmuch-process
210          (append (cons "tag"
211                        (mapcar (lambda (s) (concat "+" s)) toadd))
212                  (cons (notmuch-show-get-message-id) nil)))
213   (notmuch-show-set-tags (sort (union toadd (notmuch-show-get-tags) :test 'string=) 'string<)))
214
215 (defun notmuch-show-remove-tag (&rest toremove)
216   "Remove a tag from the current message."
217   (interactive
218    (list (notmuch-select-tag-with-completion "Tag to remove: " (notmuch-show-get-message-id))))
219   (let ((tags (notmuch-show-get-tags)))
220     (if (intersection tags toremove :test 'string=)
221         (progn
222           (apply 'notmuch-call-notmuch-process
223                  (append (cons "tag"
224                                (mapcar (lambda (s) (concat "-" s)) toremove))
225                          (cons (notmuch-show-get-message-id) nil)))
226           (notmuch-show-set-tags (sort (set-difference tags toremove :test 'string=) 'string<))))))
227
228 (defun notmuch-show-archive-thread-maybe-mark-read (markread)
229   (save-excursion
230     (goto-char (point-min))
231     (while (not (eobp))
232       (if markread
233           (notmuch-show-remove-tag "unread" "inbox")
234         (notmuch-show-remove-tag "inbox"))
235       (if (not (eobp))
236           (forward-char))
237       (if (not (re-search-forward notmuch-show-message-begin-regexp nil t))
238           (goto-char (point-max)))))
239   (let ((parent-buffer notmuch-show-parent-buffer))
240     (kill-this-buffer)
241     (if parent-buffer
242         (progn
243           (switch-to-buffer parent-buffer)
244           (forward-line)
245           (notmuch-search-show-thread)))))
246
247 (defun notmuch-show-mark-read-then-archive-thread ()
248   "Remove unread tags from thread, then archive and show next thread.
249
250 Archive each message currently shown by removing the \"unread\"
251 and \"inbox\" tag from each. Then kill this buffer and show the
252 next thread from the search from which this thread was originally
253 shown.
254
255 Note: This command is safe from any race condition of new messages
256 being delivered to the same thread. It does not archive the
257 entire thread, but only the messages shown in the current
258 buffer."
259   (interactive)
260   (notmuch-show-archive-thread-maybe-mark-read t))
261
262 (defun notmuch-show-archive-thread ()
263   "Archive each message in thread, then show next thread from search.
264
265 Archive each message currently shown by removing the \"inbox\"
266 tag from each. Then kill this buffer and show the next thread
267 from the search from which this thread was originally shown.
268
269 Note: This command is safe from any race condition of new messages
270 being delivered to the same thread. It does not archive the
271 entire thread, but only the messages shown in the current
272 buffer."
273   (interactive)
274   (notmuch-show-archive-thread-maybe-mark-read nil))
275
276 (defun notmuch-show-view-raw-message ()
277   "View the raw email of the current message."
278   (interactive)
279   (view-file (notmuch-show-get-filename)))
280
281 (defmacro with-current-notmuch-show-message (&rest body)
282   "Evaluate body with current buffer set to the text of current message"
283   `(save-excursion
284      (let ((filename (notmuch-show-get-filename)))
285        (let ((buf (generate-new-buffer (concat "*notmuch-msg-" filename "*"))))
286          (with-current-buffer buf
287            (insert-file-contents filename nil nil nil t)
288            ,@body)
289         (kill-buffer buf)))))
290
291 (defun notmuch-show-view-all-mime-parts ()
292   "Use external viewers to view all attachments from the current message."
293   (interactive)
294   (with-current-notmuch-show-message
295    (mm-display-parts (mm-dissect-buffer))))
296
297 (defun notmuch-foreach-mime-part (function mm-handle)
298   (cond ((stringp (car mm-handle))
299          (dolist (part (cdr mm-handle))
300            (notmuch-foreach-mime-part function part)))
301         ((bufferp (car mm-handle))
302          (funcall function mm-handle))
303         (t (dolist (part mm-handle)
304              (notmuch-foreach-mime-part function part)))))
305
306 (defun notmuch-count-attachments (mm-handle)
307   (let ((count 0))
308     (notmuch-foreach-mime-part
309      (lambda (p)
310        (let ((disposition (mm-handle-disposition p)))
311          (and (listp disposition)
312               (equal (car disposition) "attachment")
313               (incf count))))
314      mm-handle)
315     count))
316
317 (defun notmuch-save-attachments (mm-handle &optional queryp)
318   (notmuch-foreach-mime-part
319    (lambda (p)
320      (let ((disposition (mm-handle-disposition p)))
321        (and (listp disposition)
322             (equal (car disposition) "attachment")
323             (or (not queryp)
324                 (y-or-n-p
325                  (concat "Save '" (cdr (assq 'filename disposition)) "' ")))
326             (mm-save-part p))))
327    mm-handle))
328
329 (defun notmuch-show-save-attachments ()
330   "Save all attachments from the current message."
331   (interactive)
332   (with-current-notmuch-show-message
333    (let ((mm-handle (mm-dissect-buffer)))
334      (notmuch-save-attachments
335       mm-handle (> (notmuch-count-attachments mm-handle) 1))))
336   (message "Done"))
337
338 (defun notmuch-reply (query-string)
339   (switch-to-buffer (generate-new-buffer "notmuch-draft"))
340   (call-process notmuch-command nil t nil "reply" query-string)
341   (message-insert-signature)
342   (goto-char (point-min))
343   (if (re-search-forward "^$" nil t)
344       (progn
345         (insert "--text follows this line--")
346         (forward-line)))
347   (message-mode))
348
349 (defun notmuch-show-reply ()
350   "Begin composing a reply to the current message in a new buffer."
351   (interactive)
352   (let ((message-id (notmuch-show-get-message-id)))
353     (notmuch-reply message-id)))
354
355 (defun notmuch-show-forward-current ()
356   "Forward the current message."
357   (interactive)
358   (with-current-notmuch-show-message
359    (message-forward)))
360
361 (defun notmuch-show-pipe-message (command)
362   "Pipe the contents of the current message to the given command.
363
364 The given command will be executed with the raw contents of the
365 current email message as stdin. Anything printed by the command
366 to stdout or stderr will appear in the *Messages* buffer."
367   (interactive "sPipe message to command: ")
368   (apply 'start-process-shell-command "notmuch-pipe-command" "*notmuch-pipe*"
369          (list command " < " (shell-quote-argument (notmuch-show-get-filename)))))
370
371 (defun notmuch-show-move-to-current-message-summary-line ()
372   "Move to the beginning of the one-line summary of the current message.
373
374 This gives us a stable place to move to and work from since the
375 summary line is always visible. This is important since moving to
376 an invisible location is unreliable, (the main command loop moves
377 point either forward or backward to the next visible character
378 when a command ends with point on an invisible character).
379
380 Emits an error if point is not within a valid message, (that is
381 not pattern of `notmuch-show-message-begin-regexp' could be found
382 by searching backward)."
383   (beginning-of-line)
384   (if (not (looking-at notmuch-show-message-begin-regexp))
385       (if (re-search-backward notmuch-show-message-begin-regexp nil t)
386           (forward-line 2)
387         (error "Not within a valid message."))
388     (forward-line 2)))
389
390 (defun notmuch-show-last-message-p ()
391   "Predicate testing whether point is within the last message."
392   (save-window-excursion
393     (save-excursion
394       (notmuch-show-move-to-current-message-summary-line)
395       (not (re-search-forward notmuch-show-message-begin-regexp nil t)))))
396
397 (defun notmuch-show-message-unread-p ()
398   "Preficate testing whether current message is unread."
399   (member "unread" (notmuch-show-get-tags)))
400
401 (defun notmuch-show-next-message ()
402   "Advance to the beginning of the next message in the buffer.
403
404 Moves to the last visible character of the current message if
405 already on the last message in the buffer."
406   (interactive)
407   (notmuch-show-move-to-current-message-summary-line)
408   (if (re-search-forward notmuch-show-message-begin-regexp nil t)
409       (notmuch-show-move-to-current-message-summary-line)
410     (goto-char (- (point-max) 1))
411     (while (point-invisible-p)
412       (backward-char)))
413   (recenter 0))
414
415 (defun notmuch-show-find-next-message ()
416   "Returns the position of the next message in the buffer.
417
418 Or the position of the last visible character of the current
419 message if already within the last message in the buffer."
420   ; save-excursion doesn't save our window position
421   ; save-window-excursion doesn't save point
422   ; Looks like we have to use both.
423   (save-excursion
424     (save-window-excursion
425       (notmuch-show-next-message)
426       (point))))
427
428 (defun notmuch-show-next-unread-message ()
429   "Advance to the beginning of the next unread message in the buffer.
430
431 Moves to the last visible character of the current message if
432 there are no more unread messages past the current point."
433   (notmuch-show-next-message)
434   (while (and (not (notmuch-show-last-message-p))
435               (not (notmuch-show-message-unread-p)))
436     (notmuch-show-next-message))
437   (if (not (notmuch-show-message-unread-p))
438       (notmuch-show-next-message)))
439
440 (defun notmuch-show-next-open-message ()
441   "Advance to the next message which is not hidden.
442
443 If read messages are currently hidden, advance to the next unread
444 message. Otherwise, advance to the next message."
445   (if (or (memq 'notmuch-show-body-read buffer-invisibility-spec)
446           (assq 'notmuch-show-body-read buffer-invisibility-spec))
447       (notmuch-show-next-unread-message)
448     (notmuch-show-next-message)))
449
450 (defun notmuch-show-previous-message ()
451   "Backup to the beginning of the previous message in the buffer.
452
453 If within a message rather than at the beginning of it, then
454 simply move to the beginning of the current message."
455   (interactive)
456   (let ((start (point)))
457     (notmuch-show-move-to-current-message-summary-line)
458     (if (not (< (point) start))
459         ; Go backward twice to skip the current message's marker
460         (progn
461           (re-search-backward notmuch-show-message-begin-regexp nil t)
462           (re-search-backward notmuch-show-message-begin-regexp nil t)
463           (notmuch-show-move-to-current-message-summary-line)
464           ))
465     (recenter 0)))
466
467 (defun notmuch-show-find-previous-message ()
468   "Returns the position of the previous message in the buffer.
469
470 Or the position of the beginning of the current message if point
471 is originally within the message rather than at the beginning of
472 it."
473   ; save-excursion doesn't save our window position
474   ; save-window-excursion doesn't save point
475   ; Looks like we have to use both.
476   (save-excursion
477     (save-window-excursion
478       (notmuch-show-previous-message)
479       (point))))
480
481 (defun notmuch-show-mark-read-then-next-open-message ()
482   "Remove unread tag from this message, then advance to next open message."
483   (interactive)
484   (notmuch-show-remove-tag "unread")
485   (notmuch-show-next-open-message))
486
487 (defun notmuch-show-rewind ()
488   "Backup through the thread, (reverse scrolling compared to \\[notmuch-show-advance-marking-read-and-archiving]).
489
490 Specifically, if the beginning of the previous email is fewer
491 than `window-height' lines from the current point, move to it
492 just like `notmuch-show-previous-message'.
493
494 Otherwise, just scroll down a screenful of the current message.
495
496 This command does not modify any message tags, (it does not undo
497 any effects from previous calls to
498 `notmuch-show-advance-marking-read-and-archiving'."
499   (interactive)
500   (let ((previous (notmuch-show-find-previous-message)))
501     (if (> (count-lines previous (point)) (- (window-height) next-screen-context-lines))
502         (progn
503           (condition-case nil
504               (scroll-down nil)
505             ((beginning-of-buffer) nil))
506           (goto-char (window-start)))
507       (notmuch-show-previous-message))))
508
509 (defun notmuch-show-advance-marking-read-and-archiving ()
510   "Advance through thread, marking read and archiving.
511
512 This command is intended to be one of the simplest ways to
513 process a thread of email. It does the following:
514
515 If the current message in the thread is not yet fully visible,
516 scroll by a near screenful to read more of the message.
517
518 Otherwise, (the end of the current message is already within the
519 current window), remove the \"unread\" tag (if present) from the
520 current message and advance to the next open message.
521
522 Finally, if there is no further message to advance to, and this
523 last message is already read, then archive the entire current
524 thread, (remove the \"inbox\" tag from each message). Also kill
525 this buffer, and display the next thread from the search from
526 which this thread was originally shown."
527   (interactive)
528   (let ((next (notmuch-show-find-next-message))
529         (unread (notmuch-show-message-unread-p)))
530     (if (> next (window-end))
531         (scroll-up nil)
532       (let ((last (notmuch-show-last-message-p)))
533         (notmuch-show-mark-read-then-next-open-message)
534         (if last
535             (notmuch-show-archive-thread))))))
536
537 (defun notmuch-show-next-button ()
538   "Advance point to the next button in the buffer."
539   (interactive)
540   (goto-char (button-start (next-button (point)))))
541
542 (defun notmuch-show-previous-button ()
543   "Move point back to the previous button in the buffer."
544   (interactive)
545   (goto-char (button-start (previous-button (point)))))
546
547 (defun notmuch-toggle-invisible-action (cite-button)
548   (let ((invis-spec (button-get button 'invisibility-spec)))
549         (if (invisible-p invis-spec)
550             (remove-from-invisibility-spec invis-spec)
551           (add-to-invisibility-spec invis-spec)
552           ))
553   (force-window-update)
554   (redisplay t))
555
556 (define-button-type 'notmuch-button-invisibility-toggle-type 'action 'notmuch-toggle-invisible-action 'follow-link t)
557 (define-button-type 'notmuch-button-citation-toggle-type 'help-echo "mouse-1, RET: Show citation"
558   :supertype 'notmuch-button-invisibility-toggle-type)
559 (define-button-type 'notmuch-button-signature-toggle-type 'help-echo "mouse-1, RET: Show signature"
560   :supertype 'notmuch-button-invisibility-toggle-type)
561 (define-button-type 'notmuch-button-headers-toggle-type 'help-echo "mouse-1, RET: Show headers"
562   :supertype 'notmuch-button-invisibility-toggle-type)
563 (define-button-type 'notmuch-button-body-toggle-type 'help-echo "mouse-1, RET: Show message"
564   :supertype 'notmuch-button-invisibility-toggle-type)
565
566 (defun notmuch-show-markup-citations-region (beg end depth)
567   (goto-char beg)
568   (beginning-of-line)
569   (while (< (point) end)
570     (let ((beg-sub (point-marker))
571           (indent (make-string depth ? ))
572           (citation "[[:space:]]*>"))
573       (if (looking-at citation)
574           (progn
575             (while (looking-at citation)
576               (forward-line))
577             (let ((overlay (make-overlay beg-sub (point)))
578                   (invis-spec (make-symbol "notmuch-citation-region")))
579               (add-to-invisibility-spec invis-spec)
580               (overlay-put overlay 'invisible invis-spec)
581               (let ((p (point))
582                     (cite-button-text
583                      (concat "["  (number-to-string (count-lines beg-sub (point)))
584                              "-line citation.]")))
585                 (goto-char (- beg-sub 1))
586                 (insert (concat "\n" indent))
587                 (insert-button cite-button-text
588                                'invisibility-spec invis-spec
589                                :type 'notmuch-button-citation-toggle-type)
590                 (insert "\n")
591                 (goto-char (+ (length cite-button-text) p))
592               ))))
593       (move-to-column depth)
594       (if (looking-at notmuch-show-signature-regexp)
595           (let ((sig-lines (- (count-lines beg-sub end) 1)))
596             (if (<= sig-lines notmuch-show-signature-lines-max)
597                 (progn
598                   (let ((invis-spec (make-symbol "notmuch-signature-region")))
599                     (add-to-invisibility-spec invis-spec)
600                     (overlay-put (make-overlay beg-sub end)
601                                  'invisible invis-spec)
602                   
603                     (goto-char (- beg-sub 1))
604                     (insert (concat "\n" indent))
605                     (let ((sig-button-text (concat "[" (number-to-string sig-lines)
606                                                    "-line signature.]")))
607                       (insert-button sig-button-text 'invisibility-spec invis-spec
608                                      :type 'notmuch-button-signature-toggle-type)
609                      )
610                     (insert "\n")
611                     (goto-char end))))))
612       (forward-line))))
613
614 (defun notmuch-show-markup-part (beg end depth mime-message)
615   (if (re-search-forward notmuch-show-part-begin-regexp nil t)
616       (progn
617         (if (eq mime-message nil)
618             (let ((filename (notmuch-show-get-filename)))
619               (with-temp-buffer
620                 (insert-file-contents filename nil nil nil t)
621                 (setq mime-message (mm-dissect-buffer)))))
622         (forward-line)
623         (let ((part-beg (point-marker)))
624           (re-search-forward notmuch-show-part-end-regexp)
625
626           (let ((part-end (copy-marker (match-beginning 0))))
627             (goto-char part-end)
628             (if (not (bolp))
629                 (insert "\n"))
630             (indent-rigidly part-beg part-end depth)
631             (save-excursion
632               (goto-char part-beg)
633               (forward-line -1)
634               (beginning-of-line)
635               (let ((handle-type (mm-handle-type mime-message))
636                     mime-type)
637                 (if (sequencep (car handle-type))
638                     (setq mime-type (car handle-type))
639                   (setq mime-type (car (car (cdr handle-type))))
640                   )
641                 (if (equal mime-type "text/html")
642                     (mm-display-part mime-message))))
643
644             (notmuch-show-markup-citations-region part-beg part-end depth)
645             ; Advance to the next part (if any) (so the outer loop can
646             ; determine whether we've left the current message.
647             (if (re-search-forward notmuch-show-part-begin-regexp nil t)
648                 (beginning-of-line)))))
649     (goto-char end))
650   mime-message)
651
652 (defun notmuch-show-markup-parts-region (beg end depth)
653   (save-excursion
654     (goto-char beg)
655     (let (mime-message)
656       (while (< (point) end)
657         (setq mime-message
658               (notmuch-show-markup-part
659                beg end depth mime-message))))))
660
661 (defun notmuch-show-markup-body (depth btn)
662   (re-search-forward notmuch-show-body-begin-regexp)
663   (forward-line)
664   (let ((beg (point-marker)))
665     (re-search-forward notmuch-show-body-end-regexp)
666     (let ((end (copy-marker (match-beginning 0))))
667       (notmuch-show-markup-parts-region beg end depth)
668       (let ((invis-spec (make-symbol "notmuch-show-body-read")))
669         (overlay-put (make-overlay beg end)
670                      'invisible invis-spec)
671         (button-put btn 'invisibility-spec invis-spec)
672         (if (not (notmuch-show-message-unread-p))
673             (add-to-invisibility-spec invis-spec)))
674       (set-marker beg nil)
675       (set-marker end nil)
676       )))
677 (defun notmuch-fontify-headers ()
678   (progn
679     (if (looking-at "[Tt]o:")
680         (progn
681           (overlay-put (make-overlay (point) (re-search-forward ":"))
682                        'face 'message-header-name)
683           (overlay-put (make-overlay (point) (re-search-forward ".*$"))
684                        'face 'message-header-to))
685     (if (looking-at "[B]?[Cc][Cc]:")
686         (progn
687           (overlay-put (make-overlay (point) (re-search-forward ":"))
688                        'face 'message-header-name)
689           (overlay-put (make-overlay (point) (re-search-forward ".*$"))
690                        'face 'message-header-cc))
691     (if (looking-at "[Ss]ubject:")
692         (progn
693           (overlay-put (make-overlay (point) (re-search-forward ":"))
694                        'face 'message-header-name)
695           (overlay-put (make-overlay (point) (re-search-forward ".*$"))
696                        'face 'message-header-subject))
697     (if (looking-at "[Ff]rom:")
698         (progn
699           (overlay-put (make-overlay (point) (re-search-forward ":"))
700                        'face 'message-header-name)
701           (overlay-put (make-overlay (point) (re-search-forward ".*$"))
702                        'face 'message-header-other))))))))
703
704 (defun notmuch-show-markup-header (depth)
705   (re-search-forward notmuch-show-header-begin-regexp)
706   (forward-line)
707   (let ((beg (point-marker))
708         (btn nil))
709     (end-of-line)
710     ; Inverse video for subject
711     (overlay-put (make-overlay beg (point)) 'face '(:inverse-video t))
712     (setq btn (make-button beg (point) :type 'notmuch-button-body-toggle-type))
713     (forward-line 1)
714     (end-of-line)
715     (let ((beg-hidden (point-marker)))
716       (re-search-forward notmuch-show-header-end-regexp)
717       (beginning-of-line)
718       (let ((end (point-marker)))
719         (goto-char beg)
720         (forward-line)
721         (while (looking-at "[A-Za-z][-A-Za-z0-9]*:")
722           (beginning-of-line)
723           (notmuch-fontify-headers)
724           (forward-line)
725           )
726         (indent-rigidly beg end depth)
727         (let ((invis-spec (make-symbol "notmuch-show-header")))
728           (add-to-invisibility-spec (cons invis-spec t))
729           (overlay-put (make-overlay beg-hidden end)
730                        'invisible invis-spec)
731           (goto-char beg)
732           (forward-line)
733           (make-button (line-beginning-position) (line-end-position)
734                         'invisibility-spec (cons invis-spec t)
735                         :type 'notmuch-button-headers-toggle-type))
736         (goto-char end)
737         (insert "\n")
738         (set-marker beg nil)
739         (set-marker beg-hidden nil)
740         (set-marker end nil)
741         ))
742     btn))
743
744 (defun notmuch-show-markup-message ()
745   (if (re-search-forward notmuch-show-message-begin-regexp nil t)
746       (progn
747         (re-search-forward notmuch-show-depth-regexp)
748         (let ((depth (string-to-number (buffer-substring (match-beginning 1) (match-end 1))))
749               (btn nil))
750           (setq btn (notmuch-show-markup-header depth))
751           (notmuch-show-markup-body depth btn)))
752     (goto-char (point-max))))
753
754 (defun notmuch-show-hide-markers ()
755   (save-excursion
756     (goto-char (point-min))
757     (while (not (eobp))
758       (if (re-search-forward notmuch-show-marker-regexp nil t)
759           (progn
760             (overlay-put (make-overlay (match-beginning 0) (+ (match-end 0) 1))
761                          'invisible 'notmuch-show-marker))
762         (goto-char (point-max))))))
763
764 (defun notmuch-show-markup-messages ()
765   (save-excursion
766     (goto-char (point-min))
767     (while (not (eobp))
768       (notmuch-show-markup-message)))
769   (notmuch-show-hide-markers))
770
771 (defun notmuch-documentation-first-line (symbol)
772   "Return the first line of the documentation string for SYMBOL."
773   (let ((doc (documentation symbol)))
774     (if doc
775         (with-temp-buffer
776           (insert (documentation symbol t))
777           (goto-char (point-min))
778           (let ((beg (point)))
779             (end-of-line)
780             (buffer-substring beg (point))))
781       "")))
782
783 (defun notmuch-prefix-key-description (key)
784   "Given a prefix key code, return a human-readable string representation.
785
786 This is basically just `format-kbd-macro' but we also convert ESC to M-."
787   (let ((desc (format-kbd-macro (vector key))))
788     (if (string= desc "ESC")
789         "M-"
790       (concat desc " "))))
791
792 ; I would think that emacs would have code handy for walking a keymap
793 ; and generating strings for each key, and I would prefer to just call
794 ; that. But I couldn't find any (could be all implemented in C I
795 ; suppose), so I wrote my own here.
796 (defun notmuch-substitute-one-command-key-with-prefix (prefix binding)
797   "For a key binding, return a string showing a human-readable
798 representation of the prefixed key as well as the first line of
799 documentation from the bound function.
800
801 For a mouse binding, return nil."
802   (let ((key (car binding))
803         (action (cdr binding)))
804     (if (mouse-event-p key)
805         nil
806       (if (keymapp action)
807           (let ((substitute (apply-partially 'notmuch-substitute-one-command-key-with-prefix (notmuch-prefix-key-description key))))
808             (mapconcat substitute (cdr action) "\n"))
809         (concat prefix (format-kbd-macro (vector key))
810                 "\t"
811                 (notmuch-documentation-first-line action))))))
812
813 (defalias 'notmuch-substitute-one-command-key
814   (apply-partially 'notmuch-substitute-one-command-key-with-prefix nil))
815
816 (defun notmuch-substitute-command-keys (doc)
817   "Like `substitute-command-keys' but with documentation, not function names."
818   (let ((beg 0))
819     (while (string-match "\\\\{\\([^}[:space:]]*\\)}" doc beg)
820       (let ((map (substring doc (match-beginning 1) (match-end 1))))
821         (setq doc (replace-match (mapconcat 'notmuch-substitute-one-command-key
822                                             (cdr (symbol-value (intern map))) "\n") 1 1 doc)))
823       (setq beg (match-end 0)))
824     doc))
825
826 (defun notmuch-help ()
827   "Display help for the current notmuch mode."
828   (interactive)
829   (let ((mode major-mode))
830     (with-help-window (help-buffer)
831       (princ (substitute-command-keys (notmuch-substitute-command-keys (documentation mode t)))))))
832
833 ;;;###autoload
834 (defun notmuch-show-mode ()
835   "Major mode for viewing a thread with notmuch.
836
837 This buffer contains the results of the \"notmuch show\" command
838 for displaying a single thread of email from your email archives.
839
840 By default, various components of email messages, (citations,
841 signatures, already-read messages), are hidden. You can make
842 these parts visible by clicking with the mouse button or by
843 pressing RET after positioning the cursor on a hidden part, (for
844 which \\[notmuch-show-next-button] and \\[notmuch-show-previous-button] are helpful).
845
846 Reading the thread sequentially is well-supported by pressing
847 \\[notmuch-show-advance-marking-read-and-archiving]. This will scroll the current message (if necessary),
848 advance to the next message, or advance to the next thread (if
849 already on the last message of a thread). As each message is
850 scrolled away its \"unread\" tag will be removed, and as each
851 thread is scrolled away the \"inbox\" tag will be removed from
852 each message in the thread.
853
854 Other commands are available to read or manipulate the thread more
855 selectively, (such as '\\[notmuch-show-next-message]' and '\\[notmuch-show-previous-message]' to advance to messages without
856 removing any tags, and '\\[notmuch-show-archive-thread]' to archive an entire thread without
857 scrolling through with \\[notmuch-show-advance-marking-read-and-archiving]).
858
859 You can add or remove arbitary tags from the current message with
860 '\\[notmuch-show-add-tag]' or '\\[notmuch-show-remove-tag]'.
861
862 All currently available key bindings:
863
864 \\{notmuch-show-mode-map}"
865   (interactive)
866   (kill-all-local-variables)
867   (add-to-invisibility-spec 'notmuch-show-marker)
868   (use-local-map notmuch-show-mode-map)
869   (setq major-mode 'notmuch-show-mode
870         mode-name "notmuch-show")
871   (setq buffer-read-only t))
872
873 (defgroup notmuch nil
874   "Notmuch mail reader for Emacs."
875   :group 'mail)
876
877 (defcustom notmuch-show-hook nil
878   "List of functions to call when notmuch displays a message."
879   :type 'hook
880   :options '(goto-address)
881   :group 'notmuch)
882
883 (defcustom notmuch-search-hook nil
884   "List of functions to call when notmuch displays the search results."
885   :type 'hook
886   :options '(hl-line-mode)
887   :group 'notmuch)
888
889 ; Make show mode a bit prettier, highlighting URLs and using word wrap
890
891 (defun notmuch-show-pretty-hook ()
892   (goto-address-mode 1)
893   (visual-line-mode))
894
895 (add-hook 'notmuch-show-hook 'notmuch-show-pretty-hook)
896 (add-hook 'notmuch-search-hook
897           (lambda()
898             (hl-line-mode 1) ))
899
900 (defun notmuch-show (thread-id &optional parent-buffer)
901   "Run \"notmuch show\" with the given thread ID and display results.
902
903 The optional PARENT-BUFFER is the notmuch-search buffer from
904 which this notmuch-show command was executed, (so that the next
905 thread from that buffer can be show when done with this one)."
906   (interactive "sNotmuch show: ")
907   (let ((buffer (get-buffer-create (concat "*notmuch-show-" thread-id "*"))))
908     (switch-to-buffer buffer)
909     (notmuch-show-mode)
910     (set (make-local-variable 'notmuch-show-parent-buffer) parent-buffer)
911     (let ((proc (get-buffer-process (current-buffer)))
912           (inhibit-read-only t))
913       (if proc
914           (error "notmuch search process already running for query `%s'" thread-id)
915         )
916       (erase-buffer)
917       (goto-char (point-min))
918       (save-excursion
919         (call-process notmuch-command nil t nil "show" thread-id)
920         (notmuch-show-markup-messages)
921         )
922       (run-hooks 'notmuch-show-hook)
923       ; Move straight to the first unread message
924       (if (not (notmuch-show-message-unread-p))
925           (progn
926             (notmuch-show-next-unread-message)
927             ; But if there are no unread messages, go back to the
928             ; beginning of the buffer, and open up the bodies of all
929             ; read message.
930             (if (not (notmuch-show-message-unread-p))
931                 (progn
932                   (goto-char (point-min))
933                   (let ((btn (forward-button 1)))
934                     (while btn
935                       (if (button-has-type-p btn 'notmuch-button-body-toggle-type)
936                           (push-button))
937                       (condition-case err
938                           (setq btn (forward-button 1))
939                         (error (setq btn nil)))
940                     ))
941                   (goto-char (point-min))
942                   ))))
943       )))
944
945 (defvar notmuch-search-authors-width 40
946   "Number of columns to use to display authors in a notmuch-search buffer.")
947
948 (defvar notmuch-search-mode-map
949   (let ((map (make-sparse-keymap)))
950     (define-key map "?" 'notmuch-help)
951     (define-key map "q" 'kill-this-buffer)
952     (define-key map "x" 'kill-this-buffer)
953     (define-key map (kbd "<DEL>") 'notmuch-search-scroll-down)
954     (define-key map "b" 'notmuch-search-scroll-down)
955     (define-key map " " 'notmuch-search-scroll-up)
956     (define-key map "<" 'notmuch-search-first-thread)
957     (define-key map ">" 'notmuch-search-last-thread)
958     (define-key map "p" 'notmuch-search-previous-thread)
959     (define-key map "n" 'notmuch-search-next-thread)
960     (define-key map "r" 'notmuch-search-reply-to-thread)
961     (define-key map "m" 'message-mail)
962     (define-key map "s" 'notmuch-search)
963     (define-key map "o" 'notmuch-search-toggle-order)
964     (define-key map "=" 'notmuch-search-refresh-view)
965     (define-key map "t" 'notmuch-search-filter-by-tag)
966     (define-key map "f" 'notmuch-search-filter)
967     (define-key map [mouse-1] 'notmuch-search-show-thread)
968     (define-key map "*" 'notmuch-search-operate-all)
969     (define-key map "a" 'notmuch-search-archive-thread)
970     (define-key map "-" 'notmuch-search-remove-tag)
971     (define-key map "+" 'notmuch-search-add-tag)
972     (define-key map (kbd "RET") 'notmuch-search-show-thread)
973     map)
974   "Keymap for \"notmuch search\" buffers.")
975 (fset 'notmuch-search-mode-map notmuch-search-mode-map)
976
977 (defvar notmuch-search-query-string)
978 (defvar notmuch-search-oldest-first t
979   "Show the oldest mail first in the search-mode")
980
981 (defun notmuch-search-scroll-up ()
982   "Move forward through search results by one window's worth."
983   (interactive)
984   (condition-case nil
985       (scroll-up nil)
986     ((end-of-buffer) (notmuch-search-last-thread))))
987
988 (defun notmuch-search-scroll-down ()
989   "Move backward through the search results by one window's worth."
990   (interactive)
991   ; I don't know why scroll-down doesn't signal beginning-of-buffer
992   ; the way that scroll-up signals end-of-buffer, but c'est la vie.
993   ;
994   ; So instead of trapping a signal we instead check whether the
995   ; window begins on the first line of the buffer and if so, move
996   ; directly to that position. (We have to count lines since the
997   ; window-start position is not the same as point-min due to the
998   ; invisible thread-ID characters on the first line.
999   (if (equal (count-lines (point-min) (window-start)) 0)
1000       (goto-char (point-min))
1001     (scroll-down nil)))
1002
1003 (defun notmuch-search-next-thread ()
1004   "Select the next thread in the search results."
1005   (interactive)
1006   (next-line))
1007
1008 (defun notmuch-search-previous-thread ()
1009   "Select the previous thread in the search results."
1010   (interactive)
1011   (previous-line))
1012
1013 (defun notmuch-search-last-thread ()
1014   "Select the last thread in the search results."
1015   (interactive)
1016   (goto-char (point-max))
1017   (forward-line -2))
1018
1019 (defun notmuch-search-first-thread ()
1020   "Select the first thread in the search results."
1021   (interactive)
1022   (goto-char (point-min)))
1023
1024 (defface notmuch-tag-face
1025   '((((class color)
1026       (background dark))
1027      (:foreground "OliveDrab1"))
1028     (((class color)
1029       (background light))
1030      (:foreground "navy blue" :bold t))
1031     (t
1032      (:bold t)))
1033   "Notmuch search mode face used to highligh tags."
1034   :group 'notmuch)
1035
1036 (defvar notmuch-tag-face-alist nil
1037   "List containing the tag list that need to be highlighed")
1038
1039 (defvar notmuch-search-font-lock-keywords  nil)
1040
1041 ;;;###autoload
1042 (defun notmuch-search-mode ()
1043   "Major mode displaying results of a notmuch search.
1044
1045 This buffer contains the results of a \"notmuch search\" of your
1046 email archives. Each line in the buffer represents a single
1047 thread giving a summary of the thread (a relative date, the
1048 number of matched messages and total messages in the thread,
1049 participants in the thread, a representative subject line, and
1050 any tags).
1051
1052 Pressing \\[notmuch-search-show-thread] on any line displays that thread. The '\\[notmuch-search-add-tag]' and '\\[notmuch-search-remove-tag]'
1053 keys can be used to add or remove tags from a thread. The '\\[notmuch-search-archive-thread]' key
1054 is a convenience for archiving a thread (removing the \"inbox\"
1055 tag). The '\\[notmuch-search-operate-all]' key can be used to add or remove a tag from all
1056 threads in the current buffer.
1057
1058 Other useful commands are '\\[notmuch-search-filter]' for filtering the current search
1059 based on an additional query string, '\\[notmuch-search-filter-by-tag]' for filtering to include
1060 only messages with a given tag, and '\\[notmuch-search]' to execute a new, global
1061 search.
1062
1063 Complete list of currently available key bindings:
1064
1065 \\{notmuch-search-mode-map}"
1066   (interactive)
1067   (kill-all-local-variables)
1068   (make-local-variable 'notmuch-search-query-string)
1069   (make-local-variable 'notmuch-search-oldest-first)
1070   (set (make-local-variable 'scroll-preserve-screen-position) t)
1071   (add-to-invisibility-spec 'notmuch-search)
1072   (use-local-map notmuch-search-mode-map)
1073   (setq truncate-lines t)
1074   (setq major-mode 'notmuch-search-mode
1075         mode-name "notmuch-search")
1076   (setq buffer-read-only t)
1077   (if (not notmuch-tag-face-alist)
1078       (add-to-list 'notmuch-search-font-lock-keywords (list
1079                 "(\\([^)]*\\))$" '(1  'notmuch-tag-face)))
1080     (progn
1081   (setq notmuch-search-tags (mapcar 'car notmuch-tag-face-alist))
1082   (loop for notmuch-search-tag  in notmuch-search-tags
1083     do (add-to-list 'notmuch-search-font-lock-keywords (list
1084                                 (concat "([^)]*\\(" notmuch-search-tag "\\)[^)]*)$")
1085                     `(1  ,(cdr (assoc notmuch-search-tag notmuch-tag-face-alist))))))))
1086   (set (make-local-variable 'font-lock-defaults)
1087          '(notmuch-search-font-lock-keywords t)))
1088
1089 (defun notmuch-search-find-thread-id ()
1090   "Return the thread for the current thread"
1091   (get-text-property (point) 'notmuch-search-thread-id))
1092
1093 (defun notmuch-search-show-thread ()
1094   "Display the currently selected thread."
1095   (interactive)
1096   (let ((thread-id (notmuch-search-find-thread-id)))
1097     (if (> (length thread-id) 0)
1098         (notmuch-show thread-id (current-buffer))
1099       (error "End of search results"))))
1100
1101 (defun notmuch-search-reply-to-thread ()
1102   "Begin composing a reply to the entire current thread in a new buffer."
1103   (interactive)
1104   (let ((message-id (notmuch-search-find-thread-id)))
1105     (notmuch-reply message-id)))
1106
1107 (defun notmuch-call-notmuch-process (&rest args)
1108   "Synchronously invoke \"notmuch\" with the given list of arguments.
1109
1110 Output from the process will be presented to the user as an error
1111 and will also appear in a buffer named \"*Notmuch errors*\"."
1112   (let ((error-buffer (get-buffer-create "*Notmuch errors*")))
1113     (with-current-buffer error-buffer
1114         (erase-buffer))
1115     (if (eq (apply 'call-process notmuch-command nil error-buffer nil args) 0)
1116         (point)
1117       (progn
1118         (with-current-buffer error-buffer
1119           (let ((beg (point-min))
1120                 (end (- (point-max) 1)))
1121             (error (buffer-substring beg end))
1122             ))))))
1123
1124 (defun notmuch-search-set-tags (tags)
1125   (save-excursion
1126     (end-of-line)
1127     (re-search-backward "(")
1128     (forward-char)
1129     (let ((beg (point))
1130           (inhibit-read-only t))
1131       (re-search-forward ")")
1132       (backward-char)
1133       (let ((end (point)))
1134         (delete-region beg end)
1135         (insert (mapconcat  'identity tags " "))))))
1136
1137 (defun notmuch-search-get-tags ()
1138   (save-excursion
1139     (end-of-line)
1140     (re-search-backward "(")
1141     (let ((beg (+ (point) 1)))
1142       (re-search-forward ")")
1143       (let ((end (- (point) 1)))
1144         (split-string (buffer-substring beg end))))))
1145
1146 (defun notmuch-search-add-tag (tag)
1147   "Add a tag to the currently selected thread.
1148
1149 The tag is added to messages in the currently selected thread
1150 which match the current search terms."
1151   (interactive
1152    (list (notmuch-select-tag-with-completion "Tag to add: ")))
1153   (notmuch-call-notmuch-process "tag" (concat "+" tag) (notmuch-search-find-thread-id) " and " notmuch-search-query-string)
1154   (notmuch-search-set-tags (delete-dups (sort (cons tag (notmuch-search-get-tags)) 'string<))))
1155
1156 (defun notmuch-search-remove-tag (tag)
1157   "Remove a tag from the currently selected thread.
1158
1159 The tag is removed from messages in the currently selected thread
1160 which match the current search terms."
1161   (interactive
1162    (list (notmuch-select-tag-with-completion "Tag to remove: " (notmuch-search-find-thread-id))))
1163   (notmuch-call-notmuch-process "tag" (concat "-" tag) (notmuch-search-find-thread-id) " and " notmuch-search-query-string)
1164   (notmuch-search-set-tags (delete tag (notmuch-search-get-tags))))
1165
1166 (defun notmuch-search-archive-thread ()
1167   "Archive the currently selected thread (remove its \"inbox\" tag).
1168
1169 This function advances the next thread when finished."
1170   (interactive)
1171   (notmuch-search-remove-tag "inbox")
1172   (forward-line))
1173
1174 (defun notmuch-search-process-sentinel (proc msg)
1175   "Add a message to let user know when \"notmuch search\" exits"
1176   (let ((buffer (process-buffer proc))
1177         (status (process-status proc))
1178         (exit-status (process-exit-status proc)))
1179     (if (memq status '(exit signal))
1180         (if (buffer-live-p buffer)
1181             (with-current-buffer buffer
1182               (save-excursion
1183                 (let ((inhibit-read-only t))
1184                   (goto-char (point-max))
1185                   (if (eq status 'signal)
1186                       (insert "Incomplete search results (search process was killed).\n"))
1187                   (if (eq status 'exit)
1188                       (progn
1189                         (insert "End of search results.")
1190                         (if (not (= exit-status 0))
1191                             (insert (format " (process returned %d)" exit-status)))
1192                         (insert "\n"))))))))))
1193
1194 (defun notmuch-search-process-filter (proc string)
1195   "Process and filter the output of \"notmuch search\""
1196   (let ((buffer (process-buffer proc)))
1197     (if (buffer-live-p buffer)
1198         (with-current-buffer buffer
1199           (save-excursion
1200             (let ((line 0)
1201                   (more t)
1202                   (inhibit-read-only t))
1203               (while more
1204                 (if (string-match "^\\(thread:[0-9A-Fa-f]*\\) \\(.*\\) \\(\\[[0-9/]*\\]\\) \\([^:]*\\); \\(.*\\) (\\([^()]*\\))$" string line)
1205                     (let* ((thread-id (match-string 1 string))
1206                            (date (match-string 2 string))
1207                            (count (match-string 3 string))
1208                            (authors (match-string 4 string))
1209                            (authors-length (length authors))
1210                            (subject (match-string 5 string))
1211                            (tags (match-string 6 string)))
1212                       (if (> authors-length 40)
1213                           (set 'authors (concat (substring authors 0 (- 40 3)) "...")))
1214                       (goto-char (point-max))
1215                       (let ((beg (point-marker)))
1216                         (insert (format "%s %-7s %-40s %s (%s)\n" date count authors subject tags))
1217                         (put-text-property beg (point-marker) 'notmuch-search-thread-id thread-id))
1218                       (set 'line (match-end 0)))
1219                   (set 'more nil))))))
1220       (delete-process proc))))
1221
1222 (defun notmuch-search-operate-all (action)
1223   "Add/remove tags from all matching messages.
1224
1225 Tis command adds or removes tags from all messages matching the
1226 current search terms. When called interactively, this command
1227 will prompt for tags to be added or removed. Tags prefixed with
1228 '+' will be added and tags prefixed with '-' will be removed.
1229
1230 Each character of the tag name may consist of alphanumeric
1231 characters as well as `_.+-'.
1232 "
1233   (interactive "sOperation (+add -drop): notmuch tag ")
1234   (let ((action-split (split-string action " +")))
1235     ;; Perform some validation
1236     (let ((words action-split))
1237       (when (null words) (error "No operation given"))
1238       (while words
1239         (unless (string-match-p "^[-+][-+_.[:word:]]+$" (car words))
1240           (error "Action must be of the form `+thistag -that_tag'"))
1241         (setq words (cdr words))))
1242     (apply 'notmuch-call-notmuch-process "tag"
1243            (append action-split (list notmuch-search-query-string) nil))))
1244
1245 ;;;###autoload
1246 (defun notmuch-search (query &optional oldest-first)
1247   "Run \"notmuch search\" with the given query string and display results."
1248   (interactive "sNotmuch search: ")
1249   (let ((buffer (get-buffer-create (concat "*notmuch-search-" query "*"))))
1250     (switch-to-buffer buffer)
1251     (notmuch-search-mode)
1252     (set 'notmuch-search-query-string query)
1253     (set 'notmuch-search-oldest-first oldest-first)
1254     (let ((proc (get-buffer-process (current-buffer)))
1255           (inhibit-read-only t))
1256       (if proc
1257           (error "notmuch search process already running for query `%s'" query)
1258         )
1259       (erase-buffer)
1260       (goto-char (point-min))
1261       (save-excursion
1262         (let ((proc (start-process-shell-command
1263                      "notmuch-search" buffer notmuch-command "search"
1264                      (if oldest-first "--sort=oldest-first" "--sort=newest-first")
1265                      (shell-quote-argument query))))
1266           (set-process-sentinel proc 'notmuch-search-process-sentinel)
1267           (set-process-filter proc 'notmuch-search-process-filter))))
1268     (run-hooks 'notmuch-search-hook)))
1269
1270 (defun notmuch-search-refresh-view ()
1271   "Refresh the current view.
1272
1273 Kills the current buffer and runs a new search with the same
1274 query string as the current search. If the current thread is in
1275 the new search results, then point will be placed on the same
1276 thread. Otherwise, point will be moved to attempt to be in the
1277 same relative position within the new buffer."
1278   (interactive)
1279   (let ((here (point))
1280         (oldest-first notmuch-search-oldest-first)
1281         (thread (notmuch-search-find-thread-id))
1282         (query notmuch-search-query-string))
1283     (kill-this-buffer)
1284     (notmuch-search query oldest-first)
1285     (goto-char (point-min))
1286     (if (re-search-forward (concat "^" thread) nil t)
1287         (beginning-of-line)
1288       (goto-char here))))
1289
1290 (defun notmuch-search-toggle-order ()
1291   "Toggle the current search order.
1292
1293 By default, the \"inbox\" view created by `notmuch' is displayed
1294 in chronological order (oldest thread at the beginning of the
1295 buffer), while any global searches created by `notmuch-search'
1296 are displayed in reverse-chronological order (newest thread at
1297 the beginning of the buffer).
1298
1299 This command toggles the sort order for the current search.
1300
1301 Note that any filtered searches created by
1302 `notmuch-search-filter' retain the search order of the parent
1303 search."
1304   (interactive)
1305   (set 'notmuch-search-oldest-first (not notmuch-search-oldest-first))
1306   (notmuch-search-refresh-view))
1307
1308 (defun notmuch-search-filter (query)
1309   "Filter the current search results based on an additional query string.
1310
1311 Runs a new search matching only messages that match both the
1312 current search results AND the additional query string provided."
1313   (interactive "sFilter search: ")
1314   (notmuch-search (concat notmuch-search-query-string " and " query) notmuch-search-oldest-first))
1315
1316 (defun notmuch-search-filter-by-tag (tag)
1317   "Filter the current search results based on a single tag.
1318
1319 Runs a new search matching only messages that match both the
1320 current search results AND that are tagged with the given tag."
1321   (interactive
1322    (list (notmuch-select-tag-with-completion "Filter by tag: ")))
1323   (notmuch-search (concat notmuch-search-query-string " and tag:" tag) notmuch-search-oldest-first))
1324
1325
1326 ;;;###autoload
1327 (defun notmuch ()
1328   "Run notmuch to display all mail with tag of 'inbox'"
1329   (interactive)
1330   (notmuch-search "tag:inbox" notmuch-search-oldest-first))
1331
1332 (setq mail-user-agent 'message-user-agent)
1333
1334 (defvar notmuch-folder-mode-map
1335   (let ((map (make-sparse-keymap)))
1336     (define-key map "?" 'notmuch-help)
1337     (define-key map "x" 'kill-this-buffer)
1338     (define-key map "q" 'kill-this-buffer)
1339     (define-key map ">" 'notmuch-folder-last)
1340     (define-key map "<" 'notmuch-folder-first)
1341     (define-key map "=" 'notmuch-folder)
1342     (define-key map "s" 'notmuch-search)
1343     (define-key map [mouse-1] 'notmuch-folder-show-search)
1344     (define-key map (kbd "RET") 'notmuch-folder-show-search)
1345     (define-key map "p" 'notmuch-folder-previous)
1346     (define-key map "n" 'notmuch-folder-next)
1347     map)
1348   "Keymap for \"notmuch folder\" buffers.")
1349
1350 (fset 'notmuch-folder-mode-map notmuch-folder-mode-map)
1351
1352 (defcustom notmuch-folders (quote (("inbox" . "tag:inbox") ("unread" . "tag:unread")))
1353   "List of searches for the notmuch folder view"
1354   :type '(alist :key-type (string) :value-type (string))
1355   :group 'notmuch)
1356
1357 (defun notmuch-folder-mode ()
1358   "Major mode for showing notmuch 'folders'.
1359
1360 This buffer contains a list of message counts returned by a
1361 customizable set of searches of your email archives. Each line in
1362 the buffer shows the name of a saved search and the resulting
1363 message count.
1364
1365 Pressing RET on any line opens a search window containing the
1366 results for the saved search on that line.
1367
1368 Here is an example of how the search list could be
1369 customized, (the following text would be placed in your ~/.emacs
1370 file):
1371
1372 (setq notmuch-folders '((\"inbox\" . \"tag:inbox\")
1373                         (\"unread\" . \"tag:inbox AND tag:unread\")
1374                         (\"notmuch\" . \"tag:inbox AND to:notmuchmail.org\")))
1375
1376 Of course, you can have any number of folders, each configured
1377 with any supported search terms (see \"notmuch help search-terms\").
1378
1379 Currently available key bindings:
1380
1381 \\{notmuch-folder-mode-map}"
1382   (interactive)
1383   (kill-all-local-variables)
1384   (use-local-map 'notmuch-folder-mode-map)
1385   (setq truncate-lines t)
1386   (hl-line-mode 1)
1387   (setq major-mode 'notmuch-folder-mode
1388         mode-name "notmuch-folder")
1389   (setq buffer-read-only t))
1390
1391 (defun notmuch-folder-next ()
1392   "Select the next folder in the list."
1393   (interactive)
1394   (forward-line 1)
1395   (if (eobp)
1396       (forward-line -1)))
1397
1398 (defun notmuch-folder-previous ()
1399   "Select the previous folder in the list."
1400   (interactive)
1401   (forward-line -1))
1402
1403 (defun notmuch-folder-first ()
1404   "Select the first folder in the list."
1405   (interactive)
1406   (goto-char (point-min)))
1407
1408 (defun notmuch-folder-last ()
1409   "Select the last folder in the list."
1410   (interactive)
1411   (goto-char (point-max))
1412   (forward-line -1))
1413
1414 (defun notmuch-folder-add (folders)
1415   (if folders
1416       (let ((name (car (car folders)))
1417             (inhibit-read-only t)
1418             (search (cdr (car folders))))
1419         (insert name)
1420         (indent-to 16 1)
1421         (call-process notmuch-command nil t nil "count" search)
1422         (notmuch-folder-add (cdr folders)))))
1423
1424 (defun notmuch-folder-find-name ()
1425   (save-excursion
1426     (beginning-of-line)
1427     (let ((beg (point)))
1428       (forward-word)
1429       (filter-buffer-substring beg (point)))))
1430
1431 (defun notmuch-folder-show-search (&optional folder)
1432   "Show a search window for the search related to the specified folder."
1433   (interactive)
1434   (if (null folder)
1435       (setq folder (notmuch-folder-find-name)))
1436   (let ((search (assoc folder notmuch-folders)))
1437     (if search
1438         (notmuch-search (cdr search) notmuch-search-oldest-first))))
1439
1440 ;;;###autoload
1441 (defun notmuch-folder ()
1442   "Show the notmuch folder view and update the displayed counts."
1443   (interactive)
1444   (let ((buffer (get-buffer-create "*notmuch-folders*")))
1445     (switch-to-buffer buffer)
1446     (let ((inhibit-read-only t)
1447           (n (line-number-at-pos)))
1448       (erase-buffer)
1449       (notmuch-folder-mode)
1450       (notmuch-folder-add notmuch-folders)
1451       (goto-char (point-min))
1452       (goto-line n))))
1453
1454 (provide 'notmuch)