1 ;;; notmuch-lib.el --- common variables, functions and function declarations -*- lexical-binding: t -*-
3 ;; Copyright © Carl Worth
5 ;; This file is part of Notmuch.
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.
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.
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/>.
20 ;; Authors: Carl Worth <cworth@cworth.org>
31 (require 'notmuch-compat)
33 (unless (require 'notmuch-version nil t)
34 (defconst notmuch-emacs-version "unknown"
35 "Placeholder variable when notmuch-version.el[c] is not available."))
40 "Notmuch mail reader for Emacs."
43 (defgroup notmuch-hello nil
44 "Overview of saved searches, tags, etc."
47 (defgroup notmuch-search nil
48 "Searching and sorting mail."
51 (defgroup notmuch-show nil
52 "Showing messages and threads."
55 (defgroup notmuch-send nil
56 "Sending messages from Notmuch."
60 (defgroup notmuch-tag nil
61 "Tags and tagging in Notmuch."
64 (defgroup notmuch-crypto nil
65 "Processing and display of cryptographic MIME parts."
68 (defgroup notmuch-hooks nil
69 "Running custom code on well-defined occasions."
72 (defgroup notmuch-external nil
73 "Running external commands from within Notmuch."
76 (defgroup notmuch-address nil
80 (defgroup notmuch-faces nil
81 "Graphical attributes for displaying text"
86 (defcustom notmuch-command "notmuch"
87 "Name of the notmuch binary.
89 This can be a relative or absolute path to the notmuch binary.
90 If this is a relative path, it will be searched for in all of the
91 directories given in `exec-path' (which is, by default, based on
94 :group 'notmuch-external)
96 (defcustom notmuch-search-oldest-first t
97 "Show the oldest mail first when searching.
99 This variable defines the default sort order for displaying
100 search results. Note that any filtered searches created by
101 `notmuch-search-filter' retain the search order of the parent
104 :group 'notmuch-search)
105 (make-variable-buffer-local 'notmuch-search-oldest-first)
107 (defcustom notmuch-poll-script nil
108 "[Deprecated] Command to run to incorporate new mail into the notmuch database.
110 This option has been deprecated in favor of \"notmuch new\"
111 hooks (see man notmuch-hooks). To change the path to the notmuch
112 binary, customize `notmuch-command'.
114 This variable controls the action invoked by
115 `notmuch-poll-and-refresh-this-buffer' (bound by default to 'G')
116 to incorporate new mail into the notmuch database.
118 If set to nil (the default), new mail is processed by invoking
119 \"notmuch new\". Otherwise, this should be set to a string that
120 gives the name of an external script that processes new mail. If
121 set to the empty string, no command will be run.
123 The external script could do any of the following depending on
126 1. Invoke a program to transfer mail to the local mail store
127 2. Invoke \"notmuch new\" to incorporate the new mail
128 3. Invoke one or more \"notmuch tag\" commands to classify the mail"
129 :type '(choice (const :tag "notmuch new" nil)
130 (const :tag "Disabled" "")
131 (string :tag "Custom script"))
132 :group 'notmuch-external)
134 (defcustom notmuch-archive-tags '("-inbox")
135 "List of tag changes to apply to a message or a thread when it is archived.
137 Tags starting with \"+\" (or not starting with either \"+\" or
138 \"-\") in the list will be added, and tags starting with \"-\"
139 will be removed from the message or thread being archived.
141 For example, if you wanted to remove an \"inbox\" tag and add an
142 \"archived\" tag, you would set:
143 (\"-inbox\" \"+archived\")"
144 :type '(repeat string)
145 :group 'notmuch-search
146 :group 'notmuch-show)
150 (defvar notmuch-search-history nil
151 "Variable to store notmuch searches history.")
153 (defvar notmuch-common-keymap
154 (let ((map (make-sparse-keymap)))
155 (define-key map "?" 'notmuch-help)
156 (define-key map "v" 'notmuch-version)
157 (define-key map "q" 'notmuch-bury-or-kill-this-buffer)
158 (define-key map "s" 'notmuch-search)
159 (define-key map "t" 'notmuch-search-by-tag)
160 (define-key map "z" 'notmuch-tree)
161 (define-key map "u" 'notmuch-unthreaded)
162 (define-key map "m" 'notmuch-mua-new-mail)
163 (define-key map "g" 'notmuch-refresh-this-buffer)
164 (define-key map "=" 'notmuch-refresh-this-buffer)
165 (define-key map (kbd "M-=") 'notmuch-refresh-all-buffers)
166 (define-key map "G" 'notmuch-poll-and-refresh-this-buffer)
167 (define-key map "j" 'notmuch-jump-search)
169 "Keymap shared by all notmuch modes.")
171 ;; By default clicking on a button does not select the window
172 ;; containing the button (as opposed to clicking on a widget which
173 ;; does). This means that the button action is then executed in the
174 ;; current selected window which can cause problems if the button
175 ;; changes the buffer (e.g., id: links) or moves point.
177 ;; This provides a button type which overrides mouse-action so that
178 ;; the button's window is selected before the action is run. Other
179 ;; notmuch buttons can get the same behaviour by inheriting from this
181 (define-button-type 'notmuch-button-type
182 'mouse-action (lambda (button)
183 (select-window (posn-window (event-start last-input-event)))
184 (button-activate button)))
188 (defun notmuch-command-to-string (&rest args)
189 "Synchronously invoke \"notmuch\" with the given list of arguments.
191 If notmuch exits with a non-zero status, output from the process
192 will appear in a buffer named \"*Notmuch errors*\" and an error
195 Otherwise the output will be returned."
197 (let ((status (apply #'call-process notmuch-command nil t nil args))
198 (output (buffer-string)))
199 (notmuch-check-exit-status status (cons notmuch-command args) output)
202 (defvar notmuch--cli-sane-p nil
203 "Cache whether the CLI seems to be configured sanely.")
205 (defun notmuch-cli-sane-p ()
206 "Return t if the cli seems to be configured sanely."
207 (unless notmuch--cli-sane-p
208 (let ((status (call-process notmuch-command nil nil nil
209 "config" "get" "user.primary_email")))
210 (setq notmuch--cli-sane-p (= status 0))))
213 (defun notmuch-assert-cli-sane ()
214 (unless (notmuch-cli-sane-p)
215 (notmuch-logged-error
216 "notmuch cli seems misconfigured or unconfigured."
217 "Perhaps you haven't run \"notmuch setup\" yet? Try running this
218 on the command line, and then retry your notmuch command")))
220 (defun notmuch-cli-version ()
221 "Return a string with the notmuch cli command version number."
223 ;; Trim off the trailing newline.
224 (substring (notmuch-command-to-string "--version") 0 -1)))
225 (if (string-match "^notmuch\\( version\\)? \\(.*\\)$"
227 (match-string 2 long-string)
230 (defvar notmuch-emacs-version)
232 (defun notmuch-version ()
233 "Display the notmuch version.
234 The versions of the Emacs package and the `notmuch' executable
235 should match, but if and only if they don't, then this command
236 displays both values separately."
238 (let ((cli-version (notmuch-cli-version)))
239 (message "notmuch version %s"
240 (if (string= notmuch-emacs-version cli-version)
243 " (emacs mua version " notmuch-emacs-version ")")))))
245 ;;; Notmuch Configuration
247 (defun notmuch-config-get (item)
248 "Return a value from the notmuch configuration."
249 (let* ((val (notmuch-command-to-string "config" "get" item))
251 ;; Trim off the trailing newline (if the value is empty or not
252 ;; configured, there will be no newline).
254 (= (aref val (- len 1)) ?\n))
258 (defun notmuch-database-path ()
259 "Return the database.path value from the notmuch configuration."
260 (notmuch-config-get "database.path"))
262 (defun notmuch-user-name ()
263 "Return the user.name value from the notmuch configuration."
264 (notmuch-config-get "user.name"))
266 (defun notmuch-user-primary-email ()
267 "Return the user.primary_email value from the notmuch configuration."
268 (notmuch-config-get "user.primary_email"))
270 (defun notmuch-user-other-email ()
271 "Return the user.other_email value (as a list) from the notmuch configuration."
272 (split-string (notmuch-config-get "user.other_email") "\n" t))
274 (defun notmuch-user-emails ()
275 (cons (notmuch-user-primary-email) (notmuch-user-other-email)))
279 (defun notmuch-poll ()
280 "Run \"notmuch new\" or an external script to import mail.
282 Invokes `notmuch-poll-script', \"notmuch new\", or does nothing
283 depending on the value of `notmuch-poll-script'."
285 (message "Polling mail...")
286 (if (stringp notmuch-poll-script)
287 (unless (string= notmuch-poll-script "")
288 (unless (equal (call-process notmuch-poll-script nil nil) 0)
289 (error "Notmuch: poll script `%s' failed!" notmuch-poll-script)))
290 (notmuch-call-notmuch-process "new"))
291 (message "Polling mail...done"))
293 (defun notmuch-bury-or-kill-this-buffer ()
294 "Undisplay the current buffer.
296 Bury the current buffer, unless there is only one window showing
297 it, in which case it is killed."
299 (if (> (length (get-buffer-window-list nil nil t)) 1)
303 ;;; Describe Key Bindings
305 (defun notmuch-prefix-key-description (key)
306 "Given a prefix key code, return a human-readable string representation.
308 This is basically just `format-kbd-macro' but we also convert ESC to M-."
309 (let* ((key-vector (if (vectorp key) key (vector key)))
310 (desc (format-kbd-macro key-vector)))
311 (if (string= desc "ESC")
315 (defun notmuch-describe-key (actual-key binding prefix ua-keys tail)
316 "Prepend cons cells describing prefix-arg ACTUAL-KEY and ACTUAL-KEY to TAIL.
318 It does not prepend if ACTUAL-KEY is already listed in TAIL."
319 (let ((key-string (concat prefix (key-description actual-key))))
320 ;; We don't include documentation if the key-binding is
321 ;; over-ridden. Note, over-riding a binding automatically hides the
322 ;; prefixed version too.
323 (unless (assoc key-string tail)
324 (when (and ua-keys (symbolp binding)
325 (get binding 'notmuch-prefix-doc))
326 ;; Documentation for prefixed command
327 (let ((ua-desc (key-description ua-keys)))
328 (push (cons (concat ua-desc " " prefix (format-kbd-macro actual-key))
329 (get binding 'notmuch-prefix-doc))
331 ;; Documentation for command
332 (push (cons key-string
333 (or (and (symbolp binding)
334 (get binding 'notmuch-doc))
335 (and (functionp binding)
336 (let ((doc (documentation binding)))
338 (string-match "\\`.+" doc)
339 (match-string 0 doc))))))
343 (defun notmuch-describe-remaps (remap-keymap ua-keys base-keymap prefix tail)
344 ;; Remappings are represented as a binding whose first "event" is
345 ;; 'remap. Hence, if the keymap has any remappings, it will have a
346 ;; binding whose "key" is 'remap, and whose "binding" is itself a
347 ;; keymap that maps not from keys to commands, but from old (remapped)
348 ;; functions to the commands to use in their stead.
349 (map-keymap (lambda (command binding)
350 (mapc (lambda (actual-key)
352 (notmuch-describe-key actual-key binding
353 prefix ua-keys tail)))
354 (where-is-internal command base-keymap)))
358 (defun notmuch-describe-keymap (keymap ua-keys base-keymap &optional prefix tail)
359 "Return a list of cons cells, each describing one binding in KEYMAP.
361 Each cons cell consists of a string giving a human-readable
362 description of the key, and a one-line description of the bound
363 function. See `notmuch-help' for an overview of how this
364 documentation is extracted.
366 UA-KEYS should be a key sequence bound to `universal-argument'.
367 It will be used to describe bindings of commands that support a
368 prefix argument. PREFIX and TAIL are used internally."
370 (lambda (key binding)
371 (cond ((mouse-event-p key) nil)
375 (notmuch-describe-remaps
376 binding ua-keys base-keymap prefix tail)
377 (notmuch-describe-keymap
378 binding ua-keys base-keymap
379 (notmuch-prefix-key-description key)
383 (notmuch-describe-key (vector key)
384 binding prefix ua-keys tail)))))
388 (defun notmuch-substitute-command-keys (doc)
389 "Like `substitute-command-keys' but with documentation, not function names."
391 (while (string-match "\\\\{\\([^}[:space:]]*\\)}" doc beg)
394 (let* ((keymap-name (substring doc
397 (keymap (symbol-value (intern keymap-name)))
398 (ua-keys (where-is-internal 'universal-argument keymap t))
399 (desc-alist (notmuch-describe-keymap keymap ua-keys keymap))
400 (desc-list (mapcar (lambda (arg)
401 (concat (car arg) "\t" (cdr arg)))
403 (mapconcat #'identity desc-list "\n")))))
404 (setq doc (replace-match desc 1 1 doc)))
405 (setq beg (match-end 0)))
408 (defun notmuch-help ()
409 "Display help for the current notmuch mode.
411 This is similar to `describe-function' for the current major
412 mode, but bindings tables are shown with documentation strings
413 rather than command names. By default, this uses the first line
414 of each command's documentation string. A command can override
415 this by setting the 'notmuch-doc property of its command symbol.
416 A command that supports a prefix argument can explicitly document
417 its prefixed behavior by setting the 'notmuch-prefix-doc property
418 of its command symbol."
420 (let ((doc (substitute-command-keys
421 (notmuch-substitute-command-keys
422 (documentation major-mode t)))))
423 (with-current-buffer (generate-new-buffer "*notmuch-help*")
425 (goto-char (point-min))
426 (set-buffer-modified-p nil)
427 (view-buffer (current-buffer) 'kill-buffer-if-not-modified))))
429 (defun notmuch-subkeymap-help ()
430 "Show help for a subkeymap."
432 (let* ((key (this-command-keys-vector))
433 (prefix (make-vector (1- (length key)) nil))
435 (while (< i (length prefix))
436 (aset prefix i (aref key i))
438 (let* ((subkeymap (key-binding prefix))
439 (ua-keys (where-is-internal 'universal-argument nil t))
440 (prefix-string (notmuch-prefix-key-description prefix))
441 (desc-alist (notmuch-describe-keymap
442 subkeymap ua-keys subkeymap prefix-string))
443 (desc-list (mapcar (lambda (arg) (concat (car arg) "\t" (cdr arg)))
445 (desc (mapconcat #'identity desc-list "\n")))
446 (with-help-window (help-buffer)
447 (with-current-buffer standard-output
448 (insert "\nPress 'q' to quit this window.\n\n")
450 (pop-to-buffer (help-buffer)))))
452 ;;; Refreshing Buffers
454 (defvar-local notmuch-buffer-refresh-function nil
455 "Function to call to refresh the current buffer.")
457 (defun notmuch-refresh-this-buffer ()
458 "Refresh the current buffer."
460 (when notmuch-buffer-refresh-function
461 ;; Pass prefix argument, etc.
462 (call-interactively notmuch-buffer-refresh-function)))
464 (defun notmuch-poll-and-refresh-this-buffer ()
465 "Invoke `notmuch-poll' to import mail, then refresh the current buffer."
468 (notmuch-refresh-this-buffer))
470 (defun notmuch-refresh-all-buffers ()
471 "Invoke `notmuch-refresh-this-buffer' on all notmuch major-mode buffers.
473 The buffers are silently refreshed, i.e. they are not forced to
476 (dolist (buffer (buffer-list))
477 (let ((buffer-mode (buffer-local-value 'major-mode buffer)))
478 (when (memq buffer-mode '(notmuch-show-mode
482 (with-current-buffer buffer
483 (notmuch-refresh-this-buffer))))))
487 (defun notmuch-prettify-subject (subject)
488 ;; This function is used by `notmuch-search-process-filter',
489 ;; which requires that we not disrupt its matching state.
492 (string-match "^[ \t]*$" subject))
496 (defun notmuch-sanitize (str)
497 "Sanitize control character in STR.
499 This includes newlines, tabs, and other funny characters."
500 (replace-regexp-in-string "[[:cntrl:]\x7f\u2028\u2029]+" " " str))
502 (defun notmuch-escape-boolean-term (term)
503 "Escape a boolean term for use in a query.
505 The caller is responsible for prepending the term prefix and a
506 colon. This performs minimal escaping in order to produce
507 user-friendly queries."
509 (if (or (equal term "")
510 ;; To be pessimistic, only pass through terms composed
511 ;; entirely of ASCII printing characters other than ", (,
513 (string-match "[^!#-'*-~]" term))
515 (concat "\"" (replace-regexp-in-string "\"" "\"\"" term t t) "\"")
518 (defun notmuch-id-to-query (id)
519 "Return a query that matches the message with id ID."
520 (concat "id:" (notmuch-escape-boolean-term id)))
522 (defun notmuch-hex-encode (str)
523 "Hex-encode STR (e.g., as used by batch tagging).
525 This replaces spaces, percents, and double quotes in STR with
526 %NN where NN is the hexadecimal value of the character."
527 (replace-regexp-in-string
528 "[ %\"]" (lambda (match) (format "%%%02x" (aref match 0))) str))
530 (defun notmuch-common-do-stash (text)
531 "Common function to stash text in kill ring, and display in minibuffer."
535 (message "Stashed: %s" text))
536 ;; There is nothing to stash so stash an empty string so the user
537 ;; doesn't accidentally paste something else somewhere.
539 (message "Nothing to stash!")))
541 ;;; Generic Utilities
543 (defun notmuch-plist-delete (plist property)
546 (unless (eq property (car plist))
547 (setq p (plist-put p (car plist) (cadr plist))))
548 (setq plist (cddr plist)))
553 (defun notmuch-match-content-type (t1 t2)
554 "Return t if t1 and t2 are matching content types, taking wildcards into account."
555 (let ((st1 (split-string t1 "/"))
556 (st2 (split-string t2 "/")))
557 (if (or (string= (cadr st1) "*")
558 (string= (cadr st2) "*"))
559 ;; Comparison of content types should be case insensitive.
560 (string= (downcase (car st1))
561 (downcase (car st2)))
562 (string= (downcase t1)
565 (defvar notmuch-multipart/alternative-discouraged
566 '(;; Avoid HTML parts.
568 ;; multipart/related usually contain a text/html part and some
569 ;; associated graphics.
570 "multipart/related"))
572 (defun notmuch-multipart/alternative-determine-discouraged (msg)
573 "Return the discouraged alternatives for the specified message."
574 ;; If a function, return the result of calling it.
575 (if (functionp notmuch-multipart/alternative-discouraged)
576 (funcall notmuch-multipart/alternative-discouraged msg)
577 ;; Otherwise simply return the value of the variable, which is
578 ;; assumed to be a list of discouraged alternatives. This is the
579 ;; default behaviour.
580 notmuch-multipart/alternative-discouraged))
582 (defun notmuch-multipart/alternative-choose (msg types)
583 "Return a list of preferred types from the given list of types
584 for this message, if present."
585 ;; Based on `mm-preferred-alternative-precedence'.
586 (let ((discouraged (notmuch-multipart/alternative-determine-discouraged msg))
588 (dolist (pref (reverse discouraged))
589 (dolist (elem (copy-sequence seq))
590 (when (string-match pref elem)
591 (setq seq (nconc (delete elem seq) (list elem))))))
594 (defun notmuch-parts-filter-by-type (parts type)
595 "Given a list of message parts, return a list containing the ones matching
598 (lambda (part) (notmuch-match-content-type (plist-get part :content-type) type))
601 (defun notmuch--get-bodypart-raw (msg part process-crypto binaryp cache)
602 (let* ((plist-elem (if binaryp :content-binary :content))
603 (data (or (plist-get part plist-elem)
605 ;; Emacs internally uses a UTF-8-like multibyte string
606 ;; representation by default (regardless of the coding
607 ;; system, which only affects how it goes from outside data
608 ;; to this internal representation). This *almost* never
609 ;; matters. Annoyingly, it does matter if we use this data
610 ;; in an image descriptor, since Emacs will use its internal
611 ;; data buffer directly and this multibyte representation
612 ;; corrupts binary image formats. Since the caller is
613 ;; asking for binary data, a unibyte string is a more
614 ;; appropriate representation anyway.
616 (set-buffer-multibyte nil))
617 (let ((args `("show" "--format=raw"
618 ,(format "--part=%s" (plist-get part :id))
619 ,@(and process-crypto '("--decrypt=true"))
620 ,(notmuch-id-to-query (plist-get msg :id))))
621 (coding-system-for-read
625 (mm-charset-to-coding-system
626 (plist-get part :content-charset))))
628 ;; `mm-charset-to-coding-system' seems
629 ;; to return things that are not
630 ;; considered acceptable values for
631 ;; `coding-system-for-read'.
632 (if (coding-system-p coding-system)
634 ;; RFC 2047 says that the default
635 ;; charset is US-ASCII. RFC6657
636 ;; complicates this somewhat.
638 (apply #'call-process
639 notmuch-command nil '(t nil) nil args)
641 (when (and cache data)
642 (plist-put part plist-elem data))
645 (defun notmuch-get-bodypart-binary (msg part process-crypto &optional cache)
646 "Return the unprocessed content of PART in MSG as a unibyte string.
648 This returns the \"raw\" content of the given part after content
649 transfer decoding, but with no further processing (see the
650 discussion of --format=raw in man notmuch-show). In particular,
651 this does no charset conversion.
653 If CACHE is non-nil, the content of this part will be saved in
654 MSG (if it isn't already)."
655 (notmuch--get-bodypart-raw msg part process-crypto t cache))
657 (defun notmuch-get-bodypart-text (msg part process-crypto &optional cache)
658 "Return the text content of PART in MSG.
660 This returns the content of the given part as a multibyte Lisp
661 string after performing content transfer decoding and any
662 necessary charset decoding.
664 If CACHE is non-nil, the content of this part will be saved in
665 MSG (if it isn't already)."
666 (notmuch--get-bodypart-raw msg part process-crypto nil cache))
668 (defun notmuch-mm-display-part-inline (msg part content-type process-crypto)
669 "Use the mm-decode/mm-view functions to display a part in the
670 current buffer, if possible."
671 (let ((display-buffer (current-buffer)))
673 ;; In case we already have :content, use it and tell mm-* that
674 ;; it's already been charset-decoded by using the fake
675 ;; `gnus-decoded' charset. Otherwise, we'll fetch the binary
676 ;; part content and let mm-* decode it.
677 (let* ((have-content (plist-member part :content))
678 (charset (if have-content
680 (plist-get part :content-charset)))
681 (handle (mm-make-handle (current-buffer)
682 `(,content-type (charset . ,charset)))))
683 ;; If the user wants the part inlined, insert the content and
684 ;; test whether we are able to inline it (which includes both
685 ;; capability and suitability tests).
686 (when (mm-inlined-p handle)
688 (insert (notmuch-get-bodypart-text msg part process-crypto))
689 (insert (notmuch-get-bodypart-binary msg part process-crypto)))
690 (when (mm-inlinable-p handle)
691 (set-buffer display-buffer)
692 (mm-display-part handle)
695 ;;; Generic Utilities
697 ;; Converts a plist of headers to an alist of headers. The input plist should
698 ;; have symbols of the form :Header as keys, and the resulting alist will have
699 ;; symbols of the form 'Header as keys.
700 (defun notmuch-headers-plist-to-alist (plist)
701 (cl-loop for (key value . rest) on plist by #'cddr
702 collect (cons (intern (substring (symbol-name key) 1)) value)))
704 (defun notmuch-face-ensure-list-form (face)
705 "Return FACE in face list form.
707 If FACE is already a face list, it will be returned as-is. If
708 FACE is a face name or face plist, it will be returned as a
709 single element face list."
710 (if (and (listp face) (not (keywordp (car face))))
714 (defun notmuch-apply-face (object face &optional below start end)
715 "Combine FACE into the 'face text property of OBJECT between START and END.
717 This function combines FACE with any existing faces between START
718 and END in OBJECT. Attributes specified by FACE take precedence
719 over existing attributes unless BELOW is non-nil.
721 OBJECT may be a string, a buffer, or nil (which means the current
722 buffer). If object is a string, START and END are 0-based;
723 otherwise they are buffer positions (integers or markers). FACE
724 must be a face name (a symbol or string), a property list of face
725 attributes, or a list of these. If START and/or END are omitted,
726 they default to the beginning/end of OBJECT. For convenience
727 when applied to strings, this returns OBJECT."
728 ;; A face property can have three forms: a face name (a string or
729 ;; symbol), a property list, or a list of these two forms. In the
730 ;; list case, the faces will be combined, with the earlier faces
731 ;; taking precedent. Here we canonicalize everything to list form
732 ;; to make it easy to combine.
733 (let ((pos (cond (start start)
737 ((stringp object) (length object))
738 (t (1+ (buffer-size object)))))
739 (face-list (notmuch-face-ensure-list-form face)))
741 (let* ((cur (get-text-property pos 'face object))
742 (cur-list (notmuch-face-ensure-list-form cur))
743 (new (cond ((null cur-list) face)
744 (below (append cur-list face-list))
745 (t (append face-list cur-list))))
746 (next (next-single-property-change pos 'face object end)))
747 (put-text-property pos next 'face new object)
751 (defun notmuch-map-text-property (start end prop func &optional object)
752 "Transform text property PROP using FUNC.
754 Applies FUNC to each distinct value of the text property PROP
755 between START and END of OBJECT, setting PROP to the value
758 (let ((value (get-text-property start prop object))
759 (next (next-single-property-change start prop object end)))
760 (put-text-property start next prop (funcall func value) object)
765 (defun notmuch-logged-error (msg &optional extra)
766 "Log MSG and EXTRA to *Notmuch errors* and signal MSG.
768 This logs MSG and EXTRA to the *Notmuch errors* buffer and
769 signals MSG as an error. If EXTRA is non-nil, text referring the
770 user to the *Notmuch errors* buffer will be appended to the
771 signaled error. This function does not return."
772 (with-current-buffer (get-buffer-create "*Notmuch errors*")
773 (goto-char (point-max))
777 (insert "[" (current-time-string) "]\n" msg)
784 (error "%s%s" msg (if extra " (see *Notmuch errors* for more details)" "")))
786 (defun notmuch-check-async-exit-status (proc msg &optional command err)
787 "If PROC exited abnormally, pop up an error buffer and signal an error.
789 This is a wrapper around `notmuch-check-exit-status' for
790 asynchronous process sentinels. PROC and MSG must be the
791 arguments passed to the sentinel. COMMAND and ERR, if provided,
792 are passed to `notmuch-check-exit-status'. If COMMAND is not
793 provided, it is taken from `process-command'."
795 (cl-case (process-status proc)
796 ((exit) (process-exit-status proc))
799 (notmuch-check-exit-status exit-status
800 (or command (process-command proc))
803 (defun notmuch-check-exit-status (exit-status command &optional output err)
804 "If EXIT-STATUS is non-zero, pop up an error buffer and signal an error.
806 If EXIT-STATUS is non-zero, pop up a notmuch error buffer
807 describing the error and signal an Elisp error. EXIT-STATUS must
808 be a number indicating the exit status code of a process or a
809 string describing the signal that terminated the process (such as
810 returned by `call-process'). COMMAND must be a list giving the
811 command and its arguments. OUTPUT, if provided, is a string
812 giving the output of command. ERR, if provided, is the error
813 output of command. OUTPUT and ERR will be included in the error
816 ((eq exit-status 0) t)
818 (notmuch-logged-error "notmuch CLI version mismatch
819 Emacs requested an older output format than supported by the notmuch CLI.
820 You may need to restart Emacs or upgrade your notmuch Emacs package."))
822 (notmuch-logged-error "notmuch CLI version mismatch
823 Emacs requested a newer output format than supported by the notmuch CLI.
824 You may need to restart Emacs or upgrade your notmuch package."))
827 ((`(,command . ,args) command)
828 (command (if (equal (file-name-nondirectory command)
833 (mapconcat (lambda (arg)
834 (shell-quote-argument
835 (cond ((stringp arg) arg)
836 ((symbolp arg) (symbol-name arg))
837 (t "*UNKNOWN ARGUMENT*"))))
841 (concat "command: " command-string "\n"
842 (if (integerp exit-status)
843 (format "exit status: %s\n" exit-status)
844 (format "exit signal: %s\n" exit-status))
845 (and err (concat "stderr:\n" err))
846 (and output (concat "stdout:\n" output)))))
848 ;; We have an error message straight from the CLI.
849 (notmuch-logged-error
850 (replace-regexp-in-string "[ \n\r\t\f]*\\'" "" err) extra)
851 ;; We only have combined output from the CLI; don't inundate
852 ;; the user with it. Mimic `process-lines'.
853 (notmuch-logged-error (format "%s exited with status %s"
856 ;; `notmuch-logged-error' does not return.
859 (defun notmuch-call-notmuch--helper (destination args)
860 "Helper for synchronous notmuch invocation commands.
862 This wraps `call-process'. DESTINATION has the same meaning as
863 for `call-process'. ARGS is as described for
864 `notmuch-call-notmuch-process'."
866 (while (keywordp (car args))
868 (:stdin-string (setq stdin-string (cadr args))
869 (setq args (cddr args)))
871 (error "Unknown keyword argument: %s" (car args)))))
872 (if (null stdin-string)
873 (apply #'call-process notmuch-command nil destination nil args)
874 (insert stdin-string)
875 (apply #'call-process-region (point-min) (point-max)
876 notmuch-command t destination nil args))))
878 (defun notmuch-call-notmuch-process (&rest args)
879 "Synchronously invoke `notmuch-command' with ARGS.
881 The caller may provide keyword arguments before ARGS. Currently
882 supported keyword arguments are:
884 :stdin-string STRING - Write STRING to stdin
886 If notmuch exits with a non-zero status, output from the process
887 will appear in a buffer named \"*Notmuch errors*\" and an error
890 (let ((status (notmuch-call-notmuch--helper t args)))
891 (notmuch-check-exit-status status (cons notmuch-command args)
894 (defun notmuch-call-notmuch-sexp (&rest args)
895 "Invoke `notmuch-command' with ARGS and return the parsed S-exp output.
897 This is equivalent to `notmuch-call-notmuch-process', but parses
898 notmuch's output as an S-expression and returns the parsed value.
899 Like `notmuch-call-notmuch-process', if notmuch exits with a
900 non-zero status, this will report its output and signal an
903 (let ((err-file (make-temp-file "nmerr")))
905 (let ((status (notmuch-call-notmuch--helper (list t err-file) args))
906 (err (with-temp-buffer
907 (insert-file-contents err-file)
910 (notmuch-check-exit-status status (cons notmuch-command args)
912 (goto-char (point-min))
913 (read (current-buffer)))
914 (delete-file err-file)))))
916 (defun notmuch-start-notmuch (name buffer sentinel &rest args)
917 "Start and return an asynchronous notmuch command.
919 This starts and returns an asynchronous process running
920 `notmuch-command' with ARGS. The exit status is checked via
921 `notmuch-check-async-exit-status'. Output written to stderr is
922 redirected and displayed when the process exits (even if the
923 process exits successfully). NAME and BUFFER are the same as in
924 `start-process'. SENTINEL is a process sentinel function to call
925 when the process exits, or nil for none. The caller must *not*
926 invoke `set-process-sentinel' directly on the returned process,
927 as that will interfere with the handling of stderr and the exit
929 (let* ((command (or (executable-find notmuch-command)
930 (error "Command not found: %s" notmuch-command)))
931 (err-buffer (generate-new-buffer " *notmuch-stderr*"))
935 :command (cons command args)
936 :connection-type 'pipe
938 (err-proc (get-buffer-process err-buffer)))
939 (process-put proc 'err-buffer err-buffer)
940 (process-put proc 'sub-sentinel sentinel)
941 (set-process-sentinel proc #'notmuch-start-notmuch-sentinel)
942 (set-process-sentinel err-proc #'notmuch-start-notmuch-error-sentinel)
945 (defun notmuch-start-notmuch-sentinel (proc event)
946 "Process sentinel function used by `notmuch-start-notmuch'."
947 (let* ((err-buffer (process-get proc 'err-buffer))
948 (err (and (buffer-live-p err-buffer)
949 (not (zerop (buffer-size err-buffer)))
950 (with-current-buffer err-buffer (buffer-string))))
951 (sub-sentinel (process-get proc 'sub-sentinel)))
954 ;; Invoke the sub-sentinel, if any
956 (funcall sub-sentinel proc event))
957 ;; Check the exit status. This will signal an error if the
958 ;; exit status is non-zero. Don't do this if the process
959 ;; buffer is dead since that means Emacs killed the process
960 ;; and there's no point in telling the user that (but we
961 ;; still check for and report stderr output below).
962 (when (buffer-live-p (process-buffer proc))
963 (notmuch-check-async-exit-status proc event nil err))
964 ;; If that didn't signal an error, then any error output was
965 ;; really warning output. Show warnings, if any.
968 (with-current-buffer err-buffer
969 (goto-char (point-min))
971 ;; Show first line; stuff remaining lines in the
973 (let ((l1 (buffer-substring (point-min) (point))))
974 (skip-chars-forward "\n")
975 (cons l1 (and (not (eobp))
976 (buffer-substring (point)
979 (notmuch-logged-error (car warnings) (cdr warnings)))))
981 ;; Emacs behaves strangely if an error escapes from a sentinel,
982 ;; so turn errors into messages.
983 (message "%s" (error-message-string err))))))
985 (defun notmuch-start-notmuch-error-sentinel (proc _event)
986 (unless (process-live-p proc)
987 (let ((buffer (process-buffer proc)))
988 (when (buffer-live-p buffer)
989 (kill-buffer buffer)))))
991 (defvar-local notmuch-show-process-crypto nil)
993 ;;; Generic Utilities
995 (defun notmuch-interactive-region ()
996 "Return the bounds of the current interactive region.
998 This returns (BEG END), where BEG and END are the bounds of the
999 region if the region is active, or both `point' otherwise."
1000 (if (region-active-p)
1001 (list (region-beginning) (region-end))
1002 (list (point) (point))))
1004 (define-obsolete-function-alias
1005 'notmuch-search-interactive-region
1006 'notmuch-interactive-region
1011 (provide 'notmuch-lib)
1013 ;;; notmuch-lib.el ends here