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