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