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