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