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