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