]> git.notmuchmail.org Git - notmuch/blob - notmuch.el
notmuch.el: Add 'A' binding to archive thread after removing all "unread" tags.
[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                                    " quoted lines.]\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.]"))
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   (next-line 2)
440   (beginning-of-line)
441   (let ((beg (point)))
442     (re-search-forward notmuch-show-header-end-regexp)
443     (overlay-put (make-overlay beg (match-beginning 0))
444                  'invisible 'notmuch-show-header)))
445
446 (defun notmuch-show-markup-message ()
447   (if (re-search-forward notmuch-show-message-begin-regexp nil t)
448       (progn
449         (notmuch-show-markup-header)
450         (notmuch-show-markup-body))
451     (goto-char (point-max))))
452
453 (defun notmuch-show-hide-markers ()
454   (save-excursion
455     (goto-char (point-min))
456     (while (not (eobp))
457       (if (re-search-forward notmuch-show-marker-regexp nil t)
458           (progn
459             (overlay-put (make-overlay (match-beginning 0) (+ (match-end 0) 1))
460                          'invisible 'notmuch-show-marker))
461         (goto-char (point-max))))))
462
463 (defun notmuch-show-markup-messages ()
464   (save-excursion
465     (goto-char (point-min))
466     (while (not (eobp))
467       (notmuch-show-markup-message)))
468   (notmuch-show-hide-markers))
469
470 (defun notmuch-show-toggle-citations-visible ()
471   "Toggle visibility of citations"
472   (interactive)
473   (if notmuch-show-citations-visible
474       (add-to-invisibility-spec 'notmuch-show-citation)
475     (remove-from-invisibility-spec 'notmuch-show-citation))
476   (set 'notmuch-show-citations-visible (not notmuch-show-citations-visible))
477   ; Need to force the redisplay for some reason
478   (force-window-update)
479   (redisplay t))
480
481 (defun notmuch-show-toggle-signatures-visible ()
482   "Toggle visibility of signatures"
483   (interactive)
484   (if notmuch-show-signatures-visible
485       (add-to-invisibility-spec 'notmuch-show-signature)
486     (remove-from-invisibility-spec 'notmuch-show-signature))
487   (set 'notmuch-show-signatures-visible (not notmuch-show-signatures-visible))
488   ; Need to force the redisplay for some reason
489   (force-window-update)
490   (redisplay t))
491
492 (defun notmuch-show-toggle-headers-visible ()
493   "Toggle visibility of header fields"
494   (interactive)
495   (if notmuch-show-headers-visible
496       (add-to-invisibility-spec 'notmuch-show-header)
497     (remove-from-invisibility-spec 'notmuch-show-header))
498   (set 'notmuch-show-headers-visible (not notmuch-show-headers-visible))
499   ; Need to force the redisplay for some reason
500   (force-window-update)
501   (redisplay t))
502
503 (defun notmuch-show-toggle-body-read-visible ()
504   "Toggle visibility of message bodies of read messages"
505   (interactive)
506   (if notmuch-show-body-read-visible
507       (add-to-invisibility-spec 'notmuch-show-body-read)
508     (remove-from-invisibility-spec 'notmuch-show-body-read))
509   (set 'notmuch-show-body-read-visible (not notmuch-show-body-read-visible))
510   ; Need to force the redisplay for some reason
511   (force-window-update)
512   (redisplay t))
513
514 ;;;###autoload
515 (defun notmuch-show-mode ()
516   "Major mode for viewing a thread with notmuch.
517
518 This buffer contains the results of the \"notmuch show\" command
519 for displaying a single thread of email from your email archives.
520
521 By default, various components of email messages, (citations,
522 signatures, already-read messages), are invisible to help you
523 focus on the most important things, (new text from unread
524 messages). See the various commands below for toggling the
525 visibility of hidden components.
526
527 The `notmuch-show-next-message' and
528 `notmuch-show-previous-message' commands, (bound to 'n' and 'p by
529 default), allow you to navigate to the next and previous
530 messages. Each time you navigate away from a message with
531 `notmuch-show-next-message' the current message will have its
532 \"unread\" tag removed.
533
534 You can add or remove tags from the current message with '+' and
535 '-'.  You can also archive all messages in the current
536 view, (remove the \"inbox\" tag from each), with
537 `notmuch-show-archive-thread' (bound to 'a' by default).
538
539 \\{notmuch-show-mode-map}"
540   (interactive)
541   (kill-all-local-variables)
542   (set (make-local-variable 'notmuch-show-headers-visible) t)
543   (notmuch-show-toggle-headers-visible)
544   (set (make-local-variable 'notmuch-show-body-read-visible) t)
545   (notmuch-show-toggle-body-read-visible)
546   (set (make-local-variable 'notmuch-show-citations-visible) t)
547   (notmuch-show-toggle-citations-visible)
548   (set (make-local-variable 'notmuch-show-signatures-visible) t)
549   (notmuch-show-toggle-signatures-visible)
550   (add-to-invisibility-spec 'notmuch-show-marker)
551   (use-local-map notmuch-show-mode-map)
552   (setq major-mode 'notmuch-show-mode
553         mode-name "notmuch-show")
554   (setq buffer-read-only t))
555
556 (defun notmuch-show (thread-id &optional parent-buffer)
557   "Run \"notmuch show\" with the given thread ID and display results.
558
559 The optional PARENT-BUFFER is the notmuch-search buffer from
560 which this notmuch-show command was executed, (so that the next
561 thread from that buffer can be show when done with this one)."
562   (interactive "sNotmuch show: ")
563   (let ((buffer (get-buffer-create (concat "*notmuch-show-" thread-id "*"))))
564     (switch-to-buffer buffer)
565     (notmuch-show-mode)
566     (set (make-local-variable 'notmuch-show-parent-buffer) parent-buffer)
567     (let ((proc (get-buffer-process (current-buffer)))
568           (inhibit-read-only t))
569       (if proc
570           (error "notmuch search process already running for query `%s'" query)
571         )
572       (erase-buffer)
573       (goto-char (point-min))
574       (save-excursion
575         (call-process "notmuch" nil t nil "show" thread-id)
576         (notmuch-show-markup-messages)
577         )
578       ; Move straight to the first unread message
579       (if (not (notmuch-show-message-unread-p))
580           (progn
581             (notmuch-show-next-unread-message)
582             ; But if there are no unread messages, go back to the
583             ; beginning of the buffer, and open up the bodies of all
584             ; read message.
585             (if (not (notmuch-show-message-unread-p))
586                 (progn
587                   (goto-char (point-min))
588                   (notmuch-show-toggle-body-read-visible)))))
589       )))
590
591 (defvar notmuch-search-mode-map
592   (let ((map (make-sparse-keymap)))
593     (define-key map "a" 'notmuch-search-archive-thread)
594     (define-key map "b" 'notmuch-search-scroll-down)
595     (define-key map "f" 'notmuch-search-filter)
596     (define-key map "n" 'next-line)
597     (define-key map "p" 'previous-line)
598     (define-key map "q" 'kill-this-buffer)
599     (define-key map "s" 'notmuch-search)
600     (define-key map "t" 'notmuch-search-filter-by-tag)
601     (define-key map "x" 'kill-this-buffer)
602     (define-key map (kbd "RET") 'notmuch-search-show-thread)
603     (define-key map "+" 'notmuch-search-add-tag)
604     (define-key map "-" 'notmuch-search-remove-tag)
605     (define-key map "<" 'beginning-of-buffer)
606     (define-key map ">" 'notmuch-search-goto-last-thread)
607     (define-key map "=" 'notmuch-search-refresh-view)
608     (define-key map "\M->" 'notmuch-search-goto-last-thread)
609     (define-key map " " 'notmuch-search-scroll-up)
610     (define-key map (kbd "<DEL>") 'notmuch-search-scroll-down)
611     map)
612   "Keymap for \"notmuch search\" buffers.")
613 (fset 'notmuch-search-mode-map notmuch-search-mode-map)
614
615 (defun notmuch-search-scroll-up ()
616   "Scroll up, moving point to last message in thread if at end."
617   (interactive)
618   (condition-case nil
619       (scroll-up nil)
620     ((end-of-buffer) (notmuch-search-goto-last-thread))))
621
622 (defun notmuch-search-scroll-down ()
623   "Scroll down, moving point to first message in thread if at beginning."
624   (interactive)
625   ; I don't know why scroll-down doesn't signal beginning-of-buffer
626   ; the way that scroll-up signals end-of-buffer, but c'est la vie.
627   ;
628   ; So instead of trapping a signal we instead check whether the
629   ; window begins on the first line of the buffer and if so, move
630   ; directly to that position. (We have to count lines since the
631   ; window-start position is not the same as point-min due to the
632   ; invisible thread-ID characters on the first line.
633   (if (equal (count-lines (point-min) (window-start)) 1)
634       (goto-char (window-start))
635     (scroll-down nil)))
636
637 (defun notmuch-search-goto-last-thread (&optional arg)
638   "Move point to the last thread in the buffer."
639   (interactive "^P")
640   (end-of-buffer arg)
641   (forward-line -1))
642
643 ;;;###autoload
644 (defun notmuch-search-mode ()
645   "Major mode for searching mail with notmuch.
646
647 This buffer contains the results of a \"notmuch search\" of your
648 email archives. Each line in the buffer represents a single
649 thread giving a relative date for the thread and a subject.
650
651 Pressing RET on any line displays that thread. The '+' and '-'
652 keys can be used to add or remove tags from a thread. The 'a' key
653 is a convenience key for archiving a thread (removing the
654 \"inbox\" tag).
655
656 Other useful commands are `notmuch-search-filter' for filtering
657 the current search based on an additional query string,
658 `notmuch-search-filter-by-tag' for filtering to include only
659 messages with a given tag, and `notmuch-search' to execute a new,
660 global search.
661
662 \\{notmuch-search-mode-map}"
663   (interactive)
664   (kill-all-local-variables)
665   (make-local-variable 'notmuch-search-query-string)
666   (set (make-local-variable 'scroll-preserve-screen-position) t)
667   (add-to-invisibility-spec 'notmuch-search)
668   (use-local-map notmuch-search-mode-map)
669   (setq major-mode 'notmuch-search-mode
670         mode-name "notmuch-search")
671   (setq buffer-read-only t))
672
673 (defun notmuch-search-find-thread-id ()
674   (save-excursion
675     (beginning-of-line)
676     (let ((beg (point)))
677       (re-search-forward "thread:[a-fA-F0-9]*")
678       (filter-buffer-substring beg (point)))))
679
680 (defun notmuch-search-markup-this-thread-id ()
681   (beginning-of-line)
682   (let ((beg (point)))
683     (re-search-forward "thread:[a-fA-F0-9]*")
684     (forward-char)
685     (overlay-put (make-overlay beg (point)) 'invisible 'notmuch-search)))
686
687 (defun notmuch-search-markup-thread-ids ()
688   (save-excursion
689     (goto-char (point-min))
690     (while (not (eobp))
691       (notmuch-search-markup-this-thread-id)
692       (next-line))))
693
694 (defun notmuch-search-hide-thread-ids ()
695   (interactive)
696   (add-to-invisibility-spec 'notmuch-search)
697   (force-window-update)
698   (redisplay t))
699
700 (defun notmuch-search-show-thread-ids ()
701   (interactive)
702   (remove-from-invisibility-spec 'notmuch-search)
703   (force-window-update)
704   (redisplay t))
705
706 (defun notmuch-search-show-thread ()
707   (interactive)
708   (let ((thread-id (notmuch-search-find-thread-id)))
709     (forward-line)
710     (if (> (length thread-id) 0)
711         (notmuch-show thread-id (current-buffer))
712       (error "End of search results"))))
713
714 (defun notmuch-call-notmuch-process (&rest args)
715   "Synchronously invoke \"notmuch\" with the given list of arguments.
716
717 Output from the process will be presented to the user as an error
718 and will also appear in a buffer named \"*Notmuch errors*\"."
719   (let ((error-buffer (get-buffer-create "*Notmuch errors*")))
720     (with-current-buffer error-buffer
721         (erase-buffer))
722     (if (eq (apply 'call-process "notmuch" nil error-buffer nil args) 0)
723         (point)
724       (progn
725         (with-current-buffer error-buffer
726           (let ((beg (point-min))
727                 (end (- (point-max) 1)))
728             (error (buffer-substring beg end))
729             ))))))
730
731 (defun notmuch-search-set-tags (tags)
732   (save-excursion
733     (end-of-line)
734     (re-search-backward "(")
735     (forward-char)
736     (let ((beg (point))
737           (inhibit-read-only t))
738       (re-search-forward ")")
739       (backward-char)
740       (let ((end (point)))
741         (delete-region beg end)
742         (insert (mapconcat  'identity tags " "))))))
743
744 (defun notmuch-search-get-tags ()
745   (save-excursion
746     (end-of-line)
747     (re-search-backward "(")
748     (let ((beg (+ (point) 1)))
749       (re-search-forward ")")
750       (let ((end (- (point) 1)))
751         (split-string (buffer-substring beg end))))))
752
753 (defun notmuch-search-add-tag (tag)
754   (interactive "sTag to add: ")
755   (notmuch-call-notmuch-process "tag" (concat "+" tag) (concat "thread:" (notmuch-search-find-thread-id)))
756   (notmuch-search-set-tags (delete-dups (sort (cons tag (notmuch-search-get-tags)) 'string<))))
757
758 (defun notmuch-search-remove-tag (tag)
759   (interactive "sTag to remove: ")
760   (notmuch-call-notmuch-process "tag" (concat "-" tag) (concat "thread:" (notmuch-search-find-thread-id)))
761   (notmuch-search-set-tags (delete tag (notmuch-search-get-tags))))
762
763 (defun notmuch-search-archive-thread ()
764   "Archive the current thread (remove its \"inbox\" tag).
765
766 This function advances point to the next line when finished."
767   (interactive)
768   (notmuch-search-remove-tag "inbox")
769   (forward-line))
770
771 (defun notmuch-search (query)
772   "Run \"notmuch search\" with the given query string and display results."
773   (interactive "sNotmuch search: ")
774   (let ((buffer (get-buffer-create (concat "*notmuch-search-" query "*"))))
775     (switch-to-buffer buffer)
776     (notmuch-search-mode)
777     (set 'notmuch-search-query-string query)
778     (let ((proc (get-buffer-process (current-buffer)))
779           (inhibit-read-only t))
780       (if proc
781           (error "notmuch search process already running for query `%s'" query)
782         )
783       (erase-buffer)
784       (goto-char (point-min))
785       (save-excursion
786         (call-process "notmuch" nil t nil "search" query)
787         (notmuch-search-markup-thread-ids)
788         ))))
789
790 (defun notmuch-search-refresh-view ()
791   "Refresh the current view.
792
793 Kills the current buffer and runs a new search with the same
794 query string as the current search. If the current thread is in
795 the new search results, then point will be placed on the same
796 thread. Otherwise, point will be moved to attempt to be in the
797 same relative position within the new buffer."
798   (interactive)
799   (let ((here (point))
800         (thread (notmuch-search-find-thread-id))
801         (query notmuch-search-query-string))
802     (kill-this-buffer)
803     (notmuch-search query)
804     (goto-char (point-min))
805     (if (re-search-forward (concat "^" thread) nil t)
806         (beginning-of-line)
807       (goto-char here))))
808
809 (defun notmuch-search-filter (query)
810   "Filter the current search results based on an additional query string.
811
812 Runs a new search matching only messages that match both the
813 current search results AND the additional query string provided."
814   (interactive "sFilter search: ")
815   (notmuch-search (concat notmuch-search-query-string " and " query)))
816
817 (defun notmuch-search-filter-by-tag (tag)
818   "Filter the current search results based on a single tag.
819
820 Runs a new search matching only messages that match both the
821 current search results AND that are tagged with the given tag."
822   (interactive "sFilter by tag: ")
823   (notmuch-search (concat notmuch-search-query-string " and tag:" tag)))
824
825 (defun notmuch ()
826   "Run notmuch to display all mail with tag of 'inbox'"
827   (interactive)
828   (notmuch-search "tag:inbox"))
829
830 (provide 'notmuch)