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