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