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