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