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