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