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