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