]> git.notmuchmail.org Git - notmuch/blob - notmuch.el
282932ed7fa9ea9655b8b6056927d63d8a060c74
[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-reply (query-string)
304   (switch-to-buffer (generate-new-buffer "notmuch-draft"))
305   (call-process notmuch-command nil t nil "reply" query-string)
306   (message-insert-signature)
307   (goto-char (point-min))
308   (if (re-search-forward "^$" nil t)
309       (progn
310         (insert "--text follows this line--")
311         (forward-line)))
312   (message-mode))
313
314 (defun notmuch-show-reply ()
315   "Begin composing a reply to the current message in a new buffer."
316   (interactive)
317   (let ((message-id (notmuch-show-get-message-id)))
318     (notmuch-reply message-id)))
319
320 (defun notmuch-show-forward-current ()
321   "Forward a the current message."
322   (interactive)
323   (with-current-notmuch-show-message
324    (message-forward)))
325
326 (defun notmuch-show-pipe-message (command)
327   "Pipe the contents of the current message to the given command.
328
329 The given command will be executed with the raw contents of the
330 current email message as stdin. Anything printed by the command
331 to stdout or stderr will appear in the *Messages* buffer."
332   (interactive "sPipe message to command: ")
333   (apply 'start-process-shell-command "notmuch-pipe-command" "*notmuch-pipe*"
334          (list command " < " (shell-quote-argument (notmuch-show-get-filename)))))
335
336 (defun notmuch-show-move-to-current-message-summary-line ()
337   "Move to the beginning of the one-line summary of the current message.
338
339 This gives us a stable place to move to and work from since the
340 summary line is always visible. This is important since moving to
341 an invisible location is unreliable, (the main command loop moves
342 point either forward or backward to the next visible character
343 when a command ends with point on an invisible character).
344
345 Emits an error if point is not within a valid message, (that is
346 not pattern of `notmuch-show-message-begin-regexp' could be found
347 by searching backward)."
348   (beginning-of-line)
349   (if (not (looking-at notmuch-show-message-begin-regexp))
350       (if (re-search-backward notmuch-show-message-begin-regexp nil t)
351           (forward-line 2)
352         (error "Not within a valid message."))
353     (forward-line 2)))
354
355 (defun notmuch-show-last-message-p ()
356   "Predicate testing whether point is within the last message."
357   (save-window-excursion
358     (save-excursion
359       (notmuch-show-move-to-current-message-summary-line)
360       (not (re-search-forward notmuch-show-message-begin-regexp nil t)))))
361
362 (defun notmuch-show-message-unread-p ()
363   "Preficate testing whether current message is unread."
364   (member "unread" (notmuch-show-get-tags)))
365
366 (defun notmuch-show-next-message ()
367   "Advance to the beginning of the next message in the buffer.
368
369 Moves to the last visible character of the current message if
370 already on the last message in the buffer."
371   (interactive)
372   (notmuch-show-move-to-current-message-summary-line)
373   (if (re-search-forward notmuch-show-message-begin-regexp nil t)
374       (notmuch-show-move-to-current-message-summary-line)
375     (goto-char (- (point-max) 1))
376     (while (point-invisible-p)
377       (backward-char)))
378   (recenter 0))
379
380 (defun notmuch-show-find-next-message ()
381   "Returns the position of the next message in the buffer.
382
383 Or the position of the last visible character of the current
384 message if already within the last message in the buffer."
385   ; save-excursion doesn't save our window position
386   ; save-window-excursion doesn't save point
387   ; Looks like we have to use both.
388   (save-excursion
389     (save-window-excursion
390       (notmuch-show-next-message)
391       (point))))
392
393 (defun notmuch-show-next-unread-message ()
394   "Advance to the beginning of the next unread message in the buffer.
395
396 Moves to the last visible character of the current message if
397 there are no more unread messages past the current point."
398   (notmuch-show-next-message)
399   (while (and (not (notmuch-show-last-message-p))
400               (not (notmuch-show-message-unread-p)))
401     (notmuch-show-next-message))
402   (if (not (notmuch-show-message-unread-p))
403       (notmuch-show-next-message)))
404
405 (defun notmuch-show-next-open-message ()
406   "Advance to the next message which is not hidden.
407
408 If read messages are currently hidden, advance to the next unread
409 message. Otherwise, advance to the next message."
410   (if (or (memq 'notmuch-show-body-read buffer-invisibility-spec)
411           (assq 'notmuch-show-body-read buffer-invisibility-spec))
412       (notmuch-show-next-unread-message)
413     (notmuch-show-next-message)))
414
415 (defun notmuch-show-previous-message ()
416   "Backup to the beginning of the previous message in the buffer.
417
418 If within a message rather than at the beginning of it, then
419 simply move to the beginning of the current message."
420   (interactive)
421   (let ((start (point)))
422     (notmuch-show-move-to-current-message-summary-line)
423     (if (not (< (point) start))
424         ; Go backward twice to skip the current message's marker
425         (progn
426           (re-search-backward notmuch-show-message-begin-regexp nil t)
427           (re-search-backward notmuch-show-message-begin-regexp nil t)
428           (notmuch-show-move-to-current-message-summary-line)
429           ))
430     (recenter 0)))
431
432 (defun notmuch-show-find-previous-message ()
433   "Returns the position of the previous message in the buffer.
434
435 Or the position of the beginning of the current message if point
436 is originally within the message rather than at the beginning of
437 it."
438   ; save-excursion doesn't save our window position
439   ; save-window-excursion doesn't save point
440   ; Looks like we have to use both.
441   (save-excursion
442     (save-window-excursion
443       (notmuch-show-previous-message)
444       (point))))
445
446 (defun notmuch-show-mark-read-then-next-open-message ()
447   "Remove unread tag from current message, then advance to next unread message."
448   (interactive)
449   (notmuch-show-remove-tag "unread")
450   (notmuch-show-next-open-message))
451
452 (defun notmuch-show-rewind ()
453   "Do reverse scrolling compared to `notmuch-show-advance-marking-read-and-archiving'
454
455 Specifically, if the beginning of the previous email is fewer
456 than `window-height' lines from the current point, move to it
457 just like `notmuch-show-previous-message'.
458
459 Otherwise, just scroll down a screenful of the current message.
460
461 This command does not modify any message tags, (it does not undo
462 any effects from previous calls to
463 `notmuch-show-advance-marking-read-and-archiving'."
464   (interactive)
465   (let ((previous (notmuch-show-find-previous-message)))
466     (if (> (count-lines previous (point)) (- (window-height) next-screen-context-lines))
467         (progn
468           (condition-case nil
469               (scroll-down nil)
470             ((beginning-of-buffer) nil))
471           (goto-char (window-start)))
472       (notmuch-show-previous-message))))
473
474 (defun notmuch-show-advance-marking-read-and-archiving ()
475   "Advance through buffer, marking read and archiving.
476
477 This command is intended to be one of the simplest ways to
478 process a thread of email. It does the following:
479
480 If the current message in the thread is not yet fully visible,
481 scroll by a near screenful to read more of the message.
482
483 Otherwise, (the end of the current message is already within the
484 current window), remove the \"unread\" tag (if present) from the
485 current message and advance to the next open message.
486
487 Finally, if there is no further message to advance to, and this
488 last message is already read, then archive the entire current
489 thread, (remove the \"inbox\" tag from each message). Also kill
490 this buffer, and display the next thread from the search from
491 which this thread was originally shown."
492   (interactive)
493   (let ((next (notmuch-show-find-next-message))
494         (unread (notmuch-show-message-unread-p)))
495     (if (> next (window-end))
496         (scroll-up nil)
497       (let ((last (notmuch-show-last-message-p)))
498         (notmuch-show-mark-read-then-next-open-message)
499         (if last
500             (notmuch-show-archive-thread))))))
501
502 (defun notmuch-show-next-button ()
503   "Advance point to the next button in the buffer."
504   (interactive)
505   (goto-char (button-start (next-button (point)))))
506
507 (defun notmuch-show-previous-button ()
508   "Move point back to the previous button in the buffer."
509   (interactive)
510   (goto-char (button-start (previous-button (point)))))
511
512 (defun notmuch-toggle-invisible-action (cite-button)
513   (let ((invis-spec (button-get button 'invisibility-spec)))
514         (if (invisible-p invis-spec)
515             (remove-from-invisibility-spec invis-spec)
516           (add-to-invisibility-spec invis-spec)
517           ))
518   (force-window-update)
519   (redisplay t))
520
521 (define-button-type 'notmuch-button-invisibility-toggle-type 'action 'notmuch-toggle-invisible-action 'follow-link t)
522 (define-button-type 'notmuch-button-citation-toggle-type 'help-echo "mouse-1, RET: Show citation"
523   :supertype 'notmuch-button-invisibility-toggle-type)
524 (define-button-type 'notmuch-button-signature-toggle-type 'help-echo "mouse-1, RET: Show signature"
525   :supertype 'notmuch-button-invisibility-toggle-type)
526 (define-button-type 'notmuch-button-headers-toggle-type 'help-echo "mouse-1, RET: Show headers"
527   :supertype 'notmuch-button-invisibility-toggle-type)
528 (define-button-type 'notmuch-button-body-toggle-type 'help-echo "mouse-1, RET: Show message"
529   :supertype 'notmuch-button-invisibility-toggle-type)
530
531 (defun notmuch-show-markup-citations-region (beg end depth)
532   (goto-char beg)
533   (beginning-of-line)
534   (while (< (point) end)
535     (let ((beg-sub (point-marker))
536           (indent (make-string depth ? ))
537           (citation "[[:space:]]*>"))
538       (if (looking-at citation)
539           (progn
540             (while (looking-at citation)
541               (forward-line))
542             (let ((overlay (make-overlay beg-sub (point)))
543                   (invis-spec (make-symbol "notmuch-citation-region")))
544               (add-to-invisibility-spec invis-spec)
545               (overlay-put overlay 'invisible invis-spec)
546               (let ((p (point))
547                     (cite-button-text
548                      (concat "["  (number-to-string (count-lines beg-sub (point)))
549                              "-line citation.]")))
550                 (goto-char (- beg-sub 1))
551                 (insert (concat "\n" indent))
552                 (insert-button cite-button-text
553                                'invisibility-spec invis-spec
554                                :type 'notmuch-button-citation-toggle-type)
555                 (insert "\n")
556                 (goto-char (+ (length cite-button-text) p))
557               ))))
558       (move-to-column depth)
559       (if (looking-at notmuch-show-signature-regexp)
560           (let ((sig-lines (- (count-lines beg-sub end) 1)))
561             (if (<= sig-lines notmuch-show-signature-lines-max)
562                 (progn
563                   (let ((invis-spec (make-symbol "notmuch-signature-region")))
564                     (add-to-invisibility-spec invis-spec)
565                     (overlay-put (make-overlay beg-sub end)
566                                  'invisible invis-spec)
567                   
568                     (goto-char (- beg-sub 1))
569                     (insert (concat "\n" indent))
570                     (let ((sig-button-text (concat "[" (number-to-string sig-lines)
571                                                    "-line signature.]")))
572                       (insert-button sig-button-text 'invisibility-spec invis-spec
573                                      :type 'notmuch-button-signature-toggle-type)
574                      )
575                     (insert "\n")
576                     (goto-char end))))))
577       (forward-line))))
578
579 (defun notmuch-show-markup-part (beg end depth mime-message)
580   (if (re-search-forward notmuch-show-part-begin-regexp nil t)
581       (progn
582         (if (eq mime-message nil)
583             (let ((filename (notmuch-show-get-filename)))
584               (with-temp-buffer
585                 (insert-file-contents filename nil nil nil t)
586                 (setq mime-message (mm-dissect-buffer)))))
587         (forward-line)
588         (let ((part-beg (point-marker)))
589           (re-search-forward notmuch-show-part-end-regexp)
590
591           (let ((part-end (copy-marker (match-beginning 0))))
592             (goto-char part-end)
593             (if (not (bolp))
594                 (insert "\n"))
595             (indent-rigidly part-beg part-end depth)
596             (save-excursion
597               (goto-char part-beg)
598               (forward-line -1)
599               (beginning-of-line)
600               (let ((handle-type (mm-handle-type mime-message))
601                     mime-type)
602                 (if (sequencep (car handle-type))
603                     (setq mime-type (car handle-type))
604                   (setq mime-type (car (car (cdr handle-type))))
605                   )
606                 (if (equal mime-type "text/html")
607                     (mm-display-part mime-message))))
608
609             (notmuch-show-markup-citations-region part-beg part-end depth)
610             ; Advance to the next part (if any) (so the outer loop can
611             ; determine whether we've left the current message.
612             (if (re-search-forward notmuch-show-part-begin-regexp nil t)
613                 (beginning-of-line)))))
614     (goto-char end))
615   mime-message)
616
617 (defun notmuch-show-markup-parts-region (beg end depth)
618   (save-excursion
619     (goto-char beg)
620     (let (mime-message)
621       (while (< (point) end)
622         (setq mime-message
623               (notmuch-show-markup-part
624                beg end depth mime-message))))))
625
626 (defun notmuch-show-markup-body (depth btn)
627   (re-search-forward notmuch-show-body-begin-regexp)
628   (forward-line)
629   (let ((beg (point-marker)))
630     (re-search-forward notmuch-show-body-end-regexp)
631     (let ((end (copy-marker (match-beginning 0))))
632       (notmuch-show-markup-parts-region beg end depth)
633       (let ((invis-spec (make-symbol "notmuch-show-body-read")))
634         (overlay-put (make-overlay beg end)
635                      'invisible invis-spec)
636         (button-put btn 'invisibility-spec invis-spec)
637         (if (not (notmuch-show-message-unread-p))
638             (add-to-invisibility-spec invis-spec)))
639       (set-marker beg nil)
640       (set-marker end nil)
641       )))
642 (defun notmuch-fontify-headers ()
643   (progn
644     (if (looking-at "[Tt]o:")
645         (progn
646           (overlay-put (make-overlay (point) (re-search-forward ":"))
647                        'face 'message-header-name)
648           (overlay-put (make-overlay (point) (re-search-forward ".*$"))
649                        'face 'message-header-to))
650     (if (looking-at "[B]?[Cc][Cc]:")
651         (progn
652           (overlay-put (make-overlay (point) (re-search-forward ":"))
653                        'face 'message-header-name)
654           (overlay-put (make-overlay (point) (re-search-forward ".*$"))
655                        'face 'message-header-cc))
656     (if (looking-at "[Ss]ubject:")
657         (progn
658           (overlay-put (make-overlay (point) (re-search-forward ":"))
659                        'face 'message-header-name)
660           (overlay-put (make-overlay (point) (re-search-forward ".*$"))
661                        'face 'message-header-subject))
662     (if (looking-at "[Ff]rom:")
663         (progn
664           (overlay-put (make-overlay (point) (re-search-forward ":"))
665                        'face 'message-header-name)
666           (overlay-put (make-overlay (point) (re-search-forward ".*$"))
667                        'face 'message-header-other))))))))
668
669 (defun notmuch-show-markup-header (depth)
670   (re-search-forward notmuch-show-header-begin-regexp)
671   (forward-line)
672   (let ((beg (point-marker))
673         (btn nil))
674     (end-of-line)
675     ; Inverse video for subject
676     (overlay-put (make-overlay beg (point)) 'face '(:inverse-video t))
677     (setq btn (make-button beg (point) :type 'notmuch-button-body-toggle-type))
678     (forward-line 1)
679     (end-of-line)
680     (let ((beg-hidden (point-marker)))
681       (re-search-forward notmuch-show-header-end-regexp)
682       (beginning-of-line)
683       (let ((end (point-marker)))
684         (goto-char beg)
685         (forward-line)
686         (while (looking-at "[A-Za-z][-A-Za-z0-9]*:")
687           (beginning-of-line)
688           (notmuch-fontify-headers)
689           (forward-line)
690           )
691         (indent-rigidly beg end depth)
692         (let ((invis-spec (make-symbol "notmuch-show-header")))
693           (add-to-invisibility-spec (cons invis-spec t))
694           (overlay-put (make-overlay beg-hidden end)
695                        'invisible invis-spec)
696           (goto-char beg)
697           (forward-line)
698           (make-button (line-beginning-position) (line-end-position)
699                         'invisibility-spec (cons invis-spec t)
700                         :type 'notmuch-button-headers-toggle-type))
701         (goto-char end)
702         (insert "\n")
703         (set-marker beg nil)
704         (set-marker beg-hidden nil)
705         (set-marker end nil)
706         ))
707     btn))
708
709 (defun notmuch-show-markup-message ()
710   (if (re-search-forward notmuch-show-message-begin-regexp nil t)
711       (progn
712         (re-search-forward notmuch-show-depth-regexp)
713         (let ((depth (string-to-number (buffer-substring (match-beginning 1) (match-end 1))))
714               (btn nil))
715           (setq btn (notmuch-show-markup-header depth))
716           (notmuch-show-markup-body depth btn)))
717     (goto-char (point-max))))
718
719 (defun notmuch-show-hide-markers ()
720   (save-excursion
721     (goto-char (point-min))
722     (while (not (eobp))
723       (if (re-search-forward notmuch-show-marker-regexp nil t)
724           (progn
725             (overlay-put (make-overlay (match-beginning 0) (+ (match-end 0) 1))
726                          'invisible 'notmuch-show-marker))
727         (goto-char (point-max))))))
728
729 (defun notmuch-show-markup-messages ()
730   (save-excursion
731     (goto-char (point-min))
732     (while (not (eobp))
733       (notmuch-show-markup-message)))
734   (notmuch-show-hide-markers))
735
736 ;;;###autoload
737 (defun notmuch-show-mode ()
738   "Major mode for viewing a thread with notmuch.
739
740 This buffer contains the results of the \"notmuch show\" command
741 for displaying a single thread of email from your email archives.
742
743 By default, various components of email messages, (citations,
744 signatures, already-read messages), are invisible to help you
745 focus on the most important things, (new text from unread
746 messages). See the various commands below for toggling the
747 visibility of hidden components.
748
749 The `notmuch-show-next-message' and
750 `notmuch-show-previous-message' commands, (bound to 'n' and 'p by
751 default), allow you to navigate to the next and previous
752 messages. Each time you navigate away from a message with
753 `notmuch-show-next-message' the current message will have its
754 \"unread\" tag removed.
755
756 You can add or remove tags from the current message with '+' and
757 '-'.  You can also archive all messages in the current
758 view, (remove the \"inbox\" tag from each), with
759 `notmuch-show-archive-thread' (bound to 'a' by default).
760
761 \\{notmuch-show-mode-map}"
762   (interactive)
763   (kill-all-local-variables)
764   (add-to-invisibility-spec 'notmuch-show-marker)
765   (use-local-map notmuch-show-mode-map)
766   (setq major-mode 'notmuch-show-mode
767         mode-name "notmuch-show")
768   (setq buffer-read-only t))
769
770 ;;;###autoload
771
772 (defgroup notmuch nil
773   "Notmuch mail reader for Emacs."
774   :group 'mail)
775
776 (defcustom notmuch-show-hook nil
777   "List of functions to call when notmuch displays a message."
778   :type 'hook
779   :options '(goto-address)
780   :group 'notmuch)
781
782 (defcustom notmuch-search-hook nil
783   "List of functions to call when notmuch displays the search results."
784   :type 'hook
785   :options '(hl-line-mode)
786   :group 'notmuch)
787
788 ; Make show mode a bit prettier, highlighting URLs and using word wrap
789
790 (defun notmuch-show-pretty-hook ()
791   (goto-address-mode 1)
792   (visual-line-mode))
793
794 (add-hook 'notmuch-show-hook 'notmuch-show-pretty-hook)
795 (add-hook 'notmuch-search-hook
796           (lambda()
797             (hl-line-mode 1) ))
798
799 (defun notmuch-show (thread-id &optional parent-buffer)
800   "Run \"notmuch show\" with the given thread ID and display results.
801
802 The optional PARENT-BUFFER is the notmuch-search buffer from
803 which this notmuch-show command was executed, (so that the next
804 thread from that buffer can be show when done with this one)."
805   (interactive "sNotmuch show: ")
806   (let ((buffer (get-buffer-create (concat "*notmuch-show-" thread-id "*"))))
807     (switch-to-buffer buffer)
808     (notmuch-show-mode)
809     (set (make-local-variable 'notmuch-show-parent-buffer) parent-buffer)
810     (let ((proc (get-buffer-process (current-buffer)))
811           (inhibit-read-only t))
812       (if proc
813           (error "notmuch search process already running for query `%s'" thread-id)
814         )
815       (erase-buffer)
816       (goto-char (point-min))
817       (save-excursion
818         (call-process notmuch-command nil t nil "show" thread-id)
819         (notmuch-show-markup-messages)
820         )
821       (run-hooks 'notmuch-show-hook)
822       ; Move straight to the first unread message
823       (if (not (notmuch-show-message-unread-p))
824           (progn
825             (notmuch-show-next-unread-message)
826             ; But if there are no unread messages, go back to the
827             ; beginning of the buffer, and open up the bodies of all
828             ; read message.
829             (if (not (notmuch-show-message-unread-p))
830                 (progn
831                   (goto-char (point-min))
832                   (let ((btn (forward-button 1)))
833                     (while btn
834                       (if (button-has-type-p btn 'notmuch-button-body-toggle-type)
835                           (push-button))
836                       (condition-case err
837                           (setq btn (forward-button 1))
838                         (error (setq btn nil)))
839                     ))
840                   (beginning-of-buffer)
841                   ))))
842       )))
843
844 (defvar notmuch-search-authors-width 40
845   "Number of columns to use to display authors in a notmuch-search buffer.")
846
847 (defvar notmuch-search-mode-map
848   (let ((map (make-sparse-keymap)))
849     (define-key map "a" 'notmuch-search-archive-thread)
850     (define-key map "b" 'notmuch-search-scroll-down)
851     (define-key map "f" 'notmuch-search-filter)
852     (define-key map "m" 'message-mail)
853     (define-key map "n" 'next-line)
854     (define-key map "o" 'notmuch-search-toggle-order)
855     (define-key map "p" 'previous-line)
856     (define-key map "q" 'kill-this-buffer)
857     (define-key map "r" 'notmuch-search-reply-to-thread)
858     (define-key map "s" 'notmuch-search)
859     (define-key map "t" 'notmuch-search-filter-by-tag)
860     (define-key map "x" 'kill-this-buffer)
861     (define-key map (kbd "RET") 'notmuch-search-show-thread)
862     (define-key map [mouse-1] 'notmuch-search-show-thread)
863     (define-key map "+" 'notmuch-search-add-tag)
864     (define-key map "-" 'notmuch-search-remove-tag)
865     (define-key map "*" 'notmuch-search-operate-all)
866     (define-key map "<" 'beginning-of-buffer)
867     (define-key map ">" 'notmuch-search-goto-last-thread)
868     (define-key map "=" 'notmuch-search-refresh-view)
869     (define-key map "\M->" 'notmuch-search-goto-last-thread)
870     (define-key map " " 'notmuch-search-scroll-up)
871     (define-key map (kbd "<DEL>") 'notmuch-search-scroll-down)
872     (define-key map "?" 'describe-mode)
873     map)
874   "Keymap for \"notmuch search\" buffers.")
875 (fset 'notmuch-search-mode-map notmuch-search-mode-map)
876
877 (defvar notmuch-search-query-string)
878 (defvar notmuch-search-oldest-first t
879   "Show the oldest mail first in the search-mode")
880
881
882 (defun notmuch-search-scroll-up ()
883   "Scroll up, moving point to last message in thread if at end."
884   (interactive)
885   (condition-case nil
886       (scroll-up nil)
887     ((end-of-buffer) (notmuch-search-goto-last-thread))))
888
889 (defun notmuch-search-scroll-down ()
890   "Scroll down, moving point to first message in thread if at beginning."
891   (interactive)
892   ; I don't know why scroll-down doesn't signal beginning-of-buffer
893   ; the way that scroll-up signals end-of-buffer, but c'est la vie.
894   ;
895   ; So instead of trapping a signal we instead check whether the
896   ; window begins on the first line of the buffer and if so, move
897   ; directly to that position. (We have to count lines since the
898   ; window-start position is not the same as point-min due to the
899   ; invisible thread-ID characters on the first line.
900   (if (equal (count-lines (point-min) (window-start)) 1)
901       (goto-char (window-start))
902     (scroll-down nil)))
903
904 (defun notmuch-search-goto-last-thread ()
905   "Move point to the last thread in the buffer."
906   (interactive)
907   (goto-char (point-max))
908   (forward-line -1))
909
910 ;;;###autoload
911 (defun notmuch-search-mode ()
912   "Major mode for searching mail with notmuch.
913
914 This buffer contains the results of a \"notmuch search\" of your
915 email archives. Each line in the buffer represents a single
916 thread giving a relative date for the thread and a subject.
917
918 Pressing RET on any line displays that thread. The '+' and '-'
919 keys can be used to add or remove tags from a thread. The 'a' key
920 is a convenience key for archiving a thread (removing the
921 \"inbox\" tag).
922
923 Other useful commands are `notmuch-search-filter' for filtering
924 the current search based on an additional query string,
925 `notmuch-search-filter-by-tag' for filtering to include only
926 messages with a given tag, and `notmuch-search' to execute a new,
927 global search.
928
929 \\{notmuch-search-mode-map}"
930   (interactive)
931   (kill-all-local-variables)
932   (make-local-variable 'notmuch-search-query-string)
933   (make-local-variable 'notmuch-search-oldest-first)
934   (set (make-local-variable 'scroll-preserve-screen-position) t)
935   (add-to-invisibility-spec 'notmuch-search)
936   (use-local-map notmuch-search-mode-map)
937   (setq truncate-lines t)
938   (setq major-mode 'notmuch-search-mode
939         mode-name "notmuch-search")
940   (setq buffer-read-only t))
941
942 (defun notmuch-search-find-thread-id ()
943   "Return the thread for the current thread"
944   (get-text-property (point) 'notmuch-search-thread-id))
945
946 (defun notmuch-search-show-thread ()
947   (interactive)
948   (let ((thread-id (notmuch-search-find-thread-id)))
949     (if (> (length thread-id) 0)
950         (notmuch-show thread-id (current-buffer))
951       (error "End of search results"))))
952
953 (defun notmuch-search-reply-to-thread ()
954   "Begin composing a reply to the entire current thread in a new buffer."
955   (interactive)
956   (let ((message-id (notmuch-search-find-thread-id)))
957     (notmuch-reply message-id)))
958
959 (defun notmuch-call-notmuch-process (&rest args)
960   "Synchronously invoke \"notmuch\" with the given list of arguments.
961
962 Output from the process will be presented to the user as an error
963 and will also appear in a buffer named \"*Notmuch errors*\"."
964   (let ((error-buffer (get-buffer-create "*Notmuch errors*")))
965     (with-current-buffer error-buffer
966         (erase-buffer))
967     (if (eq (apply 'call-process notmuch-command nil error-buffer nil args) 0)
968         (point)
969       (progn
970         (with-current-buffer error-buffer
971           (let ((beg (point-min))
972                 (end (- (point-max) 1)))
973             (error (buffer-substring beg end))
974             ))))))
975
976 (defun notmuch-search-set-tags (tags)
977   (save-excursion
978     (end-of-line)
979     (re-search-backward "(")
980     (forward-char)
981     (let ((beg (point))
982           (inhibit-read-only t))
983       (re-search-forward ")")
984       (backward-char)
985       (let ((end (point)))
986         (delete-region beg end)
987         (insert (mapconcat  'identity tags " "))))))
988
989 (defun notmuch-search-get-tags ()
990   (save-excursion
991     (end-of-line)
992     (re-search-backward "(")
993     (let ((beg (+ (point) 1)))
994       (re-search-forward ")")
995       (let ((end (- (point) 1)))
996         (split-string (buffer-substring beg end))))))
997
998 (defun notmuch-search-add-tag (tag)
999   "Add a tag to messages in the current thread matching the
1000 active query."
1001   (interactive
1002    (list (notmuch-select-tag-with-completion "Tag to add: ")))
1003   (notmuch-call-notmuch-process "tag" (concat "+" tag) (notmuch-search-find-thread-id) " and " notmuch-search-query-string)
1004   (notmuch-search-set-tags (delete-dups (sort (cons tag (notmuch-search-get-tags)) 'string<))))
1005
1006 (defun notmuch-search-remove-tag (tag)
1007   "Remove a tag from messages in the current thread matching the
1008 active query."
1009   (interactive
1010    (list (notmuch-select-tag-with-completion "Tag to remove: " (notmuch-search-find-thread-id))))
1011   (notmuch-call-notmuch-process "tag" (concat "-" tag) (notmuch-search-find-thread-id) " and " notmuch-search-query-string)
1012   (notmuch-search-set-tags (delete tag (notmuch-search-get-tags))))
1013
1014 (defun notmuch-search-archive-thread ()
1015   "Archive the current thread (remove its \"inbox\" tag).
1016
1017 This function advances point to the next line when finished."
1018   (interactive)
1019   (notmuch-search-remove-tag "inbox")
1020   (forward-line))
1021
1022 (defun notmuch-search-process-sentinel (proc msg)
1023   "Add a message to let user know when \"notmuch search\" exits"
1024   (let ((buffer (process-buffer proc))
1025         (status (process-status proc))
1026         (exit-status (process-exit-status proc)))
1027     (if (memq status '(exit signal))
1028         (if (buffer-live-p buffer)
1029             (with-current-buffer buffer
1030               (save-excursion
1031                 (let ((inhibit-read-only t))
1032                   (goto-char (point-max))
1033                   (if (eq status 'signal)
1034                       (insert "Incomplete search results (search process was killed).\n"))
1035                   (if (eq status 'exit)
1036                       (progn
1037                         (insert "End of search results.")
1038                         (if (not (= exit-status 0))
1039                             (insert (format " (process returned %d)" exit-status)))
1040                         (insert "\n"))))))))))
1041
1042 (defun notmuch-search-process-filter (proc string)
1043   "Process and filter the output of \"notmuch search\""
1044   (let ((buffer (process-buffer proc)))
1045     (if (buffer-live-p buffer)
1046         (with-current-buffer buffer
1047           (save-excursion
1048             (let ((line 0)
1049                   (more t)
1050                   (inhibit-read-only t))
1051               (while more
1052                 (if (string-match "^\\(thread:[0-9A-Fa-f]*\\) \\(.*\\) \\(\\[[0-9/]*\\]\\) \\([^:]*\\); \\(.*\\) (\\([^()]*\\))$" string line)
1053                     (let* ((thread-id (match-string 1 string))
1054                            (date (match-string 2 string))
1055                            (count (match-string 3 string))
1056                            (authors (match-string 4 string))
1057                            (authors-length (length authors))
1058                            (subject (match-string 5 string))
1059                            (tags (match-string 6 string)))
1060                       (if (> authors-length 40)
1061                           (set 'authors (concat (substring authors 0 (- 40 3)) "...")))
1062                       (goto-char (point-max))
1063                       (let ((beg (point-marker)))
1064                         (insert (format "%s %-7s %-40s %s (%s)\n" date count authors subject tags))
1065                         (put-text-property beg (point-marker) 'notmuch-search-thread-id thread-id))
1066                       (set 'line (match-end 0)))
1067                   (set 'more nil))))))
1068       (delete-process proc))))
1069
1070 (defun notmuch-search-operate-all (action)
1071   "Operate on all messages matching the current query.  Any
1072 number of whitespace separated actions can be given.  Each action
1073 must have one of the two forms
1074
1075   +tagname              Add the tag `tagname'
1076   -tagname              Remove the tag `tagname'
1077
1078 Each character of the tag name may consist of alphanumeric
1079 characters as well as `_.+-'.
1080 "
1081   (interactive "sOperation (+add -drop): notmuch tag ")
1082   (let ((action-split (split-string action " +")))
1083     ;; Perform some validation
1084     (let ((words action-split))
1085       (when (null words) (error "No operation given"))
1086       (while words
1087         (unless (string-match-p "^[\+\-][_\+\-\\w]+$" (car words))
1088           (error "Action must be of the form `+thistag -that_tag'"))
1089         (setq words (cdr words))))
1090     (apply 'notmuch-call-notmuch-process "tag"
1091            (append action-split (list notmuch-search-query-string) nil))))
1092
1093 (defun notmuch-search (query &optional oldest-first)
1094   "Run \"notmuch search\" with the given query string and display results."
1095   (interactive "sNotmuch search: ")
1096   (let ((buffer (get-buffer-create (concat "*notmuch-search-" query "*"))))
1097     (switch-to-buffer buffer)
1098     (notmuch-search-mode)
1099     (set 'notmuch-search-query-string query)
1100     (set 'notmuch-search-oldest-first oldest-first)
1101     (let ((proc (get-buffer-process (current-buffer)))
1102           (inhibit-read-only t))
1103       (if proc
1104           (error "notmuch search process already running for query `%s'" query)
1105         )
1106       (erase-buffer)
1107       (goto-char (point-min))
1108       (save-excursion
1109         (let ((proc (start-process-shell-command
1110                      "notmuch-search" buffer notmuch-command "search"
1111                      (if oldest-first "--sort=oldest-first" "--sort=newest-first")
1112                      (shell-quote-argument query))))
1113           (set-process-sentinel proc 'notmuch-search-process-sentinel)
1114           (set-process-filter proc 'notmuch-search-process-filter))))
1115     (run-hooks 'notmuch-search-hook)))
1116
1117 (defun notmuch-search-refresh-view ()
1118   "Refresh the current view.
1119
1120 Kills the current buffer and runs a new search with the same
1121 query string as the current search. If the current thread is in
1122 the new search results, then point will be placed on the same
1123 thread. Otherwise, point will be moved to attempt to be in the
1124 same relative position within the new buffer."
1125   (interactive)
1126   (let ((here (point))
1127         (oldest-first notmuch-search-oldest-first)
1128         (thread (notmuch-search-find-thread-id))
1129         (query notmuch-search-query-string))
1130     (kill-this-buffer)
1131     (notmuch-search query oldest-first)
1132     (goto-char (point-min))
1133     (if (re-search-forward (concat "^" thread) nil t)
1134         (beginning-of-line)
1135       (goto-char here))))
1136
1137 (defun notmuch-search-toggle-order ()
1138   "Toggle the current search order.
1139
1140 By default, the \"inbox\" view created by `notmuch' is displayed
1141 in chronological order (oldest thread at the beginning of the
1142 buffer), while any global searches created by `notmuch-search'
1143 are displayed in reverse-chronological order (newest thread at
1144 the beginning of the buffer).
1145
1146 This command toggles the sort order for the current search.
1147
1148 Note that any filtered searches created by
1149 `notmuch-search-filter' retain the search order of the parent
1150 search."
1151   (interactive)
1152   (set 'notmuch-search-oldest-first (not notmuch-search-oldest-first))
1153   (notmuch-search-refresh-view))
1154
1155 (defun notmuch-search-filter (query)
1156   "Filter the current search results based on an additional query string.
1157
1158 Runs a new search matching only messages that match both the
1159 current search results AND the additional query string provided."
1160   (interactive "sFilter search: ")
1161   (notmuch-search (concat notmuch-search-query-string " and " query) notmuch-search-oldest-first))
1162
1163 (defun notmuch-search-filter-by-tag (tag)
1164   "Filter the current search results based on a single tag.
1165
1166 Runs a new search matching only messages that match both the
1167 current search results AND that are tagged with the given tag."
1168   (interactive
1169    (list (notmuch-select-tag-with-completion "Filter by tag: ")))
1170   (notmuch-search (concat notmuch-search-query-string " and tag:" tag) notmuch-search-oldest-first))
1171
1172 (defun notmuch ()
1173   "Run notmuch to display all mail with tag of 'inbox'"
1174   (interactive)
1175   (notmuch-search "tag:inbox" notmuch-search-oldest-first))
1176
1177 (setq mail-user-agent 'message-user-agent)
1178
1179 (defvar notmuch-folder-mode-map
1180   (let ((map (make-sparse-keymap)))
1181     (define-key map "n" 'next-line)
1182     (define-key map "p" 'previous-line)
1183     (define-key map "x" 'kill-this-buffer)
1184     (define-key map "q" 'kill-this-buffer)
1185     (define-key map "s" 'notmuch-search)
1186     (define-key map (kbd "RET") 'notmuch-folder-show-search)
1187     (define-key map "<" 'beginning-of-buffer)
1188     (define-key map "=" 'notmuch-folder)
1189     (define-key map "?" 'describe-mode)
1190     (define-key map [mouse-1] 'notmuch-folder-show-search)
1191     map)
1192   "Keymap for \"notmuch folder\" buffers.")
1193
1194 (fset 'notmuch-folder-mode-map notmuch-folder-mode-map)
1195
1196 (defcustom notmuch-folders (quote (("inbox" . "tag:inbox") ("unread" . "tag:unread")))
1197   "List of searches for the notmuch folder view"
1198   :type '(alist :key-type (string) :value-type (string))
1199   :group 'notmuch)
1200
1201 (defun notmuch-folder-mode ()
1202   "Major mode for showing notmuch 'folders'.
1203
1204 This buffer contains a list of messages counts returned by a
1205 customizable set of searches of your email archives. Each line
1206 in the buffer shows the search terms and the resulting message count.
1207
1208 Pressing RET on any line opens a search window containing the
1209 results for the search terms in that line.
1210
1211 \\{notmuch-folder-mode-map}"
1212   (interactive)
1213   (kill-all-local-variables)
1214   (use-local-map 'notmuch-folder-mode-map)
1215   (setq truncate-lines t)
1216   (hl-line-mode 1)
1217   (setq major-mode 'notmuch-folder-mode
1218         mode-name "notmuch-folder")
1219   (setq buffer-read-only t))
1220
1221 (defun notmuch-folder-add (folders)
1222   (if folders
1223       (let ((name (car (car folders)))
1224             (inhibit-read-only t)
1225             (search (cdr (car folders))))
1226         (insert name)
1227         (indent-to 16 1)
1228         (call-process notmuch-command nil t nil "count" search)
1229         (notmuch-folder-add (cdr folders)))))
1230
1231 (defun notmuch-folder-find-name ()
1232   (save-excursion
1233     (beginning-of-line)
1234     (let ((beg (point)))
1235       (forward-word)
1236       (filter-buffer-substring beg (point)))))
1237
1238 (defun notmuch-folder-show-search (&optional folder)
1239   "Show a search window for the search related to the specified folder."
1240   (interactive)
1241   (if (null folder)
1242       (setq folder (notmuch-folder-find-name)))
1243   (let ((search (assoc folder notmuch-folders)))
1244     (if search
1245         (notmuch-search (cdr search) notmuch-search-oldest-first))))
1246
1247 (defun notmuch-folder ()
1248   "Show the notmuch folder view and update the displayed counts."
1249   (interactive)
1250   (let ((buffer (get-buffer-create "*notmuch-folders*")))
1251     (switch-to-buffer buffer)
1252     (let ((inhibit-read-only t)
1253           (n (line-number-at-pos)))
1254       (erase-buffer)
1255       (notmuch-folder-mode)
1256       (notmuch-folder-add notmuch-folders)
1257       (goto-char (point-min))
1258       (goto-line n))))
1259
1260 (provide 'notmuch)