]> git.cworth.org Git - notmuch-wiki/blob - emacstips.mdwn
News for release 0.38.3
[notmuch-wiki] / emacstips.mdwn
1 [[!img notmuch-logo.png alt="Notmuch logo" class="left"]]
2 # Tips and Tricks for using Notmuch with Emacs
3
4 Here are some tips and tricks for using Notmuch with Emacs. See the [[Notmuch
5 Emacs Interface|notmuch-emacs]] page for basics.
6
7 [[!toc levels=2]]
8
9 ## Issues with Emacs 24 (unsupported since notmuch 0.31 (2020-09-05))
10
11 If notmuch-show-mode behaves badly for you in emacs 24.x try adding one of
12
13         (setq gnus-inhibit-images nil)
14
15 or
16
17         (require 'gnus-art)
18
19 to your .emacs file.
20
21 ## Controlling external handlers for attachments
22
23 You can choose e.g. which pdf viewer to invoke from notmuch-show mode by
24 adding a .mailcap file in your home directory. Here is an example:
25
26     application/pdf; /usr/bin/mupdf %s; test=test "$DISPLAY" != ""; description=Portable Document Format; nametemplate=%s.pdf
27     application/x-pdf; /usr/bin/mupdf %s; test=test "$DISPLAY" != ""; description=Portable Document Format; nametemplate=%s.pdf
28
29 ### Convert ".pdf" and ".docx" to text and pop to buffer
30
31 Add the following (hacky but effective!) code to `.emacs.d/notmuch-config.el`;
32 the overwritten `defcustom` will change action when pressing RET on top of an
33 attachment; ".pdf" and ".docx" attachments are converted to text (using
34 "pdf2text" and "docx2txt.pl" commands to do the conversion), saving to file
35 (the default action of `notmuch-show-part-button-default-action`) is offered
36 to attachments of other types.
37
38     (defun user/mm-pipe-- (handle cmd)
39       ;; conveniently, '-' '-' a args to pdftotext and docx2txt.pl work fine
40       ;; fixme: naming inconsistency (fn name and buffer name)
41       (let ((buffer (get-buffer-create "*attachment-to-text*")))
42         (with-current-buffer buffer
43           (setq buffer-read-only nil)
44           (erase-buffer))
45         (with-temp-buffer
46           ;; "based on mm-pipe-part in mm-decode.el"
47           (mm-with-unibyte-buffer
48         (mm-insert-part handle)
49         (mm-add-meta-html-tag handle)
50         (let ((coding-system-for-write 'binary))
51           (call-process-region (point-min) (point-max)
52                                cmd nil buffer nil "-" "-"))))
53         (pop-to-buffer buffer)
54         (goto-char (point-min))
55         (text-mode)
56         (visual-line-mode)
57         (view-mode)))
58
59     (defun user/notmuch-show-pop-attachment-to-buffer ()
60       ;; "based on notmuch-show-apply-to-current-part-handle"
61       (interactive)
62       (let ((handle (notmuch-show-current-part-handle)))
63         ;;(message "%s" handle)
64         (unwind-protect
65         (pcase (car (nth 1 handle))
66           ("application/pdf"
67            (user/mm-pipe-- handle "pdftotext"))
68           ("application/vnd.openxmlformats-officedocument.wordprocessingml.document"
69            (user/mm-pipe-- handle "docx2txt.pl"))
70           (_ (notmuch-show-save-part)))
71           (kill-buffer (mm-handle-buffer handle)))))
72
73     (setq notmuch-show-part-button-default-action
74           #'user/notmuch-show-pop-attachment-to-buffer)
75
76 ## Overwriting the sender address
77
78 If you want to always use the same sender address, then the following
79 defadvice can help you.
80
81        (defadvice notmuch-mua-reply (around notmuch-fix-sender)
82          (let ((sender "Max Monster <max.monster@example.com>"))
83            ad-do-it))
84        (ad-activate 'notmuch-mua-reply)
85
86 ## Initial cursor position in notmuch 0.15 hello window
87
88 In notmuch version 0.15 emacs client the handling of cursor position in
89 notmuch hello window has been simplified to a version which suits best
90 most cases.
91
92 Initially the cursor is positioned at the beginning of buffer.
93
94 Some users liked the "ancient" version where cursor was moved to the
95 first `Saved searches` button.
96
97 Add the following code to your notmuch emacs configuration file in
98 case you want this behaviour:
99
100         (add-hook 'notmuch-hello-refresh-hook
101                   (lambda ()
102                     (if (and (eq (point) (point-min))
103                              (search-forward "Saved searches:" nil t))
104                         (progn
105                           (forward-line)
106                           (widget-forward 1))
107                       (if (eq (widget-type (widget-at)) 'editable-field)
108                           (beginning-of-line)))))
109
110 ## Add a key binding to add/remove/toggle a tag
111
112 The `notmuch-{search,show,tree}-tag` functions are very useful for
113 making quick tag key bindings.  The arguments to these functions have
114 changed as notmuch has evolved but the following should work on all
115 versions of notmuch from 0.13 on.  These functions take a list of
116 tag changes as argument. For example, an argument of (list "+spam"
117 "-inbox") adds the tag spam and deletes the tag inbox. Note the
118 argument must be a list even if there is only a single tag change
119 e.g., use (list "+deleted") to add the deleted tag.
120
121 For instance, here's an example of how to make a key binding to add
122 the "spam" tag and remove the "inbox" tag in notmuch-show-mode:
123
124         (define-key notmuch-show-mode-map "S"
125           (lambda ()
126             "mark message as spam"
127             (interactive)
128             (notmuch-show-tag (list "+spam" "-inbox"))))
129
130 You can do the same for threads in `notmuch-search-mode` by just
131 replacing "show" with "search" in the keymap and called functions, or
132 for messages in `notmuch-tree-mode` by replacing "show" by "tree". If
133 you want to tag a whole thread in `notmuch-tree-mode` use
134 `notmuch-tree-tag-thread` instead of `notmuch-tree-tag`.
135
136 You may also want the function in search mode apply to the all threads
137 in the selected region (if there is one). For notmuch prior to 0.17
138 this behaviour will occur automatically with the functions given
139 above. To get this behaviour on 0.17+ do the following:
140
141         (define-key notmuch-search-mode-map "S"
142           (lambda (&optional beg end)
143             "mark thread as spam"
144             (interactive (notmuch-interactive-region))
145             (notmuch-search-tag (list "+spam" "-inbox") beg end)))
146
147 The analogous functionality in notmuch-tree is currently missing.
148
149 The definitions above make use of a lambda function, but you could
150 also define a separate function first:
151
152         (defun notmuch-show-tag-spam ()
153           "mark message as spam"
154           (interactive)
155           (notmuch-show-add-tag (list "+spam" "-inbox")))
156
157         (define-key notmuch-show-mode-map "S" 'notmuch-show-tag-spam)
158
159 Here's a more complicated example of how to add a toggle "deleted"
160 key:
161
162         (define-key notmuch-show-mode-map "d"
163           (lambda ()
164             "toggle deleted tag for message"
165             (interactive)
166             (if (member "deleted" (notmuch-show-get-tags))
167                 (notmuch-show-tag (list "-deleted"))
168               (notmuch-show-tag (list "+deleted")))))
169
170 ## Adding many tagging keybindings
171
172 If you want to have have many tagging keybindings, you can save the typing
173 the few lines of  boilerplate for every binding (for versions before 0.12,
174 you will need to change notmuch-show-apply-tag-macro).
175
176     (eval-after-load 'notmuch-show
177       '(define-key notmuch-show-mode-map "`" 'notmuch-show-apply-tag-macro))
178
179     (setq notmuch-show-tag-macro-alist
180       (list
181        '("m" "+notmuch::patch" "+notmuch::moreinfo" "-notmuch::needs-review")
182        '("n" "+notmuch::patch" "+notmuch::needs-review" "-notmuch::pushed")
183        '("o" "+notmuch::patch" "+notmuch::obsolete"
184              "-notmuch::needs-review" "-notmuch::moreinfo")
185        '("p" "-notmuch::pushed" "-notmuch::needs-review"
186          "-notmuch::moreinfo" "+pending")
187        '("P" "-pending" "-notmuch::needs-review" "-notmuch::moreinfo" "+notmuch::pushed")
188        '("r" "-notmuch::patch" "+notmuch::review")
189        '("s" "+notmuch::patch" "-notmuch::obsolete" "-notmuch::needs-review" "-notmuch::moreinfo" "+notmuch::stale")
190        '("t" "+notmuch::patch" "-notmuch::needs-review" "+notmuch::trivial")
191        '("w" "+notmuch::patch" "+notmuch::wip" "-notmuch::needs-review")))
192
193     (defun notmuch-show-apply-tag-macro (key)
194       (interactive "k")
195       (let ((macro (assoc key notmuch-show-tag-macro-alist)))
196         (apply 'notmuch-show-tag-message (cdr macro))))
197
198 ## Restore reply-to-all key binding to 'r'
199
200 Starting from notmuch 0.12 the 'r' key is bound to reply-to-sender instead of
201 reply-to-all. Here's how to swap the reply to sender/all bindings in show mode:
202
203         (define-key notmuch-show-mode-map "r" 'notmuch-show-reply)
204         (define-key notmuch-show-mode-map "R" 'notmuch-show-reply-sender)
205
206 In search mode:
207
208         (define-key notmuch-search-mode-map "r" 'notmuch-search-reply-to-thread)
209         (define-key notmuch-search-mode-map "R" 'notmuch-search-reply-to-thread-sender)
210
211 And in tree mode:
212
213         (define-key notmuch-tree-mode-map "r" (notmuch-tree-close-message-pane-and #'notmuch-show-reply))
214         (define-key notmuch-tree-mode-map "R" (notmuch-tree-close-message-pane-and #'notmuch-show-reply-sender))
215
216 ## How to do FCC/BCC...
217
218 The Emacs interface to notmuch will automatically add an `Fcc`
219 header to your outgoing mail so that any messages you send will also
220 be saved in your mail store. You can control where this copy of the
221 message is saved by setting the variable `notmuch-fcc-dirs` which defines the
222 subdirectory relative to the `database.path` setting from your
223 notmuch configuration in which to save the mail. Enter a directory
224 (without the maildir `/cur` ending which will be appended
225 automatically). Additional information can be found as usual using:
226
227        M-x describe-variable notmuch-fcc-dirs
228
229 An additional variable that can affect FCC settings in some cases is
230 `message-directory`. Emacs message-mode uses this variable for
231 postponed messages.
232
233 To customize both variables at the same time, use the fancy command:
234
235         M-x customize-apropos<RET>\(notmuch-fcc-dirs\)\|\(message-directory\)
236
237 This mechanism also allows you to select different folders to be
238 used for the outgoing mail depending on your selected `From`
239 address. Please see the documentation for the variable
240 `notmuch-fcc-dirs` in the customization window for how to arrange
241 this.
242
243 ## How to customize `notmuch-saved-searches`
244
245 When starting notmuch, a list of saved searches and message counts is
246 displayed, replacing the older `notmuch-folders` command. The set of
247 saved searches displayed can be modified directly from the notmuch
248 interface (using the `[save]` button next to a previous search) or by
249 customising the variable `notmuch-saved-searches`.
250
251 An example setting for notmuch versions up to 0.17.x might be:
252
253         (setq notmuch-saved-searches '(("inbox" . "tag:inbox")
254                         ("unread" . "tag:inbox AND tag:unread")
255                         ("notmuch" . "tag:inbox AND to:notmuchmail.org")))
256
257 Starting from notmuch 0.18 the variable changed. It is backwards
258 compatible so the above will still work but the new style will be used
259 if you use customize and there are some new features available. The above would become
260
261         (setq notmuch-saved-searches '((:name "inbox" :query "tag:inbox")
262                         (:name "unread" :query "tag:inbox AND tag:unread")
263                         (:name "notmuch" :query "tag:inbox AND to:notmuchmail.org")))
264
265 The additional features are the possibility to set the search order
266 for the search, and the possibility to specify a different query for
267 displaying the count for the saved-search. For example
268
269         (setq notmuch-saved-searches '((:name "inbox"
270                                         :query "tag:inbox"
271                                         :count-query "tag:inbox and tag:unread"
272                                         :sort-order oldest-first)))
273
274 specifies a single saved search for inbox, but the number displayed by
275 the search will be the number of unread messages in the inbox, and the
276 sort order for this search will be oldest-first.
277
278 Of course, you can have any number of saved searches, each configured
279 with any supported search terms (see "notmuch help search-terms"), and
280 in the new style variable they can each have different count-queries
281 and sort orders.
282
283 Some users find it useful to add `and not tag:delete` to those
284 searches, as they use the `delete` tag to mark messages as
285 deleted. This causes messages that are marked as deleted to be removed
286 from the commonly used views of messages.  Use whatever seems most
287 useful to you.
288
289 ## Viewing HTML messages with an external viewer
290
291 The Emacs client can generally display HTML messages inline using one of the
292 supported HTML renderers. This is controlled by the `mm-text-html-renderer`
293 variable.
294
295 Sometimes it may be necessary to display the message, or a single MIME part, in
296 an external browser. This can be done by `(notmuch-show-view-part)`, bound to
297 `. v` by default.
298
299 This command will try to view the message part the point is on with an
300 external viewer. The mime-type of the part will determine what viewer
301 will be used. Typically a 'text/html' part will be send to your
302 browser.
303
304 The configuration for this is kept in so called `mailcap`
305 files. (typically the file is `~/.mailcap` or `/etc/mailcap`) If the
306 wrong viewer is started or something else goes wrong, there's a good
307 chance something needs to be adapted in the mailcap configuration.
308
309 For Example: The `copiousoutput` setting in mailcap files needs to be
310 removed for some mime-types to prevent immediate removal of tempory
311 files so the configured viewer can access them.
312
313
314 ## msmtp, message mode and multiple accounts
315
316 As an alternative to running a mail server such as sendmail or postfix
317 just to send email, it is possible to use
318 [msmtp](http://msmtp.sourceforge.net/). This small application will
319 look like `/usr/bin/sendmail` to a MUA such as emacs message mode, but
320 will just forward the email to an external SMTP server. It's fairly
321 easy to set up and it supports several accounts for using different
322 SMTP servers. The msmtp pages have several examples.
323
324 A typical scenario is that you want to use the company SMTP server
325 for email coming from your company email address, and your personal
326 server for personal email.  If msmtp is passed the envelope address
327 on the command line (the -f/--from option) it will automatically
328 pick the matching account.  The only trick here seems to be getting
329 emacs to actually pass the envelope from.  There are a number of
330 overlapping configuration variables that control this, and it's a
331 little confusion, but setting these three works for me:
332
333  - `mail-specify-envelope-from`: `t`
334
335  - `message-sendmail-envelope-from`: `header`
336
337  - `mail-envelope-from`: `header`
338
339 With that in place, you need a `.msmtprc` with the accounts configured
340 for the domains you want to send out using specific SMTP servers and
341 the rest will go to the default account.
342
343 ## sending mail using smtpmail
344
345 <!-- By default message mode will use the system `sendmail` command to send
346 mail. However, on a typical desktop machine there may not be local SMTP
347 daemon running (nor it is configured to send mail outside of the system). -->
348
349 If setting up local `sendmail` or `msmtp` is not feasible or desirable,
350 the Emacs `smtpmail` package can be used to send email by talking to remote
351 SMTP server via TCP connection. It is pretty easy to configure:
352
353 1. Emacs variable `message-send-mail-function` has not been set
354
355    Initially, Emacs variable `message-send-mail-function` has value of
356    `sendmail-query-once`. When (notmuch) message mode is about to send email,
357    `sendmail-query-once` will ask how emacs should send email. Typing `smtp`
358    will configure `smtpmail` and Emacs may prompt for SMTP settings.
359
360 1. `M-x customize-group RET smtpmail`
361
362    As a minimum, 'Smtpmail Smtp Server' needs to be set.
363
364    After doing that, continue with `M-x load-library RET message` and
365    `M-x customize-variable RET message-send-mail-function`.
366    In the customization buffer select `message-smtpmail-send-it`.
367
368 1. Set some variables in .emacs or in [notmuch init file](/notmuch-emacs#notmuch_init_file)
369
370         (setq smtpmail-smtp-server "smtp.server.tld" ;; <-- edit this !!!
371         ;;    smtpmail-smtp-service 25 ;; 25 is default -- uncomment and edit if needed
372         ;;    smtpmail-stream-type 'starttls
373         ;;    smtpmail-debug-info t
374         ;;    smtpmail-debug-verb t
375               message-send-mail-function 'message-smtpmail-send-it)
376
377 Note that emacs 24 or newer is required for `smtpmail-stream-type`
378 (and smtp authentication) to be effective.
379
380 More information for smtpmail is available:
381
382 * In Emacs: `M-x info-display-manual smtpmail`
383 * [EmacsWiki Page](http://www.emacswiki.org/emacs/SendingMail)
384
385
386 ## <span id="address_completion">Address completion when composing</span>
387
388 There are currently three solutions to this:
389
390 ### notmuch address
391
392 Starting with Notmuch 0.21, there is a builtin command to perform
393 autocompletion directly within Notmuch. Starting with 0.22, it is
394 configured by default, so if you have previously configured another
395 completion mechanism, you may want to try out the new internal
396 method. Use `M-x customize-variable RET notmuch-address-command` and
397 reset the value to "internal address completion" (`'internal` in
398 lisp).
399
400 If you are not yet running 0.22, you can still use it by adding a
401 wrapper around the command called, say, `notmuch-address`:
402
403     #!/bin/sh
404     exec notmuch address from:"$*"
405
406 Then you can set the `notmuch-address-command` to `notmuch-address`
407 (if it is in your `$PATH` of course, otherwise use an absolute path).
408
409 ### bbdb
410
411 [bbdb](http://bbdb.sourceforge.net) is a contact database for emacs
412 that works quite nicely together with message mode, including
413 address autocompletion.
414
415 ### notmuch database as an address book
416
417 You can also use the notmuch database as a mail address book itself.
418 To do this you need a command line tool that outputs likely address
419 candidates based on a search string.  There are currently four
420 available:
421
422   * The python tool `notmuch_address.py` (`git clone
423     http://commonmeasure.org/~jkr/git/notmuch_addresses.git`) (slower, but
424     no compilation required so good for testing the setup)
425
426   * The C-based [notmuch-addrlookup](https://github.com/aperezdc/notmuch-addrlookup-c) by [Adrian Perez](http://perezdecastro.org/), which is faster but needs to be compiled.
427
428         git clone https://github.com/aperezdc/notmuch-addrlookup-c
429         cd notmuch-addrlookup-c
430         make
431
432   * The vala-based
433     [addrlookup](http://github.com/spaetz/vala-notmuch) The addrlookup binary needs to be compiled.
434     Grab
435     `http://github.com/spaetz/vala-notmuch/raw/static-sources/src/addrlookup.c`
436     and build it with:
437
438             cc -o addrlookup addrlookup.c `pkg-config --cflags --libs gobject-2.0` -lnotmuch
439
440   * Shell/fgrep/perl combination [nottoomuch-addresses.sh](https://github.com/domo141/nottoomuch/blob/master/nottoomuch-addresses.rst).
441     This tools maintains its own address "database" gathered from email
442     files notmuch knows and search from that "database" is done by `fgrep(1)`.
443
444   * python/sqlite combination [notmuch-abook](https://github.com/guyzmo/notmuch-abook/)
445     This tools also maintains an address database in sqlite after harvesting
446     from notmuch.  It also includes a vim plugin.
447
448 You can perform tab-completion using any of these programs.
449 Just add the following to your [notmuch init file](/notmuch-emacs#notmuch_init_file):
450
451         (require 'notmuch-address)
452         (setq notmuch-address-command "/path/to/address_fetching_program")
453         (notmuch-address-message-insinuate)
454
455 ### Google Contacts
456
457 [GooBook](http://code.google.com/p/goobook/) is a command-line tool for
458 accessing Google Contacts. Install and set it up according to its documentation.
459
460 To use GooBook with notmuch, use this wrapper script and set it up like the
461 programs above.
462
463         #!/bin/sh
464         goobook query "$*" | sed 's/\(.*\)\t\(.*\)\t.*/\2 \<\1\>/' | sed '/^$/d'
465
466 You can add the sender of a message to Google Contacts by piping the message
467 (`notmuch-show-pipe-message`) to `goobook add`.
468
469 ### Akonadi
470
471         git clone https://github.com/mmehnert/akonadimailsearch
472
473 Install the development packages for kdepim on your system.
474 Enter the cloned repository and create a build directory:
475
476         mkdir build
477         cd build
478         cmake ..; make;
479
480 You will find the akonadimailsearch binary in the build/src directory. Copy it to ~/bin .
481
482 You can now add the following settings to your
483 [notmuch init file](/notmuch-emacs#notmuch_init_file):
484
485         (require 'notmuch-address)
486         (setq notmuch-address-command "~/bin/akonadimailsearch")
487         (notmuch-address-message-insinuate)
488
489 ### Completion selection with helm
490
491 An address query might return multiple possible matches from which you
492 will have to select one. To ease this task, several different
493 frameworks in emacs support completion selection. One of them is
494 [helm](https://github.com/emacs-helm/helm). The following snippet
495 improves the out-of-the-box support for helm in notmuch as it enables
496 the required-match option and also does not ignore the first returned
497 address.
498
499         (setq notmuch-address-selection-function
500           (lambda (prompt collection initial-input)
501             (completing-read prompt (cons initial-input collection) nil t nil 'notmuch-address-history)))
502
503
504 ## How to sign/encrypt messages with gpg
505
506 Messages can be signed using gpg by invoking
507 `M-x mml-secure-sign-pgpmime` (or `M-x mml-secure-encrypt-pgpmime`).
508 These functions are available via the standard `message-mode` keybindings
509 `C-c C-m s p` and `C-c C-m c p`.
510
511 In Emacs 28 you will be asked whether to sign the message using the
512 sender and are offered to remember your choice.  In Emacs 27 you will
513 get a slightly misleading error and have to manually add the following
514 line to you init file.  Older Emacsen just do this unconditionally.
515
516         (setq mml-secure-openpgp-sign-with-sender t)
517
518 To sign outgoing mail by default, use the `message-setup-hook` in your
519 init file:
520
521         ;; Sign messages by default.
522         (add-hook 'message-setup-hook 'mml-secure-sign-pgpmime)
523
524 This inserts the required `<#part sign=pgpmime>` into the beginning
525 of the mail text body and will be converted into a pgp signature
526 when sending (so one can just manually delete that line if signing
527 is not required).
528
529 Alternatively, you may prefer to use `mml-secure-message-sign-pgpmime` instead
530 of `mml-secure-sign-pgpmime` to sign the whole message instead of just one
531 part.
532
533 If you want to automatically encrypt outgoing messages if the keyring
534 contains a public key for every recipient, you can add something like
535 that to your `.emacs` file:
536
537     (defun message-recipients ()
538       "Return a list of all recipients in the message, looking at TO, CC and BCC.
539
540     Each recipient is in the format of `mail-extract-address-components'."
541       (mapcan (lambda (header)
542                 (let ((header-value (message-fetch-field header)))
543                   (and
544                    header-value
545                    (mail-extract-address-components header-value t))))
546               '("To" "Cc" "Bcc")))
547
548     (defun message-all-epg-keys-available-p ()
549       "Return non-nil if the pgp keyring has a public key for each recipient."
550       (require 'epa)
551       (let ((context (epg-make-context epa-protocol)))
552         (catch 'break
553           (dolist (recipient (message-recipients))
554             (let ((recipient-email (cadr recipient)))
555               (when (and recipient-email (not (epg-list-keys context recipient-email)))
556                 (throw 'break nil))))
557           t)))
558
559     (defun message-sign-encrypt-if-all-keys-available ()
560       "Add MML tag to encrypt message when there is a key for each recipient.
561
562     Consider adding this function to `message-send-hook' to
563     systematically send encrypted emails when possible."
564       (when (message-all-epg-keys-available-p)
565         (mml-secure-message-sign-encrypt)))
566
567     (add-hook 'message-send-hook #'message-sign-encrypt-if-all-keys-available
568
569 ### Troubleshooting message-mode gpg support
570
571 - If you have trouble with expired subkeys, you may have encountered
572   emacs bug #7931.  This is fixed in git commit 301ea744c on
573   2011-02-02.  Note that if you have the Debian package easypg
574   installed, it will shadow the fixed version of easypg included with
575   emacs.
576
577 - If you wish `mml-secure-encrypt` to encrypt also for the sender, then
578   `M-x customize-variable mml2015-encrypt-to-self` might suit your need.
579
580 ## Reading and verifying encrypted and signed messages
581
582 Encrypted and signed mime messages can be read and verified with:
583
584         (setq notmuch-crypto-process-mime t)
585
586 Decrypting inline pgp messages can be done by selecting an the inline pgp area
587 and using:
588
589         M-x epa-decrypt-region RET
590
591 Verifying of inline pgp messages is not supported directly ([reasons
592 here](https://dkg.fifthhorseman.net/notes/inline-pgp-harmful/)). You can still
593 verify a part using
594
595         M-x notmuch-show-pipe-part RET gpg --verify RET
596
597 ## Multiple identities using gnus-alias
598
599 [gnus-alias](http://www.emacswiki.org/emacs/GnusAlias) allows you to
600 define multiple identities when using `message-mode`. You can specify
601 the from address, organization, extra headers (including *Bcc*), extra
602 body text, and signature for each identity. Identities are chosen
603 based on a set of rules. When you are in message mode, you can switch
604 identities using gnus-alias.
605
606 ### Installation
607
608 - put `gnus-alias.el` on your load Emacs-Lisp load path (add new directory
609   to load path by writing `(add-to-list 'load-path "/some/load/path")` into
610   your `.emacs`.
611
612 - Add the following to your `.emacs`
613
614         (autoload 'gnus-alias-determine-identity "gnus-alias" "" t)
615         (add-hook 'message-setup-hook 'gnus-alias-determine-identity)
616
617 Looking into `gnus-alias.el` gives a bit more information...
618
619 ### Example Configuration
620
621 Here is an example configuration.
622
623         ;; Define two identities, "home" and "work"
624         (setq gnus-alias-identity-alist
625               '(("home"
626                  nil ;; Does not refer to any other identity
627                  "John Doe <jdoe@example.net>" ;; Sender address
628                  nil ;; No organization header
629                  nil ;; No extra headers
630                  nil ;; No extra body text
631                  "~/.signature")
632                 ("work"
633                  nil
634                  "John Doe <john.doe@example.com>"
635                  "Example Corp."
636                  (("Bcc" . "john.doe@example.com"))
637                  nil
638                  "~/.signature.work")))
639         ;; Use "home" identity by default
640         (setq gnus-alias-default-identity "home")
641         ;; Define rules to match work identity
642         (setq gnus-alias-identity-rules
643               '(("work" ("any" "john.doe@\\(example\\.com\\|help\\.example.com\\)" both) "work")))
644         ;; Determine identity when message-mode loads
645         (add-hook 'message-setup-hook 'gnus-alias-determine-identity)
646
647 When `gnus-alias` has been loaded (using autoload, require, *M-x load-library*
648 or *M-x load-file* (load-file takes file path -- therefore it can be used
649 without any `.emacs` changes)) the following commands can be used to get(/set)
650 more information (some of these have "extensive documentation"):
651
652         M-x describe-variable RET gnus-alias-identity-alist
653         M-x describe-variable RET gnus-alias-identity-rules
654         M-x describe-variable RET gnus-alias-default-identity
655
656         M-x customize-group RET gnus-alias RET
657           or
658         M-x gnus-alias-customize RET
659
660 The last two do the same thing.
661
662 See also the **Usage:** section in `gnus-alias.el`.
663
664 ## Multiple identities (and more) with message-templ
665
666 Another option for multiple identities is
667 [message-templ](http://git.tethera.net/message-templ.git)
668 (also a available in marmalade).  This provides roughly the same
669 facilities as wanderlust's template facility.
670
671 See
672 [example.emacs.el](https://git.tethera.net/message-templ.git/tree/example.emacs.el)
673 for some simple examples of usage.
674
675 ## Resending (or bouncing) messages
676
677 Add the following to your [notmuch init file](/notmuch-emacs#notmuch_init_file) to be able
678 to resend the current message in show mode.
679
680         (define-key notmuch-show-mode-map "b"
681           (lambda (&optional address)
682             "Bounce the current message."
683             (interactive "sBounce To: ")
684             (notmuch-show-view-raw-message)
685             (message-resend address)))
686
687 ## `notmuch-hello` refresh status message
688
689 Add the following to your [notmuch init file](/notmuch-emacs#notmuch_init_file) to get a
690 status message about the change in the number of messages in the mail store
691 when refreshing the `notmuch-hello` buffer.
692
693         (defvar notmuch-hello-refresh-count 0)
694
695         (defun notmuch-hello-refresh-status-message ()
696           (unless no-display
697             (let* ((new-count
698                     (string-to-number
699                      (car (process-lines notmuch-command "count"))))
700                    (diff-count (- new-count notmuch-hello-refresh-count)))
701               (cond
702                ((= notmuch-hello-refresh-count 0)
703                 (message "You have %s messages."
704                          (notmuch-hello-nice-number new-count)))
705                ((> diff-count 0)
706                 (message "You have %s more messages since last refresh."
707                          (notmuch-hello-nice-number diff-count)))
708                ((< diff-count 0)
709                 (message "You have %s fewer messages since last refresh."
710                          (notmuch-hello-nice-number (- diff-count)))))
711               (setq notmuch-hello-refresh-count new-count))))
712
713         (add-hook 'notmuch-hello-refresh-hook 'notmuch-hello-refresh-status-message)
714
715 ## Replacing tabs with spaces in subject and header
716
717 Mailman mailing list software rewrites and rewraps long message subjects in
718 a way that causes TABs to appear in the middle of the subject and header
719 lines. Add this to your [notmuch init file](/notmuch-emacs#notmuch_init_file) to replace
720 tabs with spaces in subject lines:
721
722         (defun notmuch-show-subject-tabs-to-spaces ()
723           "Replace tabs with spaces in subject line."
724           (goto-char (point-min))
725           (when (re-search-forward "^Subject:" nil t)
726             (while (re-search-forward "\t" (line-end-position) t)
727               (replace-match " " nil nil))))
728
729         (add-hook 'notmuch-show-markup-headers-hook 'notmuch-show-subject-tabs-to-spaces)
730
731 And in header lines (this will only work with the yet to be released
732 notmuch version 0.15):
733
734         (defun notmuch-show-header-tabs-to-spaces ()
735           "Replace tabs with spaces in header line."
736           (setq header-line-format
737                 (notmuch-show-strip-re
738                  (replace-regexp-in-string "\t" " " (notmuch-show-get-subject)))))
739
740         (add-hook 'notmuch-show-hook 'notmuch-show-header-tabs-to-spaces)
741
742 ## Hiding unread messages in notmuch-show
743
744 I like to have an inbox saved search, but only show unread messages when they
745 view a thread. This takes two steps:
746
747 1. Apply
748 [this patch from Mark Walters](https://notmuchmail.org/pipermail/notmuch/2012/010817.html)
749 to add the `notmuch-show-filter-thread` function.
750 1. Add the following hook to your emacs configuration:
751
752         (defun expand-only-unread-hook () (interactive)
753           (let ((unread nil)
754                 (open (notmuch-show-get-message-ids-for-open-messages)))
755             (notmuch-show-mapc (lambda ()
756                                  (when (member "unread" (notmuch-show-get-tags))
757                                    (setq unread t))))
758             (when unread
759               (let ((notmuch-show-hook (remove 'expand-only-unread-hook notmuch-show-hook)))
760                 (notmuch-show-filter-thread "tag:unread")))))
761
762         (add-hook 'notmuch-show-hook 'expand-only-unread-hook)
763
764 ## Changing the color of a saved search based on some other search
765
766 I like to have a saved search for my inbox, but have it change color when there
767 are thread with unread messages in the inbox. I accomplish this with the
768 following code in my emacs config:
769
770         (defun color-inbox-if-unread () (interactive)
771           (save-excursion
772             (goto-char (point-min))
773             (let ((cnt (car (process-lines "notmuch" "count" "tag:inbox and tag:unread"))))
774               (when (> (string-to-number cnt) 0)
775                 (save-excursion
776                   (when (search-forward "inbox" (point-max) t)
777                     (let* ((overlays (overlays-in (match-beginning 0) (match-end 0)))
778                            (overlay (car overlays)))
779                       (when overlay
780                         (overlay-put overlay 'face '((:inherit bold) (:foreground "green")))))))))))
781         (add-hook 'notmuch-hello-refresh-hook 'color-inbox-if-unread)
782
783 ## Linking to notmuch messages and threads from the Circe IRC client
784
785 [Circe](https://github.com/jorgenschaefer/circe/wiki) is an IRC client for emacs.
786 To have clickable buttons for notmuch messages and threads, add the following to
787 `lui-buttons-list` (using, e.g. M-x customize-variable)
788
789     ("\\(?:id\\|mid\\|thread\\):[0-9A-Za-z][0-9A-Za-z.@-]*" 0 notmuch-show 0)
790
791 If you have notmuch-pick installed, it works fine for this as well.
792
793 ## Linking to notmuch messages from org-mode
794
795 Support for linking to notmuch messages is distributed with org-mode,
796 but as a contrib file, so you might have to work a bit to load it.
797
798 In Debian and derivatives,
799
800     (add-to-list 'load-path "/usr/share/org-mode/lisp")
801
802 In NixOS, using `emacsWithPackages (epkgs: [ epkgs.orgPackages.org-plus-contrib ])`,
803
804     (loop for p in load-path
805           do (if (file-accessible-directory-p p)
806                  (let ((m (directory-files-recursively p "^ol-notmuch.el$")))
807                       (if m (add-to-list 'load-path (file-name-directory (car m)))))))
808
809 Then
810
811     (require 'ol-notmuch)
812
813 In general it is nice to have a key for org-links (not just for notmuch). For example
814
815     (define-key global-map "\C-c l" 'org-store-link)
816
817 If you're using `use-package` the package can be loaded using the following:
818
819 ```emacs-lisp
820 (use-package ol-notmuch
821   :ensure t
822   :bind
823   ("C-c l" . org-store-link))
824 ```
825
826 Note the package was renamed from `org-notmuch` to `ol-notmuch` in recent
827 versions of org-mode. If you're using an old version of notmuch you might want
828 to `(require 'org-notmuch)` instead.
829
830 ## Viewing diffs in notmuch
831
832 The following code allows you to view an inline patch in diff-mode
833 directly from notmuch. This means that normal diff-mode commands like
834 refine, next hunk etc all work.
835
836     (defun my-notmuch-show-view-as-patch ()
837       "View the the current message as a patch."
838       (interactive)
839       (let* ((id (notmuch-show-get-message-id))
840              (msg (notmuch-show-get-message-properties))
841              (part (notmuch-show-get-part-properties))
842              (subject (concat "Subject: " (notmuch-show-get-subject) "\n"))
843              (diff-default-read-only t)
844              (buf (get-buffer-create (concat "*notmuch-patch-" id "*")))
845              (map (make-sparse-keymap)))
846         (define-key map "q" 'notmuch-bury-or-kill-this-buffer)
847         (switch-to-buffer buf)
848         (let ((inhibit-read-only t))
849           (erase-buffer)
850           (insert subject)
851           (insert (notmuch-get-bodypart-text msg part nil)))
852         (set-buffer-modified-p nil)
853         (diff-mode)
854         (lexical-let ((new-ro-bind (cons 'buffer-read-only map)))
855                      (add-to-list 'minor-mode-overriding-map-alist new-ro-bind))
856         (goto-char (point-min))))
857
858 and then this function needs to bound to `. d` in the keymap
859
860     (define-key 'notmuch-show-part-map "d" 'my-notmuch-show-view-as-patch)
861
862 ## Interfacing with Patchwork
863
864 [Patchwork](http://jk.ozlabs.org/projects/patchwork/) is a web-based system for
865 tracking patches sent to a mailing list. While the Notmuch project doesn't use
866 it, many other open source projects do. Having an easy way to get from a patch
867 email in your favorite mail client to the web page of the patch in the Patchwork
868 instance is a cool thing to have. Here's how to abuse the notmuch stash feature
869 to achieve this. (Don't know stash? See `notmuch-show-stash-mlarchive-link`,
870 bound to `c l` in `notmuch-show`.)
871
872 The trick needed is turning the email Message-ID into a unique Patchwork ID
873 assigned by Patchwork. We'll use the `pwclient` command-line tool to achieve
874 this. You'll first need to get that working and configured for the Patchwork
875 instance you're using. That part is beyond this tip here; please refer to
876 Patchwork documentation.
877
878 Check your configuration on the command-line, for example:
879
880     /path/to/pwclient -p <the-project> -n 5 -f "%{id}"
881
882 Note that the -f format argument may require a reasonably new version of the
883 client. Once you have the above working, you can `M-x customize-variable RET
884 notmuch-show-stash-mlarchive-link-alist RET`.
885
886 Add a new entry with "Function returning the URL:" set to:
887
888     (lambda (message-id)
889       (concat "http://patchwork.example.com/patch/"
890               (nth 0
891                    (process-lines "/path/to/pwclient" "search"
892                                   "-p" "the-project"
893                                   "-m" (concat "<" message-id ">")
894                                   "-n" "1"
895                                   "-f" "%{id}"))))
896
897 Replacing `http://patchwork.example.com/patch/`, `/path/to/pwclient`, and
898 `the-project` appropriately. You should now be able to stash the Patchwork URL
899 using `c l`.
900
901 Going further, if the patch has been committed, you can get the commit hash with
902 this:
903
904     (lambda (message-id)
905       (nth 0
906            (process-lines "/path/to/pwclient" "search"
907                           "-p" "the-project"
908                           "-m" (concat "<" message-id ">")
909                           "-n" "1"
910                           "-f" "%{commit_ref}")))
911
912 And finally, if the project has a web interface to its source repository, you
913 can turn the commit hash into a URL pointing there, for example:
914
915     (lambda (message-id)
916       (concat "http://cgit.example.com/the-project/commit/?id="
917               (nth 0
918                    (process-lines "/path/to/pwclient" "search"
919                                   "-p" "the-project"
920                                   "-m" (concat "<" message-id ">")
921                                   "-n" "1"
922                                   "-f" "%{commit_ref}"))))
923
924 ## Never forget attachments
925
926 Very often we forget to actually attach the file when we send an email
927 that's supposed to have an attachment. Did this never happen to you?
928 If not, then it will.
929
930 There is a hook out there that checks the content of the email for
931 keywords and warns you before the email is sent out if there's no
932 attachment. This is currently work in progress, but you can already
933 add the hook to your `~/.emacs.d/notmuch-config.el` file to test
934 it. Details available (and feedback welcome) in the [relevant
935 discussion](https://notmuchmail.org/pipermail/notmuch/2018/026414.html).
936
937 ## Applying patches to git repositories
938
939 The `notmuch-extract-thread-patches` and
940 `notmuch-extract-message-patches` commands from the `elpa-mailscripts`
941 package in Debian (and its derivatives) can do this for you.
942
943 ## Allow content preference based on message context
944
945 The preference for which sub-part of a multipart/alternative part is shown is
946 globally set. For example, if you prefer showing the html version over the text
947 based, you can set:
948
949     (setq notmuch-multipart/alternative-discouraged '("text/plain" "text/html"))
950
951 However, sometimes you might want to adapt your preference depending on the
952 context. You can override the default settings on a per-message basis by
953 providing a function that has access to the message and which returns the
954 discouraged type list. For example:
955
956     (defun my/determine-discouraged (msg)
957       (let* ((headers (plist-get msg :headers))
958              (from (or (plist-get headers :From) "")))
959         (cond
960          ((string-match "whatever@mail.address.com" from)
961           '("text/plain"))
962          (t
963           '("text/html" "multipart/related")))))
964
965     (setq notmuch-multipart/alternative-discouraged
966           'my/determine-discouraged)
967
968 This would discourage text/html and multipart/related generally, but discourage
969 text/plain should the message be sent from whatever@mail.address.com.