]> git.notmuchmail.org Git - notmuch-wiki/blob - emacstips.mdwn
Be sure to setup notmuch first.
[notmuch-wiki] / emacstips.mdwn
1 # Tips and Tricks for using notmuch with Emacs
2
3 One of the more popular notmuch message reading clients is
4 **notmuch.el**, an [emacs](http://www.gnu.org/software/emacs/) major
5 mode for interacting with notmuch.  It is included in the notmuch
6 package (notmuch-emacs in Debian).  This page goes over some usage
7 tips for using notmuch with Emacs.
8
9 [[!toc levels=2]]
10
11 ## Setup
12
13 Have a look at the [Howto](http://notmuchmail.org/howto/) for
14 prerequisites.  Be sure you have done the general setup using the
15 notmuch cli command!
16
17 To use the Notmuch emacs mode, first add the following line to your
18 `.emacs` rc file:
19
20         (require 'notmuch)
21
22 or you can load the package via autoload:
23
24         (autoload 'notmuch "notmuch" "notmuch mail" t)
25
26 Then, either run "emacs -f notmuch", or execute the command `M-x
27 notmuch` from within a running emacs.
28
29 ## Navigating & reading mails
30
31 When first starting notmuch in emacs, you will be presented with the
32 notmuch "hello" page.  From here you can do searches, see lists of
33 recent searches, saved searches, message tags, help information, etc.
34
35 Executing a search will open a new buffer in `notmuch-search-mode`
36 displaying the search results.  Each line in the search results
37 represents a message thread.  Hitting the '?' key will show help for
38 this mode.
39
40 In general, the 'q' will kill the current notmuch buffer and return
41 you to the previous buffer (sort of like a 'pop').
42
43 In search mode, navigating to a thread and hitting return will then
44 open a new buffer in `notmuch-show-mode`, which will show the actual
45 message contents of the thread.
46
47 ## Sending mail
48
49 In any notmuch mode, you can start a new message by hitting the 'm'
50 key.  To reply to a message or thread, just hit the 'r' key.
51
52 When composing new messages, you will be entered in emacs's
53 `message-mode`, which is a powerful mode for composing and sending
54 messages.  When in message mode, you can type `C-c ?` for help.
55
56 If you would like to use address autocompletion when composing
57 messages, see [address completion](#address_completion).
58
59 When you are ready to send a message, type `C-c C-c`. By default
60 message mode will use your sendmail command to send mail, so make sure
61 that works. One annoying standard configuration of message mode is
62 that it will hide the sent mail in your emacs frame stack, but it will
63 not close it. If you type several mails in an emacs session they will
64 accumulate and make switching between buffers more annoying. You can
65 avoid that behavior by adding `(setq message-kill-buffer-on-exit t)`
66 in your `.emacs` file (or doing `M-x
67 customize-variable<RET>message-kill-buffer-on-exit<RET>`) which will
68 really close the mail window after sending it.
69
70 ## Attaching files
71
72 Using the `M-x mml-attach-file` command, you can attach any file to be
73 sent with your mail. By default this command is bound to the menu item
74 *Attachments--Attach File* with the key binding `C-c C-a`. The
75 variable `mml-dnd-attach-options` (`M-x
76 customize-variable<RET>mml-dnd-attach-options<RET>`) can be set to
77 allow the prompting for various attachment options (such as
78 inline/attachment) if you want to do that.
79
80 For those who prefer a more graphical interface, you can also simply
81 drag and drop files from a file manager into a mail composition window
82 to have them attached. In Ubuntu this works without any modifications
83 if files are dragged from the file manager.
84
85 And for those who prefer working from command line, the following
86 script opens new emacs window with empty message and attaches files
87 mentioned as script arguments. (Note: The script expects that you have
88 `(server-start)` in your `.emacs` file.)
89
90         #!/bin/sh
91         attach_cmds=""
92         while [ "$1" ]; do
93             fullpath=$(readlink --canonicalize "$1")
94             attach_cmds="$attach_cmds (mml-attach-file \"$fullpath\")"
95             shift
96         done
97         emacsclient -a '' -c -e "(progn (compose-mail) $attach_cmds)"
98
99 ## Issues with Emacs 24
100
101 If notmuch-show-mode behaves badly for you in emacs 24.x try adding one of
102
103         (setq gnus-inhibit-images nil)
104
105 or
106
107         (require 'gnus-art)
108
109 to your .emacs file.
110
111 -----
112
113 # Advanced tips and tweaks
114
115 ## Use separate emacs lisp file for notmuch configuration
116
117 Instead of adding notmuch configuration code to `.emacs`, there
118 is an option to collect those to a separate file (which is only
119 loaded when `notmuch` is invoked). To do this, write, for example
120 a file called `~/.emacs.d/my-notmuch.el`:
121
122         ;;; my-notmuch.el -- my notmuch mail configuration
123         ;;;
124         
125         ;;; add here stuff required to be configured *before*
126         ;;; notmuch is loaded;
127
128         ;; uncomment and modify in case some elisp files are not found in load-path
129         ;; (add-to-list 'load-path "~/vc/ext/notmuch/emacs")
130
131         ;;; load notmuch 
132         (require 'notmuch)
133
134         ;;; add here stuff required to be configured *after*
135         ;;; notmuch is loaded;
136
137         ;; uncomment & modify if you want to use external smtp server to send mail
138         ;; (setq smtpmail-smtp-server "smtp.server.tld"
139         ;;       message-send-mail-function 'message-smtpmail-send-it)
140         ;; uncomment to debug smtp sending problems
141         ;; (setq smtpmail-debug-info t)
142
143 Then, add to `.emacs`:
144
145         (autoload 'notmuch "~/.emacs.d/my-notmuch" "notmuch mail" t)
146
147
148 ## Add a key binding to add/remove/toggle a tag
149
150 The `notmuch-{search,show}-{add,remove}-tag` functions are very useful
151 for making quick tag key bindings.  For instance, here's an example
152 of how to make a key binding to add the "spam" tag and remove the
153 "inbox" tag in notmuch-show-mode:
154
155 In notmuch versions up to 0.11.x
156
157         (define-key notmuch-show-mode-map "S"
158           (lambda ()
159             "mark message as spam"
160             (interactive)
161             (notmuch-show-add-tag "spam")
162             (notmuch-show-remove-tag "inbox")))
163
164 Starting from notmuch 0.12 the functions `notmuch-show-add-tag` and 
165 `notmuch-show-remove-tag` have changed to be more versatile and lost
166 noninteractive use. When upgrading to 0.12 the above needs to be 
167 changed to this:
168
169         (define-key notmuch-show-mode-map "S"
170           (lambda ()
171             "mark message as spam"
172             (interactive)
173             (notmuch-show-tag-message "+spam" "-inbox")))
174
175 You can do the same for threads in `notmuch-search-mode` by just
176 replacing "show" with "search" in the called functions.
177
178 Starting from notmuch 0.12 use `notmuch-search-tag-thread` instead:
179
180         (define-key notmuch-search-mode-map "S"
181           (lambda ()
182             "mark messages in thread as spam"
183             (interactive)
184             (notmuch-show-tag-thread "+spam" "-inbox")))
185
186 Starting from notmuch 0.13 use `notmuch-search-tag` -- it has a little
187 different usage syntax:
188
189         (define-key notmuch-search-mode-map "S"
190           (lambda ()
191             "mark messages in thread as spam"
192             (interactive)
193             (notmuch-search-tag '("+spam" "-inbox"))))
194
195 The definition above makes use of a lambda function, but you could
196 also define a separate function first:
197
198         (defun notmuch-show-tag-spam ()
199           "mark message as spam"
200           (interactive)
201           (notmuch-show-add-tag "spam")
202           (notmuch-show-remove-tag "inbox")))
203         (define-key notmuch-show-mode-map "S" 'notmuch-show-tag-spam)
204
205 (See above for analogy how to apply this for notmuch 0.12 and later)
206
207 Here's a more complicated example of how to add a toggle "deleted"
208 key:
209
210         (define-key notmuch-show-mode-map "d"
211           (lambda ()
212             "toggle deleted tag for message"
213             (interactive)
214             (if (member "deleted" (notmuch-show-get-tags))
215                 (notmuch-show-remove-tag "deleted")
216               (notmuch-show-add-tag "deleted"))))
217
218 And version for notmuch 0.12
219
220         (define-key notmuch-show-mode-map "d"
221           (lambda ()
222             "toggle deleted tag for message"
223             (interactive)
224             (notmuch-show-tag-message
225               (if (member "deleted" (notmuch-show-get-tags))
226                   "-deleted" "+deleted"))))
227
228 ## Adding many tagging keybindings
229
230 If you want to have have many tagging keybindings, you can save the typing
231 the few lines of  boilerplate for every binding (for versions before 0.12,
232 you will need to change notmuch-show-apply-tag-macro).
233
234     (eval-after-load 'notmuch-show
235       '(define-key notmuch-show-mode-map "`" 'notmuch-show-apply-tag-macro))
236
237     (setq notmuch-show-tag-macro-alist
238       (list
239        '("m" "+notmuch::patch" "+notmuch::moreinfo" "-notmuch::needs-review")
240        '("n" "+notmuch::patch" "+notmuch::needs-review" "-notmuch::pushed")
241        '("o" "+notmuch::patch" "+notmuch::obsolete"
242              "-notmuch::needs-review" "-notmuch::moreinfo")
243        '("p" "-notmuch::pushed" "-notmuch::needs-review"
244          "-notmuch::moreinfo" "+pending")
245        '("P" "-pending" "-notmuch::needs-review" "-notmuch::moreinfo" "+notmuch::pushed")
246        '("r" "-notmuch::patch" "+notmuch::review")
247        '("s" "+notmuch::patch" "-notmuch::obsolete" "-notmuch::needs-review" "-notmuch::moreinfo" "+notmuch::stale")
248        '("t" "+notmuch::patch" "-notmuch::needs-review" "+notmuch::trivial")
249        '("w" "+notmuch::patch" "+notmuch::wip" "-notmuch::needs-review")))
250
251     (defun notmuch-show-apply-tag-macro (key)
252       (interactive "k")
253       (let ((macro (assoc key notmuch-show-tag-macro-alist)))
254         (apply 'notmuch-show-tag-message (cdr macro))))
255
256 ## Restore reply-to-all key binding to 'r'
257
258 Starting from notmuch 0.12 the 'r' key is bound to reply-to-sender instead of
259 reply-to-all. Here's how to swap the reply to sender/all bindings in show mode:
260
261         (define-key notmuch-show-mode-map "r" 'notmuch-show-reply)
262         (define-key notmuch-show-mode-map "R" 'notmuch-show-reply-sender)
263
264 And in search mode:
265
266         (define-key notmuch-search-mode-map "r" 'notmuch-search-reply-to-thread)
267         (define-key notmuch-search-mode-map "R" 'notmuch-search-reply-to-thread-sender)
268
269
270 ## How to do FCC/BCC...
271
272 The Emacs interface to notmuch will automatically add an `Fcc`
273 header to your outgoing mail so that any messages you send will also
274 be saved in your mail store. You can control where this copy of the
275 message is saved by setting the variables `message-directory` (which
276 defines a base directory) and `notmuch-fcc-dirs` which defines the
277 subdirectory relative to `message-directory` in which to save the
278 mail. Enter a directory (without the maildir `/cur` ending which
279 will be appended automatically). To customize both variables at the
280 same time, use the fancy command:
281
282         M-x customize-apropos<RET>\(notmuch-fcc-dirs\)\|\(message-directory\)
283
284 This mechanism also allows you to select different folders to be
285 used for the outgoing mail depending on your selected `From`
286 address. Please see the documentation for the variable
287 `notmuch-fcc-dirs` in the customization window for how to arrange
288 this.
289
290 ## How to customize `notmuch-saved-searches`
291
292 When starting notmuch, a list of saved searches and message counts is
293 displayed, replacing the older `notmuch-folders` command. The set of
294 saved searches displayed can be modified directly from the notmuch
295 interface (using the `[save]` button next to a previous search) or by
296 customising the variable `notmuch-saved-searches`.
297
298 An example setting might be:
299
300         (setq notmuch-saved-searches '(("inbox" . "tag:inbox")
301                         ("unread" . "tag:inbox AND tag:unread")
302                         ("notmuch" . "tag:inbox AND to:notmuchmail.org")))
303
304 Of course, you can have any number of saved searches, each configured
305 with any supported search terms (see "notmuch help search-terms").
306
307 Some users find it useful to add `and not tag:delete` to those
308 searches, as they use the `delete` tag to mark messages as
309 deleted. This causes messages that are marked as deleted to be removed
310 from the commonly used views of messages.  Use whatever seems most
311 useful to you.
312
313 ## Viewing HTML messages with an external viewer
314
315 The emacs client can display an HTML message inline using either the
316 `html2text` library or some text browser, like w3m or lynx. This is
317 controlled by the `mm-text-html-renderer` variable.
318
319 The first option is theorically better, because it can generate
320 strings formatted for emacs and do whatever you want, e.g., substitute
321 text inside &lt;b&gt; tags for bold text in the buffer. The library, however
322 is still in a very early development phase and cannot yet process
323 properly many elements, like tables and <style> directives, and even
324 the generated text is often poorly formatted.
325
326 Among the available browsers, w3m seems to do a better job converting
327 the html, and if you have the w3m emacs package, you can use it,
328 instead of the w3m-standalone, and thus preserve the text formatting.
329
330 But if the rendering fails for one reason or another, or if you really
331 need to see the graphical presentation of the HTML message, it can be
332 useful to display the message in an external viewer, such as a web
333 browser. Here's a little script that Keith Packard wrote, which he
334 calls `view-html`:
335
336         #!/bin/sh
337         dir=`mktemp -d`
338         trap "rm -r $dir" 0
339         cat "$@" > "$dir"/msg
340         if munpack -C "$dir" -t < "$dir"/msg 2>&1 | grep 'Did not find'; then
341             sed -n '/[Hh][Tt][Mm][Ll]/,$p' "$dir"/msg > $dir/part1.html
342             rm "$dir"/msg
343         fi
344         for i in "$dir"/part*; do
345             if grep -q -i -e '<html>' -e 'text/html' "$i"; then
346                 iceweasel "$i" &
347                 sleep 3
348                 exit 0
349             fi
350         done
351
352 Save that script somewhere in your `${PATH}`, make it executable,
353 and change the invocation of `iceweasel` to any other HTML viewer if
354 necessary. Then within the emacs client, press '|' to pipe the
355 current message, then type "view-html".
356
357 Keith mentions the following caveat, "Note that if iceweasel isn't
358 already running, it seems to shut down when the script exits. I
359 don't know why."
360
361 ## msmtp, message mode and multiple accounts
362
363 As an alternative to running a mail server such as sendmail or postfix
364 just to send email, it is possible to use
365 [msmtp](http://msmtp.sourceforge.net/). This small application will
366 look like `/usr/bin/sendmail` to a MUA such as emacs message mode, but
367 will just forward the email to an external SMTP server. It's fairly
368 easy to set up and it supports several accounts for using different
369 SMTP servers. The msmtp pages have several examples.
370
371 A typical scenario is that you want to use the company SMTP server
372 for email coming from your company email address, and your personal
373 server for personal email.  If msmtp is passed the envelope address
374 on the command line (the -f/--from option) it will automatically
375 pick the matching account.  The only trick here seems to be getting
376 emacs to actually pass the envelope from.  There are a number of
377 overlapping configuration variables that control this, and it's a
378 little confusion, but setting these three works for me:
379
380  - `mail-specify-envelope-from`: `t`
381
382  - `message-sendmail-envelope-from`: `header`
383
384  - `mail-envelope-from`: `header`
385
386 With that in place, you need a `.msmtprc` with the accounts configured
387 for the domains you want to send out using specific SMTP servers and
388 the rest will go to the default account.
389
390 If you have a hard time getting the above to work for you, as I did,
391 it's also possible to add a message-send-mail-hook in your .emacs to
392 send the from header explicitly as an argument to msmtp as described
393 [here](http://www.emacswiki.org/cgi-bin/wiki/GnusMSMTP#toc2) on the
394 emacswiki.
395
396
397 ## <span id="address_completion">Address completion when composing</span>
398
399 There are currently three solutions to this:
400
401 ### bbdb
402
403 [bbdb](http://bbdb.sourceforge.net) is a contact database for emacs
404 that works quite nicely together with message mode, including
405 address autocompletion.
406
407 ### notmuch database as an address book
408
409 You can also use the notmuch database as a mail address book itself.
410 To do this you need a command line tool that outputs likely address
411 candidates based on a search string.  There are currently three
412 available:
413
414   * The python tool `notmuch_address.py` (`git clone
415     http://commonmeasure.org/~jkr/git/notmuch_addresses.git`) (slower, but
416     no compilation required so good for testing the setup)
417
418   * The vala-based
419     [addrlookup](http://github.com/spaetz/vala-notmuch) (faster, but
420     needs compiling).  The addrlookup binary needs to be compiled.
421     Grab
422     `http://github.com/spaetz/vala-notmuch/raw/static-sources/src/addrlookup.c`
423     and build it with:
424
425             cc -o addrlookup addrlookup.c `pkg-config --cflags --libs gobject-2.0` -lnotmuch
426
427   * Shell/fgrep/perl combination [nottoomuch-addresses.sh](http://www.iki.fi/too/nottoomuch/nottoomuch-addresses/). 
428     This tools maintains it's own address "database" gathered from email
429     files notmuch knows and search from that "database" is done by `fgrep(1)`.
430
431 You can perform tab-completion using any of these programs.
432 Just add the following to your .emacs:
433
434         (require 'notmuch-address)
435         (setq notmuch-address-command "/path/to/address_fetching_program")
436         (notmuch-address-message-insinuate)
437
438 ### Google Contacts
439
440 [GooBook](http://code.google.com/p/goobook/) is a command-line tool for
441 accessing Google Contacts. Install and set it up according to its documentation.
442
443 To use GooBook with notmuch, use this wrapper script and set it up like the
444 programs above.
445
446         #!/bin/sh
447         goobook query "$*" | sed 's/\(.*\)\t\(.*\)\t.*/\2 \<\1\>/' | sed '/^$/d'
448
449 You can add the sender of a message to Google Contacts by piping the message
450 (`notmuch-show-pipe-message`) to `goobook add`.
451
452 ## How to sign/encrypt messages with gpg
453
454 Messages can by signed using gpg by invoking 
455 `M-x mml-secure-sign-pgpmime` (or `M-x mml-secure-encrypt-pgpmime`).
456 These functions are available via the standard `message-mode` keybindings 
457 `C-c C-m s p` and `C-c C-m c p`. To sign outgoing mail by default, use the
458 `message-setup-hook` in your `.emacs` file:
459
460         ;; Sign messages by default.
461         (add-hook 'message-setup-hook 'mml-secure-sign-pgpmime)
462
463 This inserts the required `<#part sign=pgpmime>` into the beginning
464 of the mail text body and will be converted into a pgp signature
465 when sending (so one can just manually delete that line if signing
466 is not required).
467
468 Alternatively, you may prefer to use `mml-secure-message-sign-pgpmime` instead
469 of `mml-secure-sign-pgpmime` to sign the whole message instead of just one
470 part.
471
472 ### Troubleshooting message-mode gpg support
473
474 - If you have trouble with expired subkeys, you may have encountered
475   emacs bug #7931.  This is fixed in git commit 301ea744c on
476   2011-02-02.  Note that if you have the Debian package easypg
477   installed, it will shadow the fixed version of easypg included with
478   emacs.
479
480 ## Multiple identities using gnus-alias
481
482 [gnus-alias](http://www.emacswiki.org/emacs/GnusAlias) allows you to
483 define multiple identities when using `message-mode`. You can specify
484 the from address, organization, extra headers (including *Bcc*), extra
485 body text, and signature for each identity. Identities are chosen
486 based on a set of rules. When you are in message mode, you can switch
487 identities using gnus-alias.
488
489 ### Installation
490
491 - put `gnus-alias.el` on your load Emacs-Lisp load path (add new directory
492   to load path by writing `(add-to-list 'load-path "/some/load/path")` into
493   your `.emacs`.
494
495 - Add the following to your `.emacs`
496
497         (autoload 'gnus-alias-determine-identity "gnus-alias" "" t)
498         (add-hook 'message-setup-hook 'gnus-alias-determine-identity)
499
500 Looking into `gnus-alias.el` gives a bit more information...
501
502 ### Example Configuration 
503
504 Here is an example configuration.
505
506         ;; Define two identities, "home" and "work"
507         (setq gnus-alias-identity-alist
508               '(("home"
509                  nil ;; Does not refer to any other identity
510                  "John Doe <jdoe@example.net>" ;; Sender address
511                  nil ;; No organization header
512                  nil ;; No extra headers
513                  nil ;; No extra body text
514                  "~/.signature")
515                 ("work"
516                  nil
517                  "John Doe <john.doe@example.com>"
518                  "Example Corp."
519                  (("Bcc" . "john.doe@example.com"))
520                  nil
521                  "~/.signature.work")))
522         ;; Use "home" identity by default
523         (setq gnus-alias-default-identity "home")
524         ;; Define rules to match work identity
525         (setq gnus-alias-identity-rules
526               '(("work" ("any" "john.doe@\\(example\\.com\\|help\\.example.com\\)" both) "work"))
527         ;; Determine identity when message-mode loads
528         (add-hook 'message-setup-hook 'gnus-alias-determine-identity)
529
530 When `gnus-alias` has been loaded (using autoload, require, *M-x load-library*
531 or *M-x load-file* (load-file takes file path -- therefore it can be used
532 without any `.emacs` changes)) the following commands can be used to get(/set)
533 more information (some of these have "extensive documentation"):
534
535         M-x describe-variable RET gnus-alias-identity-alist
536         M-x describe-variable RET gnus-alias-identity-rules
537         M-x describe-variable RET gnus-alias-default-identity
538
539         M-x customize-group RET gnus-alias RET
540           or 
541         M-x gnus-alias-customize RET
542
543 The last two do the same thing.
544
545 See also the **Usage:** section in `gnus-alias.el`.
546
547 ## Resending (or bouncing) messages
548
549 Add the following to your `.emacs` to be able to resend the current message in
550 show mode.
551
552         (define-key notmuch-show-mode-map "b"
553           (lambda (&optional address)
554             "Bounce the current message."
555             (interactive "sBounce To: ")
556             (notmuch-show-view-raw-message)
557             (message-resend address)))
558
559 ## `notmuch-hello` refresh status message
560
561 Add the following to your `.emacs` to get a status message about the change in
562 the number of messages in the mail store when refreshing the `notmuch-hello`
563 buffer.
564
565         (defvar notmuch-hello-refresh-count 0)
566
567         (defun notmuch-hello-refresh-status-message ()
568           (unless no-display
569             (let* ((new-count
570                     (string-to-number
571                      (car (process-lines notmuch-command "count"))))
572                    (diff-count (- new-count notmuch-hello-refresh-count)))
573               (cond
574                ((= notmuch-hello-refresh-count 0)
575                 (message "You have %s messages."
576                          (notmuch-hello-nice-number new-count)))
577                ((> diff-count 0)
578                 (message "You have %s more messages since last refresh."
579                          (notmuch-hello-nice-number diff-count)))
580                ((< diff-count 0)
581                 (message "You have %s fewer messages since last refresh."
582                          (notmuch-hello-nice-number (- diff-count)))))
583               (setq notmuch-hello-refresh-count new-count))))
584
585         (add-hook 'notmuch-hello-refresh-hook 'notmuch-hello-refresh-status-message)
586
587 ## Replacing tabs with spaces in subject and header
588
589 Mailman mailing list software rewrites and rewraps long message subjects in
590 a way that causes TABs to appear in the middle of the subject and header
591 lines. Add this to your `.emacs` to replace tabs with spaces in subject
592 lines:
593
594         (defun notmuch-show-subject-tabs-to-spaces ()
595           "Replace tabs with spaces in subject line."
596           (goto-char (point-min))
597           (when (re-search-forward "^Subject:" nil t)
598             (while (re-search-forward "\t" (line-end-position) t)
599               (replace-match " " nil nil))))
600
601         (add-hook 'notmuch-show-markup-headers-hook 'notmuch-show-subject-tabs-to-spaces)
602
603 And in header lines (this will only work with the yet to be released
604 notmuch version 0.15):
605
606         (defun notmuch-show-header-tabs-to-spaces ()
607           "Replace tabs with spaces in header line."
608           (setq header-line-format
609                 (notmuch-show-strip-re
610                  (replace-regexp-in-string "\t" " " (notmuch-show-get-subject)))))
611
612         (add-hook 'notmuch-show-hook 'notmuch-show-header-tabs-to-spaces)