]> 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 ## 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 ## How to customize `notmuch-saved-searches`
232
233 When starting notmuch, a list of saved searches and message counts is
234 displayed, replacing the older `notmuch-folders` command. The set of
235 saved searches displayed can be modified directly from the notmuch
236 interface (using the `[save]` button next to a previous search) or by
237 customising the variable `notmuch-saved-searches`.
238
239 An example setting for notmuch versions up to 0.17.x might be:
240
241         (setq notmuch-saved-searches '(("inbox" . "tag:inbox")
242                         ("unread" . "tag:inbox AND tag:unread")
243                         ("notmuch" . "tag:inbox AND to:notmuchmail.org")))
244
245 Starting from notmuch 0.18 the variable changed. It is backwards
246 compatible so the above will still work but the new style will be used
247 if you use customize and there are some new features available. The above would become
248
249         (setq notmuch-saved-searches '((:name "inbox" :query "tag:inbox")
250                         (:name "unread" :query "tag:inbox AND tag:unread")
251                         (:name "notmuch" :query "tag:inbox AND to:notmuchmail.org")))
252
253 The additional features are the possibility to set the search order
254 for the search, and the possibility to specify a different query for
255 displaying the count for the saved-search. For example
256
257         (setq notmuch-saved-searches '((:name "inbox"
258                                         :query "tag:inbox"
259                                         :count-query "tag:inbox and tag:unread"
260                                         :sort-order oldest-first)))
261
262 specifies a single saved search for inbox, but the number displayed by
263 the search will be the number of unread messages in the inbox, and the
264 sort order for this search will be oldest-first.
265
266 Of course, you can have any number of saved searches, each configured
267 with any supported search terms (see "notmuch help search-terms"), and
268 in the new style variable they can each have different count-queries
269 and sort orders.
270
271 Some users find it useful to add `and not tag:delete` to those
272 searches, as they use the `delete` tag to mark messages as
273 deleted. This causes messages that are marked as deleted to be removed
274 from the commonly used views of messages.  Use whatever seems most
275 useful to you.
276
277 ## Viewing HTML messages with an external viewer
278
279 The Emacs client can generally display HTML messages inline using one of the
280 supported HTML renderers. This is controlled by the `mm-text-html-renderer`
281 variable.
282
283 Sometimes it may be necessary to display the message, or a single MIME part, in
284 an external browser. This can be done by `(notmuch-show-view-part)`, bound to
285 `. v` by default.
286
287 This command will try to view the message part the point is on with an
288 external viewer. The mime-type of the part will determine what viewer
289 will be used. Typically a 'text/html' part will be send to your
290 browser.
291
292 The configuration for this is kept in so called `mailcap`
293 files. (typically the file is `~/.mailcap` or `/etc/mailcap`) If the
294 wrong viewer is started or something else goes wrong, there's a good
295 chance something needs to be adapted in the mailcap configuration.
296
297 For Example: The `copiousoutput` setting in mailcap files needs to be
298 removed for some mime-types to prevent immediate removal of temporary
299 files so the configured viewer can access them.
300
301
302 ## msmtp, message mode and multiple accounts
303
304 As an alternative to running a mail server such as sendmail or postfix
305 just to send email, it is possible to use
306 [msmtp](http://msmtp.sourceforge.net/). This small application will
307 look like `/usr/bin/sendmail` to a MUA such as emacs message mode, but
308 will just forward the email to an external SMTP server. It's fairly
309 easy to set up and it supports several accounts for using different
310 SMTP servers. The msmtp pages have several examples.
311
312 A typical scenario is that you want to use the company SMTP server
313 for email coming from your company email address, and your personal
314 server for personal email.  If msmtp is passed the envelope address
315 on the command line (the -f/--from option) it will automatically
316 pick the matching account.  The only trick here seems to be getting
317 emacs to actually pass the envelope from.  There are a number of
318 overlapping configuration variables that control this, and it's a
319 little confusion, but setting these three works for me:
320
321  - `mail-specify-envelope-from`: `t`
322
323  - `message-sendmail-envelope-from`: `header`
324
325  - `mail-envelope-from`: `header`
326
327 With that in place, you need a `.msmtprc` with the accounts configured
328 for the domains you want to send out using specific SMTP servers and
329 the rest will go to the default account.
330
331 ## sending mail using smtpmail
332
333 <!-- By default message mode will use the system `sendmail` command to send
334 mail. However, on a typical desktop machine there may not be local SMTP
335 daemon running (nor it is configured to send mail outside of the system). -->
336
337 If setting up local `sendmail` or `msmtp` is not feasible or desirable,
338 the Emacs `smtpmail` package can be used to send email by talking to remote
339 SMTP server via TCP connection. It is pretty easy to configure:
340
341 1. Emacs variable `message-send-mail-function` has not been set
342
343    Initially, Emacs variable `message-send-mail-function` has value of
344    `sendmail-query-once`. When (notmuch) message mode is about to send email,
345    `sendmail-query-once` will ask how emacs should send email. Typing `smtp`
346    will configure `smtpmail` and Emacs may prompt for SMTP settings.
347
348 1. `M-x customize-group RET smtpmail`
349
350    As a minimum, 'Smtpmail Smtp Server' needs to be set.
351
352    After doing that, continue with `M-x load-library RET message` and
353    `M-x customize-variable RET message-send-mail-function`.
354    In the customization buffer select `message-smtpmail-send-it`.
355
356 1. Set some variables in .emacs or in [notmuch init file](/notmuch-emacs#notmuch_init_file)
357
358         (setq smtpmail-smtp-server "smtp.server.tld" ;; <-- edit this !!!
359         ;;    smtpmail-smtp-service 25 ;; 25 is default -- uncomment and edit if needed
360         ;;    smtpmail-stream-type 'starttls
361         ;;    smtpmail-debug-info t
362         ;;    smtpmail-debug-verb t
363               message-send-mail-function 'message-smtpmail-send-it)
364
365 Note that emacs 24 or newer is required for `smtpmail-stream-type`
366 (and smtp authentication) to be effective.
367
368 More information for smtpmail is available:
369
370 * In Emacs: `M-x info-display-manual smtpmail`
371 * [EmacsWiki Page](http://www.emacswiki.org/emacs/SendingMail)
372
373
374 ## <span id="address_completion">Address completion when composing</span>
375
376 There are currently three solutions to this:
377
378 ### notmuch address
379
380 Starting with Notmuch 0.21, there is a builtin command to perform
381 autocompletion directly within Notmuch. Starting with 0.22, it is
382 configured by default, so if you have previously configured another
383 completion mechanism, you may want to try out the new internal
384 method. Use `M-x customize-variable RET notmuch-address-command` and
385 reset the value to "internal address completion" (`'internal` in
386 lisp).
387
388 If you are not yet running 0.22, you can still use it by adding a
389 wrapper around the command called, say, `notmuch-address`:
390
391     #!/bin/sh
392     exec notmuch address from:"$*"
393
394 Then you can set the `notmuch-address-command` to `notmuch-address`
395 (if it is in your `$PATH` of course, otherwise use an absolute path).
396
397 ### bbdb
398
399 [bbdb](http://bbdb.sourceforge.net) is a contact database for emacs
400 that works quite nicely together with message mode, including
401 address autocompletion.
402
403 ### notmuch database as an address book
404
405 You can also use the notmuch database as a mail address book itself.
406 To do this you need a command line tool that outputs likely address
407 candidates based on a search string.  There are currently four
408 available:
409
410   * The python tool `notmuch_address.py` (`git clone
411     http://commonmeasure.org/~jkr/git/notmuch_addresses.git`) (slower, but
412     no compilation required so good for testing the setup)
413
414   * 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.
415
416         git clone https://github.com/aperezdc/notmuch-addrlookup-c
417         cd notmuch-addrlookup-c
418         make
419
420   * The vala-based
421     [addrlookup](http://github.com/spaetz/vala-notmuch) The addrlookup binary needs to be compiled.
422     Grab
423     `http://github.com/spaetz/vala-notmuch/raw/static-sources/src/addrlookup.c`
424     and build it with:
425
426             cc -o addrlookup addrlookup.c `pkg-config --cflags --libs gobject-2.0` -lnotmuch
427
428   * Shell/fgrep/perl combination [nottoomuch-addresses.sh](https://github.com/domo141/nottoomuch/blob/master/nottoomuch-addresses.rst).
429     This tools maintains its own address "database" gathered from email
430     files notmuch knows and search from that "database" is done by `fgrep(1)`.
431
432   * python/sqlite combination [notmuch-abook](https://github.com/guyzmo/notmuch-abook/)
433     This tools also maintains an address database in sqlite after harvesting
434     from notmuch.  It also includes a vim plugin.
435
436 You can perform tab-completion using any of these programs.
437 Just add the following to your [notmuch init file](/notmuch-emacs#notmuch_init_file):
438
439         (require 'notmuch-address)
440         (setq notmuch-address-command "/path/to/address_fetching_program")
441         (notmuch-address-message-insinuate)
442
443 ### Google Contacts
444
445 [GooBook](http://code.google.com/p/goobook/) is a command-line tool for
446 accessing Google Contacts. Install and set it up according to its documentation.
447
448 To use GooBook with notmuch, use this wrapper script and set it up like the
449 programs above.
450
451         #!/bin/sh
452         goobook query "$*" | sed 's/\(.*\)\t\(.*\)\t.*/\2 \<\1\>/' | sed '/^$/d'
453
454 You can add the sender of a message to Google Contacts by piping the message
455 (`notmuch-show-pipe-message`) to `goobook add`.
456
457 ### Akonadi
458
459         git clone https://github.com/mmehnert/akonadimailsearch
460
461 Install the development packages for kdepim on your system.
462 Enter the cloned repository and create a build directory:
463
464         mkdir build
465         cd build
466         cmake ..; make;
467
468 You will find the akonadimailsearch binary in the build/src directory. Copy it to ~/bin .
469
470 You can now add the following settings to your
471 [notmuch init file](/notmuch-emacs#notmuch_init_file):
472
473         (require 'notmuch-address)
474         (setq notmuch-address-command "~/bin/akonadimailsearch")
475         (notmuch-address-message-insinuate)
476
477 ### Completion selection with helm
478
479 An address query might return multiple possible matches from which you
480 will have to select one. To ease this task, several different
481 frameworks in emacs support completion selection. One of them is
482 [helm](https://github.com/emacs-helm/helm). The following snippet
483 improves the out-of-the-box support for helm in notmuch as it enables
484 the required-match option and also does not ignore the first returned
485 address.
486
487         (setq notmuch-address-selection-function
488           (lambda (prompt collection initial-input)
489             (completing-read prompt (cons initial-input collection) nil t nil 'notmuch-address-history)))
490
491
492 ## How to sign/encrypt messages with gpg
493
494 Messages can be signed using gpg by invoking
495 `M-x mml-secure-sign-pgpmime` (or `M-x mml-secure-encrypt-pgpmime`).
496 These functions are available via the standard `message-mode` keybindings
497 `C-c C-m s p` and `C-c C-m c p`.
498
499 In Emacs 28 you will be asked whether to sign the message using the
500 sender and are offered to remember your choice.  In Emacs 27 you will
501 get a slightly misleading error and have to manually add the following
502 line to you init file.  Older Emacsen just do this unconditionally.
503
504         (setq mml-secure-openpgp-sign-with-sender t)
505
506 To sign outgoing mail by default, use the `message-setup-hook` in your
507 init file:
508
509         ;; Sign messages by default.
510         (add-hook 'message-setup-hook 'mml-secure-sign-pgpmime)
511
512 This inserts the required `<#part sign=pgpmime>` into the beginning
513 of the mail text body and will be converted into a pgp signature
514 when sending (so one can just manually delete that line if signing
515 is not required).
516
517 Alternatively, you may prefer to use `mml-secure-message-sign-pgpmime` instead
518 of `mml-secure-sign-pgpmime` to sign the whole message instead of just one
519 part.
520
521 If you want to automatically encrypt outgoing messages if the keyring
522 contains a public key for every recipient, you can add something like
523 that to your `.emacs` file:
524
525     (defun message-recipients ()
526       "Return a list of all recipients in the message, looking at TO, CC and BCC.
527
528     Each recipient is in the format of `mail-extract-address-components'."
529       (mapcan (lambda (header)
530                 (let ((header-value (message-fetch-field header)))
531                   (and
532                    header-value
533                    (mail-extract-address-components header-value t))))
534               '("To" "Cc" "Bcc")))
535
536     (defun message-all-epg-keys-available-p ()
537       "Return non-nil if the pgp keyring has a public key for each recipient."
538       (require 'epa)
539       (let ((context (epg-make-context epa-protocol)))
540         (catch 'break
541           (dolist (recipient (message-recipients))
542             (let ((recipient-email (cadr recipient)))
543               (when (and recipient-email (not (epg-list-keys context recipient-email)))
544                 (throw 'break nil))))
545           t)))
546
547     (defun message-sign-encrypt-if-all-keys-available ()
548       "Add MML tag to encrypt message when there is a key for each recipient.
549
550     Consider adding this function to `message-send-hook' to
551     systematically send encrypted emails when possible."
552       (when (message-all-epg-keys-available-p)
553         (mml-secure-message-sign-encrypt)))
554
555     (add-hook 'message-send-hook #'message-sign-encrypt-if-all-keys-available
556
557 ### Troubleshooting message-mode gpg support
558
559 - If you have trouble with expired subkeys, you may have encountered
560   emacs bug #7931.  This is fixed in git commit 301ea744c on
561   2011-02-02.  Note that if you have the Debian package easypg
562   installed, it will shadow the fixed version of easypg included with
563   emacs.
564
565 - If you wish `mml-secure-encrypt` to encrypt also for the sender, then
566   `M-x customize-variable mml2015-encrypt-to-self` might suit your need.
567
568 ## Reading and verifying encrypted and signed messages
569
570 Encrypted and signed mime messages can be read and verified with:
571
572         (setq notmuch-crypto-process-mime t)
573
574 Decrypting inline pgp messages can be done by selecting an the inline pgp area
575 and using:
576
577         M-x epa-decrypt-region RET
578
579 Verifying of inline pgp messages is not supported directly ([reasons
580 here](https://dkg.fifthhorseman.net/notes/inline-pgp-harmful/)). You can still
581 verify a part using
582
583         M-x notmuch-show-pipe-part RET gpg --verify RET
584
585 ## Multiple identities using gnus-alias
586
587 [gnus-alias](http://www.emacswiki.org/emacs/GnusAlias) allows you to
588 define multiple identities when using `message-mode`. You can specify
589 the from address, organization, extra headers (including *Bcc*), extra
590 body text, and signature for each identity. Identities are chosen
591 based on a set of rules. When you are in message mode, you can switch
592 identities using gnus-alias.
593
594 ### Installation
595
596 - put `gnus-alias.el` on your load Emacs-Lisp load path (add new directory
597   to load path by writing `(add-to-list 'load-path "/some/load/path")` into
598   your `.emacs`.
599
600 - Add the following to your `.emacs`
601
602         (autoload 'gnus-alias-determine-identity "gnus-alias" "" t)
603         (add-hook 'message-setup-hook 'gnus-alias-determine-identity)
604
605 Looking into `gnus-alias.el` gives a bit more information...
606
607 ### Example Configuration
608
609 Here is an example configuration.
610
611         ;; Define two identities, "home" and "work"
612         (setq gnus-alias-identity-alist
613               '(("home"
614                  nil ;; Does not refer to any other identity
615                  "John Doe <jdoe@example.net>" ;; Sender address
616                  nil ;; No organization header
617                  nil ;; No extra headers
618                  nil ;; No extra body text
619                  "~/.signature")
620                 ("work"
621                  nil
622                  "John Doe <john.doe@example.com>"
623                  "Example Corp."
624                  (("Bcc" . "john.doe@example.com"))
625                  nil
626                  "~/.signature.work")))
627         ;; Use "home" identity by default
628         (setq gnus-alias-default-identity "home")
629         ;; Define rules to match work identity
630         (setq gnus-alias-identity-rules
631               '(("work" ("any" "john.doe@\\(example\\.com\\|help\\.example.com\\)" both) "work")))
632         ;; Determine identity when message-mode loads
633         (add-hook 'message-setup-hook 'gnus-alias-determine-identity)
634
635 When `gnus-alias` has been loaded (using autoload, require, *M-x load-library*
636 or *M-x load-file* (load-file takes file path -- therefore it can be used
637 without any `.emacs` changes)) the following commands can be used to get(/set)
638 more information (some of these have "extensive documentation"):
639
640         M-x describe-variable RET gnus-alias-identity-alist
641         M-x describe-variable RET gnus-alias-identity-rules
642         M-x describe-variable RET gnus-alias-default-identity
643
644         M-x customize-group RET gnus-alias RET
645           or
646         M-x gnus-alias-customize RET
647
648 The last two do the same thing.
649
650 See also the **Usage:** section in `gnus-alias.el`.
651
652 ## Multiple identities (and more) with message-templ
653
654 Another option for multiple identities is
655 [message-templ](http://git.tethera.net/message-templ.git)
656 (also a available in marmalade).  This provides roughly the same
657 facilities as wanderlust's template facility.
658
659 See
660 [example.emacs.el](https://git.tethera.net/message-templ.git/tree/example.emacs.el)
661 for some simple examples of usage.
662
663 ## Resending (or bouncing) messages
664
665 Add the following to your [notmuch init file](/notmuch-emacs#notmuch_init_file) to be able
666 to resend the current message in show mode.
667
668         (define-key notmuch-show-mode-map "b"
669           (lambda (&optional address)
670             "Bounce the current message."
671             (interactive "sBounce To: ")
672             (notmuch-show-view-raw-message)
673             (message-resend address)))
674
675 ## `notmuch-hello` refresh status message
676
677 Add the following to your [notmuch init file](/notmuch-emacs#notmuch_init_file) to get a
678 status message about the change in the number of messages in the mail store
679 when refreshing the `notmuch-hello` buffer.
680
681         (defvar notmuch-hello-refresh-count 0)
682
683         (defun notmuch-hello-refresh-status-message ()
684           (unless no-display
685             (let* ((new-count
686                     (string-to-number
687                      (car (process-lines notmuch-command "count"))))
688                    (diff-count (- new-count notmuch-hello-refresh-count)))
689               (cond
690                ((= notmuch-hello-refresh-count 0)
691                 (message "You have %s messages."
692                          (notmuch-hello-nice-number new-count)))
693                ((> diff-count 0)
694                 (message "You have %s more messages since last refresh."
695                          (notmuch-hello-nice-number diff-count)))
696                ((< diff-count 0)
697                 (message "You have %s fewer messages since last refresh."
698                          (notmuch-hello-nice-number (- diff-count)))))
699               (setq notmuch-hello-refresh-count new-count))))
700
701         (add-hook 'notmuch-hello-refresh-hook 'notmuch-hello-refresh-status-message)
702
703 ## Replacing tabs with spaces in subject and header
704
705 Mailman mailing list software rewrites and rewraps long message subjects in
706 a way that causes TABs to appear in the middle of the subject and header
707 lines. Add this to your [notmuch init file](/notmuch-emacs#notmuch_init_file) to replace
708 tabs with spaces in subject lines:
709
710         (defun notmuch-show-subject-tabs-to-spaces ()
711           "Replace tabs with spaces in subject line."
712           (goto-char (point-min))
713           (when (re-search-forward "^Subject:" nil t)
714             (while (re-search-forward "\t" (line-end-position) t)
715               (replace-match " " nil nil))))
716
717         (add-hook 'notmuch-show-markup-headers-hook 'notmuch-show-subject-tabs-to-spaces)
718
719 And in header lines:
720
721         (defun notmuch-show-header-tabs-to-spaces ()
722           "Replace tabs with spaces in header line."
723           (setq header-line-format
724                 (notmuch-show-strip-re
725                  (replace-regexp-in-string "\t" " " (notmuch-show-get-subject)))))
726
727         (add-hook 'notmuch-show-hook 'notmuch-show-header-tabs-to-spaces)
728
729 ## Hiding unread messages in notmuch-show
730
731 I like to have an inbox saved search, but only show unread messages when they
732 view a thread. This takes two steps:
733
734 1. Apply
735 [this patch from Mark Walters](https://notmuchmail.org/pipermail/notmuch/2012/010817.html)
736 to add the `notmuch-show-filter-thread` function.
737 1. Add the following hook to your emacs configuration:
738
739         (defun expand-only-unread-hook () (interactive)
740           (let ((unread nil)
741                 (open (notmuch-show-get-message-ids-for-open-messages)))
742             (notmuch-show-mapc (lambda ()
743                                  (when (member "unread" (notmuch-show-get-tags))
744                                    (setq unread t))))
745             (when unread
746               (let ((notmuch-show-hook (remove 'expand-only-unread-hook notmuch-show-hook)))
747                 (notmuch-show-filter-thread "tag:unread")))))
748
749         (add-hook 'notmuch-show-hook 'expand-only-unread-hook)
750
751 ## Changing the color of a saved search based on some other search
752
753 I like to have a saved search for my inbox, but have it change color when there
754 are thread with unread messages in the inbox. I accomplish this with the
755 following code in my emacs config:
756
757         (defun color-inbox-if-unread () (interactive)
758           (save-excursion
759             (goto-char (point-min))
760             (let ((cnt (car (process-lines "notmuch" "count" "tag:inbox and tag:unread"))))
761               (when (> (string-to-number cnt) 0)
762                 (save-excursion
763                   (when (search-forward "inbox" (point-max) t)
764                     (let* ((overlays (overlays-in (match-beginning 0) (match-end 0)))
765                            (overlay (car overlays)))
766                       (when overlay
767                         (overlay-put overlay 'face '((:inherit bold) (:foreground "green")))))))))))
768         (add-hook 'notmuch-hello-refresh-hook 'color-inbox-if-unread)
769
770 ## Linking to notmuch messages and threads from the Circe IRC client
771
772 [Circe](https://github.com/jorgenschaefer/circe/wiki) is an IRC client for emacs.
773 To have clickable buttons for notmuch messages and threads, add the following to
774 `lui-buttons-list` (using, e.g. M-x customize-variable)
775
776     ("\\(?:id\\|mid\\|thread\\):[0-9A-Za-z][0-9A-Za-z.@-]*" 0 notmuch-show 0)
777
778 If you have notmuch-pick installed, it works fine for this as well.
779
780 ## Linking to notmuch messages from org-mode
781
782 Support for linking to notmuch messages is distributed with org-mode,
783 but as a contrib file, so you might have to work a bit to load it.
784
785 In Debian and derivatives,
786
787     (add-to-list 'load-path "/usr/share/org-mode/lisp")
788
789 In NixOS, using `emacsWithPackages (epkgs: [ epkgs.orgPackages.org-plus-contrib ])`,
790
791     (loop for p in load-path
792           do (if (file-accessible-directory-p p)
793                  (let ((m (directory-files-recursively p "^ol-notmuch.el$")))
794                       (if m (add-to-list 'load-path (file-name-directory (car m)))))))
795
796 Then
797
798     (require 'ol-notmuch)
799
800 In general it is nice to have a key for org-links (not just for notmuch). For example
801
802     (define-key global-map "\C-c l" 'org-store-link)
803
804 If you're using `use-package` the package can be loaded using the following:
805
806 ```emacs-lisp
807 (use-package ol-notmuch
808   :ensure t
809   :bind
810   ("C-c l" . org-store-link))
811 ```
812
813 Note the package was renamed from `org-notmuch` to `ol-notmuch` in recent
814 versions of org-mode. If you're using an old version of notmuch you might want
815 to `(require 'org-notmuch)` instead.
816
817 ## Viewing diffs in notmuch
818
819 The following code allows you to view an inline patch in diff-mode
820 directly from notmuch. This means that normal diff-mode commands like
821 refine, next hunk etc all work.
822
823     (defun my-notmuch-show-view-as-patch ()
824       "View the the current message as a patch."
825       (interactive)
826       (let* ((id (notmuch-show-get-message-id))
827              (msg (notmuch-show-get-message-properties))
828              (part (notmuch-show-get-part-properties))
829              (subject (concat "Subject: " (notmuch-show-get-subject) "\n"))
830              (diff-default-read-only t)
831              (buf (get-buffer-create (concat "*notmuch-patch-" id "*")))
832              (map (make-sparse-keymap)))
833         (define-key map "q" 'notmuch-bury-or-kill-this-buffer)
834         (switch-to-buffer buf)
835         (let ((inhibit-read-only t))
836           (erase-buffer)
837           (insert subject)
838           (insert (notmuch-get-bodypart-text msg part nil)))
839         (set-buffer-modified-p nil)
840         (diff-mode)
841         (lexical-let ((new-ro-bind (cons 'buffer-read-only map)))
842                      (add-to-list 'minor-mode-overriding-map-alist new-ro-bind))
843         (goto-char (point-min))))
844
845 and then this function needs to bound to `. d` in the keymap
846
847     (define-key 'notmuch-show-part-map "d" 'my-notmuch-show-view-as-patch)
848
849 ## Interfacing with Patchwork
850
851 [Patchwork](http://jk.ozlabs.org/projects/patchwork/) is a web-based system for
852 tracking patches sent to a mailing list. While the Notmuch project doesn't use
853 it, many other open source projects do. Having an easy way to get from a patch
854 email in your favorite mail client to the web page of the patch in the Patchwork
855 instance is a cool thing to have. Here's how to abuse the notmuch stash feature
856 to achieve this. (Don't know stash? See `notmuch-show-stash-mlarchive-link`,
857 bound to `c l` in `notmuch-show`.)
858
859 The trick needed is turning the email Message-ID into a unique Patchwork ID
860 assigned by Patchwork. We'll use the `pwclient` command-line tool to achieve
861 this. You'll first need to get that working and configured for the Patchwork
862 instance you're using. That part is beyond this tip here; please refer to
863 Patchwork documentation.
864
865 Check your configuration on the command-line, for example:
866
867     /path/to/pwclient -p <the-project> -n 5 -f "%{id}"
868
869 Note that the -f format argument may require a reasonably new version of the
870 client. Once you have the above working, you can `M-x customize-variable RET
871 notmuch-show-stash-mlarchive-link-alist RET`.
872
873 Add a new entry with "Function returning the URL:" set to:
874
875     (lambda (message-id)
876       (concat "http://patchwork.example.com/patch/"
877               (nth 0
878                    (process-lines "/path/to/pwclient" "search"
879                                   "-p" "the-project"
880                                   "-m" (concat "<" message-id ">")
881                                   "-n" "1"
882                                   "-f" "%{id}"))))
883
884 Replacing `http://patchwork.example.com/patch/`, `/path/to/pwclient`, and
885 `the-project` appropriately. You should now be able to stash the Patchwork URL
886 using `c l`.
887
888 Going further, if the patch has been committed, you can get the commit hash with
889 this:
890
891     (lambda (message-id)
892       (nth 0
893            (process-lines "/path/to/pwclient" "search"
894                           "-p" "the-project"
895                           "-m" (concat "<" message-id ">")
896                           "-n" "1"
897                           "-f" "%{commit_ref}")))
898
899 And finally, if the project has a web interface to its source repository, you
900 can turn the commit hash into a URL pointing there, for example:
901
902     (lambda (message-id)
903       (concat "http://cgit.example.com/the-project/commit/?id="
904               (nth 0
905                    (process-lines "/path/to/pwclient" "search"
906                                   "-p" "the-project"
907                                   "-m" (concat "<" message-id ">")
908                                   "-n" "1"
909                                   "-f" "%{commit_ref}"))))
910
911 ## Never forget attachments
912
913 Very often we forget to actually attach the file when we send an email
914 that's supposed to have an attachment. Did this never happen to you?
915 If not, then it will.
916
917 There is a hook out there that checks the content of the email for
918 keywords and warns you before the email is sent out if there's no
919 attachment. This is currently work in progress, but you can already
920 add the hook to your `~/.emacs.d/notmuch-config.el` file to test
921 it. Details available (and feedback welcome) in the [relevant
922 discussion](https://notmuchmail.org/pipermail/notmuch/2018/026414.html).
923
924 ## Applying patches to git repositories
925
926 The `notmuch-extract-thread-patches` and
927 `notmuch-extract-message-patches` commands from the `elpa-mailscripts`
928 package in Debian (and its derivatives) can do this for you.
929
930 ## Allow content preference based on message context
931
932 The preference for which sub-part of a multipart/alternative part is shown is
933 globally set. For example, if you prefer showing the html version over the text
934 based, you can set:
935
936     (setq notmuch-multipart/alternative-discouraged '("text/plain" "text/html"))
937
938 However, sometimes you might want to adapt your preference depending on the
939 context. You can override the default settings on a per-message basis by
940 providing a function that has access to the message and which returns the
941 discouraged type list. For example:
942
943     (defun my/determine-discouraged (msg)
944       (let* ((headers (plist-get msg :headers))
945              (from (or (plist-get headers :From) "")))
946         (cond
947          ((string-match "whatever@mail.address.com" from)
948           '("text/plain"))
949          (t
950           '("text/html" "multipart/related")))))
951
952     (setq notmuch-multipart/alternative-discouraged
953           'my/determine-discouraged)
954
955 This would discourage text/html and multipart/related generally, but discourage
956 text/plain should the message be sent from whatever@mail.address.com.
957
958 ## See the recipient address instead of your address when listing sent messages
959
960 If you like to see your sent messages in unthreaded view, by default you will
961 see your address in the authors column, which is maybe not what you want. The
962 following code allows for showing the recipients if your email address (an
963 arbitrary address, whatever@mail.address.com in the example) is included in the
964 From field.
965
966     (defun my/notmuch-unthreaded-show-recipient-if-sent (format-string result)
967     (let* ((headers (plist-get result :headers))
968            (to (plist-get headers :To))
969            (author (plist-get headers :From))
970            (face (if (plist-get result :match)
971                      'notmuch-tree-match-author-face
972                    'notmuch-tree-no-match-author-face)))
973       (propertize
974        (format format-string
975                (if (string-match "whatever@mail.address.com" author)
976                    (concat "↦ " (notmuch-tree-clean-address to))
977                    (notmuch-tree-clean-address to)
978                  author))
979        'face face)))
980
981     (setq notmuch-unthreaded-result-format
982           '(("date" . "%12s  ")
983             (my/notmuch-unthreaded-show-recipient-if-sent . "%-20.20s")
984             ((("subject" . "%s"))
985              . " %-54s ")
986             ("tags" . "(%s)")))
987
988 ## Issues with Emacs 24 (unsupported since notmuch 0.31 (2020-09-05))
989
990 If notmuch-show-mode behaves badly for you in emacs 24.x try adding one of
991
992         (setq gnus-inhibit-images nil)
993
994 or
995
996         (require 'gnus-art)
997
998 to your .emacs file.