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