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