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