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