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