]> git.notmuchmail.org Git - notmuch/blob - notmuch.el
4e649d441401239b9ddafa9258ade2d838b56acf
[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 (load "cl-seq")
23
24 (defvar notmuch-show-mode-map
25   (let ((map (make-sparse-keymap)))
26     ; I don't actually want all of these toggle commands occupying
27     ; keybindings. They steal valuable key-binding space, are hard
28     ; to remember, and act globally rather than locally.
29     ;
30     ; Will be much preferable to switch to direct manipulation for
31     ; toggling visibility of these components. Probably using
32     ; overlays-at to query and manipulate the current overlay.
33     (define-key map "a" 'notmuch-show-archive-thread)
34     (define-key map "A" 'notmuch-show-mark-read-then-archive-thread)
35     (define-key map "b" 'notmuch-show-toggle-body-read-visible)
36     (define-key map "c" 'notmuch-show-toggle-citations-visible)
37     (define-key map "h" 'notmuch-show-toggle-headers-visible)
38     (define-key map "n" 'notmuch-show-next-message)
39     (define-key map "N" 'notmuch-show-mark-read-then-next-open-message)
40     (define-key map "p" 'notmuch-show-previous-message)
41     (define-key map (kbd "C-n") 'notmuch-show-next-line)
42     (define-key map (kbd "C-p") 'notmuch-show-previous-line)
43     (define-key map "q" 'kill-this-buffer)
44     (define-key map "s" 'notmuch-show-toggle-signatures-visible)
45     (define-key map "w" 'notmuch-show-view-raw-message)
46     (define-key map "x" 'kill-this-buffer)
47     (define-key map "+" 'notmuch-show-add-tag)
48     (define-key map "-" 'notmuch-show-remove-tag)
49     (define-key map (kbd "DEL") 'notmuch-show-rewind)
50     (define-key map " " 'notmuch-show-advance-marking-read-and-archiving)
51     (define-key map "|" 'notmuch-show-pipe-message)
52     map)
53   "Keymap for \"notmuch show\" buffers.")
54 (fset 'notmuch-show-mode-map notmuch-show-mode-map)
55
56 (defvar notmuch-show-signature-lines-max 6
57   "Maximum length of signature that will be hidden by default.")
58
59 (set 'notmuch-show-message-begin-regexp    "\fmessage{")
60 (set 'notmuch-show-message-end-regexp      "\fmessage}")
61 (set 'notmuch-show-header-begin-regexp     "\fheader{")
62 (set 'notmuch-show-header-end-regexp       "\fheader}")
63 (set 'notmuch-show-body-begin-regexp       "\fbody{")
64 (set 'notmuch-show-body-end-regexp         "\fbody}")
65 (set 'notmuch-show-attachment-begin-regexp "\fattachment{")
66 (set 'notmuch-show-attachment-end-regexp   "\fattachment}")
67 (set 'notmuch-show-part-begin-regexp       "\fpart{")
68 (set 'notmuch-show-part-end-regexp         "\fpart}")
69 (set 'notmuch-show-marker-regexp "\f\\(message\\|header\\|body\\|attachment\\|part\\)[{}].*$")
70
71 (set 'notmuch-show-id-regexp "id:\\([^ ]*\\)")
72 (set 'notmuch-show-filename-regexp "filename:\\(.*\\)$")
73 (set 'notmuch-show-tags-regexp "(\\([^)]*\\))$")
74
75 ; XXX: This should be a generic function in emacs somewhere, not here
76 (defun point-invisible-p ()
77   "Return whether the character at point is invisible.
78
79 Here visibility is determined by `buffer-invisibility-spec' and
80 the invisible property of any overlays for point. It doesn't have
81 anything to do with whether point is currently being displayed
82 within the current window."
83   (let ((prop (get-char-property (point) 'invisible)))
84     (if (eq buffer-invisibility-spec t)
85         prop
86       (or (memq prop buffer-invisibility-spec)
87           (assq prop buffer-invisibility-spec)))))
88
89 (defun notmuch-show-next-line ()
90   "Like builtin `next-line' but ensuring we end on a visible character.
91
92 By advancing forward until reaching a visible character.
93
94 Unlike builtin `next-line' this version accepts no arguments."
95   (interactive)
96   (set 'this-command 'next-line)
97   (call-interactively 'next-line)
98   (while (point-invisible-p)
99     (forward-char)))
100
101 (defun notmuch-show-previous-line ()
102   "Like builtin `previous-line' but ensuring we end on a visible character.
103
104 By advancing forward until reaching a visible character.
105
106 Unlike builtin `next-line' this version accepts no arguments."
107   (interactive)
108   (set 'this-command 'previous-line)
109   (call-interactively 'previous-line)
110   (while (point-invisible-p)
111     (forward-char)))
112
113 (defun notmuch-show-get-message-id ()
114   (save-excursion
115     (beginning-of-line)
116     (if (not (looking-at notmuch-show-message-begin-regexp))
117         (re-search-backward notmuch-show-message-begin-regexp))
118     (re-search-forward notmuch-show-id-regexp)
119     (buffer-substring (match-beginning 1) (match-end 1))))
120
121 (defun notmuch-show-get-filename ()
122   (save-excursion
123     (beginning-of-line)
124     (if (not (looking-at notmuch-show-message-begin-regexp))
125         (re-search-backward notmuch-show-message-begin-regexp))
126     (re-search-forward notmuch-show-filename-regexp)
127     (buffer-substring (match-beginning 1) (match-end 1))))
128
129 (defun notmuch-show-set-tags (tags)
130   (save-excursion
131     (beginning-of-line)
132     (if (not (looking-at notmuch-show-message-begin-regexp))
133         (re-search-backward notmuch-show-message-begin-regexp))
134     (re-search-forward notmuch-show-tags-regexp)
135     (let ((inhibit-read-only t)
136           (beg (match-beginning 1))
137           (end (match-end 1)))
138       (delete-region beg end)
139       (goto-char beg)
140       (insert (mapconcat 'identity tags " ")))))
141
142 (defun notmuch-show-get-tags ()
143   (save-excursion
144     (beginning-of-line)
145     (if (not (looking-at notmuch-show-message-begin-regexp))
146         (re-search-backward notmuch-show-message-begin-regexp))
147     (re-search-forward notmuch-show-tags-regexp)
148     (split-string (buffer-substring (match-beginning 1) (match-end 1)))))
149
150 (defun notmuch-show-add-tag (&rest toadd)
151   "Add a tag to the current message."
152   (interactive "sTag to add: ")
153   (apply 'notmuch-call-notmuch-process
154          (append (cons "tag"
155                        (mapcar (lambda (s) (concat "+" s)) toadd))
156                  (cons (concat "id:" (notmuch-show-get-message-id)) nil)))
157   (notmuch-show-set-tags (sort (union toadd (notmuch-show-get-tags) :test 'string=) 'string<)))
158
159 (defun notmuch-show-remove-tag (&rest toremove)
160   "Remove a tag from the current message."
161   (interactive "sTag to remove: ")
162   (let ((tags (notmuch-show-get-tags)))
163     (if (intersection tags toremove :test 'string=)
164         (progn
165           (apply 'notmuch-call-notmuch-process
166                  (append (cons "tag"
167                                (mapcar (lambda (s) (concat "-" s)) toremove))
168                          (cons (concat "id:" (notmuch-show-get-message-id)) nil)))
169           (notmuch-show-set-tags (sort (set-difference tags toremove :test 'string=) 'string<))))))
170
171 (defun notmuch-show-archive-thread-maybe-mark-read (markread)
172   (save-excursion
173     (goto-char (point-min))
174     (while (not (eobp))
175       (if markread
176           (notmuch-show-remove-tag "unread" "inbox")
177         (notmuch-show-remove-tag "inbox"))
178       (if (not (eobp))
179           (forward-char))
180       (if (not (re-search-forward notmuch-show-message-begin-regexp nil t))
181           (goto-char (point-max)))))
182   (let ((parent-buffer notmuch-show-parent-buffer))
183     (kill-this-buffer)
184     (if parent-buffer
185         (progn
186           (switch-to-buffer parent-buffer)
187           (notmuch-search-show-thread)))))
188
189 (defun notmuch-show-mark-read-then-archive-thread ()
190   "Remove \"unread\" tag from each message, then archive and show next thread.
191
192 Archive each message currrently shown by removing the \"unread\"
193 and \"inbox\" tag from each. Then kill this buffer and show the
194 next thread from the search from which this thread was originally
195 shown.
196
197 Note: This command is safe from any race condition of new messages
198 being delivered to the same thread. It does not archive the
199 entire thread, but only the messages shown in the current
200 buffer."
201   (interactive)
202   (notmuch-show-archive-thread-maybe-mark-read t))
203
204 (defun notmuch-show-archive-thread ()
205   "Archive each message in thread, and show next thread from search.
206
207 Archive each message currrently shown by removing the \"inbox\"
208 tag from each. Then kill this buffer and show the next thread
209 from the search from which this thread was originally shown.
210
211 Note: This command is safe from any race condition of new messages
212 being delivered to the same thread. It does not archive the
213 entire thread, but only the messages shown in the current
214 buffer."
215   (interactive)
216   (notmuch-show-archive-thread-maybe-mark-read nil))
217
218 (defun notmuch-show-view-raw-message ()
219   "View the raw email of the current message."
220   (interactive)
221   (view-file (notmuch-show-get-filename)))
222
223 (defun notmuch-show-pipe-message (command)
224   "Pipe the contents of the current message to the given command.
225
226 The given command will be executed with the raw contents of the
227 current email message as stdin. Anything printed by the command
228 to stdout or stderr will appear in the *Messages* buffer."
229   (interactive "sPipe message to command: ")
230   (apply 'start-process-shell-command "notmuch-pipe-command" "*notmuch-pipe*" (split-string (concat command " < " (notmuch-show-get-filename)))))
231
232 (defun notmuch-show-move-to-current-message-summary-line ()
233   "Move to the beginning of the one-line summary of the current message.
234
235 This gives us a stable place to move to and work from since the
236 summary line is always visible. This is important since moving to
237 an invisible location is unreliable, (the main command loop moves
238 point either forward or backward to the next visible character
239 when a command ends with point on an invisible character).
240
241 Emits an error if point is not within a valid message, (that is
242 not pattern of `notmuch-show-message-begin-regexp' could be found
243 by searching backward)."
244   (beginning-of-line)
245   (if (not (looking-at notmuch-show-message-begin-regexp))
246       (if (re-search-backward notmuch-show-message-begin-regexp nil t)
247           (forward-line 2)
248         (error "Not within a valid message."))
249     (forward-line 2)))
250
251 (defun notmuch-show-last-message-p ()
252   "Predicate testing whether point is within the last message."
253   (save-window-excursion
254     (save-excursion
255       (notmuch-show-move-to-current-message-summary-line)
256       (not (re-search-forward notmuch-show-message-begin-regexp nil t)))))
257
258 (defun notmuch-show-message-unread-p ()
259   "Preficate testing whether current message is unread."
260   (member "unread" (notmuch-show-get-tags)))
261
262 (defun notmuch-show-next-message ()
263   "Advance to the beginning of the next message in the buffer.
264
265 Moves to the last visible character of the current message if
266 already on the last message in the buffer."
267   (interactive)
268   (notmuch-show-move-to-current-message-summary-line)
269   (if (re-search-forward notmuch-show-message-begin-regexp nil t)
270       (notmuch-show-move-to-current-message-summary-line)
271     (goto-char (- (point-max) 1))
272     (while (point-invisible-p)
273       (backward-char)))
274   (recenter 0))
275
276 (defun notmuch-show-find-next-message ()
277   "Returns the position of the next message in the buffer.
278
279 Or the position of the last visible character of the current
280 message if already within the last message in the buffer."
281   ; save-excursion doesn't save our window position
282   ; save-window-excursion doesn't save point
283   ; Looks like we have to use both.
284   (save-excursion
285     (save-window-excursion
286       (notmuch-show-next-message)
287       (point))))
288
289 (defun notmuch-show-next-unread-message ()
290   "Advance to the beginning of the next unread message in the buffer.
291
292 Moves to the last visible character of the current message if
293 there are no more unread messages past the current point."
294   (notmuch-show-next-message)
295   (while (and (not (notmuch-show-last-message-p))
296               (not (notmuch-show-message-unread-p)))
297     (notmuch-show-next-message))
298   (if (not (notmuch-show-message-unread-p))
299       (notmuch-show-next-message)))
300
301 (defun notmuch-show-next-open-message ()
302   "Advance to the the next message which is not hidden.
303
304 If read messages are currently hidden, advance to the next unread
305 message. Otherwise, advance to the next message."
306   (if (or (memq 'notmuch-show-body-read buffer-invisibility-spec)
307           (assq 'notmuch-show-body-read buffer-invisibility-spec))
308       (notmuch-show-next-unread-message)
309     (notmuch-show-next-message)))
310
311 (defun notmuch-show-previous-message ()
312   "Backup to the beginning of the previous message in the buffer.
313
314 If within a message rather than at the beginning of it, then
315 simply move to the beginning of the current message."
316   (interactive)
317   (let ((start (point)))
318     (notmuch-show-move-to-current-message-summary-line)
319     (if (not (< (point) start))
320         ; Go backward twice to skip the current message's marker
321         (progn
322           (re-search-backward notmuch-show-message-begin-regexp nil t)
323           (re-search-backward notmuch-show-message-begin-regexp nil t)
324           (notmuch-show-move-to-current-message-summary-line)
325           ))
326     (recenter 0)))
327
328 (defun notmuch-show-find-previous-message ()
329   "Returns the position of the previous message in the buffer.
330
331 Or the position of the beginning of the current message if point
332 is originally within the message rather than at the beginning of
333 it."
334   ; save-excursion doesn't save our window position
335   ; save-window-excursion doesn't save point
336   ; Looks like we have to use both.
337   (save-excursion
338     (save-window-excursion
339       (notmuch-show-previous-message)
340       (point))))
341
342 (defun notmuch-show-mark-read-then-next-open-message ()
343   "Remove unread tag from current message, then advance to next unread message."
344   (interactive)
345   (notmuch-show-remove-tag "unread")
346   (notmuch-show-next-open-message))
347
348 (defun notmuch-show-rewind ()
349   "Do reverse scrolling compared to `notmuch-show-advance-marking-read-and-archiving'
350
351 Specifically, if the beginning of the previous email is fewer
352 than `window-height' lines from the current point, move to it
353 just like `notmuch-show-previous-message'.
354
355 Otherwise, just scroll down a screenful of the current message.
356
357 This command does not modify any message tags, (it does not undo
358 any effects from previous calls to
359 `notmuch-show-advance-marking-read-and-archiving'."
360   (interactive)
361   (let ((previous (notmuch-show-find-previous-message)))
362     (if (> (count-lines previous (point)) (- (window-height) next-screen-context-lines))
363         (progn
364           (condition-case nil
365               (scroll-down nil)
366             ((beginning-of-buffer) nil))
367           (goto-char (window-start)))
368       (notmuch-show-previous-message))))
369
370 (defun notmuch-show-advance-marking-read-and-archiving ()
371   "Advance through buffer, marking read and archiving.
372
373 This command is intended to be one of the simplest ways to
374 process a thread of email. It does the following:
375
376 If the current message in the thread is not yet fully visible,
377 scroll by a near screenful to read more of the message.
378
379 Otherwise, (the end of the current message is already within the
380 current window), remove the \"unread\" tag (if present) from the
381 current message and advance to the next open message.
382
383 Finally, if there is no further message to advance to, and this
384 last message is already read, then archive the entire current
385 thread, (remove the \"inbox\" tag from each message). Also kill
386 this buffer, and display the next thread from the search from
387 which this thread was originally shown."
388   (interactive)
389   (let ((next (notmuch-show-find-next-message))
390         (unread (notmuch-show-message-unread-p)))
391     (if (> next (window-end))
392         (scroll-up nil)
393       (let ((last (notmuch-show-last-message-p)))
394         (notmuch-show-mark-read-then-next-open-message)
395         (if last
396             (notmuch-show-archive-thread))))))
397
398 (defun notmuch-show-markup-citations-region (beg end)
399   (goto-char beg)
400   (beginning-of-line)
401   (while (< (point) end)
402     (let ((beg-sub (point)))
403       (if (looking-at ">")
404           (progn
405             (while (looking-at ">")
406               (forward-line))
407             (let ((overlay (make-overlay beg-sub (point))))
408               (overlay-put overlay 'invisible 'notmuch-show-citation)
409               (overlay-put overlay 'before-string
410                            (concat "[" (number-to-string (count-lines beg-sub (point)))
411                                    "-line citation. Press 'c' to show.]\n")))))
412       (if (looking-at "--[ ]?$")
413           (let ((sig-lines (count-lines beg-sub end)))
414             (if (<= sig-lines notmuch-show-signature-lines-max)
415                 (progn
416                   (overlay-put (make-overlay beg-sub (+ beg-sub 1))
417                                'before-string
418                                (concat "[" (number-to-string sig-lines)
419                                        "-line signature. Press 's' to show.]"))
420                   (overlay-put (make-overlay (+ beg-sub 2) end)
421                                'invisible 'notmuch-show-signature)
422                   (goto-char end)))))
423       (forward-line))))
424
425 (defun notmuch-show-markup-body ()
426   (re-search-forward notmuch-show-body-begin-regexp)
427   (next-line 1)
428   (beginning-of-line)
429   (let ((beg (point)))
430     (re-search-forward notmuch-show-body-end-regexp)
431     (let ((end (match-beginning 0)))
432       (notmuch-show-markup-citations-region beg end)
433       (if (not (notmuch-show-message-unread-p))
434           (overlay-put (make-overlay beg end)
435                        'invisible 'notmuch-show-body-read)))))
436
437 (defun notmuch-show-markup-header ()
438   (re-search-forward notmuch-show-header-begin-regexp)
439   (forward-line 1)
440   (beginning-of-line)
441   (let ((beg (point)))
442     (end-of-line)
443     ; Inverse video for subject
444     (overlay-put (make-overlay beg (point)) 'face '((cons :inverse-video t)))
445     (beginning-of-line)
446     (forward-line 2)
447     (set 'beg (point))
448     (re-search-forward notmuch-show-header-end-regexp)
449     (overlay-put (make-overlay beg (match-beginning 0))
450                  'invisible 'notmuch-show-header)))
451
452 (defun notmuch-show-markup-message ()
453   (if (re-search-forward notmuch-show-message-begin-regexp nil t)
454       (progn
455         (notmuch-show-markup-header)
456         (notmuch-show-markup-body))
457     (goto-char (point-max))))
458
459 (defun notmuch-show-hide-markers ()
460   (save-excursion
461     (goto-char (point-min))
462     (while (not (eobp))
463       (if (re-search-forward notmuch-show-marker-regexp nil t)
464           (progn
465             (overlay-put (make-overlay (match-beginning 0) (+ (match-end 0) 1))
466                          'invisible 'notmuch-show-marker))
467         (goto-char (point-max))))))
468
469 (defun notmuch-show-markup-messages ()
470   (save-excursion
471     (goto-char (point-min))
472     (while (not (eobp))
473       (notmuch-show-markup-message)))
474   (notmuch-show-hide-markers))
475
476 (defun notmuch-show-toggle-citations-visible ()
477   "Toggle visibility of citations"
478   (interactive)
479   (if notmuch-show-citations-visible
480       (add-to-invisibility-spec 'notmuch-show-citation)
481     (remove-from-invisibility-spec 'notmuch-show-citation))
482   (set 'notmuch-show-citations-visible (not notmuch-show-citations-visible))
483   ; Need to force the redisplay for some reason
484   (force-window-update)
485   (redisplay t))
486
487 (defun notmuch-show-toggle-signatures-visible ()
488   "Toggle visibility of signatures"
489   (interactive)
490   (if notmuch-show-signatures-visible
491       (add-to-invisibility-spec 'notmuch-show-signature)
492     (remove-from-invisibility-spec 'notmuch-show-signature))
493   (set 'notmuch-show-signatures-visible (not notmuch-show-signatures-visible))
494   ; Need to force the redisplay for some reason
495   (force-window-update)
496   (redisplay t))
497
498 (defun notmuch-show-toggle-headers-visible ()
499   "Toggle visibility of header fields"
500   (interactive)
501   (if notmuch-show-headers-visible
502       (add-to-invisibility-spec 'notmuch-show-header)
503     (remove-from-invisibility-spec 'notmuch-show-header))
504   (set 'notmuch-show-headers-visible (not notmuch-show-headers-visible))
505   ; Need to force the redisplay for some reason
506   (force-window-update)
507   (redisplay t))
508
509 (defun notmuch-show-toggle-body-read-visible ()
510   "Toggle visibility of message bodies of read messages"
511   (interactive)
512   (if notmuch-show-body-read-visible
513       (add-to-invisibility-spec 'notmuch-show-body-read)
514     (remove-from-invisibility-spec 'notmuch-show-body-read))
515   (set 'notmuch-show-body-read-visible (not notmuch-show-body-read-visible))
516   ; Need to force the redisplay for some reason
517   (force-window-update)
518   (redisplay t))
519
520 ;;;###autoload
521 (defun notmuch-show-mode ()
522   "Major mode for viewing a thread with notmuch.
523
524 This buffer contains the results of the \"notmuch show\" command
525 for displaying a single thread of email from your email archives.
526
527 By default, various components of email messages, (citations,
528 signatures, already-read messages), are invisible to help you
529 focus on the most important things, (new text from unread
530 messages). See the various commands below for toggling the
531 visibility of hidden components.
532
533 The `notmuch-show-next-message' and
534 `notmuch-show-previous-message' commands, (bound to 'n' and 'p by
535 default), allow you to navigate to the next and previous
536 messages. Each time you navigate away from a message with
537 `notmuch-show-next-message' the current message will have its
538 \"unread\" tag removed.
539
540 You can add or remove tags from the current message with '+' and
541 '-'.  You can also archive all messages in the current
542 view, (remove the \"inbox\" tag from each), with
543 `notmuch-show-archive-thread' (bound to 'a' by default).
544
545 \\{notmuch-show-mode-map}"
546   (interactive)
547   (kill-all-local-variables)
548   (set (make-local-variable 'notmuch-show-headers-visible) t)
549   (notmuch-show-toggle-headers-visible)
550   (set (make-local-variable 'notmuch-show-body-read-visible) t)
551   (notmuch-show-toggle-body-read-visible)
552   (set (make-local-variable 'notmuch-show-citations-visible) t)
553   (notmuch-show-toggle-citations-visible)
554   (set (make-local-variable 'notmuch-show-signatures-visible) t)
555   (notmuch-show-toggle-signatures-visible)
556   (add-to-invisibility-spec 'notmuch-show-marker)
557   (use-local-map notmuch-show-mode-map)
558   (setq major-mode 'notmuch-show-mode
559         mode-name "notmuch-show")
560   (setq buffer-read-only t))
561
562 (defun notmuch-show (thread-id &optional parent-buffer)
563   "Run \"notmuch show\" with the given thread ID and display results.
564
565 The optional PARENT-BUFFER is the notmuch-search buffer from
566 which this notmuch-show command was executed, (so that the next
567 thread from that buffer can be show when done with this one)."
568   (interactive "sNotmuch show: ")
569   (let ((buffer (get-buffer-create (concat "*notmuch-show-" thread-id "*"))))
570     (switch-to-buffer buffer)
571     (notmuch-show-mode)
572     (set (make-local-variable 'notmuch-show-parent-buffer) parent-buffer)
573     (let ((proc (get-buffer-process (current-buffer)))
574           (inhibit-read-only t))
575       (if proc
576           (error "notmuch search process already running for query `%s'" query)
577         )
578       (erase-buffer)
579       (goto-char (point-min))
580       (save-excursion
581         (call-process "notmuch" nil t nil "show" thread-id)
582         (notmuch-show-markup-messages)
583         )
584       ; Move straight to the first unread message
585       (if (not (notmuch-show-message-unread-p))
586           (progn
587             (notmuch-show-next-unread-message)
588             ; But if there are no unread messages, go back to the
589             ; beginning of the buffer, and open up the bodies of all
590             ; read message.
591             (if (not (notmuch-show-message-unread-p))
592                 (progn
593                   (goto-char (point-min))
594                   (notmuch-show-toggle-body-read-visible)))))
595       )))
596
597 (defvar notmuch-search-mode-map
598   (let ((map (make-sparse-keymap)))
599     (define-key map "a" 'notmuch-search-archive-thread)
600     (define-key map "b" 'notmuch-search-scroll-down)
601     (define-key map "f" 'notmuch-search-filter)
602     (define-key map "n" 'next-line)
603     (define-key map "p" 'previous-line)
604     (define-key map "q" 'kill-this-buffer)
605     (define-key map "s" 'notmuch-search)
606     (define-key map "t" 'notmuch-search-filter-by-tag)
607     (define-key map "x" 'kill-this-buffer)
608     (define-key map (kbd "RET") 'notmuch-search-show-thread)
609     (define-key map "+" 'notmuch-search-add-tag)
610     (define-key map "-" 'notmuch-search-remove-tag)
611     (define-key map "<" 'beginning-of-buffer)
612     (define-key map ">" 'notmuch-search-goto-last-thread)
613     (define-key map "=" 'notmuch-search-refresh-view)
614     (define-key map "\M->" 'notmuch-search-goto-last-thread)
615     (define-key map " " 'notmuch-search-scroll-up)
616     (define-key map (kbd "<DEL>") 'notmuch-search-scroll-down)
617     map)
618   "Keymap for \"notmuch search\" buffers.")
619 (fset 'notmuch-search-mode-map notmuch-search-mode-map)
620
621 (defun notmuch-search-scroll-up ()
622   "Scroll up, moving point to last message in thread if at end."
623   (interactive)
624   (condition-case nil
625       (scroll-up nil)
626     ((end-of-buffer) (notmuch-search-goto-last-thread))))
627
628 (defun notmuch-search-scroll-down ()
629   "Scroll down, moving point to first message in thread if at beginning."
630   (interactive)
631   ; I don't know why scroll-down doesn't signal beginning-of-buffer
632   ; the way that scroll-up signals end-of-buffer, but c'est la vie.
633   ;
634   ; So instead of trapping a signal we instead check whether the
635   ; window begins on the first line of the buffer and if so, move
636   ; directly to that position. (We have to count lines since the
637   ; window-start position is not the same as point-min due to the
638   ; invisible thread-ID characters on the first line.
639   (if (equal (count-lines (point-min) (window-start)) 1)
640       (goto-char (window-start))
641     (scroll-down nil)))
642
643 (defun notmuch-search-goto-last-thread (&optional arg)
644   "Move point to the last thread in the buffer."
645   (interactive "^P")
646   (end-of-buffer arg)
647   (forward-line -1))
648
649 ;;;###autoload
650 (defun notmuch-search-mode ()
651   "Major mode for searching mail with notmuch.
652
653 This buffer contains the results of a \"notmuch search\" of your
654 email archives. Each line in the buffer represents a single
655 thread giving a relative date for the thread and a subject.
656
657 Pressing RET on any line displays that thread. The '+' and '-'
658 keys can be used to add or remove tags from a thread. The 'a' key
659 is a convenience key for archiving a thread (removing the
660 \"inbox\" tag).
661
662 Other useful commands are `notmuch-search-filter' for filtering
663 the current search based on an additional query string,
664 `notmuch-search-filter-by-tag' for filtering to include only
665 messages with a given tag, and `notmuch-search' to execute a new,
666 global search.
667
668 \\{notmuch-search-mode-map}"
669   (interactive)
670   (kill-all-local-variables)
671   (make-local-variable 'notmuch-search-query-string)
672   (set (make-local-variable 'scroll-preserve-screen-position) t)
673   (add-to-invisibility-spec 'notmuch-search)
674   (use-local-map notmuch-search-mode-map)
675   (setq major-mode 'notmuch-search-mode
676         mode-name "notmuch-search")
677   (setq buffer-read-only t))
678
679 (defun notmuch-search-find-thread-id ()
680   (save-excursion
681     (beginning-of-line)
682     (let ((beg (point)))
683       (re-search-forward "thread:[a-fA-F0-9]*" nil t)
684       (filter-buffer-substring beg (point)))))
685
686 (defun notmuch-search-markup-this-thread-id ()
687   (beginning-of-line)
688   (let ((beg (point)))
689     (if (re-search-forward "thread:[a-fA-F0-9]*" nil t)
690         (progn
691           (forward-char)
692           (overlay-put (make-overlay beg (point)) 'invisible 'notmuch-search)))))
693
694 (defun notmuch-search-markup-thread-ids ()
695   (save-excursion
696     (goto-char (point-min))
697     (while (not (eobp))
698       (notmuch-search-markup-this-thread-id)
699       (next-line))))
700
701 (defun notmuch-search-hide-thread-ids ()
702   (interactive)
703   (add-to-invisibility-spec 'notmuch-search)
704   (force-window-update)
705   (redisplay t))
706
707 (defun notmuch-search-show-thread-ids ()
708   (interactive)
709   (remove-from-invisibility-spec 'notmuch-search)
710   (force-window-update)
711   (redisplay t))
712
713 (defun notmuch-search-show-thread ()
714   (interactive)
715   (let ((thread-id (notmuch-search-find-thread-id)))
716     (forward-line)
717     (if (> (length thread-id) 0)
718         (notmuch-show thread-id (current-buffer))
719       (error "End of search results"))))
720
721 (defun notmuch-call-notmuch-process (&rest args)
722   "Synchronously invoke \"notmuch\" with the given list of arguments.
723
724 Output from the process will be presented to the user as an error
725 and will also appear in a buffer named \"*Notmuch errors*\"."
726   (let ((error-buffer (get-buffer-create "*Notmuch errors*")))
727     (with-current-buffer error-buffer
728         (erase-buffer))
729     (if (eq (apply 'call-process "notmuch" nil error-buffer nil args) 0)
730         (point)
731       (progn
732         (with-current-buffer error-buffer
733           (let ((beg (point-min))
734                 (end (- (point-max) 1)))
735             (error (buffer-substring beg end))
736             ))))))
737
738 (defun notmuch-search-set-tags (tags)
739   (save-excursion
740     (end-of-line)
741     (re-search-backward "(")
742     (forward-char)
743     (let ((beg (point))
744           (inhibit-read-only t))
745       (re-search-forward ")")
746       (backward-char)
747       (let ((end (point)))
748         (delete-region beg end)
749         (insert (mapconcat  'identity tags " "))))))
750
751 (defun notmuch-search-get-tags ()
752   (save-excursion
753     (end-of-line)
754     (re-search-backward "(")
755     (let ((beg (+ (point) 1)))
756       (re-search-forward ")")
757       (let ((end (- (point) 1)))
758         (split-string (buffer-substring beg end))))))
759
760 (defun notmuch-search-add-tag (tag)
761   (interactive "sTag to add: ")
762   (notmuch-call-notmuch-process "tag" (concat "+" tag) (concat "thread:" (notmuch-search-find-thread-id)))
763   (notmuch-search-set-tags (delete-dups (sort (cons tag (notmuch-search-get-tags)) 'string<))))
764
765 (defun notmuch-search-remove-tag (tag)
766   (interactive "sTag to remove: ")
767   (notmuch-call-notmuch-process "tag" (concat "-" tag) (concat "thread:" (notmuch-search-find-thread-id)))
768   (notmuch-search-set-tags (delete tag (notmuch-search-get-tags))))
769
770 (defun notmuch-search-archive-thread ()
771   "Archive the current thread (remove its \"inbox\" tag).
772
773 This function advances point to the next line when finished."
774   (interactive)
775   (notmuch-search-remove-tag "inbox")
776   (forward-line))
777
778 (defun notmuch-search (query)
779   "Run \"notmuch search\" with the given query string and display results."
780   (interactive "sNotmuch search: ")
781   (let ((buffer (get-buffer-create (concat "*notmuch-search-" query "*"))))
782     (switch-to-buffer buffer)
783     (notmuch-search-mode)
784     (set 'notmuch-search-query-string query)
785     (let ((proc (get-buffer-process (current-buffer)))
786           (inhibit-read-only t))
787       (if proc
788           (error "notmuch search process already running for query `%s'" query)
789         )
790       (erase-buffer)
791       (goto-char (point-min))
792       (save-excursion
793         (call-process "notmuch" nil t nil "search" query)
794         (notmuch-search-markup-thread-ids)
795         ))))
796
797 (defun notmuch-search-refresh-view ()
798   "Refresh the current view.
799
800 Kills the current buffer and runs a new search with the same
801 query string as the current search. If the current thread is in
802 the new search results, then point will be placed on the same
803 thread. Otherwise, point will be moved to attempt to be in the
804 same relative position within the new buffer."
805   (interactive)
806   (let ((here (point))
807         (thread (notmuch-search-find-thread-id))
808         (query notmuch-search-query-string))
809     (kill-this-buffer)
810     (notmuch-search query)
811     (goto-char (point-min))
812     (if (re-search-forward (concat "^" thread) nil t)
813         (beginning-of-line)
814       (goto-char here))))
815
816 (defun notmuch-search-filter (query)
817   "Filter the current search results based on an additional query string.
818
819 Runs a new search matching only messages that match both the
820 current search results AND the additional query string provided."
821   (interactive "sFilter search: ")
822   (notmuch-search (concat notmuch-search-query-string " and " query)))
823
824 (defun notmuch-search-filter-by-tag (tag)
825   "Filter the current search results based on a single tag.
826
827 Runs a new search matching only messages that match both the
828 current search results AND that are tagged with the given tag."
829   (interactive "sFilter by tag: ")
830   (notmuch-search (concat notmuch-search-query-string " and tag:" tag)))
831
832 (defun notmuch ()
833   "Run notmuch to display all mail with tag of 'inbox'"
834   (interactive)
835   (notmuch-search "tag:inbox"))
836
837 (provide 'notmuch)