]> git.notmuchmail.org Git - notmuch/blob - notmuch.el
notmuch search: Remove the chunked-searching hack.
[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 2)
609     (let ((beg-hidden (point-marker)))
610       (re-search-forward notmuch-show-header-end-regexp)
611       (beginning-of-line)
612       (let ((end (point-marker)))
613         (goto-char beg)
614         (forward-line)
615         (while (looking-at "[A-Za-z][-A-Za-z0-9]*:")
616           (beginning-of-line)
617           (overlay-put (make-overlay (point) (re-search-forward ":"))
618                        'face 'bold)
619           (forward-line)
620           )
621         (indent-rigidly beg end depth)
622         (overlay-put (make-overlay beg-hidden end)
623                      'invisible 'notmuch-show-header)
624         (goto-char end)
625         (insert "\n")
626         (set-marker beg nil)
627         (set-marker beg-hidden nil)
628         (set-marker end nil)
629         ))))
630
631 (defun notmuch-show-markup-message ()
632   (if (re-search-forward notmuch-show-message-begin-regexp nil t)
633       (progn
634         (re-search-forward notmuch-show-depth-regexp)
635         (let ((depth (string-to-number (buffer-substring (match-beginning 1) (match-end 1)))))
636           (notmuch-show-markup-header depth)
637           (notmuch-show-markup-body depth)))
638     (goto-char (point-max))))
639
640 (defun notmuch-show-hide-markers ()
641   (save-excursion
642     (goto-char (point-min))
643     (while (not (eobp))
644       (if (re-search-forward notmuch-show-marker-regexp nil t)
645           (progn
646             (overlay-put (make-overlay (match-beginning 0) (+ (match-end 0) 1))
647                          'invisible 'notmuch-show-marker))
648         (goto-char (point-max))))))
649
650 (defun notmuch-show-markup-messages ()
651   (save-excursion
652     (goto-char (point-min))
653     (while (not (eobp))
654       (notmuch-show-markup-message)))
655   (notmuch-show-hide-markers))
656
657 (defun notmuch-show-toggle-citations-visible ()
658   "Toggle visibility of citations"
659   (interactive)
660   (if notmuch-show-citations-visible
661       (add-to-invisibility-spec 'notmuch-show-citation)
662     (remove-from-invisibility-spec 'notmuch-show-citation))
663   (set 'notmuch-show-citations-visible (not notmuch-show-citations-visible))
664   ; Need to force the redisplay for some reason
665   (force-window-update)
666   (redisplay t))
667
668 (defun notmuch-show-toggle-signatures-visible ()
669   "Toggle visibility of signatures"
670   (interactive)
671   (if notmuch-show-signatures-visible
672       (add-to-invisibility-spec 'notmuch-show-signature)
673     (remove-from-invisibility-spec 'notmuch-show-signature))
674   (set 'notmuch-show-signatures-visible (not notmuch-show-signatures-visible))
675   ; Need to force the redisplay for some reason
676   (force-window-update)
677   (redisplay t))
678
679 (defun notmuch-show-toggle-headers-visible ()
680   "Toggle visibility of header fields"
681   (interactive)
682   (if notmuch-show-headers-visible
683       (add-to-invisibility-spec 'notmuch-show-header)
684     (remove-from-invisibility-spec 'notmuch-show-header))
685   (set 'notmuch-show-headers-visible (not notmuch-show-headers-visible))
686   ; Need to force the redisplay for some reason
687   (force-window-update)
688   (redisplay t))
689
690 (defun notmuch-show-toggle-body-read-visible ()
691   "Toggle visibility of message bodies of read messages"
692   (interactive)
693   (if notmuch-show-body-read-visible
694       (add-to-invisibility-spec 'notmuch-show-body-read)
695     (remove-from-invisibility-spec 'notmuch-show-body-read))
696   (set 'notmuch-show-body-read-visible (not notmuch-show-body-read-visible))
697   ; Need to force the redisplay for some reason
698   (force-window-update)
699   (redisplay t))
700
701 ;;;###autoload
702 (defun notmuch-show-mode ()
703   "Major mode for viewing a thread with notmuch.
704
705 This buffer contains the results of the \"notmuch show\" command
706 for displaying a single thread of email from your email archives.
707
708 By default, various components of email messages, (citations,
709 signatures, already-read messages), are invisible to help you
710 focus on the most important things, (new text from unread
711 messages). See the various commands below for toggling the
712 visibility of hidden components.
713
714 The `notmuch-show-next-message' and
715 `notmuch-show-previous-message' commands, (bound to 'n' and 'p by
716 default), allow you to navigate to the next and previous
717 messages. Each time you navigate away from a message with
718 `notmuch-show-next-message' the current message will have its
719 \"unread\" tag removed.
720
721 You can add or remove tags from the current message with '+' and
722 '-'.  You can also archive all messages in the current
723 view, (remove the \"inbox\" tag from each), with
724 `notmuch-show-archive-thread' (bound to 'a' by default).
725
726 \\{notmuch-show-mode-map}"
727   (interactive)
728   (kill-all-local-variables)
729   (set (make-local-variable 'notmuch-show-headers-visible) t)
730   (notmuch-show-toggle-headers-visible)
731   (set (make-local-variable 'notmuch-show-body-read-visible) t)
732   (notmuch-show-toggle-body-read-visible)
733   (set (make-local-variable 'notmuch-show-citations-visible) t)
734   (notmuch-show-toggle-citations-visible)
735   (set (make-local-variable 'notmuch-show-signatures-visible) t)
736   (notmuch-show-toggle-signatures-visible)
737   (add-to-invisibility-spec 'notmuch-show-marker)
738   (use-local-map notmuch-show-mode-map)
739   (setq major-mode 'notmuch-show-mode
740         mode-name "notmuch-show")
741   (setq buffer-read-only t))
742
743 ;;;###autoload
744
745 (defgroup notmuch nil
746   "Notmuch mail reader for Emacs."
747   :group 'mail)
748
749 (defcustom notmuch-show-hook nil
750   "List of functions to call when notmuch displays a message."
751   :type 'hook
752   :options '(goto-address)
753   :group 'notmuch)
754
755 (defcustom notmuch-search-hook nil
756   "List of functions to call when notmuch displays the search results."
757   :type 'hook
758   :options '(hl-line-mode)
759   :group 'notmuch)
760
761 ; Make show mode a bit prettier, highlighting URLs and using word wrap
762
763 (defun notmuch-show-pretty-hook ()
764   (goto-address-mode 1)
765   (visual-line-mode))
766
767 (add-hook 'notmuch-show-hook 'notmuch-show-pretty-hook)
768 (add-hook 'notmuch-search-hook
769           (lambda()
770             (hl-line-mode 1) ))
771
772 (defun notmuch-show (thread-id &optional parent-buffer)
773   "Run \"notmuch show\" with the given thread ID and display results.
774
775 The optional PARENT-BUFFER is the notmuch-search buffer from
776 which this notmuch-show command was executed, (so that the next
777 thread from that buffer can be show when done with this one)."
778   (interactive "sNotmuch show: ")
779   (let ((buffer (get-buffer-create (concat "*notmuch-show-" thread-id "*"))))
780     (switch-to-buffer buffer)
781     (notmuch-show-mode)
782     (set (make-local-variable 'notmuch-show-parent-buffer) parent-buffer)
783     (let ((proc (get-buffer-process (current-buffer)))
784           (inhibit-read-only t))
785       (if proc
786           (error "notmuch search process already running for query `%s'" thread-id)
787         )
788       (erase-buffer)
789       (goto-char (point-min))
790       (save-excursion
791         (call-process notmuch-command nil t nil "show" thread-id)
792         (notmuch-show-markup-messages)
793         )
794       (run-hooks 'notmuch-show-hook)
795       ; Move straight to the first unread message
796       (if (not (notmuch-show-message-unread-p))
797           (progn
798             (notmuch-show-next-unread-message)
799             ; But if there are no unread messages, go back to the
800             ; beginning of the buffer, and open up the bodies of all
801             ; read message.
802             (if (not (notmuch-show-message-unread-p))
803                 (progn
804                   (goto-char (point-min))
805                   (notmuch-show-toggle-body-read-visible)))))
806       )))
807
808 (defvar notmuch-search-authors-width 40
809   "Number of columns to use to display authors in a notmuch-search buffer.")
810
811 (defvar notmuch-search-mode-map
812   (let ((map (make-sparse-keymap)))
813     (define-key map "a" 'notmuch-search-archive-thread)
814     (define-key map "b" 'notmuch-search-scroll-down)
815     (define-key map "f" 'notmuch-search-filter)
816     (define-key map "m" 'message-mail)
817     (define-key map "n" 'next-line)
818     (define-key map "o" 'notmuch-search-toggle-order)
819     (define-key map "p" 'previous-line)
820     (define-key map "q" 'kill-this-buffer)
821     (define-key map "r" 'notmuch-search-reply-to-thread)
822     (define-key map "s" 'notmuch-search)
823     (define-key map "t" 'notmuch-search-filter-by-tag)
824     (define-key map "x" 'kill-this-buffer)
825     (define-key map (kbd "RET") 'notmuch-search-show-thread)
826     (define-key map [mouse-1] 'notmuch-search-show-thread)
827     (define-key map "+" 'notmuch-search-add-tag)
828     (define-key map "-" 'notmuch-search-remove-tag)
829     (define-key map "<" 'beginning-of-buffer)
830     (define-key map ">" 'notmuch-search-goto-last-thread)
831     (define-key map "=" 'notmuch-search-refresh-view)
832     (define-key map "\M->" 'notmuch-search-goto-last-thread)
833     (define-key map " " 'notmuch-search-scroll-up)
834     (define-key map (kbd "<DEL>") 'notmuch-search-scroll-down)
835     (define-key map "?" 'describe-mode)
836     map)
837   "Keymap for \"notmuch search\" buffers.")
838 (fset 'notmuch-search-mode-map notmuch-search-mode-map)
839
840 (defvar notmuch-search-query-string)
841 (defvar notmuch-search-oldest-first)
842
843 (defun notmuch-search-scroll-up ()
844   "Scroll up, moving point to last message in thread if at end."
845   (interactive)
846   (condition-case nil
847       (scroll-up nil)
848     ((end-of-buffer) (notmuch-search-goto-last-thread))))
849
850 (defun notmuch-search-scroll-down ()
851   "Scroll down, moving point to first message in thread if at beginning."
852   (interactive)
853   ; I don't know why scroll-down doesn't signal beginning-of-buffer
854   ; the way that scroll-up signals end-of-buffer, but c'est la vie.
855   ;
856   ; So instead of trapping a signal we instead check whether the
857   ; window begins on the first line of the buffer and if so, move
858   ; directly to that position. (We have to count lines since the
859   ; window-start position is not the same as point-min due to the
860   ; invisible thread-ID characters on the first line.
861   (if (equal (count-lines (point-min) (window-start)) 1)
862       (goto-char (window-start))
863     (scroll-down nil)))
864
865 (defun notmuch-search-goto-last-thread ()
866   "Move point to the last thread in the buffer."
867   (interactive)
868   (goto-char (point-max))
869   (forward-line -1))
870
871 ;;;###autoload
872 (defun notmuch-search-mode ()
873   "Major mode for searching mail with notmuch.
874
875 This buffer contains the results of a \"notmuch search\" of your
876 email archives. Each line in the buffer represents a single
877 thread giving a relative date for the thread and a subject.
878
879 Pressing RET on any line displays that thread. The '+' and '-'
880 keys can be used to add or remove tags from a thread. The 'a' key
881 is a convenience key for archiving a thread (removing the
882 \"inbox\" tag).
883
884 Other useful commands are `notmuch-search-filter' for filtering
885 the current search based on an additional query string,
886 `notmuch-search-filter-by-tag' for filtering to include only
887 messages with a given tag, and `notmuch-search' to execute a new,
888 global search.
889
890 \\{notmuch-search-mode-map}"
891   (interactive)
892   (kill-all-local-variables)
893   (make-local-variable 'notmuch-search-query-string)
894   (make-local-variable 'notmuch-search-oldest-first)
895   (set (make-local-variable 'scroll-preserve-screen-position) t)
896   (add-to-invisibility-spec 'notmuch-search)
897   (use-local-map notmuch-search-mode-map)
898   (setq truncate-lines t)
899   (setq major-mode 'notmuch-search-mode
900         mode-name "notmuch-search")
901   (setq buffer-read-only t))
902
903 (defun notmuch-search-find-thread-id ()
904   (save-excursion
905     (beginning-of-line)
906     (let ((beg (point)))
907       (re-search-forward "thread:[a-fA-F0-9]*" nil t)
908       (filter-buffer-substring beg (point)))))
909
910 (defun notmuch-search-markup-this-thread-id ()
911   (beginning-of-line)
912   (let ((beg (point)))
913     (if (re-search-forward "thread:[a-fA-F0-9]*" nil t)
914         (progn
915           (forward-char)
916           (overlay-put (make-overlay beg (point)) 'invisible 'notmuch-search)
917           (re-search-forward ".*\\[[0-9]*/[0-9]*\\] \\([^;]*\\)\\(;\\)")
918           (let* ((authors (buffer-substring (match-beginning 1) (match-end 1)))
919                  (authors-length (length authors)))
920             ;; Drop the semi-colon
921             (replace-match "" t nil nil 2)
922             (if (<= authors-length notmuch-search-authors-width)
923                 (replace-match (concat authors (make-string
924                                                 (- notmuch-search-authors-width
925                                                    authors-length) ? )) t t nil 1)
926               (replace-match (concat (substring authors 0 (- notmuch-search-authors-width 3)) "...") t t nil 1)))))))
927
928 (defun notmuch-search-markup-thread-ids ()
929   (save-excursion
930     (goto-char (point-min))
931     (while (not (eobp))
932       (notmuch-search-markup-this-thread-id)
933       (forward-line))))
934
935 (defun notmuch-search-show-thread ()
936   (interactive)
937   (let ((thread-id (notmuch-search-find-thread-id)))
938     (if (> (length thread-id) 0)
939         (notmuch-show thread-id (current-buffer))
940       (error "End of search results"))))
941
942 (defun notmuch-search-reply-to-thread ()
943   "Begin composing a reply to the entire current thread in a new buffer."
944   (interactive)
945   (let ((message-id (notmuch-search-find-thread-id)))
946     (notmuch-reply message-id)))
947
948 (defun notmuch-call-notmuch-process (&rest args)
949   "Synchronously invoke \"notmuch\" with the given list of arguments.
950
951 Output from the process will be presented to the user as an error
952 and will also appear in a buffer named \"*Notmuch errors*\"."
953   (let ((error-buffer (get-buffer-create "*Notmuch errors*")))
954     (with-current-buffer error-buffer
955         (erase-buffer))
956     (if (eq (apply 'call-process notmuch-command nil error-buffer nil args) 0)
957         (point)
958       (progn
959         (with-current-buffer error-buffer
960           (let ((beg (point-min))
961                 (end (- (point-max) 1)))
962             (error (buffer-substring beg end))
963             ))))))
964
965 (defun notmuch-search-set-tags (tags)
966   (save-excursion
967     (end-of-line)
968     (re-search-backward "(")
969     (forward-char)
970     (let ((beg (point))
971           (inhibit-read-only t))
972       (re-search-forward ")")
973       (backward-char)
974       (let ((end (point)))
975         (delete-region beg end)
976         (insert (mapconcat  'identity tags " "))))))
977
978 (defun notmuch-search-get-tags ()
979   (save-excursion
980     (end-of-line)
981     (re-search-backward "(")
982     (let ((beg (+ (point) 1)))
983       (re-search-forward ")")
984       (let ((end (- (point) 1)))
985         (split-string (buffer-substring beg end))))))
986
987 (defun notmuch-search-add-tag (tag)
988   (interactive "sTag to add: ")
989   (notmuch-call-notmuch-process "tag" (concat "+" tag) (notmuch-search-find-thread-id))
990   (notmuch-search-set-tags (delete-dups (sort (cons tag (notmuch-search-get-tags)) 'string<))))
991
992 (defun notmuch-search-remove-tag (tag)
993   (interactive "sTag to remove: ")
994   (notmuch-call-notmuch-process "tag" (concat "-" tag) (notmuch-search-find-thread-id))
995   (notmuch-search-set-tags (delete tag (notmuch-search-get-tags))))
996
997 (defun notmuch-search-archive-thread ()
998   "Archive the current thread (remove its \"inbox\" tag).
999
1000 This function advances point to the next line when finished."
1001   (interactive)
1002   (notmuch-search-remove-tag "inbox")
1003   (forward-line))
1004
1005 (defun notmuch-search (query &optional oldest-first)
1006   "Run \"notmuch search\" with the given query string and display results."
1007   (interactive "sNotmuch search: ")
1008   (let ((buffer (get-buffer-create (concat "*notmuch-search-" query "*"))))
1009     (switch-to-buffer buffer)
1010     (notmuch-search-mode)
1011     (set 'notmuch-search-query-string query)
1012     (set 'notmuch-search-oldest-first oldest-first)
1013     (let ((proc (get-buffer-process (current-buffer)))
1014           (inhibit-read-only t))
1015       (if proc
1016           (error "notmuch search process already running for query `%s'" query)
1017         )
1018       (erase-buffer)
1019       (goto-char (point-min))
1020       (save-excursion
1021         (if oldest-first
1022             (call-process notmuch-command nil t nil "search" "--sort=oldest-first" query)
1023           (call-process notmuch-command nil t nil "search" "--sort=newest-first" query))
1024         (notmuch-search-markup-thread-ids)
1025         ))
1026     (run-hooks 'notmuch-search-hook)))
1027
1028 (defun notmuch-search-refresh-view ()
1029   "Refresh the current view.
1030
1031 Kills the current buffer and runs a new search with the same
1032 query string as the current search. If the current thread is in
1033 the new search results, then point will be placed on the same
1034 thread. Otherwise, point will be moved to attempt to be in the
1035 same relative position within the new buffer."
1036   (interactive)
1037   (let ((here (point))
1038         (oldest-first notmuch-search-oldest-first)
1039         (thread (notmuch-search-find-thread-id))
1040         (query notmuch-search-query-string))
1041     (kill-this-buffer)
1042     (notmuch-search query oldest-first)
1043     (goto-char (point-min))
1044     (if (re-search-forward (concat "^" thread) nil t)
1045         (beginning-of-line)
1046       (goto-char here))))
1047
1048 (defun notmuch-search-toggle-order ()
1049   "Toggle the current search order.
1050
1051 By default, the \"inbox\" view created by `notmuch' is displayed
1052 in chronological order (oldest thread at the beginning of the
1053 buffer), while any global searches created by `notmuch-search'
1054 are displayed in reverse-chronological order (newest thread at
1055 the beginning of the buffer).
1056
1057 This command toggles the sort order for the current search.
1058
1059 Note that any filtered searches created by
1060 `notmuch-search-filter' retain the search order of the parent
1061 search."
1062   (interactive)
1063   (set 'notmuch-search-oldest-first (not notmuch-search-oldest-first))
1064   (notmuch-search-refresh-view))
1065
1066 (defun notmuch-search-filter (query)
1067   "Filter the current search results based on an additional query string.
1068
1069 Runs a new search matching only messages that match both the
1070 current search results AND the additional query string provided."
1071   (interactive "sFilter search: ")
1072   (notmuch-search (concat notmuch-search-query-string " and " query) notmuch-search-oldest-first))
1073
1074 (defun notmuch-search-filter-by-tag (tag)
1075   "Filter the current search results based on a single tag.
1076
1077 Runs a new search matching only messages that match both the
1078 current search results AND that are tagged with the given tag."
1079   (interactive "sFilter by tag: ")
1080   (notmuch-search (concat notmuch-search-query-string " and tag:" tag) notmuch-search-oldest-first))
1081
1082 (defun notmuch ()
1083   "Run notmuch to display all mail with tag of 'inbox'"
1084   (interactive)
1085   (notmuch-search "tag:inbox" t))
1086
1087 (setq mail-user-agent 'message-user-agent)
1088
1089 (defvar notmuch-folder-mode-map
1090   (let ((map (make-sparse-keymap)))
1091     (define-key map "n" 'next-line)
1092     (define-key map "p" 'previous-line)
1093     (define-key map "x" 'kill-this-buffer)
1094     (define-key map "q" 'kill-this-buffer)
1095     (define-key map "s" 'notmuch-search)
1096     (define-key map (kbd "RET") 'notmuch-folder-show-search)
1097     (define-key map "<" 'beginning-of-buffer)
1098     (define-key map "=" 'notmuch-folder)
1099     (define-key map "?" 'describe-mode)
1100     (define-key map [mouse-1] 'notmuch-folder-show-search)
1101     map)
1102   "Keymap for \"notmuch folder\" buffers.")
1103
1104 (fset 'notmuch-folder-mode-map notmuch-folder-mode-map)
1105
1106 (defcustom notmuch-folders (quote (("inbox" . "tag:inbox") ("unread" . "tag:unread")))
1107   "List of searches for the notmuch folder view"
1108   :type '(alist :key-type (string) :value-type (string))
1109   :group 'notmuch)
1110
1111 (defun notmuch-folder-mode ()
1112   "Major mode for showing notmuch 'folders'.
1113
1114 This buffer contains a list of messages counts returned by a
1115 customizable set of searches of your email archives. Each line
1116 in the buffer shows the search terms and the resulting message count.
1117
1118 Pressing RET on any line opens a search window containing the
1119 results for the search terms in that line.
1120
1121 \\{notmuch-folder-mode-map}"
1122   (interactive)
1123   (kill-all-local-variables)
1124   (use-local-map 'notmuch-folder-mode-map)
1125   (setq truncate-lines t)
1126   (hl-line-mode 1)
1127   (setq major-mode 'notmuch-folder-mode
1128         mode-name "notmuch-folder")
1129   (setq buffer-read-only t))
1130
1131 (defun notmuch-folder-add (folders)
1132   (if folders
1133       (let ((name (car (car folders)))
1134             (inhibit-read-only t)
1135             (search (cdr (car folders))))
1136         (insert name)
1137         (indent-to 16 1)
1138         (call-process notmuch-command nil t nil "count" search)
1139         (notmuch-folder-add (cdr folders)))))
1140
1141 (defun notmuch-folder-find-name ()
1142   (save-excursion
1143     (beginning-of-line)
1144     (let ((beg (point)))
1145       (forward-word)
1146       (filter-buffer-substring beg (point)))))
1147
1148 (defun notmuch-folder-show-search (&optional folder)
1149   "Show a search window for the search related to the specified folder."
1150   (interactive)
1151   (if (null folder)
1152       (setq folder (notmuch-folder-find-name)))
1153   (let ((search (assoc folder notmuch-folders)))
1154     (if search
1155         (notmuch-search (cdr search) t))))
1156
1157 (defun notmuch-folder ()
1158   "Show the notmuch folder view and update the displayed counts."
1159   (interactive)
1160   (let ((buffer (get-buffer-create "*notmuch-folders*")))
1161     (switch-to-buffer buffer)
1162     (let ((inhibit-read-only t)
1163           (n (line-number-at-pos)))
1164       (erase-buffer)
1165       (notmuch-folder-mode)
1166       (notmuch-folder-add notmuch-folders)
1167       (goto-char (point-min))
1168       (goto-line n))))
1169
1170 (provide 'notmuch)