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