]> git.notmuchmail.org Git - notmuch/blob - notmuch.el
notmuch: Break notmuch.c up into several smaller files.
[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           (forward-line)
188           (notmuch-search-show-thread)))))
189
190 (defun notmuch-show-mark-read-then-archive-thread ()
191   "Remove \"unread\" tag from each message, then archive and show next thread.
192
193 Archive each message currrently shown by removing the \"unread\"
194 and \"inbox\" tag from each. Then kill this buffer and show the
195 next thread from the search from which this thread was originally
196 shown.
197
198 Note: This command is safe from any race condition of new messages
199 being delivered to the same thread. It does not archive the
200 entire thread, but only the messages shown in the current
201 buffer."
202   (interactive)
203   (notmuch-show-archive-thread-maybe-mark-read t))
204
205 (defun notmuch-show-archive-thread ()
206   "Archive each message in thread, and show next thread from search.
207
208 Archive each message currrently shown by removing the \"inbox\"
209 tag from each. Then kill this buffer and show the next thread
210 from the search from which this thread was originally shown.
211
212 Note: This command is safe from any race condition of new messages
213 being delivered to the same thread. It does not archive the
214 entire thread, but only the messages shown in the current
215 buffer."
216   (interactive)
217   (notmuch-show-archive-thread-maybe-mark-read nil))
218
219 (defun notmuch-show-view-raw-message ()
220   "View the raw email of the current message."
221   (interactive)
222   (view-file (notmuch-show-get-filename)))
223
224 (defun notmuch-show-pipe-message (command)
225   "Pipe the contents of the current message to the given command.
226
227 The given command will be executed with the raw contents of the
228 current email message as stdin. Anything printed by the command
229 to stdout or stderr will appear in the *Messages* buffer."
230   (interactive "sPipe message to command: ")
231   (apply 'start-process-shell-command "notmuch-pipe-command" "*notmuch-pipe*" (split-string (concat command " < " (notmuch-show-get-filename)))))
232
233 (defun notmuch-show-move-to-current-message-summary-line ()
234   "Move to the beginning of the one-line summary of the current message.
235
236 This gives us a stable place to move to and work from since the
237 summary line is always visible. This is important since moving to
238 an invisible location is unreliable, (the main command loop moves
239 point either forward or backward to the next visible character
240 when a command ends with point on an invisible character).
241
242 Emits an error if point is not within a valid message, (that is
243 not pattern of `notmuch-show-message-begin-regexp' could be found
244 by searching backward)."
245   (beginning-of-line)
246   (if (not (looking-at notmuch-show-message-begin-regexp))
247       (if (re-search-backward notmuch-show-message-begin-regexp nil t)
248           (forward-line 2)
249         (error "Not within a valid message."))
250     (forward-line 2)))
251
252 (defun notmuch-show-last-message-p ()
253   "Predicate testing whether point is within the last message."
254   (save-window-excursion
255     (save-excursion
256       (notmuch-show-move-to-current-message-summary-line)
257       (not (re-search-forward notmuch-show-message-begin-regexp nil t)))))
258
259 (defun notmuch-show-message-unread-p ()
260   "Preficate testing whether current message is unread."
261   (member "unread" (notmuch-show-get-tags)))
262
263 (defun notmuch-show-next-message ()
264   "Advance to the beginning of the next message in the buffer.
265
266 Moves to the last visible character of the current message if
267 already on the last message in the buffer."
268   (interactive)
269   (notmuch-show-move-to-current-message-summary-line)
270   (if (re-search-forward notmuch-show-message-begin-regexp nil t)
271       (notmuch-show-move-to-current-message-summary-line)
272     (goto-char (- (point-max) 1))
273     (while (point-invisible-p)
274       (backward-char)))
275   (recenter 0))
276
277 (defun notmuch-show-find-next-message ()
278   "Returns the position of the next message in the buffer.
279
280 Or the position of the last visible character of the current
281 message if already within the last message in the buffer."
282   ; save-excursion doesn't save our window position
283   ; save-window-excursion doesn't save point
284   ; Looks like we have to use both.
285   (save-excursion
286     (save-window-excursion
287       (notmuch-show-next-message)
288       (point))))
289
290 (defun notmuch-show-next-unread-message ()
291   "Advance to the beginning of the next unread message in the buffer.
292
293 Moves to the last visible character of the current message if
294 there are no more unread messages past the current point."
295   (notmuch-show-next-message)
296   (while (and (not (notmuch-show-last-message-p))
297               (not (notmuch-show-message-unread-p)))
298     (notmuch-show-next-message))
299   (if (not (notmuch-show-message-unread-p))
300       (notmuch-show-next-message)))
301
302 (defun notmuch-show-next-open-message ()
303   "Advance to the the next message which is not hidden.
304
305 If read messages are currently hidden, advance to the next unread
306 message. Otherwise, advance to the next message."
307   (if (or (memq 'notmuch-show-body-read buffer-invisibility-spec)
308           (assq 'notmuch-show-body-read buffer-invisibility-spec))
309       (notmuch-show-next-unread-message)
310     (notmuch-show-next-message)))
311
312 (defun notmuch-show-previous-message ()
313   "Backup to the beginning of the previous message in the buffer.
314
315 If within a message rather than at the beginning of it, then
316 simply move to the beginning of the current message."
317   (interactive)
318   (let ((start (point)))
319     (notmuch-show-move-to-current-message-summary-line)
320     (if (not (< (point) start))
321         ; Go backward twice to skip the current message's marker
322         (progn
323           (re-search-backward notmuch-show-message-begin-regexp nil t)
324           (re-search-backward notmuch-show-message-begin-regexp nil t)
325           (notmuch-show-move-to-current-message-summary-line)
326           ))
327     (recenter 0)))
328
329 (defun notmuch-show-find-previous-message ()
330   "Returns the position of the previous message in the buffer.
331
332 Or the position of the beginning of the current message if point
333 is originally within the message rather than at the beginning of
334 it."
335   ; save-excursion doesn't save our window position
336   ; save-window-excursion doesn't save point
337   ; Looks like we have to use both.
338   (save-excursion
339     (save-window-excursion
340       (notmuch-show-previous-message)
341       (point))))
342
343 (defun notmuch-show-mark-read-then-next-open-message ()
344   "Remove unread tag from current message, then advance to next unread message."
345   (interactive)
346   (notmuch-show-remove-tag "unread")
347   (notmuch-show-next-open-message))
348
349 (defun notmuch-show-rewind ()
350   "Do reverse scrolling compared to `notmuch-show-advance-marking-read-and-archiving'
351
352 Specifically, if the beginning of the previous email is fewer
353 than `window-height' lines from the current point, move to it
354 just like `notmuch-show-previous-message'.
355
356 Otherwise, just scroll down a screenful of the current message.
357
358 This command does not modify any message tags, (it does not undo
359 any effects from previous calls to
360 `notmuch-show-advance-marking-read-and-archiving'."
361   (interactive)
362   (let ((previous (notmuch-show-find-previous-message)))
363     (if (> (count-lines previous (point)) (- (window-height) next-screen-context-lines))
364         (progn
365           (condition-case nil
366               (scroll-down nil)
367             ((beginning-of-buffer) nil))
368           (goto-char (window-start)))
369       (notmuch-show-previous-message))))
370
371 (defun notmuch-show-advance-marking-read-and-archiving ()
372   "Advance through buffer, marking read and archiving.
373
374 This command is intended to be one of the simplest ways to
375 process a thread of email. It does the following:
376
377 If the current message in the thread is not yet fully visible,
378 scroll by a near screenful to read more of the message.
379
380 Otherwise, (the end of the current message is already within the
381 current window), remove the \"unread\" tag (if present) from the
382 current message and advance to the next open message.
383
384 Finally, if there is no further message to advance to, and this
385 last message is already read, then archive the entire current
386 thread, (remove the \"inbox\" tag from each message). Also kill
387 this buffer, and display the next thread from the search from
388 which this thread was originally shown."
389   (interactive)
390   (let ((next (notmuch-show-find-next-message))
391         (unread (notmuch-show-message-unread-p)))
392     (if (> next (window-end))
393         (scroll-up nil)
394       (let ((last (notmuch-show-last-message-p)))
395         (notmuch-show-mark-read-then-next-open-message)
396         (if last
397             (notmuch-show-archive-thread))))))
398
399 (defun notmuch-show-markup-citations-region (beg end)
400   (goto-char beg)
401   (beginning-of-line)
402   (while (< (point) end)
403     (let ((beg-sub (point)))
404       (if (looking-at ">")
405           (progn
406             (while (looking-at ">")
407               (forward-line))
408             (let ((overlay (make-overlay beg-sub (point))))
409               (overlay-put overlay 'invisible 'notmuch-show-citation)
410               (overlay-put overlay 'before-string
411                            (concat "[" (number-to-string (count-lines beg-sub (point)))
412                                    "-line citation. Press 'c' to show.]\n")))))
413       (if (looking-at "--[ ]?$")
414           (let ((sig-lines (count-lines beg-sub end)))
415             (if (<= sig-lines notmuch-show-signature-lines-max)
416                 (progn
417                   (overlay-put (make-overlay beg-sub (+ beg-sub 1))
418                                'before-string
419                                (concat "[" (number-to-string sig-lines)
420                                        "-line signature. Press 's' to show.]"))
421                   (overlay-put (make-overlay (+ beg-sub 2) end)
422                                'invisible 'notmuch-show-signature)
423                   (goto-char end)))))
424       (forward-line))))
425
426 (defun notmuch-show-markup-body ()
427   (re-search-forward notmuch-show-body-begin-regexp)
428   (next-line 1)
429   (beginning-of-line)
430   (let ((beg (point)))
431     (re-search-forward notmuch-show-body-end-regexp)
432     (let ((end (match-beginning 0)))
433       (notmuch-show-markup-citations-region beg end)
434       (if (not (notmuch-show-message-unread-p))
435           (overlay-put (make-overlay beg end)
436                        'invisible 'notmuch-show-body-read)))))
437
438 (defun notmuch-show-markup-header ()
439   (re-search-forward notmuch-show-header-begin-regexp)
440   (forward-line 1)
441   (beginning-of-line)
442   (let ((beg (point)))
443     (end-of-line)
444     ; Inverse video for subject
445     (overlay-put (make-overlay beg (point)) 'face '((cons :inverse-video t)))
446     (beginning-of-line)
447     (forward-line 2)
448     (set 'beg (point))
449     (re-search-forward notmuch-show-header-end-regexp)
450     (overlay-put (make-overlay beg (match-beginning 0))
451                  'invisible 'notmuch-show-header)))
452
453 (defun notmuch-show-markup-message ()
454   (if (re-search-forward notmuch-show-message-begin-regexp nil t)
455       (progn
456         (notmuch-show-markup-header)
457         (notmuch-show-markup-body))
458     (goto-char (point-max))))
459
460 (defun notmuch-show-hide-markers ()
461   (save-excursion
462     (goto-char (point-min))
463     (while (not (eobp))
464       (if (re-search-forward notmuch-show-marker-regexp nil t)
465           (progn
466             (overlay-put (make-overlay (match-beginning 0) (+ (match-end 0) 1))
467                          'invisible 'notmuch-show-marker))
468         (goto-char (point-max))))))
469
470 (defun notmuch-show-markup-messages ()
471   (save-excursion
472     (goto-char (point-min))
473     (while (not (eobp))
474       (notmuch-show-markup-message)))
475   (notmuch-show-hide-markers))
476
477 (defun notmuch-show-toggle-citations-visible ()
478   "Toggle visibility of citations"
479   (interactive)
480   (if notmuch-show-citations-visible
481       (add-to-invisibility-spec 'notmuch-show-citation)
482     (remove-from-invisibility-spec 'notmuch-show-citation))
483   (set 'notmuch-show-citations-visible (not notmuch-show-citations-visible))
484   ; Need to force the redisplay for some reason
485   (force-window-update)
486   (redisplay t))
487
488 (defun notmuch-show-toggle-signatures-visible ()
489   "Toggle visibility of signatures"
490   (interactive)
491   (if notmuch-show-signatures-visible
492       (add-to-invisibility-spec 'notmuch-show-signature)
493     (remove-from-invisibility-spec 'notmuch-show-signature))
494   (set 'notmuch-show-signatures-visible (not notmuch-show-signatures-visible))
495   ; Need to force the redisplay for some reason
496   (force-window-update)
497   (redisplay t))
498
499 (defun notmuch-show-toggle-headers-visible ()
500   "Toggle visibility of header fields"
501   (interactive)
502   (if notmuch-show-headers-visible
503       (add-to-invisibility-spec 'notmuch-show-header)
504     (remove-from-invisibility-spec 'notmuch-show-header))
505   (set 'notmuch-show-headers-visible (not notmuch-show-headers-visible))
506   ; Need to force the redisplay for some reason
507   (force-window-update)
508   (redisplay t))
509
510 (defun notmuch-show-toggle-body-read-visible ()
511   "Toggle visibility of message bodies of read messages"
512   (interactive)
513   (if notmuch-show-body-read-visible
514       (add-to-invisibility-spec 'notmuch-show-body-read)
515     (remove-from-invisibility-spec 'notmuch-show-body-read))
516   (set 'notmuch-show-body-read-visible (not notmuch-show-body-read-visible))
517   ; Need to force the redisplay for some reason
518   (force-window-update)
519   (redisplay t))
520
521 ;;;###autoload
522 (defun notmuch-show-mode ()
523   "Major mode for viewing a thread with notmuch.
524
525 This buffer contains the results of the \"notmuch show\" command
526 for displaying a single thread of email from your email archives.
527
528 By default, various components of email messages, (citations,
529 signatures, already-read messages), are invisible to help you
530 focus on the most important things, (new text from unread
531 messages). See the various commands below for toggling the
532 visibility of hidden components.
533
534 The `notmuch-show-next-message' and
535 `notmuch-show-previous-message' commands, (bound to 'n' and 'p by
536 default), allow you to navigate to the next and previous
537 messages. Each time you navigate away from a message with
538 `notmuch-show-next-message' the current message will have its
539 \"unread\" tag removed.
540
541 You can add or remove tags from the current message with '+' and
542 '-'.  You can also archive all messages in the current
543 view, (remove the \"inbox\" tag from each), with
544 `notmuch-show-archive-thread' (bound to 'a' by default).
545
546 \\{notmuch-show-mode-map}"
547   (interactive)
548   (kill-all-local-variables)
549   (set (make-local-variable 'notmuch-show-headers-visible) t)
550   (notmuch-show-toggle-headers-visible)
551   (set (make-local-variable 'notmuch-show-body-read-visible) t)
552   (notmuch-show-toggle-body-read-visible)
553   (set (make-local-variable 'notmuch-show-citations-visible) t)
554   (notmuch-show-toggle-citations-visible)
555   (set (make-local-variable 'notmuch-show-signatures-visible) t)
556   (notmuch-show-toggle-signatures-visible)
557   (add-to-invisibility-spec 'notmuch-show-marker)
558   (use-local-map notmuch-show-mode-map)
559   (setq major-mode 'notmuch-show-mode
560         mode-name "notmuch-show")
561   (setq buffer-read-only t))
562
563 (defun notmuch-show (thread-id &optional parent-buffer)
564   "Run \"notmuch show\" with the given thread ID and display results.
565
566 The optional PARENT-BUFFER is the notmuch-search buffer from
567 which this notmuch-show command was executed, (so that the next
568 thread from that buffer can be show when done with this one)."
569   (interactive "sNotmuch show: ")
570   (let ((buffer (get-buffer-create (concat "*notmuch-show-" thread-id "*"))))
571     (switch-to-buffer buffer)
572     (notmuch-show-mode)
573     (set (make-local-variable 'notmuch-show-parent-buffer) parent-buffer)
574     (let ((proc (get-buffer-process (current-buffer)))
575           (inhibit-read-only t))
576       (if proc
577           (error "notmuch search process already running for query `%s'" query)
578         )
579       (erase-buffer)
580       (goto-char (point-min))
581       (save-excursion
582         (call-process "notmuch" nil t nil "show" thread-id)
583         (notmuch-show-markup-messages)
584         )
585       ; Move straight to the first unread message
586       (if (not (notmuch-show-message-unread-p))
587           (progn
588             (notmuch-show-next-unread-message)
589             ; But if there are no unread messages, go back to the
590             ; beginning of the buffer, and open up the bodies of all
591             ; read message.
592             (if (not (notmuch-show-message-unread-p))
593                 (progn
594                   (goto-char (point-min))
595                   (notmuch-show-toggle-body-read-visible)))))
596       )))
597
598 (defvar notmuch-search-mode-map
599   (let ((map (make-sparse-keymap)))
600     (define-key map "a" 'notmuch-search-archive-thread)
601     (define-key map "b" 'notmuch-search-scroll-down)
602     (define-key map "f" 'notmuch-search-filter)
603     (define-key map "n" 'next-line)
604     (define-key map "p" 'previous-line)
605     (define-key map "q" 'kill-this-buffer)
606     (define-key map "s" 'notmuch-search)
607     (define-key map "t" 'notmuch-search-filter-by-tag)
608     (define-key map "x" 'kill-this-buffer)
609     (define-key map (kbd "RET") 'notmuch-search-show-thread)
610     (define-key map "+" 'notmuch-search-add-tag)
611     (define-key map "-" 'notmuch-search-remove-tag)
612     (define-key map "<" 'beginning-of-buffer)
613     (define-key map ">" 'notmuch-search-goto-last-thread)
614     (define-key map "=" 'notmuch-search-refresh-view)
615     (define-key map "\M->" 'notmuch-search-goto-last-thread)
616     (define-key map " " 'notmuch-search-scroll-up)
617     (define-key map (kbd "<DEL>") 'notmuch-search-scroll-down)
618     map)
619   "Keymap for \"notmuch search\" buffers.")
620 (fset 'notmuch-search-mode-map notmuch-search-mode-map)
621
622 (defun notmuch-search-scroll-up ()
623   "Scroll up, moving point to last message in thread if at end."
624   (interactive)
625   (condition-case nil
626       (scroll-up nil)
627     ((end-of-buffer) (notmuch-search-goto-last-thread))))
628
629 (defun notmuch-search-scroll-down ()
630   "Scroll down, moving point to first message in thread if at beginning."
631   (interactive)
632   ; I don't know why scroll-down doesn't signal beginning-of-buffer
633   ; the way that scroll-up signals end-of-buffer, but c'est la vie.
634   ;
635   ; So instead of trapping a signal we instead check whether the
636   ; window begins on the first line of the buffer and if so, move
637   ; directly to that position. (We have to count lines since the
638   ; window-start position is not the same as point-min due to the
639   ; invisible thread-ID characters on the first line.
640   (if (equal (count-lines (point-min) (window-start)) 1)
641       (goto-char (window-start))
642     (scroll-down nil)))
643
644 (defun notmuch-search-goto-last-thread (&optional arg)
645   "Move point to the last thread in the buffer."
646   (interactive "^P")
647   (end-of-buffer arg)
648   (forward-line -1))
649
650 ;;;###autoload
651 (defun notmuch-search-mode ()
652   "Major mode for searching mail with notmuch.
653
654 This buffer contains the results of a \"notmuch search\" of your
655 email archives. Each line in the buffer represents a single
656 thread giving a relative date for the thread and a subject.
657
658 Pressing RET on any line displays that thread. The '+' and '-'
659 keys can be used to add or remove tags from a thread. The 'a' key
660 is a convenience key for archiving a thread (removing the
661 \"inbox\" tag).
662
663 Other useful commands are `notmuch-search-filter' for filtering
664 the current search based on an additional query string,
665 `notmuch-search-filter-by-tag' for filtering to include only
666 messages with a given tag, and `notmuch-search' to execute a new,
667 global search.
668
669 \\{notmuch-search-mode-map}"
670   (interactive)
671   (kill-all-local-variables)
672   (make-local-variable 'notmuch-search-query-string)
673   (set (make-local-variable 'scroll-preserve-screen-position) t)
674   (add-to-invisibility-spec 'notmuch-search)
675   (use-local-map notmuch-search-mode-map)
676   (setq major-mode 'notmuch-search-mode
677         mode-name "notmuch-search")
678   (setq buffer-read-only t))
679
680 (defun notmuch-search-find-thread-id ()
681   (save-excursion
682     (beginning-of-line)
683     (let ((beg (point)))
684       (re-search-forward "thread:[a-fA-F0-9]*" nil t)
685       (filter-buffer-substring beg (point)))))
686
687 (defun notmuch-search-markup-this-thread-id ()
688   (beginning-of-line)
689   (let ((beg (point)))
690     (if (re-search-forward "thread:[a-fA-F0-9]*" nil t)
691         (progn
692           (forward-char)
693           (overlay-put (make-overlay beg (point)) 'invisible 'notmuch-search)))))
694
695 (defun notmuch-search-markup-thread-ids ()
696   (save-excursion
697     (goto-char (point-min))
698     (while (not (eobp))
699       (notmuch-search-markup-this-thread-id)
700       (next-line))))
701
702 (defun notmuch-search-hide-thread-ids ()
703   (interactive)
704   (add-to-invisibility-spec 'notmuch-search)
705   (force-window-update)
706   (redisplay t))
707
708 (defun notmuch-search-show-thread-ids ()
709   (interactive)
710   (remove-from-invisibility-spec 'notmuch-search)
711   (force-window-update)
712   (redisplay t))
713
714 (defun notmuch-search-show-thread ()
715   (interactive)
716   (let ((thread-id (notmuch-search-find-thread-id)))
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) (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) (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)