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