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