]> git.notmuchmail.org Git - notmuch/blob - notmuch.el
Simplify "unread" tag handling in emacs UI.
[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 ()
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   (interactive)
514   (notmuch-show-move-to-current-message-summary-line)
515   (if (re-search-forward notmuch-show-message-begin-regexp nil t)
516       (progn
517         (notmuch-show-move-to-current-message-summary-line)
518         (recenter 0)
519         t)
520     (goto-char (- (point-max) 1))
521     (while (point-invisible-p)
522       (backward-char))
523     (recenter 0)
524     nil)
525   (notmuch-show-mark-read))
526
527 (defun notmuch-show-find-next-message ()
528   "Returns the position of the next message in the buffer.
529
530 Or the position of the last visible character of the current
531 message if already within the last message in the buffer."
532   ; save-excursion doesn't save our window position
533   ; save-window-excursion doesn't save point
534   ; Looks like we have to use both.
535   (save-excursion
536     (save-window-excursion
537       (notmuch-show-next-message)
538       (point))))
539
540 (defun notmuch-show-next-unread-message ()
541   "Advance to the beginning of the next unread message in the buffer.
542
543 Moves to the last visible character of the current message if
544 there are no more unread messages past the current point."
545   (notmuch-show-next-message)
546   (while (and (not (notmuch-show-last-message-p))
547               (not (notmuch-show-message-unread-p)))
548     (notmuch-show-next-message))
549   (if (not (notmuch-show-message-unread-p))
550       (notmuch-show-next-message)))
551
552 (defun notmuch-show-next-open-message ()
553   "Advance to the next open message (that is, body is not invisible)."
554   (while (and (notmuch-show-next-message)
555               (not (notmuch-show-message-open-p)))))
556
557 (defun notmuch-show-previous-message ()
558   "Backup to the beginning of the previous message in the buffer.
559
560 If within a message rather than at the beginning of it, then
561 simply move to the beginning of the current message."
562   (interactive)
563   (let ((start (point)))
564     (notmuch-show-move-to-current-message-summary-line)
565     (if (not (< (point) start))
566         ; Go backward twice to skip the current message's marker
567         (progn
568           (re-search-backward notmuch-show-message-begin-regexp nil t)
569           (re-search-backward notmuch-show-message-begin-regexp nil t)
570           (notmuch-show-move-to-current-message-summary-line)
571           ))
572     (recenter 0)))
573
574 (defun notmuch-show-find-previous-message ()
575   "Returns the position of the previous message in the buffer.
576
577 Or the position of the beginning of the current message if point
578 is originally within the message rather than at the beginning of
579 it."
580   ; save-excursion doesn't save our window position
581   ; save-window-excursion doesn't save point
582   ; Looks like we have to use both.
583   (save-excursion
584     (save-window-excursion
585       (notmuch-show-previous-message)
586       (point))))
587
588 (defun notmuch-show-rewind ()
589   "Backup through the thread, (reverse scrolling compared to \\[notmuch-show-advance-and-archive]).
590
591 Specifically, if the beginning of the previous email is fewer
592 than `window-height' lines from the current point, move to it
593 just like `notmuch-show-previous-message'.
594
595 Otherwise, just scroll down a screenful of the current message.
596
597 This command does not modify any message tags, (it does not undo
598 any effects from previous calls to
599 `notmuch-show-advance-and-archive'."
600   (interactive)
601   (let ((previous (notmuch-show-find-previous-message)))
602     (if (> (count-lines previous (point)) (- (window-height) next-screen-context-lines))
603         (progn
604           (condition-case nil
605               (scroll-down nil)
606             ((beginning-of-buffer) nil))
607           (goto-char (window-start)))
608       (notmuch-show-previous-message))))
609
610 (defun notmuch-show-advance-and-archive ()
611   "Advance through thread and archive.
612
613 This command is intended to be one of the simplest ways to
614 process a thread of email. It does the following:
615
616 If the current message in the thread is not yet fully visible,
617 scroll by a near screenful to read more of the message.
618
619 Otherwise, (the end of the current message is already within the
620 current window), advance to the next open message.
621
622 Finally, if there is no further message to advance to, and this
623 last message is already read, then archive the entire current
624 thread, (remove the \"inbox\" tag from each message). Also kill
625 this buffer, and display the next thread from the search from
626 which this thread was originally shown."
627   (interactive)
628   (let ((next (notmuch-show-find-next-message))
629         (unread (notmuch-show-message-unread-p)))
630     (if (> next (window-end))
631         (scroll-up nil)
632       (let ((last (notmuch-show-last-message-p)))
633         (notmuch-show-next-open-message)
634         (if last
635             (notmuch-show-archive-thread))))))
636
637 (defun notmuch-show-next-button ()
638   "Advance point to the next button in the buffer."
639   (interactive)
640   (forward-button 1))
641
642 (defun notmuch-show-previous-button ()
643   "Move point back to the previous button in the buffer."
644   (interactive)
645   (backward-button 1))
646
647 (defun notmuch-toggle-invisible-action (cite-button)
648   (let ((invis-spec (button-get cite-button 'invisibility-spec)))
649         (if (invisible-p invis-spec)
650             (remove-from-invisibility-spec invis-spec)
651           (add-to-invisibility-spec invis-spec)
652           ))
653   (force-window-update)
654   (redisplay t))
655
656 (defun notmuch-show-toggle-current-body ()
657   "Toggle the display of the current message body."
658   (interactive)
659   (save-excursion
660     (notmuch-show-move-to-current-message-summary-line)
661     (unless (button-at (point))
662       (notmuch-show-next-button))
663     (push-button))
664   )
665
666 (defun notmuch-show-toggle-current-header ()
667   "Toggle the display of the current message header."
668   (interactive)
669   (save-excursion
670     (notmuch-show-move-to-current-message-summary-line)
671     (forward-line)
672     (unless (button-at (point))
673       (notmuch-show-next-button))
674     (push-button))
675   )
676
677 (define-button-type 'notmuch-button-invisibility-toggle-type
678   'action 'notmuch-toggle-invisible-action
679   'follow-link t
680   'face 'font-lock-comment-face)
681 (define-button-type 'notmuch-button-citation-toggle-type 'help-echo "mouse-1, RET: Show citation"
682   :supertype 'notmuch-button-invisibility-toggle-type)
683 (define-button-type 'notmuch-button-signature-toggle-type 'help-echo "mouse-1, RET: Show signature"
684   :supertype 'notmuch-button-invisibility-toggle-type)
685 (define-button-type 'notmuch-button-headers-toggle-type 'help-echo "mouse-1, RET: Show headers"
686   :supertype 'notmuch-button-invisibility-toggle-type)
687 (define-button-type 'notmuch-button-body-toggle-type
688   'help-echo "mouse-1, RET: Show message"
689   'face 'notmuch-message-summary-face
690   :supertype 'notmuch-button-invisibility-toggle-type)
691
692 (defun notmuch-show-citation-regexp (depth)
693   "Build a regexp for matching citations at a given DEPTH (indent)"
694   (let ((line-regexp (format "[[:space:]]\\{%d\\}>.*\n" depth)))
695     (concat "\\(?:^" line-regexp
696             "\\(?:[[:space:]]*\n" line-regexp
697             "\\)?\\)+")))
698
699 (defun notmuch-show-region-to-button (beg end type prefix button-text)
700   "Auxilary function to do the actual making of overlays and buttons
701
702 BEG and END are buffer locations. TYPE should a string, either
703 \"citation\" or \"signature\". PREFIX is some arbitrary text to
704 insert before the button, probably for indentation.  BUTTON-TEXT
705 is what to put on the button."
706
707 ;; This uses some slightly tricky conversions between strings and
708 ;; symbols because of the way the button code works. Note that
709 ;; replacing intern-soft with make-symbol will cause this to fail,
710 ;; since the newly created symbol has no plist.
711
712   (let ((overlay (make-overlay beg end))
713         (invis-spec (make-symbol (concat "notmuch-" type "-region")))
714         (button-type (intern-soft (concat "notmuch-button-"
715                                           type "-toggle-type"))))
716     (add-to-invisibility-spec invis-spec)
717     (overlay-put overlay 'invisible invis-spec)
718     (goto-char (1+ end))
719     (save-excursion
720       (goto-char (1- beg))
721       (insert prefix)
722       (insert-button button-text
723                      'invisibility-spec invis-spec
724                      :type button-type)
725       )))
726
727
728 (defun notmuch-show-markup-citations-region (beg end depth)
729   "Markup citations, and up to one signature in the given region"
730   ;; it would be nice if the untabify was not required, but
731   ;; that would require notmuch to indent with spaces.
732   (untabify beg end)
733   (let ((citation-regexp (notmuch-show-citation-regexp depth))
734         (signature-regexp (concat (format "^[[:space:]]\\{%d\\}" depth)
735                                   notmuch-show-signature-regexp))
736         (indent (concat "\n" (make-string depth ? ))))
737     (goto-char beg)
738     (beginning-of-line)
739     (while (and (< (point) end)
740                 (re-search-forward citation-regexp end t))
741       (let* ((cite-start (match-beginning 0))
742              (cite-end  (match-end 0))
743              (cite-lines (count-lines cite-start cite-end)))
744         (when (> cite-lines (1+ notmuch-show-citation-lines-prefix))
745           (goto-char cite-start)
746           (forward-line notmuch-show-citation-lines-prefix)
747           (notmuch-show-region-to-button
748            (point) cite-end
749            "citation"
750            indent
751            (format notmuch-show-citation-button-format
752                    (- cite-lines notmuch-show-citation-lines-prefix))
753            ))))
754     (if (and (< (point) end)
755              (re-search-forward signature-regexp end t))
756         (let* ((sig-start (match-beginning 0))
757                (sig-end (match-end 0))
758                (sig-lines (1- (count-lines sig-start end))))
759           (if (<= sig-lines notmuch-show-signature-lines-max)
760               (notmuch-show-region-to-button
761                sig-start
762                end
763                "signature"
764                indent
765                (format notmuch-show-signature-button-format sig-lines)
766                ))))))
767
768 (defun notmuch-show-markup-part (beg end depth)
769   (if (re-search-forward notmuch-show-part-begin-regexp nil t)
770       (progn
771         (let (mime-message mime-type)
772           (save-excursion
773             (re-search-forward notmuch-show-contentype-regexp end t)
774             (setq mime-type (car (split-string (buffer-substring
775                                                 (match-beginning 1) (match-end 1))))))
776
777           (if (equal mime-type "text/html")
778               (let ((filename (notmuch-show-get-filename)))
779                 (with-temp-buffer
780                   (insert-file-contents filename nil nil nil t)
781                   (setq mime-message (mm-dissect-buffer)))))
782           (forward-line)
783           (let ((beg (point-marker)))
784             (re-search-forward notmuch-show-part-end-regexp)
785             (let ((end (copy-marker (match-beginning 0))))
786               (goto-char end)
787               (if (not (bolp))
788                   (insert "\n"))
789               (indent-rigidly beg end depth)
790               (if (not (eq mime-message nil))
791                   (save-excursion
792                     (goto-char beg)
793                     (forward-line -1)
794                     (let ((handle-type (mm-handle-type mime-message))
795                           mime-type)
796                       (if (sequencep (car handle-type))
797                           (setq mime-type (car handle-type))
798                         (setq mime-type (car (car (cdr handle-type))))
799                         )
800                       (if (equal mime-type "text/html")
801                           (mm-display-part mime-message))))
802                 )
803               (notmuch-show-markup-citations-region beg end depth)
804               ; Advance to the next part (if any) (so the outer loop can
805               ; determine whether we've left the current message.
806               (if (re-search-forward notmuch-show-part-begin-regexp nil t)
807                   (beginning-of-line)))))
808         (goto-char end))
809     (goto-char end)))
810
811 (defun notmuch-show-markup-parts-region (beg end depth)
812   (save-excursion
813     (goto-char beg)
814     (while (< (point) end)
815       (notmuch-show-markup-part beg end depth))))
816
817 (defun notmuch-show-markup-body (depth match btn)
818   "Markup a message body, (indenting, buttonizing citations,
819 etc.), and conditionally hiding the body itself if the message
820 has been read and does not match the current search.
821
822 DEPTH specifies the depth at which this message appears in the
823 tree of the current thread, (the top-level messages have depth 0
824 and each reply increases depth by 1). MATCH indicates whether
825 this message is regarded as matching the current search. BTN is
826 the button which is used to toggle the visibility of this
827 message.
828
829 When this function is called, point must be within the message, but
830 before the delimiter marking the beginning of the body."
831   (re-search-forward notmuch-show-body-begin-regexp)
832   (forward-line)
833   (let ((beg (point-marker)))
834     (re-search-forward notmuch-show-body-end-regexp)
835     (let ((end (copy-marker (match-beginning 0))))
836       (notmuch-show-markup-parts-region beg end depth)
837       (let ((invis-spec (make-symbol "notmuch-show-body-read")))
838         (overlay-put (make-overlay beg end)
839                      'invisible invis-spec)
840         (button-put btn 'invisibility-spec invis-spec)
841         (if (not (or (notmuch-show-message-unread-p) match))
842             (add-to-invisibility-spec invis-spec)))
843       (set-marker beg nil)
844       (set-marker end nil)
845       )))
846
847 (defun notmuch-fontify-headers ()
848   (while (looking-at "[[:space:]]")
849     (forward-char))
850   (if (looking-at "[Tt]o:")
851       (progn
852         (overlay-put (make-overlay (point) (re-search-forward ":"))
853                      'face 'message-header-name)
854         (overlay-put (make-overlay (point) (re-search-forward ".*$"))
855                      'face 'message-header-to))
856     (if (looking-at "[B]?[Cc][Cc]:")
857         (progn
858           (overlay-put (make-overlay (point) (re-search-forward ":"))
859                        'face 'message-header-name)
860           (overlay-put (make-overlay (point) (re-search-forward ".*$"))
861                        'face 'message-header-cc))
862       (if (looking-at "[Ss]ubject:")
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-subject))
868         (if (looking-at "[Ff]rom:")
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-other)))))))
874
875 (defun notmuch-show-markup-header (message-begin depth)
876   "Buttonize and decorate faces in a message header.
877
878 MESSAGE-BEGIN is the position of the absolute first character in
879 the message (including all delimiters that will end up being
880 invisible etc.). This is to allow a button to reliably extend to
881 the beginning of the message even if point is positioned at an
882 invisible character (such as the beginning of the buffer).
883
884 DEPTH specifies the depth at which this message appears in the
885 tree of the current thread, (the top-level messages have depth 0
886 and each reply increases depth by 1)."
887   (re-search-forward notmuch-show-header-begin-regexp)
888   (forward-line)
889   (let ((beg (point-marker))
890         (summary-end (copy-marker (line-beginning-position 2)))
891         (subject-end (copy-marker (line-end-position 2)))
892         (invis-spec (make-symbol "notmuch-show-header"))
893         (btn nil))
894     (re-search-forward notmuch-show-header-end-regexp)
895     (beginning-of-line)
896     (let ((end (point-marker)))
897       (indent-rigidly beg end depth)
898       (goto-char beg)
899       (setq btn (make-button message-begin summary-end :type 'notmuch-button-body-toggle-type))
900       (forward-line)
901       (add-to-invisibility-spec invis-spec)
902       (overlay-put (make-overlay subject-end end)
903                    'invisible invis-spec)
904       (make-button (line-beginning-position) subject-end
905                    'invisibility-spec invis-spec
906                    :type 'notmuch-button-headers-toggle-type)
907       (while (looking-at "[[:space:]]*[A-Za-z][-A-Za-z0-9]*:")
908         (beginning-of-line)
909         (notmuch-fontify-headers)
910         (forward-line)
911         )
912       (goto-char end)
913       (insert "\n")
914       (set-marker beg nil)
915       (set-marker summary-end nil)
916       (set-marker subject-end nil)
917       (set-marker end nil)
918       )
919   btn))
920
921 (defun notmuch-show-markup-message ()
922   (if (re-search-forward notmuch-show-message-begin-regexp nil t)
923       (let ((message-begin (match-beginning 0)))
924         (re-search-forward notmuch-show-depth-match-regexp)
925         (let ((depth (string-to-number (buffer-substring (match-beginning 1) (match-end 1))))
926               (match (string= "1" (buffer-substring (match-beginning 2) (match-end 2))))
927               (btn nil))
928           (setq btn (notmuch-show-markup-header message-begin depth))
929           (notmuch-show-markup-body depth match btn)))
930     (goto-char (point-max))))
931
932 (defun notmuch-show-hide-markers ()
933   (save-excursion
934     (goto-char (point-min))
935     (while (not (eobp))
936       (if (re-search-forward notmuch-show-marker-regexp nil t)
937           (progn
938             (overlay-put (make-overlay (match-beginning 0) (+ (match-end 0) 1))
939                          'invisible 'notmuch-show-marker))
940         (goto-char (point-max))))))
941
942 (defun notmuch-show-markup-messages ()
943   (save-excursion
944     (goto-char (point-min))
945     (while (not (eobp))
946       (notmuch-show-markup-message)))
947   (notmuch-show-hide-markers))
948
949 (defun notmuch-documentation-first-line (symbol)
950   "Return the first line of the documentation string for SYMBOL."
951   (let ((doc (documentation symbol)))
952     (if doc
953         (with-temp-buffer
954           (insert (documentation symbol t))
955           (goto-char (point-min))
956           (let ((beg (point)))
957             (end-of-line)
958             (buffer-substring beg (point))))
959       "")))
960
961 (defun notmuch-prefix-key-description (key)
962   "Given a prefix key code, return a human-readable string representation.
963
964 This is basically just `format-kbd-macro' but we also convert ESC to M-."
965   (let ((desc (format-kbd-macro (vector key))))
966     (if (string= desc "ESC")
967         "M-"
968       (concat desc " "))))
969
970 ; I would think that emacs would have code handy for walking a keymap
971 ; and generating strings for each key, and I would prefer to just call
972 ; that. But I couldn't find any (could be all implemented in C I
973 ; suppose), so I wrote my own here.
974 (defun notmuch-substitute-one-command-key-with-prefix (prefix binding)
975   "For a key binding, return a string showing a human-readable
976 representation of the prefixed key as well as the first line of
977 documentation from the bound function.
978
979 For a mouse binding, return nil."
980   (let ((key (car binding))
981         (action (cdr binding)))
982     (if (mouse-event-p key)
983         nil
984       (if (keymapp action)
985           (let ((substitute (apply-partially 'notmuch-substitute-one-command-key-with-prefix (notmuch-prefix-key-description key)))
986                 (as-list))
987             (map-keymap (lambda (a b)
988                           (push (cons a b) as-list))
989                         action)
990             (mapconcat substitute as-list "\n"))
991         (concat prefix (format-kbd-macro (vector key))
992                 "\t"
993                 (notmuch-documentation-first-line action))))))
994
995 (defalias 'notmuch-substitute-one-command-key
996   (apply-partially 'notmuch-substitute-one-command-key-with-prefix nil))
997
998 (defun notmuch-substitute-command-keys (doc)
999   "Like `substitute-command-keys' but with documentation, not function names."
1000   (let ((beg 0))
1001     (while (string-match "\\\\{\\([^}[:space:]]*\\)}" doc beg)
1002       (let ((map (substring doc (match-beginning 1) (match-end 1))))
1003         (setq doc (replace-match (mapconcat 'notmuch-substitute-one-command-key
1004                                             (cdr (symbol-value (intern map))) "\n") 1 1 doc)))
1005       (setq beg (match-end 0)))
1006     doc))
1007
1008 (defun notmuch-help ()
1009   "Display help for the current notmuch mode."
1010   (interactive)
1011   (let* ((mode major-mode)
1012          (doc (substitute-command-keys (notmuch-substitute-command-keys (documentation mode t)))))
1013     (with-current-buffer (generate-new-buffer "*notmuch-help*")
1014       (insert doc)
1015       (goto-char (point-min))
1016       (set-buffer-modified-p nil)
1017       (view-buffer (current-buffer) 'kill-buffer-if-not-modified))))
1018
1019 ;;;###autoload
1020 (defun notmuch-show-mode ()
1021   "Major mode for viewing a thread with notmuch.
1022
1023 This buffer contains the results of the \"notmuch show\" command
1024 for displaying a single thread of email from your email archives.
1025
1026 By default, various components of email messages, (citations,
1027 signatures, already-read messages), are hidden. You can make
1028 these parts visible by clicking with the mouse button or by
1029 pressing RET after positioning the cursor on a hidden part, (for
1030 which \\[notmuch-show-next-button] and \\[notmuch-show-previous-button] are helpful).
1031
1032 Reading the thread sequentially is well-supported by pressing
1033 \\[notmuch-show-advance-and-archive]. This will
1034 scroll the current message (if necessary), advance to the next
1035 message, or advance to the next thread (if already on the last
1036 message of a thread).
1037
1038 Other commands are available to read or manipulate the thread more
1039 selectively, (such as '\\[notmuch-show-next-message]' and '\\[notmuch-show-previous-message]' to advance to messages without
1040 removing any tags, and '\\[notmuch-show-archive-thread]' to archive an entire thread without
1041 scrolling through with \\[notmuch-show-advance-and-archive]).
1042
1043 You can add or remove arbitary tags from the current message with
1044 '\\[notmuch-show-add-tag]' or '\\[notmuch-show-remove-tag]'.
1045
1046 All currently available key bindings:
1047
1048 \\{notmuch-show-mode-map}"
1049   (interactive)
1050   (kill-all-local-variables)
1051   (add-to-invisibility-spec 'notmuch-show-marker)
1052   (use-local-map notmuch-show-mode-map)
1053   (setq major-mode 'notmuch-show-mode
1054         mode-name "notmuch-show")
1055   (setq buffer-read-only t))
1056
1057 (defgroup notmuch nil
1058   "Notmuch mail reader for Emacs."
1059   :group 'mail)
1060
1061 (defcustom notmuch-show-hook nil
1062   "List of functions to call when notmuch displays a message."
1063   :type 'hook
1064   :options '(goto-address)
1065   :group 'notmuch)
1066
1067 (defcustom notmuch-search-hook nil
1068   "List of functions to call when notmuch displays the search results."
1069   :type 'hook
1070   :options '(hl-line-mode)
1071   :group 'notmuch)
1072
1073 (defun notmuch-show-do-stash (text)
1074     (kill-new text)
1075     (message (concat "Saved: " text)))
1076
1077 (defun notmuch-show-stash-cc ()
1078   "Copy CC field of current message to kill-ring."
1079   (interactive)
1080   (notmuch-show-do-stash (notmuch-show-get-cc)))
1081
1082 (defun notmuch-show-stash-date ()
1083   "Copy date of current message to kill-ring."
1084   (interactive)
1085   (notmuch-show-do-stash (notmuch-show-get-date)))
1086
1087 (defun notmuch-show-stash-filename ()
1088   "Copy filename of current message to kill-ring."
1089   (interactive)
1090   (notmuch-show-do-stash (notmuch-show-get-filename)))
1091
1092 (defun notmuch-show-stash-from ()
1093   "Copy From address of current message to kill-ring."
1094   (interactive)
1095   (notmuch-show-do-stash (notmuch-show-get-from)))
1096
1097 (defun notmuch-show-stash-message-id ()
1098   "Copy message ID of current message to kill-ring."
1099   (interactive)
1100   (notmuch-show-do-stash (notmuch-show-get-message-id)))
1101
1102 (defun notmuch-show-stash-subject ()
1103   "Copy Subject field of current message to kill-ring."
1104   (interactive)
1105   (notmuch-show-do-stash (notmuch-show-get-subject)))
1106
1107 (defun notmuch-show-stash-tags ()
1108   "Copy tags of current message to kill-ring as a comma separated list."
1109   (interactive)
1110   (notmuch-show-do-stash (mapconcat 'identity (notmuch-show-get-tags) ",")))
1111
1112 (defun notmuch-show-stash-to ()
1113   "Copy To address of current message to kill-ring."
1114   (interactive)
1115   (notmuch-show-do-stash (notmuch-show-get-to)))
1116
1117 ; Make show mode a bit prettier, highlighting URLs and using word wrap
1118
1119 (defun notmuch-show-mark-read ()
1120   (notmuch-show-remove-tag "unread"))
1121
1122 (defun notmuch-show-pretty-hook ()
1123   (goto-address-mode 1)
1124   (visual-line-mode))
1125
1126 (add-hook 'notmuch-show-hook 'notmuch-show-mark-read)
1127 (add-hook 'notmuch-show-hook 'notmuch-show-pretty-hook)
1128 (add-hook 'notmuch-search-hook
1129           (lambda()
1130             (hl-line-mode 1) ))
1131
1132 (defun notmuch-show (thread-id &optional parent-buffer query-context)
1133   "Run \"notmuch show\" with the given thread ID and display results.
1134
1135 The optional PARENT-BUFFER is the notmuch-search buffer from
1136 which this notmuch-show command was executed, (so that the next
1137 thread from that buffer can be show when done with this one).
1138
1139 The optional QUERY-CONTEXT is a notmuch search term. Only messages from the thread
1140 matching this search term are shown if non-nil. "
1141   (interactive "sNotmuch show: ")
1142   (let ((buffer (get-buffer-create (concat "*notmuch-show-" thread-id "*"))))
1143     (switch-to-buffer buffer)
1144     (notmuch-show-mode)
1145     (set (make-local-variable 'notmuch-show-parent-buffer) parent-buffer)
1146     (let ((proc (get-buffer-process (current-buffer)))
1147           (inhibit-read-only t))
1148       (if proc
1149           (error "notmuch search process already running for query `%s'" thread-id)
1150         )
1151       (erase-buffer)
1152       (goto-char (point-min))
1153       (save-excursion
1154         (let* ((basic-args (list notmuch-command nil t nil "show" "--entire-thread" thread-id))
1155                 (args (if query-context (append basic-args (list "and (" query-context ")")) basic-args)))
1156           (apply 'call-process args)
1157           (when (and (eq (buffer-size) 0) query-context)
1158             (apply 'call-process basic-args)))
1159         (notmuch-show-markup-messages)
1160         )
1161       (run-hooks 'notmuch-show-hook)
1162       ; Move straight to the first open message
1163       (if (not (notmuch-show-message-open-p))
1164           (notmuch-show-next-open-message))
1165       )))
1166
1167 (defvar notmuch-search-authors-width 40
1168   "Number of columns to use to display authors in a notmuch-search buffer.")
1169
1170 (defvar notmuch-search-mode-map
1171   (let ((map (make-sparse-keymap)))
1172     (define-key map "?" 'notmuch-help)
1173     (define-key map "q" 'kill-this-buffer)
1174     (define-key map "x" 'kill-this-buffer)
1175     (define-key map (kbd "<DEL>") 'notmuch-search-scroll-down)
1176     (define-key map "b" 'notmuch-search-scroll-down)
1177     (define-key map " " 'notmuch-search-scroll-up)
1178     (define-key map "<" 'notmuch-search-first-thread)
1179     (define-key map ">" 'notmuch-search-last-thread)
1180     (define-key map "p" 'notmuch-search-previous-thread)
1181     (define-key map "n" 'notmuch-search-next-thread)
1182     (define-key map "r" 'notmuch-search-reply-to-thread)
1183     (define-key map "m" 'message-mail)
1184     (define-key map "s" 'notmuch-search)
1185     (define-key map "o" 'notmuch-search-toggle-order)
1186     (define-key map "=" 'notmuch-search-refresh-view)
1187     (define-key map "t" 'notmuch-search-filter-by-tag)
1188     (define-key map "f" 'notmuch-search-filter)
1189     (define-key map [mouse-1] 'notmuch-search-show-thread)
1190     (define-key map "*" 'notmuch-search-operate-all)
1191     (define-key map "a" 'notmuch-search-archive-thread)
1192     (define-key map "-" 'notmuch-search-remove-tag)
1193     (define-key map "+" 'notmuch-search-add-tag)
1194     (define-key map (kbd "RET") 'notmuch-search-show-thread)
1195     map)
1196   "Keymap for \"notmuch search\" buffers.")
1197 (fset 'notmuch-search-mode-map notmuch-search-mode-map)
1198
1199 (defvar notmuch-search-query-string)
1200 (defvar notmuch-search-oldest-first t
1201   "Show the oldest mail first in the search-mode")
1202
1203 (defvar notmuch-search-disjunctive-regexp      "\\<[oO][rR]\\>")
1204
1205 (defun notmuch-search-scroll-up ()
1206   "Move forward through search results by one window's worth."
1207   (interactive)
1208   (condition-case nil
1209       (scroll-up nil)
1210     ((end-of-buffer) (notmuch-search-last-thread))))
1211
1212 (defun notmuch-search-scroll-down ()
1213   "Move backward through the search results by one window's worth."
1214   (interactive)
1215   ; I don't know why scroll-down doesn't signal beginning-of-buffer
1216   ; the way that scroll-up signals end-of-buffer, but c'est la vie.
1217   ;
1218   ; So instead of trapping a signal we instead check whether the
1219   ; window begins on the first line of the buffer and if so, move
1220   ; directly to that position. (We have to count lines since the
1221   ; window-start position is not the same as point-min due to the
1222   ; invisible thread-ID characters on the first line.
1223   (if (equal (count-lines (point-min) (window-start)) 0)
1224       (goto-char (point-min))
1225     (scroll-down nil)))
1226
1227 (defun notmuch-search-next-thread ()
1228   "Select the next thread in the search results."
1229   (interactive)
1230   (forward-line 1))
1231
1232 (defun notmuch-search-previous-thread ()
1233   "Select the previous thread in the search results."
1234   (interactive)
1235   (forward-line -1))
1236
1237 (defun notmuch-search-last-thread ()
1238   "Select the last thread in the search results."
1239   (interactive)
1240   (goto-char (point-max))
1241   (forward-line -2))
1242
1243 (defun notmuch-search-first-thread ()
1244   "Select the first thread in the search results."
1245   (interactive)
1246   (goto-char (point-min)))
1247
1248 (defface notmuch-message-summary-face
1249  '((((class color) (background light)) (:background "#f0f0f0"))
1250    (((class color) (background dark)) (:background "#303030")))
1251  "Face for the single-line message summary in notmuch-show-mode."
1252  :group 'notmuch)
1253
1254 (defface notmuch-tag-face
1255   '((((class color)
1256       (background dark))
1257      (:foreground "OliveDrab1"))
1258     (((class color)
1259       (background light))
1260      (:foreground "navy blue" :bold t))
1261     (t
1262      (:bold t)))
1263   "Notmuch search mode face used to highligh tags."
1264   :group 'notmuch)
1265
1266 (defvar notmuch-tag-face-alist nil
1267   "List containing the tag list that need to be highlighed")
1268
1269 (defvar notmuch-search-font-lock-keywords  nil)
1270
1271 ;;;###autoload
1272 (defun notmuch-search-mode ()
1273   "Major mode displaying results of a notmuch search.
1274
1275 This buffer contains the results of a \"notmuch search\" of your
1276 email archives. Each line in the buffer represents a single
1277 thread giving a summary of the thread (a relative date, the
1278 number of matched messages and total messages in the thread,
1279 participants in the thread, a representative subject line, and
1280 any tags).
1281
1282 Pressing \\[notmuch-search-show-thread] on any line displays that thread. The '\\[notmuch-search-add-tag]' and '\\[notmuch-search-remove-tag]'
1283 keys can be used to add or remove tags from a thread. The '\\[notmuch-search-archive-thread]' key
1284 is a convenience for archiving a thread (removing the \"inbox\"
1285 tag). The '\\[notmuch-search-operate-all]' key can be used to add or remove a tag from all
1286 threads in the current buffer.
1287
1288 Other useful commands are '\\[notmuch-search-filter]' for filtering the current search
1289 based on an additional query string, '\\[notmuch-search-filter-by-tag]' for filtering to include
1290 only messages with a given tag, and '\\[notmuch-search]' to execute a new, global
1291 search.
1292
1293 Complete list of currently available key bindings:
1294
1295 \\{notmuch-search-mode-map}"
1296   (interactive)
1297   (kill-all-local-variables)
1298   (make-local-variable 'notmuch-search-query-string)
1299   (make-local-variable 'notmuch-search-oldest-first)
1300   (set (make-local-variable 'scroll-preserve-screen-position) t)
1301   (add-to-invisibility-spec 'notmuch-search)
1302   (use-local-map notmuch-search-mode-map)
1303   (setq truncate-lines t)
1304   (setq major-mode 'notmuch-search-mode
1305         mode-name "notmuch-search")
1306   (setq buffer-read-only t)
1307   (if (not notmuch-tag-face-alist)
1308       (add-to-list 'notmuch-search-font-lock-keywords (list
1309                 "(\\([^)]*\\))$" '(1  'notmuch-tag-face)))
1310     (let ((notmuch-search-tags (mapcar 'car notmuch-tag-face-alist)))
1311       (loop for notmuch-search-tag  in notmuch-search-tags
1312             do (add-to-list 'notmuch-search-font-lock-keywords (list
1313                         (concat "([^)]*\\(" notmuch-search-tag "\\)[^)]*)$")
1314                         `(1  ,(cdr (assoc notmuch-search-tag notmuch-tag-face-alist))))))))
1315   (set (make-local-variable 'font-lock-defaults)
1316          '(notmuch-search-font-lock-keywords t)))
1317
1318 (defun notmuch-search-find-thread-id ()
1319   "Return the thread for the current thread"
1320   (get-text-property (point) 'notmuch-search-thread-id))
1321
1322 (defun notmuch-search-find-authors ()
1323   "Return the authors for the current thread"
1324   (get-text-property (point) 'notmuch-search-authors))
1325
1326 (defun notmuch-search-find-subject ()
1327   "Return the subject for the current thread"
1328   (get-text-property (point) 'notmuch-search-subject))
1329
1330 (defun notmuch-search-show-thread ()
1331   "Display the currently selected thread."
1332   (interactive)
1333   (let ((thread-id (notmuch-search-find-thread-id)))
1334     (if (> (length thread-id) 0)
1335         (notmuch-show thread-id (current-buffer) notmuch-search-query-string)
1336       (error "End of search results"))))
1337
1338 (defun notmuch-search-reply-to-thread ()
1339   "Begin composing a reply to the entire current thread in a new buffer."
1340   (interactive)
1341   (let ((message-id (notmuch-search-find-thread-id)))
1342     (notmuch-reply message-id)))
1343
1344 (defun notmuch-call-notmuch-process (&rest args)
1345   "Synchronously invoke \"notmuch\" with the given list of arguments.
1346
1347 Output from the process will be presented to the user as an error
1348 and will also appear in a buffer named \"*Notmuch errors*\"."
1349   (let ((error-buffer (get-buffer-create "*Notmuch errors*")))
1350     (with-current-buffer error-buffer
1351         (erase-buffer))
1352     (if (eq (apply 'call-process notmuch-command nil error-buffer nil args) 0)
1353         (point)
1354       (progn
1355         (with-current-buffer error-buffer
1356           (let ((beg (point-min))
1357                 (end (- (point-max) 1)))
1358             (error (buffer-substring beg end))
1359             ))))))
1360
1361 (defun notmuch-search-set-tags (tags)
1362   (save-excursion
1363     (end-of-line)
1364     (re-search-backward "(")
1365     (forward-char)
1366     (let ((beg (point))
1367           (inhibit-read-only t))
1368       (re-search-forward ")")
1369       (backward-char)
1370       (let ((end (point)))
1371         (delete-region beg end)
1372         (insert (mapconcat  'identity tags " "))))))
1373
1374 (defun notmuch-search-get-tags ()
1375   (save-excursion
1376     (end-of-line)
1377     (re-search-backward "(")
1378     (let ((beg (+ (point) 1)))
1379       (re-search-forward ")")
1380       (let ((end (- (point) 1)))
1381         (split-string (buffer-substring beg end))))))
1382
1383 (defun notmuch-search-add-tag (tag)
1384   "Add a tag to the currently selected thread.
1385
1386 The tag is added to messages in the currently selected thread
1387 which match the current search terms."
1388   (interactive
1389    (list (notmuch-select-tag-with-completion "Tag to add: ")))
1390   (notmuch-call-notmuch-process "tag" (concat "+" tag) (notmuch-search-find-thread-id))
1391   (notmuch-search-set-tags (delete-dups (sort (cons tag (notmuch-search-get-tags)) 'string<))))
1392
1393 (defun notmuch-search-remove-tag (tag)
1394   "Remove a tag from the currently selected thread.
1395
1396 The tag is removed from messages in the currently selected thread
1397 which match the current search terms."
1398   (interactive
1399    (list (notmuch-select-tag-with-completion "Tag to remove: " (notmuch-search-find-thread-id))))
1400   (notmuch-call-notmuch-process "tag" (concat "-" tag) (notmuch-search-find-thread-id))
1401   (notmuch-search-set-tags (delete tag (notmuch-search-get-tags))))
1402
1403 (defun notmuch-search-archive-thread ()
1404   "Archive the currently selected thread (remove its \"inbox\" tag).
1405
1406 This function advances the next thread when finished."
1407   (interactive)
1408   (notmuch-search-remove-tag "inbox")
1409   (forward-line))
1410
1411 (defun notmuch-search-process-sentinel (proc msg)
1412   "Add a message to let user know when \"notmuch search\" exits"
1413   (let ((buffer (process-buffer proc))
1414         (status (process-status proc))
1415         (exit-status (process-exit-status proc)))
1416     (if (memq status '(exit signal))
1417         (if (buffer-live-p buffer)
1418             (with-current-buffer buffer
1419               (save-excursion
1420                 (let ((inhibit-read-only t))
1421                   (goto-char (point-max))
1422                   (if (eq status 'signal)
1423                       (insert "Incomplete search results (search process was killed).\n"))
1424                   (if (eq status 'exit)
1425                       (progn
1426                         (insert "End of search results.")
1427                         (if (not (= exit-status 0))
1428                             (insert (format " (process returned %d)" exit-status)))
1429                         (insert "\n"))))))))))
1430
1431 (defun notmuch-search-process-filter (proc string)
1432   "Process and filter the output of \"notmuch search\""
1433   (let ((buffer (process-buffer proc)))
1434     (if (buffer-live-p buffer)
1435         (with-current-buffer buffer
1436           (save-excursion
1437             (let ((line 0)
1438                   (more t)
1439                   (inhibit-read-only t))
1440               (while more
1441                 (if (string-match "^\\(thread:[0-9A-Fa-f]*\\) \\(.*\\) \\(\\[[0-9/]*\\]\\) \\([^;]*\\); \\(.*\\) (\\([^()]*\\))$" string line)
1442                     (let* ((thread-id (match-string 1 string))
1443                            (date (match-string 2 string))
1444                            (count (match-string 3 string))
1445                            (authors (match-string 4 string))
1446                            (authors-length (length authors))
1447                            (subject (match-string 5 string))
1448                            (tags (match-string 6 string)))
1449                       (if (> authors-length 40)
1450                           (set 'authors (concat (substring authors 0 (- 40 3)) "...")))
1451                       (goto-char (point-max))
1452                       (let ((beg (point-marker)))
1453                         (insert (format "%s %-7s %-40s %s (%s)\n" date count authors subject tags))
1454                         (put-text-property beg (point-marker) 'notmuch-search-thread-id thread-id)
1455                         (put-text-property beg (point-marker) 'notmuch-search-authors authors)
1456                         (put-text-property beg (point-marker) 'notmuch-search-subject subject))
1457                       (set 'line (match-end 0)))
1458                   (set 'more nil))))))
1459       (delete-process proc))))
1460
1461 (defun notmuch-search-operate-all (action)
1462   "Add/remove tags from all matching messages.
1463
1464 Tis command adds or removes tags from all messages matching the
1465 current search terms. When called interactively, this command
1466 will prompt for tags to be added or removed. Tags prefixed with
1467 '+' will be added and tags prefixed with '-' will be removed.
1468
1469 Each character of the tag name may consist of alphanumeric
1470 characters as well as `_.+-'.
1471 "
1472   (interactive "sOperation (+add -drop): notmuch tag ")
1473   (let ((action-split (split-string action " +")))
1474     ;; Perform some validation
1475     (let ((words action-split))
1476       (when (null words) (error "No operation given"))
1477       (while words
1478         (unless (string-match-p "^[-+][-+_.[:word:]]+$" (car words))
1479           (error "Action must be of the form `+thistag -that_tag'"))
1480         (setq words (cdr words))))
1481     (apply 'notmuch-call-notmuch-process "tag"
1482            (append action-split (list notmuch-search-query-string) nil))))
1483
1484 ;;;###autoload
1485 (defun notmuch-search (query &optional oldest-first)
1486   "Run \"notmuch search\" with the given query string and display results."
1487   (interactive "sNotmuch search: ")
1488   (let ((buffer (get-buffer-create (concat "*notmuch-search-" query "*"))))
1489     (switch-to-buffer buffer)
1490     (notmuch-search-mode)
1491     (set 'notmuch-search-query-string query)
1492     (set 'notmuch-search-oldest-first oldest-first)
1493     (let ((proc (get-buffer-process (current-buffer)))
1494           (inhibit-read-only t))
1495       (if proc
1496           (error "notmuch search process already running for query `%s'" query)
1497         )
1498       (erase-buffer)
1499       (goto-char (point-min))
1500       (save-excursion
1501         (let ((proc (start-process-shell-command
1502                      "notmuch-search" buffer notmuch-command "search"
1503                      (if oldest-first "--sort=oldest-first" "--sort=newest-first")
1504                      (shell-quote-argument query))))
1505           (set-process-sentinel proc 'notmuch-search-process-sentinel)
1506           (set-process-filter proc 'notmuch-search-process-filter))))
1507     (run-hooks 'notmuch-search-hook)))
1508
1509 (defun notmuch-search-refresh-view ()
1510   "Refresh the current view.
1511
1512 Kills the current buffer and runs a new search with the same
1513 query string as the current search. If the current thread is in
1514 the new search results, then point will be placed on the same
1515 thread. Otherwise, point will be moved to attempt to be in the
1516 same relative position within the new buffer."
1517   (interactive)
1518   (let ((here (point))
1519         (oldest-first notmuch-search-oldest-first)
1520         (thread (notmuch-search-find-thread-id))
1521         (query notmuch-search-query-string))
1522     (kill-this-buffer)
1523     (notmuch-search query oldest-first)
1524     (goto-char (point-min))
1525     (if (re-search-forward (concat "^" thread) nil t)
1526         (beginning-of-line)
1527       (goto-char here))))
1528
1529 (defun notmuch-search-toggle-order ()
1530   "Toggle the current search order.
1531
1532 By default, the \"inbox\" view created by `notmuch' is displayed
1533 in chronological order (oldest thread at the beginning of the
1534 buffer), while any global searches created by `notmuch-search'
1535 are displayed in reverse-chronological order (newest thread at
1536 the beginning of the buffer).
1537
1538 This command toggles the sort order for the current search.
1539
1540 Note that any filtered searches created by
1541 `notmuch-search-filter' retain the search order of the parent
1542 search."
1543   (interactive)
1544   (set 'notmuch-search-oldest-first (not notmuch-search-oldest-first))
1545   (notmuch-search-refresh-view))
1546
1547 (defun notmuch-search-filter (query)
1548   "Filter the current search results based on an additional query string.
1549
1550 Runs a new search matching only messages that match both the
1551 current search results AND the additional query string provided."
1552   (interactive "sFilter search: ")
1553   (let ((grouped-query (if (string-match-p notmuch-search-disjunctive-regexp query) (concat "( " query " )") query)))
1554     (notmuch-search (concat notmuch-search-query-string " and " grouped-query) notmuch-search-oldest-first)))
1555
1556 (defun notmuch-search-filter-by-tag (tag)
1557   "Filter the current search results based on a single tag.
1558
1559 Runs a new search matching only messages that match both the
1560 current search results AND that are tagged with the given tag."
1561   (interactive
1562    (list (notmuch-select-tag-with-completion "Filter by tag: ")))
1563   (notmuch-search (concat notmuch-search-query-string " and tag:" tag) notmuch-search-oldest-first))
1564
1565
1566 ;;;###autoload
1567 (defun notmuch ()
1568   "Run notmuch to display all mail with tag of 'inbox'"
1569   (interactive)
1570   (notmuch-search "tag:inbox" notmuch-search-oldest-first))
1571
1572 (setq mail-user-agent 'message-user-agent)
1573
1574 (defvar notmuch-folder-mode-map
1575   (let ((map (make-sparse-keymap)))
1576     (define-key map "?" 'notmuch-help)
1577     (define-key map "x" 'kill-this-buffer)
1578     (define-key map "q" 'kill-this-buffer)
1579     (define-key map "m" 'message-mail)
1580     (define-key map "e" 'notmuch-folder-show-empty-toggle)
1581     (define-key map ">" 'notmuch-folder-last)
1582     (define-key map "<" 'notmuch-folder-first)
1583     (define-key map "=" 'notmuch-folder)
1584     (define-key map "s" 'notmuch-search)
1585     (define-key map [mouse-1] 'notmuch-folder-show-search)
1586     (define-key map (kbd "RET") 'notmuch-folder-show-search)
1587     (define-key map " " 'notmuch-folder-show-search)
1588     (define-key map "p" 'notmuch-folder-previous)
1589     (define-key map "n" 'notmuch-folder-next)
1590     map)
1591   "Keymap for \"notmuch folder\" buffers.")
1592
1593 (fset 'notmuch-folder-mode-map notmuch-folder-mode-map)
1594
1595 (defcustom notmuch-folders (quote (("inbox" . "tag:inbox") ("unread" . "tag:unread")))
1596   "List of searches for the notmuch folder view"
1597   :type '(alist :key-type (string) :value-type (string))
1598   :group 'notmuch)
1599
1600 (defun notmuch-folder-mode ()
1601   "Major mode for showing notmuch 'folders'.
1602
1603 This buffer contains a list of message counts returned by a
1604 customizable set of searches of your email archives. Each line in
1605 the buffer shows the name of a saved search and the resulting
1606 message count.
1607
1608 Pressing RET on any line opens a search window containing the
1609 results for the saved search on that line.
1610
1611 Here is an example of how the search list could be
1612 customized, (the following text would be placed in your ~/.emacs
1613 file):
1614
1615 (setq notmuch-folders '((\"inbox\" . \"tag:inbox\")
1616                         (\"unread\" . \"tag:inbox AND tag:unread\")
1617                         (\"notmuch\" . \"tag:inbox AND to:notmuchmail.org\")))
1618
1619 Of course, you can have any number of folders, each configured
1620 with any supported search terms (see \"notmuch help search-terms\").
1621
1622 Currently available key bindings:
1623
1624 \\{notmuch-folder-mode-map}"
1625   (interactive)
1626   (kill-all-local-variables)
1627   (use-local-map 'notmuch-folder-mode-map)
1628   (setq truncate-lines t)
1629   (hl-line-mode 1)
1630   (setq major-mode 'notmuch-folder-mode
1631         mode-name "notmuch-folder")
1632   (setq buffer-read-only t))
1633
1634 (defun notmuch-folder-next ()
1635   "Select the next folder in the list."
1636   (interactive)
1637   (forward-line 1)
1638   (if (eobp)
1639       (forward-line -1)))
1640
1641 (defun notmuch-folder-previous ()
1642   "Select the previous folder in the list."
1643   (interactive)
1644   (forward-line -1))
1645
1646 (defun notmuch-folder-first ()
1647   "Select the first folder in the list."
1648   (interactive)
1649   (goto-char (point-min)))
1650
1651 (defun notmuch-folder-last ()
1652   "Select the last folder in the list."
1653   (interactive)
1654   (goto-char (point-max))
1655   (forward-line -1))
1656
1657 (defun notmuch-folder-count (search)
1658   (car (process-lines notmuch-command "count" search)))
1659
1660 (setq notmuch-folder-show-empty t)
1661
1662 (defun notmuch-folder-show-empty-toggle ()
1663   "Toggle the listing of empty folders"
1664   (interactive)
1665   (setq notmuch-folder-show-empty (not notmuch-folder-show-empty))
1666   (notmuch-folder))
1667
1668 (defun notmuch-folder-add (folders)
1669   (if folders
1670       (let* ((name (car (car folders)))
1671             (inhibit-read-only t)
1672             (search (cdr (car folders)))
1673             (count (notmuch-folder-count search)))
1674         (if (or notmuch-folder-show-empty
1675                 (not (equal count "0")))
1676             (progn
1677               (insert name)
1678               (indent-to 16 1)
1679               (insert count)
1680               (insert "\n")
1681               )
1682           )
1683         (notmuch-folder-add (cdr folders)))))
1684
1685 (defun notmuch-folder-find-name ()
1686   (save-excursion
1687     (beginning-of-line)
1688     (let ((beg (point)))
1689       (re-search-forward "\\([ \t]*[^ \t]+\\)")
1690       (filter-buffer-substring (match-beginning 1) (match-end 1)))))
1691
1692 (defun notmuch-folder-show-search (&optional folder)
1693   "Show a search window for the search related to the specified folder."
1694   (interactive)
1695   (if (null folder)
1696       (setq folder (notmuch-folder-find-name)))
1697   (let ((search (assoc folder notmuch-folders)))
1698     (if search
1699         (notmuch-search (cdr search) notmuch-search-oldest-first))))
1700
1701 ;;;###autoload
1702 (defun notmuch-folder ()
1703   "Show the notmuch folder view and update the displayed counts."
1704   (interactive)
1705   (let ((buffer (get-buffer-create "*notmuch-folders*")))
1706     (switch-to-buffer buffer)
1707     (let ((inhibit-read-only t)
1708           (n (line-number-at-pos)))
1709       (erase-buffer)
1710       (notmuch-folder-mode)
1711       (notmuch-folder-add notmuch-folders)
1712       (goto-char (point-min))
1713       (goto-line n))))
1714
1715 (provide 'notmuch)