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