]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-lib.el
emacs: Add new option notmuch-search-hide-excluded
[notmuch] / emacs / notmuch-lib.el
1 ;;; notmuch-lib.el --- common variables, functions and function declarations  -*- lexical-binding: t -*-
2 ;;
3 ;; Copyright © Carl Worth
4 ;;
5 ;; This file is part of Notmuch.
6 ;;
7 ;; Notmuch is free software: you can redistribute it and/or modify it
8 ;; under the terms of the GNU General Public License as published by
9 ;; the Free Software Foundation, either version 3 of the License, or
10 ;; (at your option) any later version.
11 ;;
12 ;; Notmuch is distributed in the hope that it will be useful, but
13 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 ;; General Public License for more details.
16 ;;
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with Notmuch.  If not, see <https://www.gnu.org/licenses/>.
19 ;;
20 ;; Authors: Carl Worth <cworth@cworth.org>
21
22 ;;; Code:
23
24 (require 'cl-lib)
25 (require 'pcase)
26 (require 'subr-x)
27
28 (require 'mm-util)
29 (require 'mm-view)
30 (require 'mm-decode)
31
32 (require 'notmuch-compat)
33
34 (unless (require 'notmuch-version nil t)
35   (defconst notmuch-emacs-version "unknown"
36     "Placeholder variable when notmuch-version.el[c] is not available."))
37
38 ;;; Groups
39
40 (defgroup notmuch nil
41   "Notmuch mail reader for Emacs."
42   :group 'mail)
43
44 (defgroup notmuch-hello nil
45   "Overview of saved searches, tags, etc."
46   :group 'notmuch)
47
48 (defgroup notmuch-search nil
49   "Searching and sorting mail."
50   :group 'notmuch)
51
52 (defgroup notmuch-show nil
53   "Showing messages and threads."
54   :group 'notmuch)
55
56 (defgroup notmuch-send nil
57   "Sending messages from Notmuch."
58   :group 'notmuch
59   :group 'message)
60
61 (defgroup notmuch-tag nil
62   "Tags and tagging in Notmuch."
63   :group 'notmuch)
64
65 (defgroup notmuch-crypto nil
66   "Processing and display of cryptographic MIME parts."
67   :group 'notmuch)
68
69 (defgroup notmuch-hooks nil
70   "Running custom code on well-defined occasions."
71   :group 'notmuch)
72
73 (defgroup notmuch-external nil
74   "Running external commands from within Notmuch."
75   :group 'notmuch)
76
77 (defgroup notmuch-address nil
78   "Address completion."
79   :group 'notmuch)
80
81 (defgroup notmuch-faces nil
82   "Graphical attributes for displaying text"
83   :group 'notmuch)
84
85 ;;; Options
86
87 (defcustom notmuch-command "notmuch"
88   "Name of the notmuch binary.
89
90 This can be a relative or absolute path to the notmuch binary.
91 If this is a relative path, it will be searched for in all of the
92 directories given in `exec-path' (which is, by default, based on
93 $PATH)."
94   :type 'string
95   :group 'notmuch-external)
96
97 (defcustom notmuch-search-oldest-first t
98   "Show the oldest mail first when searching.
99
100 This variable defines the default sort order for displaying
101 search results. Note that any filtered searches created by
102 `notmuch-search-filter' retain the search order of the parent
103 search."
104   :type 'boolean
105   :group 'notmuch-search)
106 (make-variable-buffer-local 'notmuch-search-oldest-first)
107
108 (defcustom notmuch-search-hide-excluded t
109   "Hide mail tagged with a excluded tag.
110
111 Excluded tags are defined in the users configuration file under
112 the search section. When this variable is true, any mail with
113 such a tag will not be shown in the search output."
114   :type 'boolean
115   :group 'notmuch-search)
116 (make-variable-buffer-local 'notmuch-search-hide-excluded)
117
118 (defcustom notmuch-poll-script nil
119   "[Deprecated] Command to run to incorporate new mail into the notmuch database.
120
121 This option has been deprecated in favor of \"notmuch new\"
122 hooks (see man notmuch-hooks).  To change the path to the notmuch
123 binary, customize `notmuch-command'.
124
125 This variable controls the action invoked by
126 `notmuch-poll-and-refresh-this-buffer' (bound by default to 'G')
127 to incorporate new mail into the notmuch database.
128
129 If set to nil (the default), new mail is processed by invoking
130 \"notmuch new\". Otherwise, this should be set to a string that
131 gives the name of an external script that processes new mail. If
132 set to the empty string, no command will be run.
133
134 The external script could do any of the following depending on
135 the user's needs:
136
137 1. Invoke a program to transfer mail to the local mail store
138 2. Invoke \"notmuch new\" to incorporate the new mail
139 3. Invoke one or more \"notmuch tag\" commands to classify the mail"
140   :type '(choice (const :tag "notmuch new" nil)
141                  (const :tag "Disabled" "")
142                  (string :tag "Custom script"))
143   :group 'notmuch-external)
144
145 (defcustom notmuch-archive-tags '("-inbox")
146   "List of tag changes to apply to a message or a thread when it is archived.
147
148 Tags starting with \"+\" (or not starting with either \"+\" or
149 \"-\") in the list will be added, and tags starting with \"-\"
150 will be removed from the message or thread being archived.
151
152 For example, if you wanted to remove an \"inbox\" tag and add an
153 \"archived\" tag, you would set:
154     (\"-inbox\" \"+archived\")"
155   :type '(repeat string)
156   :group 'notmuch-search
157   :group 'notmuch-show)
158
159 ;;; Variables
160
161 (defvar notmuch-search-history nil
162   "Variable to store notmuch searches history.")
163
164 (defvar notmuch-common-keymap
165   (let ((map (make-sparse-keymap)))
166     (define-key map "?" 'notmuch-help)
167     (define-key map "v" 'notmuch-version)
168     (define-key map "q" 'notmuch-bury-or-kill-this-buffer)
169     (define-key map "s" 'notmuch-search)
170     (define-key map "t" 'notmuch-search-by-tag)
171     (define-key map "z" 'notmuch-tree)
172     (define-key map "u" 'notmuch-unthreaded)
173     (define-key map "m" 'notmuch-mua-new-mail)
174     (define-key map "g" 'notmuch-refresh-this-buffer)
175     (define-key map "=" 'notmuch-refresh-this-buffer)
176     (define-key map (kbd "M-=") 'notmuch-refresh-all-buffers)
177     (define-key map "G" 'notmuch-poll-and-refresh-this-buffer)
178     (define-key map "j" 'notmuch-jump-search)
179     (define-key map [remap undo] 'notmuch-tag-undo)
180     map)
181   "Keymap shared by all notmuch modes.")
182
183 ;; By default clicking on a button does not select the window
184 ;; containing the button (as opposed to clicking on a widget which
185 ;; does). This means that the button action is then executed in the
186 ;; current selected window which can cause problems if the button
187 ;; changes the buffer (e.g., id: links) or moves point.
188 ;;
189 ;; This provides a button type which overrides mouse-action so that
190 ;; the button's window is selected before the action is run. Other
191 ;; notmuch buttons can get the same behaviour by inheriting from this
192 ;; button type.
193 (define-button-type 'notmuch-button-type
194   'mouse-action (lambda (button)
195                   (select-window (posn-window (event-start last-input-event)))
196                   (button-activate button)))
197
198 ;;; CLI Utilities
199
200 (defun notmuch-command-to-string (&rest args)
201   "Synchronously invoke \"notmuch\" with the given list of arguments.
202
203 If notmuch exits with a non-zero status, output from the process
204 will appear in a buffer named \"*Notmuch errors*\" and an error
205 will be signaled.
206
207 Otherwise the output will be returned."
208   (with-temp-buffer
209     (let ((status (apply #'notmuch--call-process notmuch-command nil t nil args))
210           (output (buffer-string)))
211       (notmuch-check-exit-status status (cons notmuch-command args) output)
212       output)))
213
214 (defvar notmuch--cli-sane-p nil
215   "Cache whether the CLI seems to be configured sanely.")
216
217 (defun notmuch-cli-sane-p ()
218   "Return t if the cli seems to be configured sanely."
219   (unless notmuch--cli-sane-p
220     (let ((status (notmuch--call-process notmuch-command nil nil nil
221                                 "config" "get" "user.primary_email")))
222       (setq notmuch--cli-sane-p (= status 0))))
223   notmuch--cli-sane-p)
224
225 (defun notmuch-assert-cli-sane ()
226   (unless (notmuch-cli-sane-p)
227     (notmuch-logged-error
228      "notmuch cli seems misconfigured or unconfigured."
229      "Perhaps you haven't run \"notmuch setup\" yet? Try running this
230 on the command line, and then retry your notmuch command")))
231
232 (defun notmuch-cli-version ()
233   "Return a string with the notmuch cli command version number."
234   (let ((long-string
235          ;; Trim off the trailing newline.
236          (substring (notmuch-command-to-string "--version") 0 -1)))
237     (if (string-match "^notmuch\\( version\\)? \\(.*\\)$"
238                       long-string)
239         (match-string 2 long-string)
240       "unknown")))
241
242 (defvar notmuch-emacs-version)
243
244 (defun notmuch-version ()
245   "Display the notmuch version.
246 The versions of the Emacs package and the `notmuch' executable
247 should match, but if and only if they don't, then this command
248 displays both values separately."
249   (interactive)
250   (let ((cli-version (notmuch-cli-version)))
251     (message "notmuch version %s"
252              (if (string= notmuch-emacs-version cli-version)
253                  cli-version
254                (concat cli-version
255                        " (emacs mua version " notmuch-emacs-version ")")))))
256
257 ;;; Notmuch Configuration
258
259 (defun notmuch-config-get (item)
260   "Return a value from the notmuch configuration."
261   (let* ((val (notmuch-command-to-string "config" "get" item))
262          (len (length val)))
263     ;; Trim off the trailing newline (if the value is empty or not
264     ;; configured, there will be no newline).
265     (if (and (> len 0)
266              (= (aref val (- len 1)) ?\n))
267         (substring val 0 -1)
268       val)))
269
270 (defun notmuch-database-path ()
271   "Return the database.path value from the notmuch configuration."
272   (notmuch-config-get "database.path"))
273
274 (defun notmuch-user-name ()
275   "Return the user.name value from the notmuch configuration."
276   (notmuch-config-get "user.name"))
277
278 (defun notmuch-user-primary-email ()
279   "Return the user.primary_email value from the notmuch configuration."
280   (notmuch-config-get "user.primary_email"))
281
282 (defun notmuch-user-other-email ()
283   "Return the user.other_email value (as a list) from the notmuch configuration."
284   (split-string (notmuch-config-get "user.other_email") "\n" t))
285
286 (defun notmuch-user-emails ()
287   (cons (notmuch-user-primary-email) (notmuch-user-other-email)))
288
289 ;;; Commands
290
291 (defun notmuch-poll ()
292   "Run \"notmuch new\" or an external script to import mail.
293
294 Invokes `notmuch-poll-script', \"notmuch new\", or does nothing
295 depending on the value of `notmuch-poll-script'."
296   (interactive)
297   (message "Polling mail...")
298   (if (stringp notmuch-poll-script)
299       (unless (string-empty-p notmuch-poll-script)
300         (unless (equal (notmuch--call-process notmuch-poll-script nil nil) 0)
301           (error "Notmuch: poll script `%s' failed!" notmuch-poll-script)))
302     (notmuch-call-notmuch-process "new"))
303   (message "Polling mail...done"))
304
305 (defun notmuch-bury-or-kill-this-buffer ()
306   "Undisplay the current buffer.
307
308 Bury the current buffer, unless there is only one window showing
309 it, in which case it is killed."
310   (interactive)
311   (if (> (length (get-buffer-window-list nil nil t)) 1)
312       (bury-buffer)
313     (kill-buffer)))
314
315 ;;; Describe Key Bindings
316
317 (defun notmuch-prefix-key-description (key)
318   "Given a prefix key code, return a human-readable string representation.
319
320 This is basically just `format-kbd-macro' but we also convert ESC to M-."
321   (let* ((key-vector (if (vectorp key) key (vector key)))
322          (desc (format-kbd-macro key-vector)))
323     (if (string= desc "ESC")
324         "M-"
325       (concat desc " "))))
326
327 (defun notmuch-describe-key (actual-key binding prefix ua-keys tail)
328   "Prepend cons cells describing prefix-arg ACTUAL-KEY and ACTUAL-KEY to TAIL.
329
330 It does not prepend if ACTUAL-KEY is already listed in TAIL."
331   (let ((key-string (concat prefix (key-description actual-key))))
332     ;; We don't include documentation if the key-binding is
333     ;; over-ridden. Note, over-riding a binding automatically hides the
334     ;; prefixed version too.
335     (unless (assoc key-string tail)
336       (when (and ua-keys (symbolp binding)
337                  (get binding 'notmuch-prefix-doc))
338         ;; Documentation for prefixed command
339         (let ((ua-desc (key-description ua-keys)))
340           (push (cons (concat ua-desc " " prefix (format-kbd-macro actual-key))
341                       (get binding 'notmuch-prefix-doc))
342                 tail)))
343       ;; Documentation for command
344       (push (cons key-string
345                   (or (and (symbolp binding)
346                            (get binding 'notmuch-doc))
347                       (and (functionp binding)
348                            (let ((doc (documentation binding)))
349                              (and doc
350                                   (string-match "\\`.+" doc)
351                                   (match-string 0 doc))))))
352             tail)))
353   tail)
354
355 (defun notmuch-describe-remaps (remap-keymap ua-keys base-keymap prefix tail)
356   ;; Remappings are represented as a binding whose first "event" is
357   ;; 'remap.  Hence, if the keymap has any remappings, it will have a
358   ;; binding whose "key" is 'remap, and whose "binding" is itself a
359   ;; keymap that maps not from keys to commands, but from old (remapped)
360   ;; functions to the commands to use in their stead.
361   (map-keymap (lambda (command binding)
362                 (mapc (lambda (actual-key)
363                         (setq tail
364                               (notmuch-describe-key actual-key binding
365                                                     prefix ua-keys tail)))
366                       (where-is-internal command base-keymap)))
367               remap-keymap)
368   tail)
369
370 (defun notmuch-describe-keymap (keymap ua-keys base-keymap &optional prefix tail)
371   "Return a list of cons cells, each describing one binding in KEYMAP.
372
373 Each cons cell consists of a string giving a human-readable
374 description of the key, and a one-line description of the bound
375 function.  See `notmuch-help' for an overview of how this
376 documentation is extracted.
377
378 UA-KEYS should be a key sequence bound to `universal-argument'.
379 It will be used to describe bindings of commands that support a
380 prefix argument.  PREFIX and TAIL are used internally."
381   (map-keymap
382    (lambda (key binding)
383      (cond ((mouse-event-p key) nil)
384            ((keymapp binding)
385             (setq tail
386                   (if (eq key 'remap)
387                       (notmuch-describe-remaps
388                        binding ua-keys base-keymap prefix tail)
389                     (notmuch-describe-keymap
390                      binding ua-keys base-keymap
391                      (notmuch-prefix-key-description key)
392                      tail))))
393            (binding
394             (setq tail
395                   (notmuch-describe-key (vector key)
396                                         binding prefix ua-keys tail)))))
397    keymap)
398   tail)
399
400 (defun notmuch-substitute-command-keys (doc)
401   "Like `substitute-command-keys' but with documentation, not function names."
402   (let ((beg 0))
403     (while (string-match "\\\\{\\([^}[:space:]]*\\)}" doc beg)
404       (let ((desc
405              (save-match-data
406                (let* ((keymap-name (substring doc
407                                               (match-beginning 1)
408                                               (match-end 1)))
409                       (keymap (symbol-value (intern keymap-name)))
410                       (ua-keys (where-is-internal 'universal-argument keymap t))
411                       (desc-alist (notmuch-describe-keymap keymap ua-keys keymap))
412                       (desc-list (mapcar (lambda (arg)
413                                            (concat (car arg) "\t" (cdr arg)))
414                                          desc-alist)))
415                  (mapconcat #'identity desc-list "\n")))))
416         (setq doc (replace-match desc 1 1 doc)))
417       (setq beg (match-end 0)))
418     doc))
419
420 (defun notmuch-help ()
421   "Display help for the current notmuch mode.
422
423 This is similar to `describe-function' for the current major
424 mode, but bindings tables are shown with documentation strings
425 rather than command names.  By default, this uses the first line
426 of each command's documentation string.  A command can override
427 this by setting the \\='notmuch-doc property of its command symbol.
428 A command that supports a prefix argument can explicitly document
429 its prefixed behavior by setting the \\='notmuch-prefix-doc property
430 of its command symbol."
431   (interactive)
432   (let ((doc (substitute-command-keys
433               (notmuch-substitute-command-keys
434                (documentation major-mode t)))))
435     (with-current-buffer (generate-new-buffer "*notmuch-help*")
436       (insert doc)
437       (goto-char (point-min))
438       (set-buffer-modified-p nil)
439       (view-buffer (current-buffer) 'kill-buffer-if-not-modified))))
440
441 (defun notmuch-subkeymap-help ()
442   "Show help for a subkeymap."
443   (interactive)
444   (let* ((key (this-command-keys-vector))
445          (prefix (make-vector (1- (length key)) nil))
446          (i 0))
447     (while (< i (length prefix))
448       (aset prefix i (aref key i))
449       (cl-incf i))
450     (let* ((subkeymap (key-binding prefix))
451            (ua-keys (where-is-internal 'universal-argument nil t))
452            (prefix-string (notmuch-prefix-key-description prefix))
453            (desc-alist (notmuch-describe-keymap
454                         subkeymap ua-keys subkeymap prefix-string))
455            (desc-list (mapcar (lambda (arg) (concat (car arg) "\t" (cdr arg)))
456                               desc-alist))
457            (desc (mapconcat #'identity desc-list "\n")))
458       (with-help-window (help-buffer)
459         (with-current-buffer standard-output
460           (insert "\nPress 'q' to quit this window.\n\n")
461           (insert desc)))
462       (pop-to-buffer (help-buffer)))))
463
464 ;;; Refreshing Buffers
465
466 (defvar-local notmuch-buffer-refresh-function nil
467   "Function to call to refresh the current buffer.")
468
469 (defun notmuch-refresh-this-buffer ()
470   "Refresh the current buffer."
471   (interactive)
472   (when notmuch-buffer-refresh-function
473     ;; Pass prefix argument, etc.
474     (call-interactively notmuch-buffer-refresh-function)))
475
476 (defun notmuch-poll-and-refresh-this-buffer ()
477   "Invoke `notmuch-poll' to import mail, then refresh the current buffer."
478   (interactive)
479   (notmuch-poll)
480   (notmuch-refresh-this-buffer))
481
482 (defun notmuch-refresh-all-buffers ()
483   "Invoke `notmuch-refresh-this-buffer' on all notmuch major-mode buffers.
484
485 The buffers are silently refreshed, i.e. they are not forced to
486 be displayed."
487   (interactive)
488   (dolist (buffer (buffer-list))
489     (let ((buffer-mode (buffer-local-value 'major-mode buffer)))
490       (when (memq buffer-mode '(notmuch-show-mode
491                                 notmuch-tree-mode
492                                 notmuch-search-mode
493                                 notmuch-hello-mode))
494         (with-current-buffer buffer
495           (notmuch-refresh-this-buffer))))))
496
497 ;;; String Utilities
498
499 (defun notmuch-prettify-subject (subject)
500   ;; This function is used by `notmuch-search-process-filter',
501   ;; which requires that we not disrupt its matching state.
502   (save-match-data
503     (if (and subject
504              (string-match "^[ \t]*$" subject))
505         "[No Subject]"
506       subject)))
507
508 (defun notmuch-sanitize (str)
509   "Sanitize control character in STR.
510
511 This includes newlines, tabs, and other funny characters."
512   (replace-regexp-in-string "[[:cntrl:]\x7f\u2028\u2029]+" " " str))
513
514 (defun notmuch-escape-boolean-term (term)
515   "Escape a boolean term for use in a query.
516
517 The caller is responsible for prepending the term prefix and a
518 colon.  This performs minimal escaping in order to produce
519 user-friendly queries."
520   (save-match-data
521     (if (or (equal term "")
522             ;; To be pessimistic, only pass through terms composed
523             ;; entirely of ASCII printing characters other than ", (,
524             ;; and ).
525             (string-match "[^!#-'*-~]" term))
526         ;; Requires escaping
527         (concat "\"" (replace-regexp-in-string "\"" "\"\"" term t t) "\"")
528       term)))
529
530 (defun notmuch-id-to-query (id)
531   "Return a query that matches the message with id ID."
532   (concat "id:" (notmuch-escape-boolean-term id)))
533
534 (defun notmuch-hex-encode (str)
535   "Hex-encode STR (e.g., as used by batch tagging).
536
537 This replaces spaces, percents, and double quotes in STR with
538 %NN where NN is the hexadecimal value of the character."
539   (replace-regexp-in-string
540    "[ %\"]" (lambda (match) (format "%%%02x" (aref match 0))) str))
541
542 (defun notmuch-common-do-stash (text)
543   "Common function to stash text in kill ring, and display in minibuffer."
544   (if text
545       (progn
546         (kill-new text)
547         (message "Stashed: %s" text))
548     ;; There is nothing to stash so stash an empty string so the user
549     ;; doesn't accidentally paste something else somewhere.
550     (kill-new "")
551     (message "Nothing to stash!")))
552
553 ;;; Generic Utilities
554
555 (defun notmuch-plist-delete (plist property)
556   (let (p)
557     (while plist
558       (unless (eq property (car plist))
559         (setq p (plist-put p (car plist) (cadr plist))))
560       (setq plist (cddr plist)))
561     p))
562
563 ;;; MML Utilities
564
565 (defun notmuch-match-content-type (t1 t2)
566   "Return t if t1 and t2 are matching content types.
567 Take wildcards into account."
568   (and (stringp t1)
569        (stringp t2)
570        (let ((st1 (split-string t1 "/"))
571              (st2 (split-string t2 "/")))
572          (if (or (string= (cadr st1) "*")
573                  (string= (cadr st2) "*"))
574              ;; Comparison of content types should be case insensitive.
575              (string= (downcase (car st1))
576                       (downcase (car st2)))
577            (string= (downcase t1)
578                     (downcase t2))))))
579
580 (defcustom notmuch-multipart/alternative-discouraged
581   '(;; Avoid HTML parts.
582     "text/html"
583     ;; multipart/related usually contain a text/html part and some
584     ;; associated graphics.
585     "multipart/related")
586   "Which mime types to hide by default for multipart messages.
587
588 Can either be a list of mime types (as strings) or a function
589 mapping a plist representing the current message to such a list.
590 See Info node `(notmuch-emacs) notmuch-show' for a sample function."
591   :group 'notmuch-show
592   :type '(radio (repeat :tag "MIME Types" string)
593                 (function :tag "Function")))
594
595 (defun notmuch-multipart/alternative-determine-discouraged (msg)
596   "Return the discouraged alternatives for the specified message."
597   ;; If a function, return the result of calling it.
598   (if (functionp notmuch-multipart/alternative-discouraged)
599       (funcall notmuch-multipart/alternative-discouraged msg)
600     ;; Otherwise simply return the value of the variable, which is
601     ;; assumed to be a list of discouraged alternatives. This is the
602     ;; default behaviour.
603     notmuch-multipart/alternative-discouraged))
604
605 (defun notmuch-multipart/alternative-choose (msg types)
606   "Return a list of preferred types from the given list of types
607 for this message, if present."
608   ;; Based on `mm-preferred-alternative-precedence'.
609   (let ((discouraged (notmuch-multipart/alternative-determine-discouraged msg))
610         (seq types))
611     (dolist (pref (reverse discouraged))
612       (dolist (elem (copy-sequence seq))
613         (when (string-match pref elem)
614           (setq seq (nconc (delete elem seq) (list elem))))))
615     seq))
616
617 (defun notmuch-parts-filter-by-type (parts type)
618   "Given a list of message parts, return a list containing the ones matching
619 the given type."
620   (cl-remove-if-not
621    (lambda (part) (notmuch-match-content-type (plist-get part :content-type) type))
622    parts))
623
624 (defun notmuch--get-bodypart-raw (msg part process-crypto binaryp cache)
625   (let* ((plist-elem (if binaryp :content-binary :content))
626          (data (or (plist-get part plist-elem)
627                    (with-temp-buffer
628                      ;; Emacs internally uses a UTF-8-like multibyte string
629                      ;; representation by default (regardless of the coding
630                      ;; system, which only affects how it goes from outside data
631                      ;; to this internal representation).  This *almost* never
632                      ;; matters.  Annoyingly, it does matter if we use this data
633                      ;; in an image descriptor, since Emacs will use its internal
634                      ;; data buffer directly and this multibyte representation
635                      ;; corrupts binary image formats.  Since the caller is
636                      ;; asking for binary data, a unibyte string is a more
637                      ;; appropriate representation anyway.
638                      (when binaryp
639                        (set-buffer-multibyte nil))
640                      (let ((args `("show" "--format=raw"
641                                    ,(format "--part=%s" (plist-get part :id))
642                                    ,@(and process-crypto '("--decrypt=true"))
643                                    ,(notmuch-id-to-query (plist-get msg :id))))
644                            (coding-system-for-read
645                             (if binaryp
646                                 'no-conversion
647                               (let ((coding-system
648                                      (mm-charset-to-coding-system
649                                       (plist-get part :content-charset))))
650                                 ;; Sadly,
651                                 ;; `mm-charset-to-coding-system' seems
652                                 ;; to return things that are not
653                                 ;; considered acceptable values for
654                                 ;; `coding-system-for-read'.
655                                 (if (coding-system-p coding-system)
656                                     coding-system
657                                   ;; RFC 2047 says that the default
658                                   ;; charset is US-ASCII. RFC6657
659                                   ;; complicates this somewhat.
660                                   'us-ascii)))))
661                        (apply #'notmuch--call-process
662                               notmuch-command nil '(t nil) nil args)
663                        (buffer-string))))))
664     (when (and cache data)
665       (plist-put part plist-elem data))
666     data))
667
668 (defun notmuch-get-bodypart-binary (msg part process-crypto &optional cache)
669   "Return the unprocessed content of PART in MSG as a unibyte string.
670
671 This returns the \"raw\" content of the given part after content
672 transfer decoding, but with no further processing (see the
673 discussion of --format=raw in man notmuch-show).  In particular,
674 this does no charset conversion.
675
676 If CACHE is non-nil, the content of this part will be saved in
677 MSG (if it isn't already)."
678   (notmuch--get-bodypart-raw msg part process-crypto t cache))
679
680 (defun notmuch-get-bodypart-text (msg part process-crypto &optional cache)
681   "Return the text content of PART in MSG.
682
683 This returns the content of the given part as a multibyte Lisp
684 string after performing content transfer decoding and any
685 necessary charset decoding.
686
687 If CACHE is non-nil, the content of this part will be saved in
688 MSG (if it isn't already)."
689   (notmuch--get-bodypart-raw msg part process-crypto nil cache))
690
691 (defun notmuch-mm-display-part-inline (msg part content-type process-crypto)
692   "Use the mm-decode/mm-view functions to display a part in the
693 current buffer, if possible."
694   (let ((display-buffer (current-buffer)))
695     (with-temp-buffer
696       ;; In case we already have :content, use it and tell mm-* that
697       ;; it's already been charset-decoded by using the fake
698       ;; `gnus-decoded' charset.  Otherwise, we'll fetch the binary
699       ;; part content and let mm-* decode it.
700       (let* ((have-content (plist-member part :content))
701              (charset (if have-content
702                           'gnus-decoded
703                         (plist-get part :content-charset)))
704              (handle (mm-make-handle (current-buffer)
705                                      `(,content-type (charset . ,charset)))))
706         ;; If the user wants the part inlined, insert the content and
707         ;; test whether we are able to inline it (which includes both
708         ;; capability and suitability tests).
709         (when (mm-inlined-p handle)
710           (if have-content
711               (insert (notmuch-get-bodypart-text msg part process-crypto))
712             (insert (notmuch-get-bodypart-binary msg part process-crypto)))
713           (when (mm-inlinable-p handle)
714             (set-buffer display-buffer)
715             (mm-display-part handle)
716             (plist-put part :undisplayer (mm-handle-undisplayer handle))
717             t))))))
718
719 ;;; Generic Utilities
720
721 ;; Converts a plist of headers to an alist of headers. The input plist should
722 ;; have symbols of the form :Header as keys, and the resulting alist will have
723 ;; symbols of the form 'Header as keys.
724 (defun notmuch-headers-plist-to-alist (plist)
725   (cl-loop for (key value . rest) on plist by #'cddr
726            collect (cons (intern (substring (symbol-name key) 1)) value)))
727
728 (defun notmuch-face-ensure-list-form (face)
729   "Return FACE in face list form.
730
731 If FACE is already a face list, it will be returned as-is.  If
732 FACE is a face name or face plist, it will be returned as a
733 single element face list."
734   (if (and (listp face) (not (keywordp (car face))))
735       face
736     (list face)))
737
738 (defun notmuch-apply-face (object face &optional below start end)
739   "Combine FACE into the \\='face text property of OBJECT between START and END.
740
741 This function combines FACE with any existing faces between START
742 and END in OBJECT.  Attributes specified by FACE take precedence
743 over existing attributes unless BELOW is non-nil.
744
745 OBJECT may be a string, a buffer, or nil (which means the current
746 buffer).  If object is a string, START and END are 0-based;
747 otherwise they are buffer positions (integers or markers).  FACE
748 must be a face name (a symbol or string), a property list of face
749 attributes, or a list of these.  If START and/or END are omitted,
750 they default to the beginning/end of OBJECT.  For convenience
751 when applied to strings, this returns OBJECT."
752   ;; A face property can have three forms: a face name (a string or
753   ;; symbol), a property list, or a list of these two forms.  In the
754   ;; list case, the faces will be combined, with the earlier faces
755   ;; taking precedent.  Here we canonicalize everything to list form
756   ;; to make it easy to combine.
757   (let ((pos (cond (start start)
758                    ((stringp object) 0)
759                    (t 1)))
760         (end (cond (end end)
761                    ((stringp object) (length object))
762                    (t (1+ (buffer-size object)))))
763         (face-list (notmuch-face-ensure-list-form face)))
764     (while (< pos end)
765       (let* ((cur (get-text-property pos 'face object))
766              (cur-list (notmuch-face-ensure-list-form cur))
767              (new (cond ((null cur-list) face)
768                         (below (append cur-list face-list))
769                         (t (append face-list cur-list))))
770              (next (next-single-property-change pos 'face object end)))
771         (put-text-property pos next 'face new object)
772         (setq pos next))))
773   object)
774
775 (defun notmuch-map-text-property (start end prop func &optional object)
776   "Transform text property PROP using FUNC.
777
778 Applies FUNC to each distinct value of the text property PROP
779 between START and END of OBJECT, setting PROP to the value
780 returned by FUNC."
781   (while (< start end)
782     (let ((value (get-text-property start prop object))
783           (next (next-single-property-change start prop object end)))
784       (put-text-property start next prop (funcall func value) object)
785       (setq start next))))
786
787 ;;; Running Notmuch
788
789 (defun notmuch-logged-error (msg &optional extra)
790   "Log MSG and EXTRA to *Notmuch errors* and signal MSG.
791
792 This logs MSG and EXTRA to the *Notmuch errors* buffer and
793 signals MSG as an error.  If EXTRA is non-nil, text referring the
794 user to the *Notmuch errors* buffer will be appended to the
795 signaled error.  This function does not return."
796   (with-current-buffer (get-buffer-create "*Notmuch errors*")
797     (goto-char (point-max))
798     (unless (bobp)
799       (newline))
800     (save-excursion
801       (insert "[" (current-time-string) "]\n" msg)
802       (unless (bolp)
803         (newline))
804       (when extra
805         (insert extra)
806         (unless (bolp)
807           (newline)))))
808   (error "%s%s" msg (if extra " (see *Notmuch errors* for more details)" "")))
809
810 (defun notmuch-check-async-exit-status (proc msg &optional command err)
811   "If PROC exited abnormally, pop up an error buffer and signal an error.
812
813 This is a wrapper around `notmuch-check-exit-status' for
814 asynchronous process sentinels.  PROC and MSG must be the
815 arguments passed to the sentinel.  COMMAND and ERR, if provided,
816 are passed to `notmuch-check-exit-status'.  If COMMAND is not
817 provided, it is taken from `process-command'."
818   (let ((exit-status
819          (cl-case (process-status proc)
820            ((exit) (process-exit-status proc))
821            ((signal) msg))))
822     (when exit-status
823       (notmuch-check-exit-status exit-status
824                                  (or command (process-command proc))
825                                  nil err))))
826
827 (defun notmuch-check-exit-status (exit-status command &optional output err)
828   "If EXIT-STATUS is non-zero, pop up an error buffer and signal an error.
829
830 If EXIT-STATUS is non-zero, pop up a notmuch error buffer
831 describing the error and signal an Elisp error.  EXIT-STATUS must
832 be a number indicating the exit status code of a process or a
833 string describing the signal that terminated the process (such as
834 returned by `call-process').  COMMAND must be a list giving the
835 command and its arguments.  OUTPUT, if provided, is a string
836 giving the output of command.  ERR, if provided, is the error
837 output of command.  OUTPUT and ERR will be included in the error
838 message."
839   (cond
840    ((eq exit-status 0) t)
841    ((eq exit-status 20)
842     (notmuch-logged-error "notmuch CLI version mismatch
843 Emacs requested an older output format than supported by the notmuch CLI.
844 You may need to restart Emacs or upgrade your notmuch Emacs package."))
845    ((eq exit-status 21)
846     (notmuch-logged-error "notmuch CLI version mismatch
847 Emacs requested a newer output format than supported by the notmuch CLI.
848 You may need to restart Emacs or upgrade your notmuch package."))
849    (t
850     (pcase-let*
851         ((`(,command . ,args) command)
852          (command (if (equal (file-name-nondirectory command)
853                              notmuch-command)
854                       notmuch-command
855                     command))
856          (command-string
857           (mapconcat (lambda (arg)
858                        (shell-quote-argument
859                         (cond ((stringp arg) arg)
860                               ((symbolp arg) (symbol-name arg))
861                               (t "*UNKNOWN ARGUMENT*"))))
862                      (cons command args)
863                      " "))
864          (extra
865           (concat "command: " command-string "\n"
866                   (if (integerp exit-status)
867                       (format "exit status: %s\n" exit-status)
868                     (format "exit signal: %s\n" exit-status))
869                   (and err    (concat "stderr:\n" err))
870                   (and output (concat "stdout:\n" output)))))
871       (if err
872           ;; We have an error message straight from the CLI.
873           (notmuch-logged-error
874            (replace-regexp-in-string "[ \n\r\t\f]*\\'" "" err) extra)
875         ;; We only have combined output from the CLI; don't inundate
876         ;; the user with it.  Mimic `process-lines'.
877         (notmuch-logged-error (format "%s exited with status %s"
878                                       command exit-status)
879                               extra))
880       ;; `notmuch-logged-error' does not return.
881       ))))
882
883 (defmacro notmuch--apply-with-env (func &rest args)
884   `(let ((default-directory "~"))
885      (apply ,func ,@args)))
886
887 (defun notmuch--process-lines (program &rest args)
888   "Wrap process-lines, binding DEFAULT-DIRECTORY to a safe
889 default"
890   (notmuch--apply-with-env #'process-lines program args))
891
892 (defun notmuch--make-process (&rest args)
893   "Wrap make-process, binding DEFAULT-DIRECTORY to a safe
894 default"
895   (notmuch--apply-with-env #'make-process args))
896
897 (defun notmuch--call-process-region (start end program
898                                            &optional delete buffer display
899                                            &rest args)
900   "Wrap call-process-region, binding DEFAULT-DIRECTORY to a safe
901 default"
902   (notmuch--apply-with-env
903    #'call-process-region start end program delete buffer display args))
904
905 (defun notmuch--call-process (program &optional infile destination display &rest args)
906   "Wrap call-process, binding DEFAULT-DIRECTORY to a safe default"
907   (notmuch--apply-with-env #'call-process program infile destination display args))
908
909 (defun notmuch-call-notmuch--helper (destination args)
910   "Helper for synchronous notmuch invocation commands.
911
912 This wraps `call-process'.  DESTINATION has the same meaning as
913 for `call-process'.  ARGS is as described for
914 `notmuch-call-notmuch-process'."
915   (let (stdin-string)
916     (while (keywordp (car args))
917       (cl-case (car args)
918         (:stdin-string (setq stdin-string (cadr args))
919                        (setq args (cddr args)))
920         (otherwise
921          (error "Unknown keyword argument: %s" (car args)))))
922     (if (null stdin-string)
923         (apply #'notmuch--call-process notmuch-command nil destination nil args)
924       (insert stdin-string)
925       (apply #'notmuch--call-process-region (point-min) (point-max)
926              notmuch-command t destination nil args))))
927
928 (defun notmuch-call-notmuch-process (&rest args)
929   "Synchronously invoke `notmuch-command' with ARGS.
930
931 The caller may provide keyword arguments before ARGS.  Currently
932 supported keyword arguments are:
933
934   :stdin-string STRING - Write STRING to stdin
935
936 If notmuch exits with a non-zero status, output from the process
937 will appear in a buffer named \"*Notmuch errors*\" and an error
938 will be signaled."
939   (with-temp-buffer
940     (let ((status (notmuch-call-notmuch--helper t args)))
941       (notmuch-check-exit-status status (cons notmuch-command args)
942                                  (buffer-string)))))
943
944 (defun notmuch-call-notmuch-sexp (&rest args)
945   "Invoke `notmuch-command' with ARGS and return the parsed S-exp output.
946
947 This is equivalent to `notmuch-call-notmuch-process', but parses
948 notmuch's output as an S-expression and returns the parsed value.
949 Like `notmuch-call-notmuch-process', if notmuch exits with a
950 non-zero status, this will report its output and signal an
951 error."
952   (with-temp-buffer
953     (let ((err-file (make-temp-file "nmerr")))
954       (unwind-protect
955           (let ((status (notmuch-call-notmuch--helper (list t err-file) args))
956                 (err (with-temp-buffer
957                        (insert-file-contents err-file)
958                        (unless (eobp)
959                          (buffer-string)))))
960             (notmuch-check-exit-status status (cons notmuch-command args)
961                                        (buffer-string) err)
962             (goto-char (point-min))
963             (read (current-buffer)))
964         (delete-file err-file)))))
965
966 (defun notmuch-start-notmuch (name buffer sentinel &rest args)
967   "Start and return an asynchronous notmuch command.
968
969 This starts and returns an asynchronous process running
970 `notmuch-command' with ARGS.  The exit status is checked via
971 `notmuch-check-async-exit-status'.  Output written to stderr is
972 redirected and displayed when the process exits (even if the
973 process exits successfully).  NAME and BUFFER are the same as in
974 `start-process'.  SENTINEL is a process sentinel function to call
975 when the process exits, or nil for none.  The caller must *not*
976 invoke `set-process-sentinel' directly on the returned process,
977 as that will interfere with the handling of stderr and the exit
978 status."
979   (let* ((command (or (executable-find notmuch-command)
980                       (error "Command not found: %s" notmuch-command)))
981          (err-buffer (generate-new-buffer " *notmuch-stderr*"))
982          (proc (notmuch--make-process
983                 :name name
984                 :buffer buffer
985                 :command (cons command args)
986                 :connection-type 'pipe
987                 :stderr err-buffer))
988          (err-proc (get-buffer-process err-buffer)))
989     (process-put proc 'err-buffer err-buffer)
990     (process-put proc 'sub-sentinel sentinel)
991     (set-process-sentinel proc #'notmuch-start-notmuch-sentinel)
992     (set-process-sentinel err-proc #'notmuch-start-notmuch-error-sentinel)
993     proc))
994
995 (defun notmuch-start-notmuch-sentinel (proc event)
996   "Process sentinel function used by `notmuch-start-notmuch'."
997   (let* ((err-buffer (process-get proc 'err-buffer))
998          (err (and (buffer-live-p err-buffer)
999                    (not (zerop (buffer-size err-buffer)))
1000                    (with-current-buffer err-buffer (buffer-string))))
1001          (sub-sentinel (process-get proc 'sub-sentinel)))
1002     (condition-case err
1003         (progn
1004           ;; Invoke the sub-sentinel, if any
1005           (when sub-sentinel
1006             (funcall sub-sentinel proc event))
1007           ;; Check the exit status.  This will signal an error if the
1008           ;; exit status is non-zero.  Don't do this if the process
1009           ;; buffer is dead since that means Emacs killed the process
1010           ;; and there's no point in telling the user that (but we
1011           ;; still check for and report stderr output below).
1012           (when (buffer-live-p (process-buffer proc))
1013             (notmuch-check-async-exit-status proc event nil err))
1014           ;; If that didn't signal an error, then any error output was
1015           ;; really warning output.  Show warnings, if any.
1016           (let ((warnings
1017                  (and err
1018                       (with-current-buffer err-buffer
1019                         (goto-char (point-min))
1020                         (end-of-line)
1021                         ;; Show first line; stuff remaining lines in the
1022                         ;; errors buffer.
1023                         (let ((l1 (buffer-substring (point-min) (point))))
1024                           (skip-chars-forward "\n")
1025                           (cons l1 (and (not (eobp))
1026                                         (buffer-substring (point)
1027                                                           (point-max)))))))))
1028             (when warnings
1029               (notmuch-logged-error (car warnings) (cdr warnings)))))
1030       (error
1031        ;; Emacs behaves strangely if an error escapes from a sentinel,
1032        ;; so turn errors into messages.
1033        (message "%s" (error-message-string err))))))
1034
1035 (defun notmuch-start-notmuch-error-sentinel (proc _event)
1036   (unless (process-live-p proc)
1037     (let ((buffer (process-buffer proc)))
1038       (when (buffer-live-p buffer)
1039         (kill-buffer buffer)))))
1040
1041 (defvar-local notmuch-show-process-crypto nil)
1042
1043 (defun notmuch--run-show (search-terms &optional duplicate)
1044   "Return a list of threads of messages matching SEARCH-TERMS.
1045
1046 A thread is a forest or list of trees. A tree is a two element
1047 list where the first element is a message, and the second element
1048 is a possibly empty forest of replies."
1049   (let ((args '("show" "--format=sexp" "--format-version=5")))
1050     (when notmuch-show-process-crypto
1051       (setq args (append args '("--decrypt=true"))))
1052     (when duplicate
1053       (setq args (append args (list (format "--duplicate=%d" duplicate)))))
1054     (setq args (append args search-terms))
1055     (apply #'notmuch-call-notmuch-sexp args)))
1056
1057 ;;; Generic Utilities
1058
1059 (defun notmuch-interactive-region ()
1060   "Return the bounds of the current interactive region.
1061
1062 This returns (BEG END), where BEG and END are the bounds of the
1063 region if the region is active, or both `point' otherwise."
1064   (if (region-active-p)
1065       (list (region-beginning) (region-end))
1066     (list (point) (point))))
1067
1068 (define-obsolete-function-alias
1069   'notmuch-search-interactive-region
1070   'notmuch-interactive-region
1071   "notmuch 0.29")
1072
1073 (defun notmuch--inline-override-types ()
1074   "Override mm-inline-override-types to stop application/*
1075 parts from being displayed unless the user has customized
1076 it themselves."
1077   (if (equal mm-inline-override-types
1078              (eval (car (get 'mm-inline-override-types 'standard-value))))
1079       (cons "application/.*" mm-inline-override-types)
1080     mm-inline-override-types))
1081 ;;; _
1082
1083 (provide 'notmuch-lib)
1084
1085 ;;; notmuch-lib.el ends here