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