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