]> git.notmuchmail.org Git - notmuch/blob - notmuch.el
ff4a0bd0205a1afa58837e1054205600917580b2
[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 (require 'message)
53
54 (defvar notmuch-show-mode-map
55   (let ((map (make-sparse-keymap)))
56     (define-key map "?" 'notmuch-help)
57     (define-key map "q" 'kill-this-buffer)
58     (define-key map (kbd "C-p") 'notmuch-show-previous-line)
59     (define-key map (kbd "C-n") 'notmuch-show-next-line)
60     (define-key map (kbd "M-TAB") 'notmuch-show-previous-button)
61     (define-key map (kbd "TAB") 'notmuch-show-next-button)
62     (define-key map "s" 'notmuch-search)
63     (define-key map "m" 'message-mail)
64     (define-key map "f" 'notmuch-show-forward-current)
65     (define-key map "r" 'notmuch-show-reply)
66     (define-key map "|" 'notmuch-show-pipe-message)
67     (define-key map "w" 'notmuch-show-save-attachments)
68     (define-key map "V" 'notmuch-show-view-raw-message)
69     (define-key map "v" 'notmuch-show-view-all-mime-parts)
70     (define-key map "b" 'notmuch-show-toggle-current-body)
71     (define-key map "h" 'notmuch-show-toggle-current-header)
72     (define-key map "-" 'notmuch-show-remove-tag)
73     (define-key map "+" 'notmuch-show-add-tag)
74     (define-key map "X" 'notmuch-show-mark-read-then-archive-then-exit)
75     (define-key map "x" 'notmuch-show-archive-thread-then-exit)
76     (define-key map "A" 'notmuch-show-mark-read-then-archive-thread)
77     (define-key map "a" 'notmuch-show-archive-thread)
78     (define-key map "p" 'notmuch-show-previous-message)
79     (define-key map "N" 'notmuch-show-mark-read-then-next-open-message)
80     (define-key map "n" 'notmuch-show-next-message)
81     (define-key map (kbd "DEL") 'notmuch-show-rewind)
82     (define-key map " " 'notmuch-show-advance-marking-read-and-archiving)
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-button-format
98   "[ %d-line signature. Click/Enter to toggle visibility. ]"
99   "String used to construct button text for hidden signatures
100
101 Can use up to one integer format parameter, i.e. %d")
102
103 (defvar notmuch-show-citation-button-format
104   "[ %d more citation lines. Click/Enter to toggle visibility. ]"
105   "String used to construct button text for hidden citations.
106
107 Can use up to one integer format parameter, i.e. %d")
108
109 (defvar notmuch-show-signature-lines-max 12
110   "Maximum length of signature that will be hidden by default.")
111
112 (defvar notmuch-show-citation-lines-prefix 4
113   "Always show at least this many lines of a citation.
114
115 If there is one more line, show that, otherwise collapse
116 remaining lines into a button.")
117
118 (defvar notmuch-command "notmuch"
119   "Command to run the notmuch binary.")
120
121 (defvar notmuch-show-message-begin-regexp    "\fmessage{")
122 (defvar notmuch-show-message-end-regexp      "\fmessage}")
123 (defvar notmuch-show-header-begin-regexp     "\fheader{")
124 (defvar notmuch-show-header-end-regexp       "\fheader}")
125 (defvar notmuch-show-body-begin-regexp       "\fbody{")
126 (defvar notmuch-show-body-end-regexp         "\fbody}")
127 (defvar notmuch-show-attachment-begin-regexp "\fattachment{")
128 (defvar notmuch-show-attachment-end-regexp   "\fattachment}")
129 (defvar notmuch-show-part-begin-regexp       "\fpart{")
130 (defvar notmuch-show-part-end-regexp         "\fpart}")
131 (defvar notmuch-show-marker-regexp "\f\\(message\\|header\\|body\\|attachment\\|part\\)[{}].*$")
132
133 (defvar notmuch-show-id-regexp "\\(id:[^ ]*\\)")
134 (defvar notmuch-show-depth-match-regexp " depth:\\([0-9]*\\).*match:\\([01]\\) ")
135 (defvar notmuch-show-filename-regexp "filename:\\(.*\\)$")
136 (defvar notmuch-show-contentype-regexp "Content-type: \\(.*\\)")
137
138 (defvar notmuch-show-tags-regexp "(\\([^)]*\\))$")
139
140 (defvar notmuch-show-parent-buffer nil)
141 (defvar notmuch-show-body-read-visible nil)
142 (defvar notmuch-show-citations-visible nil)
143 (defvar notmuch-show-signatures-visible nil)
144 (defvar notmuch-show-headers-visible nil)
145
146 ; XXX: This should be a generic function in emacs somewhere, not here
147 (defun point-invisible-p ()
148   "Return whether the character at point is invisible.
149
150 Here visibility is determined by `buffer-invisibility-spec' and
151 the invisible property of any overlays for point. It doesn't have
152 anything to do with whether point is currently being displayed
153 within the current window."
154   (let ((prop (get-char-property (point) 'invisible)))
155     (if (eq buffer-invisibility-spec t)
156         prop
157       (or (memq prop buffer-invisibility-spec)
158           (assq prop buffer-invisibility-spec)))))
159
160 (defun notmuch-select-tag-with-completion (prompt &rest search-terms)
161   (let ((tag-list
162          (with-output-to-string
163            (with-current-buffer standard-output
164              (apply 'call-process notmuch-command nil t nil "search-tags" search-terms)))))
165     (completing-read prompt (split-string tag-list "\n+" t) nil nil nil)))
166
167 (defun notmuch-show-next-line ()
168   "Like builtin `next-line' but ensuring we end on a visible character.
169
170 By advancing forward until reaching a visible character.
171
172 Unlike builtin `next-line' this version accepts no arguments."
173   (interactive)
174   (set 'this-command 'next-line)
175   (call-interactively 'next-line)
176   (while (point-invisible-p)
177     (forward-char)))
178
179 (defun notmuch-show-previous-line ()
180   "Like builtin `previous-line' but ensuring we end on a visible character.
181
182 By advancing forward until reaching a visible character.
183
184 Unlike builtin `previous-line' this version accepts no arguments."
185   (interactive)
186   (set 'this-command 'previous-line)
187   (call-interactively 'previous-line)
188   (while (point-invisible-p)
189     (forward-char)))
190
191 (defun notmuch-show-get-message-id ()
192   (save-excursion
193     (beginning-of-line)
194     (if (not (looking-at notmuch-show-message-begin-regexp))
195         (re-search-backward notmuch-show-message-begin-regexp))
196     (re-search-forward notmuch-show-id-regexp)
197     (buffer-substring-no-properties (match-beginning 1) (match-end 1))))
198
199 (defun notmuch-show-get-filename ()
200   (save-excursion
201     (beginning-of-line)
202     (if (not (looking-at notmuch-show-message-begin-regexp))
203         (re-search-backward notmuch-show-message-begin-regexp))
204     (re-search-forward notmuch-show-filename-regexp)
205     (buffer-substring-no-properties (match-beginning 1) (match-end 1))))
206
207 (defun notmuch-show-set-tags (tags)
208   (save-excursion
209     (beginning-of-line)
210     (if (not (looking-at notmuch-show-message-begin-regexp))
211         (re-search-backward notmuch-show-message-begin-regexp))
212     (re-search-forward notmuch-show-tags-regexp)
213     (let ((inhibit-read-only t)
214           (beg (match-beginning 1))
215           (end (match-end 1)))
216       (delete-region beg end)
217       (goto-char beg)
218       (insert (mapconcat 'identity tags " ")))))
219
220 (defun notmuch-show-get-tags ()
221   (save-excursion
222     (beginning-of-line)
223     (if (not (looking-at notmuch-show-message-begin-regexp))
224         (re-search-backward notmuch-show-message-begin-regexp))
225     (re-search-forward notmuch-show-tags-regexp)
226     (split-string (buffer-substring (match-beginning 1) (match-end 1)))))
227
228 (defun notmuch-show-add-tag (&rest toadd)
229   "Add a tag to the current message."
230   (interactive
231    (list (notmuch-select-tag-with-completion "Tag to add: ")))
232   (apply 'notmuch-call-notmuch-process
233          (append (cons "tag"
234                        (mapcar (lambda (s) (concat "+" s)) toadd))
235                  (cons (notmuch-show-get-message-id) nil)))
236   (notmuch-show-set-tags (sort (union toadd (notmuch-show-get-tags) :test 'string=) 'string<)))
237
238 (defun notmuch-show-remove-tag (&rest toremove)
239   "Remove a tag from the current message."
240   (interactive
241    (list (notmuch-select-tag-with-completion "Tag to remove: " (notmuch-show-get-message-id))))
242   (let ((tags (notmuch-show-get-tags)))
243     (if (intersection tags toremove :test 'string=)
244         (progn
245           (apply 'notmuch-call-notmuch-process
246                  (append (cons "tag"
247                                (mapcar (lambda (s) (concat "-" s)) toremove))
248                          (cons (notmuch-show-get-message-id) nil)))
249           (notmuch-show-set-tags (sort (set-difference tags toremove :test 'string=) 'string<))))))
250
251 (defun notmuch-show-archive-thread-maybe-mark-read (markread)
252   (save-excursion
253     (goto-char (point-min))
254     (while (not (eobp))
255       (if markread
256           (notmuch-show-remove-tag "unread" "inbox")
257         (notmuch-show-remove-tag "inbox"))
258       (if (not (eobp))
259           (forward-char))
260       (if (not (re-search-forward notmuch-show-message-begin-regexp nil t))
261           (goto-char (point-max)))))
262   (let ((parent-buffer notmuch-show-parent-buffer))
263     (kill-this-buffer)
264     (if parent-buffer
265         (progn
266           (switch-to-buffer parent-buffer)
267           (forward-line)
268           (notmuch-search-show-thread)))))
269
270 (defun notmuch-show-mark-read-then-archive-thread ()
271   "Remove unread tags from thread, then archive and show next thread.
272
273 Archive each message currently shown by removing the \"unread\"
274 and \"inbox\" tag from each. Then kill this buffer and show the
275 next thread from the search from which this thread was originally
276 shown.
277
278 Note: This command is safe from any race condition of new messages
279 being delivered to the same thread. It does not archive the
280 entire thread, but only the messages shown in the current
281 buffer."
282   (interactive)
283   (notmuch-show-archive-thread-maybe-mark-read t))
284
285 (defun notmuch-show-archive-thread ()
286   "Archive each message in thread, then show next thread from search.
287
288 Archive each message currently shown by removing the \"inbox\"
289 tag from each. Then kill this buffer and show the next thread
290 from the search from which this thread was originally shown.
291
292 Note: This command is safe from any race condition of new messages
293 being delivered to the same thread. It does not archive the
294 entire thread, but only the messages shown in the current
295 buffer."
296   (interactive)
297   (notmuch-show-archive-thread-maybe-mark-read nil))
298
299 (defun notmuch-show-archive-thread-then-exit ()
300   "Archive each message in thread, then exit back to search results."
301   (interactive)
302   (notmuch-show-archive-thread)
303   (kill-this-buffer))
304
305 (defun notmuch-show-mark-read-then-archive-then-exit ()
306   "Remove unread tags from thread, then archive and exit to search results."
307   (interactive)
308   (notmuch-show-mark-read-then-archive-thread)
309   (kill-this-buffer))
310
311 (defun notmuch-show-view-raw-message ()
312   "View the raw email of the current message."
313   (interactive)
314   (view-file (notmuch-show-get-filename)))
315
316 (defmacro with-current-notmuch-show-message (&rest body)
317   "Evaluate body with current buffer set to the text of current message"
318   `(save-excursion
319      (let ((filename (notmuch-show-get-filename)))
320        (let ((buf (generate-new-buffer (concat "*notmuch-msg-" filename "*"))))
321          (with-current-buffer buf
322            (insert-file-contents filename nil nil nil t)
323            ,@body)
324         (kill-buffer buf)))))
325
326 (defun notmuch-show-view-all-mime-parts ()
327   "Use external viewers to view all attachments from the current message."
328   (interactive)
329   (with-current-notmuch-show-message
330    (mm-display-parts (mm-dissect-buffer))))
331
332 (defun notmuch-foreach-mime-part (function mm-handle)
333   (cond ((stringp (car mm-handle))
334          (dolist (part (cdr mm-handle))
335            (notmuch-foreach-mime-part function part)))
336         ((bufferp (car mm-handle))
337          (funcall function mm-handle))
338         (t (dolist (part mm-handle)
339              (notmuch-foreach-mime-part function part)))))
340
341 (defun notmuch-count-attachments (mm-handle)
342   (let ((count 0))
343     (notmuch-foreach-mime-part
344      (lambda (p)
345        (let ((disposition (mm-handle-disposition p)))
346          (and (listp disposition)
347               (or (equal (car disposition) "attachment")
348                   (and (equal (car disposition) "inline")
349                        (assq 'filename disposition)))
350               (incf count))))
351      mm-handle)
352     count))
353
354 (defun notmuch-save-attachments (mm-handle &optional queryp)
355   (notmuch-foreach-mime-part
356    (lambda (p)
357      (let ((disposition (mm-handle-disposition p)))
358        (and (listp disposition)
359             (or (equal (car disposition) "attachment")
360                 (and (equal (car disposition) "inline")
361                      (assq 'filename disposition)))
362             (or (not queryp)
363                 (y-or-n-p
364                  (concat "Save '" (cdr (assq 'filename disposition)) "' ")))
365             (mm-save-part p))))
366    mm-handle))
367
368 (defun notmuch-show-save-attachments ()
369   "Save all attachments from the current message."
370   (interactive)
371   (with-current-notmuch-show-message
372    (let ((mm-handle (mm-dissect-buffer)))
373      (notmuch-save-attachments
374       mm-handle (> (notmuch-count-attachments mm-handle) 1))))
375   (message "Done"))
376
377 (defun notmuch-reply (query-string)
378   (switch-to-buffer (generate-new-buffer "notmuch-draft"))
379   (call-process notmuch-command nil t nil "reply" query-string)
380   (message-insert-signature)
381   (goto-char (point-min))
382   (if (re-search-forward "^$" nil t)
383       (progn
384         (insert "--text follows this line--")
385         (forward-line)))
386   (message-mode))
387
388 (defun notmuch-show-reply ()
389   "Begin composing a reply to the current message in a new buffer."
390   (interactive)
391   (let ((message-id (notmuch-show-get-message-id)))
392     (notmuch-reply message-id)))
393
394 (defun notmuch-show-forward-current ()
395   "Forward the current message."
396   (interactive)
397   (with-current-notmuch-show-message
398    (message-forward)))
399
400 (defun notmuch-show-pipe-message (command)
401   "Pipe the contents of the current message to the given command.
402
403 The given command will be executed with the raw contents of the
404 current email message as stdin. Anything printed by the command
405 to stdout or stderr will appear in the *Messages* buffer."
406   (interactive "sPipe message to command: ")
407   (apply 'start-process-shell-command "notmuch-pipe-command" "*notmuch-pipe*"
408          (list command " < " (shell-quote-argument (notmuch-show-get-filename)))))
409
410 (defun notmuch-show-move-to-current-message-summary-line ()
411   "Move to the beginning of the one-line summary of the current message.
412
413 This gives us a stable place to move to and work from since the
414 summary line is always visible. This is important since moving to
415 an invisible location is unreliable, (the main command loop moves
416 point either forward or backward to the next visible character
417 when a command ends with point on an invisible character).
418
419 Emits an error if point is not within a valid message, (that is
420 no pattern of `notmuch-show-message-begin-regexp' could be found
421 by searching backward)."
422   (beginning-of-line)
423   (if (not (looking-at notmuch-show-message-begin-regexp))
424       (if (re-search-backward notmuch-show-message-begin-regexp nil t)
425           (forward-line 2)
426         (error "Not within a valid message."))
427     (forward-line 2)))
428
429 (defun notmuch-show-last-message-p ()
430   "Predicate testing whether point is within the last message."
431   (save-window-excursion
432     (save-excursion
433       (notmuch-show-move-to-current-message-summary-line)
434       (not (re-search-forward notmuch-show-message-begin-regexp nil t)))))
435
436 (defun notmuch-show-message-unread-p ()
437   "Predicate testing whether current message is unread."
438   (member "unread" (notmuch-show-get-tags)))
439
440 (defun notmuch-show-message-open-p ()
441   "Predicate testing whether current message is open (body is visible)."
442   (let ((btn (previous-button (point) t)))
443     (while (not (button-has-type-p btn 'notmuch-button-body-toggle-type))
444       (setq btn (previous-button (button-start btn))))
445     (not (invisible-p (button-get btn 'invisibility-spec)))))
446
447 (defun notmuch-show-next-message ()
448   "Advance to the beginning of the next message in the buffer.
449
450 Moves to the last visible character of the current message if
451 already on the last message in the buffer.
452
453 Returns nil if already on the last message in the buffer."
454   (interactive)
455   (notmuch-show-move-to-current-message-summary-line)
456   (if (re-search-forward notmuch-show-message-begin-regexp nil t)
457       (progn
458         (notmuch-show-move-to-current-message-summary-line)
459         (recenter 0)
460         t)
461     (goto-char (- (point-max) 1))
462     (while (point-invisible-p)
463       (backward-char))
464     (recenter 0)
465     nil))
466
467 (defun notmuch-show-find-next-message ()
468   "Returns the position of the next message in the buffer.
469
470 Or the position of the last visible character of the current
471 message if already within the last message in the buffer."
472   ; save-excursion doesn't save our window position
473   ; save-window-excursion doesn't save point
474   ; Looks like we have to use both.
475   (save-excursion
476     (save-window-excursion
477       (notmuch-show-next-message)
478       (point))))
479
480 (defun notmuch-show-next-unread-message ()
481   "Advance to the beginning of the next unread message in the buffer.
482
483 Moves to the last visible character of the current message if
484 there are no more unread messages past the current point."
485   (notmuch-show-next-message)
486   (while (and (not (notmuch-show-last-message-p))
487               (not (notmuch-show-message-unread-p)))
488     (notmuch-show-next-message))
489   (if (not (notmuch-show-message-unread-p))
490       (notmuch-show-next-message)))
491
492 (defun notmuch-show-next-open-message ()
493   "Advance to the next open message (that is, body is not invisible)."
494   (while (and (notmuch-show-next-message)
495               (not (notmuch-show-message-open-p)))))
496
497 (defun notmuch-show-previous-message ()
498   "Backup to the beginning of the previous message in the buffer.
499
500 If within a message rather than at the beginning of it, then
501 simply move to the beginning of the current message."
502   (interactive)
503   (let ((start (point)))
504     (notmuch-show-move-to-current-message-summary-line)
505     (if (not (< (point) start))
506         ; Go backward twice to skip the current message's marker
507         (progn
508           (re-search-backward notmuch-show-message-begin-regexp nil t)
509           (re-search-backward notmuch-show-message-begin-regexp nil t)
510           (notmuch-show-move-to-current-message-summary-line)
511           ))
512     (recenter 0)))
513
514 (defun notmuch-show-find-previous-message ()
515   "Returns the position of the previous message in the buffer.
516
517 Or the position of the beginning of the current message if point
518 is originally within the message rather than at the beginning of
519 it."
520   ; save-excursion doesn't save our window position
521   ; save-window-excursion doesn't save point
522   ; Looks like we have to use both.
523   (save-excursion
524     (save-window-excursion
525       (notmuch-show-previous-message)
526       (point))))
527
528 (defun notmuch-show-mark-read-then-next-open-message ()
529   "Remove unread tag from this message, then advance to next open message."
530   (interactive)
531   (notmuch-show-remove-tag "unread")
532   (notmuch-show-next-open-message))
533
534 (defun notmuch-show-rewind ()
535   "Backup through the thread, (reverse scrolling compared to \\[notmuch-show-advance-marking-read-and-archiving]).
536
537 Specifically, if the beginning of the previous email is fewer
538 than `window-height' lines from the current point, move to it
539 just like `notmuch-show-previous-message'.
540
541 Otherwise, just scroll down a screenful of the current message.
542
543 This command does not modify any message tags, (it does not undo
544 any effects from previous calls to
545 `notmuch-show-advance-marking-read-and-archiving'."
546   (interactive)
547   (let ((previous (notmuch-show-find-previous-message)))
548     (if (> (count-lines previous (point)) (- (window-height) next-screen-context-lines))
549         (progn
550           (condition-case nil
551               (scroll-down nil)
552             ((beginning-of-buffer) nil))
553           (goto-char (window-start)))
554       (notmuch-show-previous-message))))
555
556 (defun notmuch-show-advance-marking-read-and-archiving ()
557   "Advance through thread, marking read and archiving.
558
559 This command is intended to be one of the simplest ways to
560 process a thread of email. It does the following:
561
562 If the current message in the thread is not yet fully visible,
563 scroll by a near screenful to read more of the message.
564
565 Otherwise, (the end of the current message is already within the
566 current window), remove the \"unread\" tag (if present) from the
567 current message and advance to the next open message.
568
569 Finally, if there is no further message to advance to, and this
570 last message is already read, then archive the entire current
571 thread, (remove the \"inbox\" tag from each message). Also kill
572 this buffer, and display the next thread from the search from
573 which this thread was originally shown."
574   (interactive)
575   (let ((next (notmuch-show-find-next-message))
576         (unread (notmuch-show-message-unread-p)))
577     (if (> next (window-end))
578         (scroll-up nil)
579       (let ((last (notmuch-show-last-message-p)))
580         (notmuch-show-mark-read-then-next-open-message)
581         (if last
582             (notmuch-show-archive-thread))))))
583
584 (defun notmuch-show-next-button ()
585   "Advance point to the next button in the buffer."
586   (interactive)
587   (forward-button 1))
588
589 (defun notmuch-show-previous-button ()
590   "Move point back to the previous button in the buffer."
591   (interactive)
592   (backward-button 1))
593
594 (defun notmuch-toggle-invisible-action (cite-button)
595   (let ((invis-spec (button-get cite-button 'invisibility-spec)))
596         (if (invisible-p invis-spec)
597             (remove-from-invisibility-spec invis-spec)
598           (add-to-invisibility-spec invis-spec)
599           ))
600   (force-window-update)
601   (redisplay t))
602
603 (defun notmuch-show-toggle-current-body ()
604   "Toggle the display of the current message body."
605   (interactive)
606   (save-excursion
607     (notmuch-show-move-to-current-message-summary-line)
608     (unless (button-at (point))
609       (notmuch-show-next-button))
610     (push-button))
611   )
612
613 (defun notmuch-show-toggle-current-header ()
614   "Toggle the display of the current message header."
615   (interactive)
616   (save-excursion
617     (notmuch-show-move-to-current-message-summary-line)
618     (forward-line)
619     (unless (button-at (point))
620       (notmuch-show-next-button))
621     (push-button))
622   )
623
624 (define-button-type 'notmuch-button-invisibility-toggle-type
625   'action 'notmuch-toggle-invisible-action
626   'follow-link t
627   'face 'font-lock-comment-face)
628 (define-button-type 'notmuch-button-citation-toggle-type 'help-echo "mouse-1, RET: Show citation"
629   :supertype 'notmuch-button-invisibility-toggle-type)
630 (define-button-type 'notmuch-button-signature-toggle-type 'help-echo "mouse-1, RET: Show signature"
631   :supertype 'notmuch-button-invisibility-toggle-type)
632 (define-button-type 'notmuch-button-headers-toggle-type 'help-echo "mouse-1, RET: Show headers"
633   :supertype 'notmuch-button-invisibility-toggle-type)
634 (define-button-type 'notmuch-button-body-toggle-type
635   'help-echo "mouse-1, RET: Show message"
636   'face 'notmuch-message-summary-face
637   :supertype 'notmuch-button-invisibility-toggle-type)
638
639 (defun notmuch-show-citation-regexp (depth)
640   "Build a regexp for matching citations at a given DEPTH (indent)"
641   (let ((line-regexp (format "[[:space:]]\\{%d\\}>.*\n" depth)))
642     (concat "\\(?:^" line-regexp
643             "\\(?:[[:space:]]*\n" line-regexp
644             "\\)?\\)+")))
645
646 (defun notmuch-show-region-to-button (beg end type prefix button-text)
647   "Auxilary function to do the actual making of overlays and buttons
648
649 BEG and END are buffer locations. TYPE should a string, either
650 \"citation\" or \"signature\". PREFIX is some arbitrary text to
651 insert before the button, probably for indentation.  BUTTON-TEXT
652 is what to put on the button."
653
654 ;; This uses some slightly tricky conversions between strings and
655 ;; symbols because of the way the button code works. Note that
656 ;; replacing intern-soft with make-symbol will cause this to fail,
657 ;; since the newly created symbol has no plist.
658
659   (let ((overlay (make-overlay beg end))
660         (invis-spec (make-symbol (concat "notmuch-" type "-region")))
661         (button-type (intern-soft (concat "notmuch-button-"
662                                           type "-toggle-type"))))
663     (add-to-invisibility-spec invis-spec)
664     (overlay-put overlay 'invisible invis-spec)
665     (goto-char (1+ end))
666     (save-excursion
667       (goto-char (1- beg))
668       (insert prefix)
669       (insert-button button-text
670                      'invisibility-spec invis-spec
671                      :type button-type)
672       )))
673
674
675 (defun notmuch-show-markup-citations-region (beg end depth)
676   "Markup citations, and up to one signature in the given region"
677   ;; it would be nice if the untabify was not required, but
678   ;; that would require notmuch to indent with spaces.
679   (untabify beg end)
680   (let ((citation-regexp (notmuch-show-citation-regexp depth))
681         (signature-regexp (concat (format "^[[:space:]]\\{%d\\}" depth)
682                                   notmuch-show-signature-regexp))
683         (indent (concat "\n" (make-string depth ? ))))
684     (goto-char beg)
685     (beginning-of-line)
686     (while (and (< (point) end)
687                 (re-search-forward citation-regexp end t))
688       (let* ((cite-start (match-beginning 0))
689              (cite-end  (match-end 0))
690              (cite-lines (count-lines cite-start cite-end)))
691         (when (> cite-lines (1+ notmuch-show-citation-lines-prefix))
692           (goto-char cite-start)
693           (forward-line notmuch-show-citation-lines-prefix)
694           (notmuch-show-region-to-button
695            (point) cite-end
696            "citation"
697            indent
698            (format notmuch-show-citation-button-format
699                    (- cite-lines notmuch-show-citation-lines-prefix))
700            ))))
701     (if (and (< (point) end)
702              (re-search-forward signature-regexp end t))
703         (let* ((sig-start (match-beginning 0))
704                (sig-end (match-end 0))
705                (sig-lines (1- (count-lines sig-start end))))
706           (if (<= sig-lines notmuch-show-signature-lines-max)
707               (notmuch-show-region-to-button
708                sig-start
709                end
710                "signature"
711                indent
712                (format notmuch-show-signature-button-format sig-lines)
713                ))))))
714
715 (defun notmuch-show-markup-part (beg end depth)
716   (if (re-search-forward notmuch-show-part-begin-regexp nil t)
717       (progn
718         (let (mime-message mime-type)
719           (save-excursion
720             (re-search-forward notmuch-show-contentype-regexp end t)
721             (setq mime-type (car (split-string (buffer-substring 
722                                                 (match-beginning 1) (match-end 1))))))
723
724           (if (equal mime-type "text/html")
725               (let ((filename (notmuch-show-get-filename)))
726                 (with-temp-buffer
727                   (insert-file-contents filename nil nil nil t)
728                   (setq mime-message (mm-dissect-buffer)))))
729           (forward-line)
730           (let ((beg (point-marker)))
731             (re-search-forward notmuch-show-part-end-regexp)
732             (let ((end (copy-marker (match-beginning 0))))
733               (goto-char end)
734               (if (not (bolp))
735                   (insert "\n"))
736               (indent-rigidly beg end depth)
737               (if (not (eq mime-message nil))
738                   (save-excursion
739                     (goto-char beg)
740                     (forward-line -1)
741                     (let ((handle-type (mm-handle-type mime-message))
742                           mime-type)
743                       (if (sequencep (car handle-type))
744                           (setq mime-type (car handle-type))
745                         (setq mime-type (car (car (cdr handle-type))))
746                         )
747                       (if (equal mime-type "text/html")
748                           (mm-display-part mime-message))))
749                 )
750               (notmuch-show-markup-citations-region beg end depth)
751               ; Advance to the next part (if any) (so the outer loop can
752               ; determine whether we've left the current message.
753               (if (re-search-forward notmuch-show-part-begin-regexp nil t)
754                   (beginning-of-line)))))
755         (goto-char end))
756     (goto-char end)))
757
758 (defun notmuch-show-markup-parts-region (beg end depth)
759   (save-excursion
760     (goto-char beg)
761     (while (< (point) end)
762       (notmuch-show-markup-part beg end depth))))
763
764 (defun notmuch-show-markup-body (depth match btn)
765   "Markup a message body, (indenting, buttonizing citations,
766 etc.), and conditionally hiding the body itself if the message
767 has been read and does not match the current search.
768
769 DEPTH specifies the depth at which this message appears in the
770 tree of the current thread, (the top-level messages have depth 0
771 and each reply increases depth by 1). MATCH indicates whether
772 this message is regarded as matching the current search. BTN is
773 the button which is used to toggle the visibility of this
774 message.
775
776 When this function is called, point must be within the message, but
777 before the delimiter marking the beginning of the body."
778   (re-search-forward notmuch-show-body-begin-regexp)
779   (forward-line)
780   (let ((beg (point-marker)))
781     (re-search-forward notmuch-show-body-end-regexp)
782     (let ((end (copy-marker (match-beginning 0))))
783       (notmuch-show-markup-parts-region beg end depth)
784       (let ((invis-spec (make-symbol "notmuch-show-body-read")))
785         (overlay-put (make-overlay beg end)
786                      'invisible invis-spec)
787         (button-put btn 'invisibility-spec invis-spec)
788         (if (not (or (notmuch-show-message-unread-p) match))
789             (add-to-invisibility-spec invis-spec)))
790       (set-marker beg nil)
791       (set-marker end nil)
792       )))
793
794 (defun notmuch-fontify-headers ()
795   (while (looking-at "[[:space:]]")
796     (forward-char))
797   (if (looking-at "[Tt]o:")
798       (progn
799         (overlay-put (make-overlay (point) (re-search-forward ":"))
800                      'face 'message-header-name)
801         (overlay-put (make-overlay (point) (re-search-forward ".*$"))
802                      'face 'message-header-to))
803     (if (looking-at "[B]?[Cc][Cc]:")
804         (progn
805           (overlay-put (make-overlay (point) (re-search-forward ":"))
806                        'face 'message-header-name)
807           (overlay-put (make-overlay (point) (re-search-forward ".*$"))
808                        'face 'message-header-cc))
809       (if (looking-at "[Ss]ubject:")
810           (progn
811             (overlay-put (make-overlay (point) (re-search-forward ":"))
812                          'face 'message-header-name)
813             (overlay-put (make-overlay (point) (re-search-forward ".*$"))
814                          'face 'message-header-subject))
815         (if (looking-at "[Ff]rom:")
816             (progn
817               (overlay-put (make-overlay (point) (re-search-forward ":"))
818                            'face 'message-header-name)
819               (overlay-put (make-overlay (point) (re-search-forward ".*$"))
820                            'face 'message-header-other)))))))
821
822 (defun notmuch-show-markup-header (message-begin depth)
823   "Buttonize and decorate faces in a message header.
824
825 MESSAGE-BEGIN is the position of the absolute first character in
826 the message (including all delimiters that will end up being
827 invisible etc.). This is to allow a button to reliably extend to
828 the beginning of the message even if point is positioned at an
829 invisible character (such as the beginning of the buffer).
830
831 DEPTH specifies the depth at which this message appears in the
832 tree of the current thread, (the top-level messages have depth 0
833 and each reply increases depth by 1)."
834   (re-search-forward notmuch-show-header-begin-regexp)
835   (forward-line)
836   (let ((beg (point-marker))
837         (summary-end (copy-marker (line-beginning-position 2)))
838         (subject-end (copy-marker (line-end-position 2)))
839         (invis-spec (make-symbol "notmuch-show-header"))
840         (btn nil))
841     (re-search-forward notmuch-show-header-end-regexp)
842     (beginning-of-line)
843     (let ((end (point-marker)))
844       (indent-rigidly beg end depth)
845       (goto-char beg)
846       (setq btn (make-button message-begin summary-end :type 'notmuch-button-body-toggle-type))
847       (forward-line)
848       (add-to-invisibility-spec invis-spec)
849       (overlay-put (make-overlay subject-end end)
850                    'invisible invis-spec)
851       (make-button (line-beginning-position) subject-end
852                    'invisibility-spec invis-spec
853                    :type 'notmuch-button-headers-toggle-type)
854       (while (looking-at "[[:space:]]*[A-Za-z][-A-Za-z0-9]*:")
855         (beginning-of-line)
856         (notmuch-fontify-headers)
857         (forward-line)
858         )
859       (goto-char end)
860       (insert "\n")
861       (set-marker beg nil)
862       (set-marker summary-end nil)
863       (set-marker subject-end nil)
864       (set-marker end nil)
865       )
866   btn))
867
868 (defun notmuch-show-markup-message ()
869   (if (re-search-forward notmuch-show-message-begin-regexp nil t)
870       (let ((message-begin (match-beginning 0)))
871         (re-search-forward notmuch-show-depth-match-regexp)
872         (let ((depth (string-to-number (buffer-substring (match-beginning 1) (match-end 1))))
873               (match (string= "1" (buffer-substring (match-beginning 2) (match-end 2))))
874               (btn nil))
875           (setq btn (notmuch-show-markup-header message-begin depth))
876           (notmuch-show-markup-body depth match btn)))
877     (goto-char (point-max))))
878
879 (defun notmuch-show-hide-markers ()
880   (save-excursion
881     (goto-char (point-min))
882     (while (not (eobp))
883       (if (re-search-forward notmuch-show-marker-regexp nil t)
884           (progn
885             (overlay-put (make-overlay (match-beginning 0) (+ (match-end 0) 1))
886                          'invisible 'notmuch-show-marker))
887         (goto-char (point-max))))))
888
889 (defun notmuch-show-markup-messages ()
890   (save-excursion
891     (goto-char (point-min))
892     (while (not (eobp))
893       (notmuch-show-markup-message)))
894   (notmuch-show-hide-markers))
895
896 (defun notmuch-documentation-first-line (symbol)
897   "Return the first line of the documentation string for SYMBOL."
898   (let ((doc (documentation symbol)))
899     (if doc
900         (with-temp-buffer
901           (insert (documentation symbol t))
902           (goto-char (point-min))
903           (let ((beg (point)))
904             (end-of-line)
905             (buffer-substring beg (point))))
906       "")))
907
908 (defun notmuch-prefix-key-description (key)
909   "Given a prefix key code, return a human-readable string representation.
910
911 This is basically just `format-kbd-macro' but we also convert ESC to M-."
912   (let ((desc (format-kbd-macro (vector key))))
913     (if (string= desc "ESC")
914         "M-"
915       (concat desc " "))))
916
917 ; I would think that emacs would have code handy for walking a keymap
918 ; and generating strings for each key, and I would prefer to just call
919 ; that. But I couldn't find any (could be all implemented in C I
920 ; suppose), so I wrote my own here.
921 (defun notmuch-substitute-one-command-key-with-prefix (prefix binding)
922   "For a key binding, return a string showing a human-readable
923 representation of the prefixed key as well as the first line of
924 documentation from the bound function.
925
926 For a mouse binding, return nil."
927   (let ((key (car binding))
928         (action (cdr binding)))
929     (if (mouse-event-p key)
930         nil
931       (if (keymapp action)
932           (let ((substitute (apply-partially 'notmuch-substitute-one-command-key-with-prefix (notmuch-prefix-key-description key))))
933             (mapconcat substitute (cdr action) "\n"))
934         (concat prefix (format-kbd-macro (vector key))
935                 "\t"
936                 (notmuch-documentation-first-line action))))))
937
938 (defalias 'notmuch-substitute-one-command-key
939   (apply-partially 'notmuch-substitute-one-command-key-with-prefix nil))
940
941 (defun notmuch-substitute-command-keys (doc)
942   "Like `substitute-command-keys' but with documentation, not function names."
943   (let ((beg 0))
944     (while (string-match "\\\\{\\([^}[:space:]]*\\)}" doc beg)
945       (let ((map (substring doc (match-beginning 1) (match-end 1))))
946         (setq doc (replace-match (mapconcat 'notmuch-substitute-one-command-key
947                                             (cdr (symbol-value (intern map))) "\n") 1 1 doc)))
948       (setq beg (match-end 0)))
949     doc))
950
951 (defun notmuch-help ()
952   "Display help for the current notmuch mode."
953   (interactive)
954   (let* ((mode major-mode)
955          (doc (substitute-command-keys (notmuch-substitute-command-keys (documentation mode t)))))
956     (with-current-buffer (generate-new-buffer "*notmuch-help*")
957       (insert doc)
958       (goto-char (point-min))
959       (set-buffer-modified-p nil)
960       (view-buffer (current-buffer) 'kill-buffer-if-not-modified))))
961
962 ;;;###autoload
963 (defun notmuch-show-mode ()
964   "Major mode for viewing a thread with notmuch.
965
966 This buffer contains the results of the \"notmuch show\" command
967 for displaying a single thread of email from your email archives.
968
969 By default, various components of email messages, (citations,
970 signatures, already-read messages), are hidden. You can make
971 these parts visible by clicking with the mouse button or by
972 pressing RET after positioning the cursor on a hidden part, (for
973 which \\[notmuch-show-next-button] and \\[notmuch-show-previous-button] are helpful).
974
975 Reading the thread sequentially is well-supported by pressing
976 \\[notmuch-show-advance-marking-read-and-archiving]. This will scroll the current message (if necessary),
977 advance to the next message, or advance to the next thread (if
978 already on the last message of a thread). As each message is
979 scrolled away its \"unread\" tag will be removed, and as each
980 thread is scrolled away the \"inbox\" tag will be removed from
981 each message in the thread.
982
983 Other commands are available to read or manipulate the thread more
984 selectively, (such as '\\[notmuch-show-next-message]' and '\\[notmuch-show-previous-message]' to advance to messages without
985 removing any tags, and '\\[notmuch-show-archive-thread]' to archive an entire thread without
986 scrolling through with \\[notmuch-show-advance-marking-read-and-archiving]).
987
988 You can add or remove arbitary tags from the current message with
989 '\\[notmuch-show-add-tag]' or '\\[notmuch-show-remove-tag]'.
990
991 All currently available key bindings:
992
993 \\{notmuch-show-mode-map}"
994   (interactive)
995   (kill-all-local-variables)
996   (add-to-invisibility-spec 'notmuch-show-marker)
997   (use-local-map notmuch-show-mode-map)
998   (setq major-mode 'notmuch-show-mode
999         mode-name "notmuch-show")
1000   (setq buffer-read-only t))
1001
1002 (defgroup notmuch nil
1003   "Notmuch mail reader for Emacs."
1004   :group 'mail)
1005
1006 (defcustom notmuch-show-hook nil
1007   "List of functions to call when notmuch displays a message."
1008   :type 'hook
1009   :options '(goto-address)
1010   :group 'notmuch)
1011
1012 (defcustom notmuch-search-hook nil
1013   "List of functions to call when notmuch displays the search results."
1014   :type 'hook
1015   :options '(hl-line-mode)
1016   :group 'notmuch)
1017
1018 ; Make show mode a bit prettier, highlighting URLs and using word wrap
1019
1020 (defun notmuch-show-pretty-hook ()
1021   (goto-address-mode 1)
1022   (visual-line-mode))
1023
1024 (add-hook 'notmuch-show-hook 'notmuch-show-pretty-hook)
1025 (add-hook 'notmuch-search-hook
1026           (lambda()
1027             (hl-line-mode 1) ))
1028
1029 (defun notmuch-show (thread-id &optional parent-buffer query-context)
1030   "Run \"notmuch show\" with the given thread ID and display results.
1031
1032 The optional PARENT-BUFFER is the notmuch-search buffer from
1033 which this notmuch-show command was executed, (so that the next
1034 thread from that buffer can be show when done with this one).
1035
1036 The optional QUERY-CONTEXT is a notmuch search term. Only messages from the thread
1037 matching this search term are shown if non-nil. "
1038   (interactive "sNotmuch show: ")
1039   (let ((buffer (get-buffer-create (concat "*notmuch-show-" thread-id "*"))))
1040     (switch-to-buffer buffer)
1041     (notmuch-show-mode)
1042     (set (make-local-variable 'notmuch-show-parent-buffer) parent-buffer)
1043     (let ((proc (get-buffer-process (current-buffer)))
1044           (inhibit-read-only t))
1045       (if proc
1046           (error "notmuch search process already running for query `%s'" thread-id)
1047         )
1048       (erase-buffer)
1049       (goto-char (point-min))
1050       (save-excursion
1051         (let* ((basic-args (list notmuch-command nil t nil "show" "--entire-thread" thread-id))
1052                 (args (if query-context (append basic-args (list "and (" query-context ")")) basic-args)))
1053           (apply 'call-process args)
1054           (when (and (eq (buffer-size) 0) query-context)
1055             (apply 'call-process basic-args)))
1056         (notmuch-show-markup-messages)
1057         )
1058       (run-hooks 'notmuch-show-hook)
1059       ; Move straight to the first open message
1060       (if (not (notmuch-show-message-open-p))
1061           (notmuch-show-next-open-message))
1062       )))
1063
1064 (defvar notmuch-search-authors-width 40
1065   "Number of columns to use to display authors in a notmuch-search buffer.")
1066
1067 (defvar notmuch-search-mode-map
1068   (let ((map (make-sparse-keymap)))
1069     (define-key map "?" 'notmuch-help)
1070     (define-key map "q" 'kill-this-buffer)
1071     (define-key map "x" 'kill-this-buffer)
1072     (define-key map (kbd "<DEL>") 'notmuch-search-scroll-down)
1073     (define-key map "b" 'notmuch-search-scroll-down)
1074     (define-key map " " 'notmuch-search-scroll-up)
1075     (define-key map "<" 'notmuch-search-first-thread)
1076     (define-key map ">" 'notmuch-search-last-thread)
1077     (define-key map "p" 'notmuch-search-previous-thread)
1078     (define-key map "n" 'notmuch-search-next-thread)
1079     (define-key map "r" 'notmuch-search-reply-to-thread)
1080     (define-key map "m" 'message-mail)
1081     (define-key map "s" 'notmuch-search)
1082     (define-key map "o" 'notmuch-search-toggle-order)
1083     (define-key map "=" 'notmuch-search-refresh-view)
1084     (define-key map "t" 'notmuch-search-filter-by-tag)
1085     (define-key map "f" 'notmuch-search-filter)
1086     (define-key map [mouse-1] 'notmuch-search-show-thread)
1087     (define-key map "*" 'notmuch-search-operate-all)
1088     (define-key map "a" 'notmuch-search-archive-thread)
1089     (define-key map "-" 'notmuch-search-remove-tag)
1090     (define-key map "+" 'notmuch-search-add-tag)
1091     (define-key map (kbd "RET") 'notmuch-search-show-thread)
1092     map)
1093   "Keymap for \"notmuch search\" buffers.")
1094 (fset 'notmuch-search-mode-map notmuch-search-mode-map)
1095
1096 (defvar notmuch-search-query-string)
1097 (defvar notmuch-search-oldest-first t
1098   "Show the oldest mail first in the search-mode")
1099
1100 (defvar notmuch-search-disjunctive-regexp      "\\<[oO][rR]\\>")
1101
1102 (defun notmuch-search-scroll-up ()
1103   "Move forward through search results by one window's worth."
1104   (interactive)
1105   (condition-case nil
1106       (scroll-up nil)
1107     ((end-of-buffer) (notmuch-search-last-thread))))
1108
1109 (defun notmuch-search-scroll-down ()
1110   "Move backward through the search results by one window's worth."
1111   (interactive)
1112   ; I don't know why scroll-down doesn't signal beginning-of-buffer
1113   ; the way that scroll-up signals end-of-buffer, but c'est la vie.
1114   ;
1115   ; So instead of trapping a signal we instead check whether the
1116   ; window begins on the first line of the buffer and if so, move
1117   ; directly to that position. (We have to count lines since the
1118   ; window-start position is not the same as point-min due to the
1119   ; invisible thread-ID characters on the first line.
1120   (if (equal (count-lines (point-min) (window-start)) 0)
1121       (goto-char (point-min))
1122     (scroll-down nil)))
1123
1124 (defun notmuch-search-next-thread ()
1125   "Select the next thread in the search results."
1126   (interactive)
1127   (forward-line 1))
1128
1129 (defun notmuch-search-previous-thread ()
1130   "Select the previous thread in the search results."
1131   (interactive)
1132   (forward-line -1))
1133
1134 (defun notmuch-search-last-thread ()
1135   "Select the last thread in the search results."
1136   (interactive)
1137   (goto-char (point-max))
1138   (forward-line -2))
1139
1140 (defun notmuch-search-first-thread ()
1141   "Select the first thread in the search results."
1142   (interactive)
1143   (goto-char (point-min)))
1144
1145 (defface notmuch-message-summary-face
1146  '((((class color) (background light)) (:background "#f0f0f0"))
1147    (((class color) (background dark)) (:background "#303030")))
1148  "Face for the single-line message summary in notmuch-show-mode."
1149  :group 'notmuch)
1150
1151 (defface notmuch-tag-face
1152   '((((class color)
1153       (background dark))
1154      (:foreground "OliveDrab1"))
1155     (((class color)
1156       (background light))
1157      (:foreground "navy blue" :bold t))
1158     (t
1159      (:bold t)))
1160   "Notmuch search mode face used to highligh tags."
1161   :group 'notmuch)
1162
1163 (defvar notmuch-tag-face-alist nil
1164   "List containing the tag list that need to be highlighed")
1165
1166 (defvar notmuch-search-font-lock-keywords  nil)
1167
1168 ;;;###autoload
1169 (defun notmuch-search-mode ()
1170   "Major mode displaying results of a notmuch search.
1171
1172 This buffer contains the results of a \"notmuch search\" of your
1173 email archives. Each line in the buffer represents a single
1174 thread giving a summary of the thread (a relative date, the
1175 number of matched messages and total messages in the thread,
1176 participants in the thread, a representative subject line, and
1177 any tags).
1178
1179 Pressing \\[notmuch-search-show-thread] on any line displays that thread. The '\\[notmuch-search-add-tag]' and '\\[notmuch-search-remove-tag]'
1180 keys can be used to add or remove tags from a thread. The '\\[notmuch-search-archive-thread]' key
1181 is a convenience for archiving a thread (removing the \"inbox\"
1182 tag). The '\\[notmuch-search-operate-all]' key can be used to add or remove a tag from all
1183 threads in the current buffer.
1184
1185 Other useful commands are '\\[notmuch-search-filter]' for filtering the current search
1186 based on an additional query string, '\\[notmuch-search-filter-by-tag]' for filtering to include
1187 only messages with a given tag, and '\\[notmuch-search]' to execute a new, global
1188 search.
1189
1190 Complete list of currently available key bindings:
1191
1192 \\{notmuch-search-mode-map}"
1193   (interactive)
1194   (kill-all-local-variables)
1195   (make-local-variable 'notmuch-search-query-string)
1196   (make-local-variable 'notmuch-search-oldest-first)
1197   (set (make-local-variable 'scroll-preserve-screen-position) t)
1198   (add-to-invisibility-spec 'notmuch-search)
1199   (use-local-map notmuch-search-mode-map)
1200   (setq truncate-lines t)
1201   (setq major-mode 'notmuch-search-mode
1202         mode-name "notmuch-search")
1203   (setq buffer-read-only t)
1204   (if (not notmuch-tag-face-alist)
1205       (add-to-list 'notmuch-search-font-lock-keywords (list
1206                 "(\\([^)]*\\))$" '(1  'notmuch-tag-face)))
1207     (let ((notmuch-search-tags (mapcar 'car notmuch-tag-face-alist)))
1208       (loop for notmuch-search-tag  in notmuch-search-tags
1209             do (add-to-list 'notmuch-search-font-lock-keywords (list
1210                         (concat "([^)]*\\(" notmuch-search-tag "\\)[^)]*)$")
1211                         `(1  ,(cdr (assoc notmuch-search-tag notmuch-tag-face-alist))))))))
1212   (set (make-local-variable 'font-lock-defaults)
1213          '(notmuch-search-font-lock-keywords t)))
1214
1215 (defun notmuch-search-find-thread-id ()
1216   "Return the thread for the current thread"
1217   (get-text-property (point) 'notmuch-search-thread-id))
1218
1219 (defun notmuch-search-find-authors ()
1220   "Return the authors for the current thread"
1221   (get-text-property (point) 'notmuch-search-authors))
1222
1223 (defun notmuch-search-find-subject ()
1224   "Return the subject for the current thread"
1225   (get-text-property (point) 'notmuch-search-subject))
1226
1227 (defun notmuch-search-show-thread ()
1228   "Display the currently selected thread."
1229   (interactive)
1230   (let ((thread-id (notmuch-search-find-thread-id)))
1231     (if (> (length thread-id) 0)
1232         (notmuch-show thread-id (current-buffer) notmuch-search-query-string)
1233       (error "End of search results"))))
1234
1235 (defun notmuch-search-reply-to-thread ()
1236   "Begin composing a reply to the entire current thread in a new buffer."
1237   (interactive)
1238   (let ((message-id (notmuch-search-find-thread-id)))
1239     (notmuch-reply message-id)))
1240
1241 (defun notmuch-call-notmuch-process (&rest args)
1242   "Synchronously invoke \"notmuch\" with the given list of arguments.
1243
1244 Output from the process will be presented to the user as an error
1245 and will also appear in a buffer named \"*Notmuch errors*\"."
1246   (let ((error-buffer (get-buffer-create "*Notmuch errors*")))
1247     (with-current-buffer error-buffer
1248         (erase-buffer))
1249     (if (eq (apply 'call-process notmuch-command nil error-buffer nil args) 0)
1250         (point)
1251       (progn
1252         (with-current-buffer error-buffer
1253           (let ((beg (point-min))
1254                 (end (- (point-max) 1)))
1255             (error (buffer-substring beg end))
1256             ))))))
1257
1258 (defun notmuch-search-set-tags (tags)
1259   (save-excursion
1260     (end-of-line)
1261     (re-search-backward "(")
1262     (forward-char)
1263     (let ((beg (point))
1264           (inhibit-read-only t))
1265       (re-search-forward ")")
1266       (backward-char)
1267       (let ((end (point)))
1268         (delete-region beg end)
1269         (insert (mapconcat  'identity tags " "))))))
1270
1271 (defun notmuch-search-get-tags ()
1272   (save-excursion
1273     (end-of-line)
1274     (re-search-backward "(")
1275     (let ((beg (+ (point) 1)))
1276       (re-search-forward ")")
1277       (let ((end (- (point) 1)))
1278         (split-string (buffer-substring beg end))))))
1279
1280 (defun notmuch-search-add-tag (tag)
1281   "Add a tag to the currently selected thread.
1282
1283 The tag is added to messages in the currently selected thread
1284 which match the current search terms."
1285   (interactive
1286    (list (notmuch-select-tag-with-completion "Tag to add: ")))
1287   (notmuch-call-notmuch-process "tag" (concat "+" tag) (notmuch-search-find-thread-id))
1288   (notmuch-search-set-tags (delete-dups (sort (cons tag (notmuch-search-get-tags)) 'string<))))
1289
1290 (defun notmuch-search-remove-tag (tag)
1291   "Remove a tag from the currently selected thread.
1292
1293 The tag is removed from messages in the currently selected thread
1294 which match the current search terms."
1295   (interactive
1296    (list (notmuch-select-tag-with-completion "Tag to remove: " (notmuch-search-find-thread-id))))
1297   (notmuch-call-notmuch-process "tag" (concat "-" tag) (notmuch-search-find-thread-id))
1298   (notmuch-search-set-tags (delete tag (notmuch-search-get-tags))))
1299
1300 (defun notmuch-search-archive-thread ()
1301   "Archive the currently selected thread (remove its \"inbox\" tag).
1302
1303 This function advances the next thread when finished."
1304   (interactive)
1305   (notmuch-search-remove-tag "inbox")
1306   (forward-line))
1307
1308 (defun notmuch-search-process-sentinel (proc msg)
1309   "Add a message to let user know when \"notmuch search\" exits"
1310   (let ((buffer (process-buffer proc))
1311         (status (process-status proc))
1312         (exit-status (process-exit-status proc)))
1313     (if (memq status '(exit signal))
1314         (if (buffer-live-p buffer)
1315             (with-current-buffer buffer
1316               (save-excursion
1317                 (let ((inhibit-read-only t))
1318                   (goto-char (point-max))
1319                   (if (eq status 'signal)
1320                       (insert "Incomplete search results (search process was killed).\n"))
1321                   (if (eq status 'exit)
1322                       (progn
1323                         (insert "End of search results.")
1324                         (if (not (= exit-status 0))
1325                             (insert (format " (process returned %d)" exit-status)))
1326                         (insert "\n"))))))))))
1327
1328 (defun notmuch-search-process-filter (proc string)
1329   "Process and filter the output of \"notmuch search\""
1330   (let ((buffer (process-buffer proc)))
1331     (if (buffer-live-p buffer)
1332         (with-current-buffer buffer
1333           (save-excursion
1334             (let ((line 0)
1335                   (more t)
1336                   (inhibit-read-only t))
1337               (while more
1338                 (if (string-match "^\\(thread:[0-9A-Fa-f]*\\) \\(.*\\) \\(\\[[0-9/]*\\]\\) \\([^:]*\\); \\(.*\\) (\\([^()]*\\))$" string line)
1339                     (let* ((thread-id (match-string 1 string))
1340                            (date (match-string 2 string))
1341                            (count (match-string 3 string))
1342                            (authors (match-string 4 string))
1343                            (authors-length (length authors))
1344                            (subject (match-string 5 string))
1345                            (tags (match-string 6 string)))
1346                       (if (> authors-length 40)
1347                           (set 'authors (concat (substring authors 0 (- 40 3)) "...")))
1348                       (goto-char (point-max))
1349                       (let ((beg (point-marker)))
1350                         (insert (format "%s %-7s %-40s %s (%s)\n" date count authors subject tags))
1351                         (put-text-property beg (point-marker) 'notmuch-search-thread-id thread-id)
1352                         (put-text-property beg (point-marker) 'notmuch-search-authors authors)
1353                         (put-text-property beg (point-marker) 'notmuch-search-subject subject))
1354                       (set 'line (match-end 0)))
1355                   (set 'more nil))))))
1356       (delete-process proc))))
1357
1358 (defun notmuch-search-operate-all (action)
1359   "Add/remove tags from all matching messages.
1360
1361 Tis command adds or removes tags from all messages matching the
1362 current search terms. When called interactively, this command
1363 will prompt for tags to be added or removed. Tags prefixed with
1364 '+' will be added and tags prefixed with '-' will be removed.
1365
1366 Each character of the tag name may consist of alphanumeric
1367 characters as well as `_.+-'.
1368 "
1369   (interactive "sOperation (+add -drop): notmuch tag ")
1370   (let ((action-split (split-string action " +")))
1371     ;; Perform some validation
1372     (let ((words action-split))
1373       (when (null words) (error "No operation given"))
1374       (while words
1375         (unless (string-match-p "^[-+][-+_.[:word:]]+$" (car words))
1376           (error "Action must be of the form `+thistag -that_tag'"))
1377         (setq words (cdr words))))
1378     (apply 'notmuch-call-notmuch-process "tag"
1379            (append action-split (list notmuch-search-query-string) nil))))
1380
1381 ;;;###autoload
1382 (defun notmuch-search (query &optional oldest-first)
1383   "Run \"notmuch search\" with the given query string and display results."
1384   (interactive "sNotmuch search: ")
1385   (let ((buffer (get-buffer-create (concat "*notmuch-search-" query "*"))))
1386     (switch-to-buffer buffer)
1387     (notmuch-search-mode)
1388     (set 'notmuch-search-query-string query)
1389     (set 'notmuch-search-oldest-first oldest-first)
1390     (let ((proc (get-buffer-process (current-buffer)))
1391           (inhibit-read-only t))
1392       (if proc
1393           (error "notmuch search process already running for query `%s'" query)
1394         )
1395       (erase-buffer)
1396       (goto-char (point-min))
1397       (save-excursion
1398         (let ((proc (start-process-shell-command
1399                      "notmuch-search" buffer notmuch-command "search"
1400                      (if oldest-first "--sort=oldest-first" "--sort=newest-first")
1401                      (shell-quote-argument query))))
1402           (set-process-sentinel proc 'notmuch-search-process-sentinel)
1403           (set-process-filter proc 'notmuch-search-process-filter))))
1404     (run-hooks 'notmuch-search-hook)))
1405
1406 (defun notmuch-search-refresh-view ()
1407   "Refresh the current view.
1408
1409 Kills the current buffer and runs a new search with the same
1410 query string as the current search. If the current thread is in
1411 the new search results, then point will be placed on the same
1412 thread. Otherwise, point will be moved to attempt to be in the
1413 same relative position within the new buffer."
1414   (interactive)
1415   (let ((here (point))
1416         (oldest-first notmuch-search-oldest-first)
1417         (thread (notmuch-search-find-thread-id))
1418         (query notmuch-search-query-string))
1419     (kill-this-buffer)
1420     (notmuch-search query oldest-first)
1421     (goto-char (point-min))
1422     (if (re-search-forward (concat "^" thread) nil t)
1423         (beginning-of-line)
1424       (goto-char here))))
1425
1426 (defun notmuch-search-toggle-order ()
1427   "Toggle the current search order.
1428
1429 By default, the \"inbox\" view created by `notmuch' is displayed
1430 in chronological order (oldest thread at the beginning of the
1431 buffer), while any global searches created by `notmuch-search'
1432 are displayed in reverse-chronological order (newest thread at
1433 the beginning of the buffer).
1434
1435 This command toggles the sort order for the current search.
1436
1437 Note that any filtered searches created by
1438 `notmuch-search-filter' retain the search order of the parent
1439 search."
1440   (interactive)
1441   (set 'notmuch-search-oldest-first (not notmuch-search-oldest-first))
1442   (notmuch-search-refresh-view))
1443
1444 (defun notmuch-search-filter (query)
1445   "Filter the current search results based on an additional query string.
1446
1447 Runs a new search matching only messages that match both the
1448 current search results AND the additional query string provided."
1449   (interactive "sFilter search: ")
1450   (let ((grouped-query (if (string-match-p notmuch-search-disjunctive-regexp query) (concat "( " query " )") query)))
1451     (notmuch-search (concat notmuch-search-query-string " and " grouped-query) notmuch-search-oldest-first)))
1452
1453 (defun notmuch-search-filter-by-tag (tag)
1454   "Filter the current search results based on a single tag.
1455
1456 Runs a new search matching only messages that match both the
1457 current search results AND that are tagged with the given tag."
1458   (interactive
1459    (list (notmuch-select-tag-with-completion "Filter by tag: ")))
1460   (notmuch-search (concat notmuch-search-query-string " and tag:" tag) notmuch-search-oldest-first))
1461
1462
1463 ;;;###autoload
1464 (defun notmuch ()
1465   "Run notmuch to display all mail with tag of 'inbox'"
1466   (interactive)
1467   (notmuch-search "tag:inbox" notmuch-search-oldest-first))
1468
1469 (setq mail-user-agent 'message-user-agent)
1470
1471 (defvar notmuch-folder-mode-map
1472   (let ((map (make-sparse-keymap)))
1473     (define-key map "?" 'notmuch-help)
1474     (define-key map "x" 'kill-this-buffer)
1475     (define-key map "q" 'kill-this-buffer)
1476     (define-key map "m" 'message-mail)
1477     (define-key map "e" 'notmuch-folder-show-empty-toggle)
1478     (define-key map ">" 'notmuch-folder-last)
1479     (define-key map "<" 'notmuch-folder-first)
1480     (define-key map "=" 'notmuch-folder)
1481     (define-key map "s" 'notmuch-search)
1482     (define-key map [mouse-1] 'notmuch-folder-show-search)
1483     (define-key map (kbd "RET") 'notmuch-folder-show-search)
1484     (define-key map " " 'notmuch-folder-show-search)
1485     (define-key map "p" 'notmuch-folder-previous)
1486     (define-key map "n" 'notmuch-folder-next)
1487     map)
1488   "Keymap for \"notmuch folder\" buffers.")
1489
1490 (fset 'notmuch-folder-mode-map notmuch-folder-mode-map)
1491
1492 (defcustom notmuch-folders (quote (("inbox" . "tag:inbox") ("unread" . "tag:unread")))
1493   "List of searches for the notmuch folder view"
1494   :type '(alist :key-type (string) :value-type (string))
1495   :group 'notmuch)
1496
1497 (defun notmuch-folder-mode ()
1498   "Major mode for showing notmuch 'folders'.
1499
1500 This buffer contains a list of message counts returned by a
1501 customizable set of searches of your email archives. Each line in
1502 the buffer shows the name of a saved search and the resulting
1503 message count.
1504
1505 Pressing RET on any line opens a search window containing the
1506 results for the saved search on that line.
1507
1508 Here is an example of how the search list could be
1509 customized, (the following text would be placed in your ~/.emacs
1510 file):
1511
1512 (setq notmuch-folders '((\"inbox\" . \"tag:inbox\")
1513                         (\"unread\" . \"tag:inbox AND tag:unread\")
1514                         (\"notmuch\" . \"tag:inbox AND to:notmuchmail.org\")))
1515
1516 Of course, you can have any number of folders, each configured
1517 with any supported search terms (see \"notmuch help search-terms\").
1518
1519 Currently available key bindings:
1520
1521 \\{notmuch-folder-mode-map}"
1522   (interactive)
1523   (kill-all-local-variables)
1524   (use-local-map 'notmuch-folder-mode-map)
1525   (setq truncate-lines t)
1526   (hl-line-mode 1)
1527   (setq major-mode 'notmuch-folder-mode
1528         mode-name "notmuch-folder")
1529   (setq buffer-read-only t))
1530
1531 (defun notmuch-folder-next ()
1532   "Select the next folder in the list."
1533   (interactive)
1534   (forward-line 1)
1535   (if (eobp)
1536       (forward-line -1)))
1537
1538 (defun notmuch-folder-previous ()
1539   "Select the previous folder in the list."
1540   (interactive)
1541   (forward-line -1))
1542
1543 (defun notmuch-folder-first ()
1544   "Select the first folder in the list."
1545   (interactive)
1546   (goto-char (point-min)))
1547
1548 (defun notmuch-folder-last ()
1549   "Select the last folder in the list."
1550   (interactive)
1551   (goto-char (point-max))
1552   (forward-line -1))
1553
1554 (defun notmuch-folder-count (search)
1555   (car (process-lines notmuch-command "count" search)))
1556
1557 (setq notmuch-folder-show-empty t)
1558
1559 (defun notmuch-folder-show-empty-toggle ()
1560   "Toggle the listing of empty folders"
1561   (interactive)
1562   (setq notmuch-folder-show-empty (not notmuch-folder-show-empty))
1563   (notmuch-folder))
1564
1565 (defun notmuch-folder-add (folders)
1566   (if folders
1567       (let* ((name (car (car folders)))
1568             (inhibit-read-only t)
1569             (search (cdr (car folders)))
1570             (count (notmuch-folder-count search)))
1571         (if (or notmuch-folder-show-empty
1572                 (not (equal count "0")))
1573             (progn
1574               (insert name)
1575               (indent-to 16 1)
1576               (insert count)
1577               (insert "\n")
1578               )
1579           )
1580         (notmuch-folder-add (cdr folders)))))
1581
1582 (defun notmuch-folder-find-name ()
1583   (save-excursion
1584     (beginning-of-line)
1585     (let ((beg (point)))
1586       (re-search-forward "\\([ \t]*[^ \t]+\\)")
1587       (filter-buffer-substring (match-beginning 1) (match-end 1)))))
1588
1589 (defun notmuch-folder-show-search (&optional folder)
1590   "Show a search window for the search related to the specified folder."
1591   (interactive)
1592   (if (null folder)
1593       (setq folder (notmuch-folder-find-name)))
1594   (let ((search (assoc folder notmuch-folders)))
1595     (if search
1596         (notmuch-search (cdr search) notmuch-search-oldest-first))))
1597
1598 ;;;###autoload
1599 (defun notmuch-folder ()
1600   "Show the notmuch folder view and update the displayed counts."
1601   (interactive)
1602   (let ((buffer (get-buffer-create "*notmuch-folders*")))
1603     (switch-to-buffer buffer)
1604     (let ((inhibit-read-only t)
1605           (n (line-number-at-pos)))
1606       (erase-buffer)
1607       (notmuch-folder-mode)
1608       (notmuch-folder-add notmuch-folders)
1609       (goto-char (point-min))
1610       (goto-line n))))
1611
1612 (provide 'notmuch)