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