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