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>
30 (require 'notmuch-compat)
32 (unless (require 'notmuch-version nil t)
33 (defconst notmuch-emacs-version "unknown"
34 "Placeholder variable when notmuch-version.el[c] is not available."))
39 "Notmuch mail reader for Emacs."
42 (defgroup notmuch-hello nil
43 "Overview of saved searches, tags, etc."
46 (defgroup notmuch-search nil
47 "Searching and sorting mail."
50 (defgroup notmuch-show nil
51 "Showing messages and threads."
54 (defgroup notmuch-send nil
55 "Sending messages from Notmuch."
59 (defgroup notmuch-tag nil
60 "Tags and tagging in Notmuch."
63 (defgroup notmuch-crypto nil
64 "Processing and display of cryptographic MIME parts."
67 (defgroup notmuch-hooks nil
68 "Running custom code on well-defined occasions."
71 (defgroup notmuch-external nil
72 "Running external commands from within Notmuch."
75 (defgroup notmuch-address nil
79 (defgroup notmuch-faces nil
80 "Graphical attributes for displaying text"
85 (defcustom notmuch-command "notmuch"
86 "Name of the notmuch binary.
88 This can be a relative or absolute path to the notmuch binary.
89 If this is a relative path, it will be searched for in all of the
90 directories given in `exec-path' (which is, by default, based on
93 :group 'notmuch-external)
95 (defcustom notmuch-search-oldest-first t
96 "Show the oldest mail first when searching.
98 This variable defines the default sort order for displaying
99 search results. Note that any filtered searches created by
100 `notmuch-search-filter' retain the search order of the parent
103 :group 'notmuch-search)
104 (make-variable-buffer-local 'notmuch-search-oldest-first)
106 (defcustom notmuch-poll-script nil
107 "[Deprecated] Command to run to incorporate new mail into the notmuch database.
109 This option has been deprecated in favor of \"notmuch new\"
110 hooks (see man notmuch-hooks). To change the path to the notmuch
111 binary, customize `notmuch-command'.
113 This variable controls the action invoked by
114 `notmuch-poll-and-refresh-this-buffer' (bound by default to 'G')
115 to incorporate new mail into the notmuch database.
117 If set to nil (the default), new mail is processed by invoking
118 \"notmuch new\". Otherwise, this should be set to a string that
119 gives the name of an external script that processes new mail. If
120 set to the empty string, no command will be run.
122 The external script could do any of the following depending on
125 1. Invoke a program to transfer mail to the local mail store
126 2. Invoke \"notmuch new\" to incorporate the new mail
127 3. Invoke one or more \"notmuch tag\" commands to classify the mail"
128 :type '(choice (const :tag "notmuch new" nil)
129 (const :tag "Disabled" "")
130 (string :tag "Custom script"))
131 :group 'notmuch-external)
133 (defcustom notmuch-archive-tags '("-inbox")
134 "List of tag changes to apply to a message or a thread when it is archived.
136 Tags starting with \"+\" (or not starting with either \"+\" or
137 \"-\") in the list will be added, and tags starting with \"-\"
138 will be removed from the message or thread being archived.
140 For example, if you wanted to remove an \"inbox\" tag and add an
141 \"archived\" tag, you would set:
142 (\"-inbox\" \"+archived\")"
143 :type '(repeat string)
144 :group 'notmuch-search
145 :group 'notmuch-show)
149 (defvar notmuch-search-history nil
150 "Variable to store notmuch searches history.")
152 (defvar notmuch-common-keymap
153 (let ((map (make-sparse-keymap)))
154 (define-key map "?" 'notmuch-help)
155 (define-key map "v" 'notmuch-version)
156 (define-key map "q" 'notmuch-bury-or-kill-this-buffer)
157 (define-key map "s" 'notmuch-search)
158 (define-key map "t" 'notmuch-search-by-tag)
159 (define-key map "z" 'notmuch-tree)
160 (define-key map "u" 'notmuch-unthreaded)
161 (define-key map "m" 'notmuch-mua-new-mail)
162 (define-key map "g" 'notmuch-refresh-this-buffer)
163 (define-key map "=" 'notmuch-refresh-this-buffer)
164 (define-key map (kbd "M-=") 'notmuch-refresh-all-buffers)
165 (define-key map "G" 'notmuch-poll-and-refresh-this-buffer)
166 (define-key map "j" 'notmuch-jump-search)
168 "Keymap shared by all notmuch modes.")
170 ;; By default clicking on a button does not select the window
171 ;; containing the button (as opposed to clicking on a widget which
172 ;; does). This means that the button action is then executed in the
173 ;; current selected window which can cause problems if the button
174 ;; changes the buffer (e.g., id: links) or moves point.
176 ;; This provides a button type which overrides mouse-action so that
177 ;; the button's window is selected before the action is run. Other
178 ;; notmuch buttons can get the same behaviour by inheriting from this
180 (define-button-type 'notmuch-button-type
181 'mouse-action (lambda (button)
182 (select-window (posn-window (event-start last-input-event)))
183 (button-activate button)))
187 (defun notmuch-command-to-string (&rest args)
188 "Synchronously invoke \"notmuch\" with the given list of arguments.
190 If notmuch exits with a non-zero status, output from the process
191 will appear in a buffer named \"*Notmuch errors*\" and an error
194 Otherwise the output will be returned."
196 (let ((status (apply #'call-process notmuch-command nil t nil args))
197 (output (buffer-string)))
198 (notmuch-check-exit-status status (cons notmuch-command args) output)
201 (defvar notmuch--cli-sane-p nil
202 "Cache whether the CLI seems to be configured sanely.")
204 (defun notmuch-cli-sane-p ()
205 "Return t if the cli seems to be configured sanely."
206 (unless notmuch--cli-sane-p
207 (let ((status (call-process notmuch-command nil nil nil
208 "config" "get" "user.primary_email")))
209 (setq notmuch--cli-sane-p (= status 0))))
212 (defun notmuch-assert-cli-sane ()
213 (unless (notmuch-cli-sane-p)
214 (notmuch-logged-error
215 "notmuch cli seems misconfigured or unconfigured."
216 "Perhaps you haven't run \"notmuch setup\" yet? Try running this
217 on the command line, and then retry your notmuch command")))
219 (defun notmuch-cli-version ()
220 "Return a string with the notmuch cli command version number."
222 ;; Trim off the trailing newline.
223 (substring (notmuch-command-to-string "--version") 0 -1)))
224 (if (string-match "^notmuch\\( version\\)? \\(.*\\)$"
226 (match-string 2 long-string)
229 (defvar notmuch-emacs-version)
231 (defun notmuch-version ()
232 "Display the notmuch version.
233 The versions of the Emacs package and the `notmuch' executable
234 should match, but if and only if they don't, then this command
235 displays both values separately."
237 (let ((cli-version (notmuch-cli-version)))
238 (message "notmuch version %s"
239 (if (string= notmuch-emacs-version cli-version)
242 " (emacs mua version " notmuch-emacs-version ")")))))
244 ;;; Notmuch Configuration
246 (defun notmuch-config-get (item)
247 "Return a value from the notmuch configuration."
248 (let* ((val (notmuch-command-to-string "config" "get" item))
250 ;; Trim off the trailing newline (if the value is empty or not
251 ;; configured, there will be no newline).
253 (= (aref val (- len 1)) ?\n))
257 (defun notmuch-database-path ()
258 "Return the database.path value from the notmuch configuration."
259 (notmuch-config-get "database.path"))
261 (defun notmuch-user-name ()
262 "Return the user.name value from the notmuch configuration."
263 (notmuch-config-get "user.name"))
265 (defun notmuch-user-primary-email ()
266 "Return the user.primary_email value from the notmuch configuration."
267 (notmuch-config-get "user.primary_email"))
269 (defun notmuch-user-other-email ()
270 "Return the user.other_email value (as a list) from the notmuch configuration."
271 (split-string (notmuch-config-get "user.other_email") "\n" t))
273 (defun notmuch-user-emails ()
274 (cons (notmuch-user-primary-email) (notmuch-user-other-email)))
278 (defun notmuch-poll ()
279 "Run \"notmuch new\" or an external script to import mail.
281 Invokes `notmuch-poll-script', \"notmuch new\", or does nothing
282 depending on the value of `notmuch-poll-script'."
284 (message "Polling mail...")
285 (if (stringp notmuch-poll-script)
286 (unless (string= notmuch-poll-script "")
287 (unless (equal (call-process notmuch-poll-script nil nil) 0)
288 (error "Notmuch: poll script `%s' failed!" notmuch-poll-script)))
289 (notmuch-call-notmuch-process "new"))
290 (message "Polling mail...done"))
292 (defun notmuch-bury-or-kill-this-buffer ()
293 "Undisplay the current buffer.
295 Bury the current buffer, unless there is only one window showing
296 it, in which case it is killed."
298 (if (> (length (get-buffer-window-list nil nil t)) 1)
302 ;;; Describe Key Bindings
304 (defun notmuch-prefix-key-description (key)
305 "Given a prefix key code, return a human-readable string representation.
307 This is basically just `format-kbd-macro' but we also convert ESC to M-."
308 (let* ((key-vector (if (vectorp key) key (vector key)))
309 (desc (format-kbd-macro key-vector)))
310 (if (string= desc "ESC")
314 (defun notmuch-describe-key (actual-key binding prefix ua-keys tail)
315 "Prepend cons cells describing prefix-arg ACTUAL-KEY and ACTUAL-KEY to TAIL.
317 It does not prepend if ACTUAL-KEY is already listed in TAIL."
318 (let ((key-string (concat prefix (key-description actual-key))))
319 ;; We don't include documentation if the key-binding is
320 ;; over-ridden. Note, over-riding a binding automatically hides the
321 ;; prefixed version too.
322 (unless (assoc key-string tail)
323 (when (and ua-keys (symbolp binding)
324 (get binding 'notmuch-prefix-doc))
325 ;; Documentation for prefixed command
326 (let ((ua-desc (key-description ua-keys)))
327 (push (cons (concat ua-desc " " prefix (format-kbd-macro actual-key))
328 (get binding 'notmuch-prefix-doc))
330 ;; Documentation for command
331 (push (cons key-string
332 (or (and (symbolp binding)
333 (get binding 'notmuch-doc))
334 (and (functionp binding)
335 (let ((doc (documentation binding)))
337 (string-match "\\`.+" doc)
338 (match-string 0 doc))))))
342 (defun notmuch-describe-remaps (remap-keymap ua-keys base-keymap prefix tail)
343 ;; Remappings are represented as a binding whose first "event" is
344 ;; 'remap. Hence, if the keymap has any remappings, it will have a
345 ;; binding whose "key" is 'remap, and whose "binding" is itself a
346 ;; keymap that maps not from keys to commands, but from old (remapped)
347 ;; functions to the commands to use in their stead.
348 (map-keymap (lambda (command binding)
349 (mapc (lambda (actual-key)
351 (notmuch-describe-key actual-key binding
352 prefix ua-keys tail)))
353 (where-is-internal command base-keymap)))
357 (defun notmuch-describe-keymap (keymap ua-keys base-keymap &optional prefix tail)
358 "Return a list of cons cells, each describing one binding in KEYMAP.
360 Each cons cell consists of a string giving a human-readable
361 description of the key, and a one-line description of the bound
362 function. See `notmuch-help' for an overview of how this
363 documentation is extracted.
365 UA-KEYS should be a key sequence bound to `universal-argument'.
366 It will be used to describe bindings of commands that support a
367 prefix argument. PREFIX and TAIL are used internally."
369 (lambda (key binding)
370 (cond ((mouse-event-p key) nil)
374 (notmuch-describe-remaps
375 binding ua-keys base-keymap prefix tail)
376 (notmuch-describe-keymap
377 binding ua-keys base-keymap
378 (notmuch-prefix-key-description key)
382 (notmuch-describe-key (vector key)
383 binding prefix ua-keys tail)))))
387 (defun notmuch-substitute-command-keys (doc)
388 "Like `substitute-command-keys' but with documentation, not function names."
390 (while (string-match "\\\\{\\([^}[:space:]]*\\)}" doc beg)
393 (let* ((keymap-name (substring doc
396 (keymap (symbol-value (intern keymap-name)))
397 (ua-keys (where-is-internal 'universal-argument keymap t))
398 (desc-alist (notmuch-describe-keymap keymap ua-keys keymap))
399 (desc-list (mapcar (lambda (arg)
400 (concat (car arg) "\t" (cdr arg)))
402 (mapconcat #'identity desc-list "\n")))))
403 (setq doc (replace-match desc 1 1 doc)))
404 (setq beg (match-end 0)))
407 (defun notmuch-help ()
408 "Display help for the current notmuch mode.
410 This is similar to `describe-function' for the current major
411 mode, but bindings tables are shown with documentation strings
412 rather than command names. By default, this uses the first line
413 of each command's documentation string. A command can override
414 this by setting the 'notmuch-doc property of its command symbol.
415 A command that supports a prefix argument can explicitly document
416 its prefixed behavior by setting the 'notmuch-prefix-doc property
417 of its command symbol."
419 (let* ((mode major-mode)
420 (doc (substitute-command-keys
421 (notmuch-substitute-command-keys (documentation mode t)))))
422 (with-current-buffer (generate-new-buffer "*notmuch-help*")
424 (goto-char (point-min))
425 (set-buffer-modified-p nil)
426 (view-buffer (current-buffer) 'kill-buffer-if-not-modified))))
428 (defun notmuch-subkeymap-help ()
429 "Show help for a subkeymap."
431 (let* ((key (this-command-keys-vector))
432 (prefix (make-vector (1- (length key)) nil))
434 (while (< i (length prefix))
435 (aset prefix i (aref key i))
437 (let* ((subkeymap (key-binding prefix))
438 (ua-keys (where-is-internal 'universal-argument nil t))
439 (prefix-string (notmuch-prefix-key-description prefix))
440 (desc-alist (notmuch-describe-keymap
441 subkeymap ua-keys subkeymap prefix-string))
442 (desc-list (mapcar (lambda (arg) (concat (car arg) "\t" (cdr arg)))
444 (desc (mapconcat #'identity desc-list "\n")))
445 (with-help-window (help-buffer)
446 (with-current-buffer standard-output
447 (insert "\nPress 'q' to quit this window.\n\n")
449 (pop-to-buffer (help-buffer)))))
451 ;;; Refreshing Buffers
453 (defvar-local notmuch-buffer-refresh-function nil
454 "Function to call to refresh the current buffer.")
456 (defun notmuch-refresh-this-buffer ()
457 "Refresh the current buffer."
459 (when notmuch-buffer-refresh-function
460 ;; Pass prefix argument, etc.
461 (call-interactively notmuch-buffer-refresh-function)))
463 (defun notmuch-poll-and-refresh-this-buffer ()
464 "Invoke `notmuch-poll' to import mail, then refresh the current buffer."
467 (notmuch-refresh-this-buffer))
469 (defun notmuch-refresh-all-buffers ()
470 "Invoke `notmuch-refresh-this-buffer' on all notmuch major-mode buffers.
472 The buffers are silently refreshed, i.e. they are not forced to
475 (dolist (buffer (buffer-list))
476 (let ((buffer-mode (buffer-local-value 'major-mode buffer)))
477 (when (memq buffer-mode '(notmuch-show-mode
481 (with-current-buffer buffer
482 (notmuch-refresh-this-buffer))))))
486 (defun notmuch-prettify-subject (subject)
487 ;; This function is used by `notmuch-search-process-filter',
488 ;; which requires that we not disrupt its matching state.
491 (string-match "^[ \t]*$" subject))
495 (defun notmuch-sanitize (str)
496 "Sanitize control character in STR.
498 This includes newlines, tabs, and other funny characters."
499 (replace-regexp-in-string "[[:cntrl:]\x7f\u2028\u2029]+" " " str))
501 (defun notmuch-escape-boolean-term (term)
502 "Escape a boolean term for use in a query.
504 The caller is responsible for prepending the term prefix and a
505 colon. This performs minimal escaping in order to produce
506 user-friendly queries."
508 (if (or (equal term "")
509 ;; To be pessimistic, only pass through terms composed
510 ;; entirely of ASCII printing characters other than ", (,
512 (string-match "[^!#-'*-~]" term))
514 (concat "\"" (replace-regexp-in-string "\"" "\"\"" term t t) "\"")
517 (defun notmuch-id-to-query (id)
518 "Return a query that matches the message with id ID."
519 (concat "id:" (notmuch-escape-boolean-term id)))
521 (defun notmuch-hex-encode (str)
522 "Hex-encode STR (e.g., as used by batch tagging).
524 This replaces spaces, percents, and double quotes in STR with
525 %NN where NN is the hexadecimal value of the character."
526 (replace-regexp-in-string
527 "[ %\"]" (lambda (match) (format "%%%02x" (aref match 0))) str))
529 (defun notmuch-common-do-stash (text)
530 "Common function to stash text in kill ring, and display in minibuffer."
534 (message "Stashed: %s" text))
535 ;; There is nothing to stash so stash an empty string so the user
536 ;; doesn't accidentally paste something else somewhere.
538 (message "Nothing to stash!")))
540 ;;; Generic Utilities
542 (defun notmuch-plist-delete (plist property)
545 (unless (eq property (car plist))
546 (setq p (plist-put p (car plist) (cadr plist))))
547 (setq plist (cddr plist)))
552 (defun notmuch-match-content-type (t1 t2)
553 "Return t if t1 and t2 are matching content types, taking wildcards into account."
554 (let ((st1 (split-string t1 "/"))
555 (st2 (split-string t2 "/")))
556 (if (or (string= (cadr st1) "*")
557 (string= (cadr st2) "*"))
558 ;; Comparison of content types should be case insensitive.
559 (string= (downcase (car st1))
560 (downcase (car st2)))
561 (string= (downcase t1)
564 (defvar notmuch-multipart/alternative-discouraged
565 '(;; Avoid HTML parts.
567 ;; multipart/related usually contain a text/html part and some
568 ;; associated graphics.
569 "multipart/related"))
571 (defun notmuch-multipart/alternative-determine-discouraged (msg)
572 "Return the discouraged alternatives for the specified message."
573 ;; If a function, return the result of calling it.
574 (if (functionp notmuch-multipart/alternative-discouraged)
575 (funcall notmuch-multipart/alternative-discouraged msg)
576 ;; Otherwise simply return the value of the variable, which is
577 ;; assumed to be a list of discouraged alternatives. This is the
578 ;; default behaviour.
579 notmuch-multipart/alternative-discouraged))
581 (defun notmuch-multipart/alternative-choose (msg types)
582 "Return a list of preferred types from the given list of types
583 for this message, if present."
584 ;; Based on `mm-preferred-alternative-precedence'.
585 (let ((discouraged (notmuch-multipart/alternative-determine-discouraged msg))
587 (dolist (pref (reverse discouraged))
588 (dolist (elem (copy-sequence seq))
589 (when (string-match pref elem)
590 (setq seq (nconc (delete elem seq) (list elem))))))
593 (defun notmuch-parts-filter-by-type (parts type)
594 "Given a list of message parts, return a list containing the ones matching
597 (lambda (part) (notmuch-match-content-type (plist-get part :content-type) type))
600 (defun notmuch--get-bodypart-raw (msg part process-crypto binaryp cache)
601 (let* ((plist-elem (if binaryp :content-binary :content))
602 (data (or (plist-get part plist-elem)
604 ;; Emacs internally uses a UTF-8-like multibyte string
605 ;; representation by default (regardless of the coding
606 ;; system, which only affects how it goes from outside data
607 ;; to this internal representation). This *almost* never
608 ;; matters. Annoyingly, it does matter if we use this data
609 ;; in an image descriptor, since Emacs will use its internal
610 ;; data buffer directly and this multibyte representation
611 ;; corrupts binary image formats. Since the caller is
612 ;; asking for binary data, a unibyte string is a more
613 ;; appropriate representation anyway.
615 (set-buffer-multibyte nil))
616 (let ((args `("show" "--format=raw"
617 ,(format "--part=%s" (plist-get part :id))
618 ,@(and process-crypto '("--decrypt=true"))
619 ,(notmuch-id-to-query (plist-get msg :id))))
620 (coding-system-for-read
624 (mm-charset-to-coding-system
625 (plist-get part :content-charset))))
627 ;; `mm-charset-to-coding-system' seems
628 ;; to return things that are not
629 ;; considered acceptable values for
630 ;; `coding-system-for-read'.
631 (if (coding-system-p coding-system)
633 ;; RFC 2047 says that the default
634 ;; charset is US-ASCII. RFC6657
635 ;; complicates this somewhat.
637 (apply #'call-process
638 notmuch-command nil '(t nil) nil args)
640 (when (and cache data)
641 (plist-put part plist-elem data))
644 (defun notmuch-get-bodypart-binary (msg part process-crypto &optional cache)
645 "Return the unprocessed content of PART in MSG as a unibyte string.
647 This returns the \"raw\" content of the given part after content
648 transfer decoding, but with no further processing (see the
649 discussion of --format=raw in man notmuch-show). In particular,
650 this does no charset conversion.
652 If CACHE is non-nil, the content of this part will be saved in
653 MSG (if it isn't already)."
654 (notmuch--get-bodypart-raw msg part process-crypto t cache))
656 (defun notmuch-get-bodypart-text (msg part process-crypto &optional cache)
657 "Return the text content of PART in MSG.
659 This returns the content of the given part as a multibyte Lisp
660 string after performing content transfer decoding and any
661 necessary charset decoding.
663 If CACHE is non-nil, the content of this part will be saved in
664 MSG (if it isn't already)."
665 (notmuch--get-bodypart-raw msg part process-crypto nil cache))
667 (defun notmuch-mm-display-part-inline (msg part content-type process-crypto)
668 "Use the mm-decode/mm-view functions to display a part in the
669 current buffer, if possible."
670 (let ((display-buffer (current-buffer)))
672 ;; In case we already have :content, use it and tell mm-* that
673 ;; it's already been charset-decoded by using the fake
674 ;; `gnus-decoded' charset. Otherwise, we'll fetch the binary
675 ;; part content and let mm-* decode it.
676 (let* ((have-content (plist-member part :content))
677 (charset (if have-content
679 (plist-get part :content-charset)))
680 (handle (mm-make-handle (current-buffer)
681 `(,content-type (charset . ,charset)))))
682 ;; If the user wants the part inlined, insert the content and
683 ;; test whether we are able to inline it (which includes both
684 ;; capability and suitability tests).
685 (when (mm-inlined-p handle)
687 (insert (notmuch-get-bodypart-text msg part process-crypto))
688 (insert (notmuch-get-bodypart-binary msg part process-crypto)))
689 (when (mm-inlinable-p handle)
690 (set-buffer display-buffer)
691 (mm-display-part handle)
694 ;;; Generic Utilities
696 ;; Converts a plist of headers to an alist of headers. The input plist should
697 ;; have symbols of the form :Header as keys, and the resulting alist will have
698 ;; symbols of the form 'Header as keys.
699 (defun notmuch-headers-plist-to-alist (plist)
700 (cl-loop for (key value . rest) on plist by #'cddr
701 collect (cons (intern (substring (symbol-name key) 1)) value)))
703 (defun notmuch-face-ensure-list-form (face)
704 "Return FACE in face list form.
706 If FACE is already a face list, it will be returned as-is. If
707 FACE is a face name or face plist, it will be returned as a
708 single element face list."
709 (if (and (listp face) (not (keywordp (car face))))
713 (defun notmuch-apply-face (object face &optional below start end)
714 "Combine FACE into the 'face text property of OBJECT between START and END.
716 This function combines FACE with any existing faces between START
717 and END in OBJECT. Attributes specified by FACE take precedence
718 over existing attributes unless BELOW is non-nil.
720 OBJECT may be a string, a buffer, or nil (which means the current
721 buffer). If object is a string, START and END are 0-based;
722 otherwise they are buffer positions (integers or markers). FACE
723 must be a face name (a symbol or string), a property list of face
724 attributes, or a list of these. If START and/or END are omitted,
725 they default to the beginning/end of OBJECT. For convenience
726 when applied to strings, this returns OBJECT."
727 ;; A face property can have three forms: a face name (a string or
728 ;; symbol), a property list, or a list of these two forms. In the
729 ;; list case, the faces will be combined, with the earlier faces
730 ;; taking precedent. Here we canonicalize everything to list form
731 ;; to make it easy to combine.
732 (let ((pos (cond (start start)
736 ((stringp object) (length object))
737 (t (1+ (buffer-size object)))))
738 (face-list (notmuch-face-ensure-list-form face)))
740 (let* ((cur (get-text-property pos 'face object))
741 (cur-list (notmuch-face-ensure-list-form cur))
742 (new (cond ((null cur-list) face)
743 (below (append cur-list face-list))
744 (t (append face-list cur-list))))
745 (next (next-single-property-change pos 'face object end)))
746 (put-text-property pos next 'face new object)
750 (defun notmuch-map-text-property (start end prop func &optional object)
751 "Transform text property PROP using FUNC.
753 Applies FUNC to each distinct value of the text property PROP
754 between START and END of OBJECT, setting PROP to the value
757 (let ((value (get-text-property start prop object))
758 (next (next-single-property-change start prop object end)))
759 (put-text-property start next prop (funcall func value) object)
764 (defun notmuch-logged-error (msg &optional extra)
765 "Log MSG and EXTRA to *Notmuch errors* and signal MSG.
767 This logs MSG and EXTRA to the *Notmuch errors* buffer and
768 signals MSG as an error. If EXTRA is non-nil, text referring the
769 user to the *Notmuch errors* buffer will be appended to the
770 signaled error. This function does not return."
771 (with-current-buffer (get-buffer-create "*Notmuch errors*")
772 (goto-char (point-max))
776 (insert "[" (current-time-string) "]\n" msg)
783 (error "%s%s" msg (if extra " (see *Notmuch errors* for more details)" "")))
785 (defun notmuch-check-async-exit-status (proc msg &optional command err)
786 "If PROC exited abnormally, pop up an error buffer and signal an error.
788 This is a wrapper around `notmuch-check-exit-status' for
789 asynchronous process sentinels. PROC and MSG must be the
790 arguments passed to the sentinel. COMMAND and ERR, if provided,
791 are passed to `notmuch-check-exit-status'. If COMMAND is not
792 provided, it is taken from `process-command'."
794 (cl-case (process-status proc)
795 ((exit) (process-exit-status proc))
798 (notmuch-check-exit-status exit-status
799 (or command (process-command proc))
802 (defun notmuch-check-exit-status (exit-status command &optional output err)
803 "If EXIT-STATUS is non-zero, pop up an error buffer and signal an error.
805 If EXIT-STATUS is non-zero, pop up a notmuch error buffer
806 describing the error and signal an Elisp error. EXIT-STATUS must
807 be a number indicating the exit status code of a process or a
808 string describing the signal that terminated the process (such as
809 returned by `call-process'). COMMAND must be a list giving the
810 command and its arguments. OUTPUT, if provided, is a string
811 giving the output of command. ERR, if provided, is the error
812 output of command. OUTPUT and ERR will be included in the error
815 ((eq exit-status 0) t)
817 (notmuch-logged-error "notmuch CLI version mismatch
818 Emacs requested an older output format than supported by the notmuch CLI.
819 You may need to restart Emacs or upgrade your notmuch Emacs package."))
821 (notmuch-logged-error "notmuch CLI version mismatch
822 Emacs requested a newer output format than supported by the notmuch CLI.
823 You may need to restart Emacs or upgrade your notmuch package."))
826 ((`(,command . ,args) command)
827 (command (if (equal (file-name-nondirectory command)
832 (mapconcat (lambda (arg)
833 (shell-quote-argument
834 (cond ((stringp arg) arg)
835 ((symbolp arg) (symbol-name arg))
836 (t "*UNKNOWN ARGUMENT*"))))
840 (concat "command: " command-string "\n"
841 (if (integerp exit-status)
842 (format "exit status: %s\n" exit-status)
843 (format "exit signal: %s\n" exit-status))
844 (and err (concat "stderr:\n" err))
845 (and output (concat "stdout:\n" output)))))
847 ;; We have an error message straight from the CLI.
848 (notmuch-logged-error
849 (replace-regexp-in-string "[ \n\r\t\f]*\\'" "" err) extra)
850 ;; We only have combined output from the CLI; don't inundate
851 ;; the user with it. Mimic `process-lines'.
852 (notmuch-logged-error (format "%s exited with status %s"
855 ;; `notmuch-logged-error' does not return.
858 (defun notmuch-call-notmuch--helper (destination args)
859 "Helper for synchronous notmuch invocation commands.
861 This wraps `call-process'. DESTINATION has the same meaning as
862 for `call-process'. ARGS is as described for
863 `notmuch-call-notmuch-process'."
865 (while (keywordp (car args))
867 (:stdin-string (setq stdin-string (cadr args))
868 (setq args (cddr args)))
870 (error "Unknown keyword argument: %s" (car args)))))
871 (if (null stdin-string)
872 (apply #'call-process notmuch-command nil destination nil args)
873 (insert stdin-string)
874 (apply #'call-process-region (point-min) (point-max)
875 notmuch-command t destination nil args))))
877 (defun notmuch-call-notmuch-process (&rest args)
878 "Synchronously invoke `notmuch-command' with ARGS.
880 The caller may provide keyword arguments before ARGS. Currently
881 supported keyword arguments are:
883 :stdin-string STRING - Write STRING to stdin
885 If notmuch exits with a non-zero status, output from the process
886 will appear in a buffer named \"*Notmuch errors*\" and an error
889 (let ((status (notmuch-call-notmuch--helper t args)))
890 (notmuch-check-exit-status status (cons notmuch-command args)
893 (defun notmuch-call-notmuch-sexp (&rest args)
894 "Invoke `notmuch-command' with ARGS and return the parsed S-exp output.
896 This is equivalent to `notmuch-call-notmuch-process', but parses
897 notmuch's output as an S-expression and returns the parsed value.
898 Like `notmuch-call-notmuch-process', if notmuch exits with a
899 non-zero status, this will report its output and signal an
902 (let ((err-file (make-temp-file "nmerr")))
904 (let ((status (notmuch-call-notmuch--helper (list t err-file) args))
905 (err (with-temp-buffer
906 (insert-file-contents err-file)
909 (notmuch-check-exit-status status (cons notmuch-command args)
911 (goto-char (point-min))
912 (read (current-buffer)))
913 (delete-file err-file)))))
915 (defun notmuch-start-notmuch (name buffer sentinel &rest args)
916 "Start and return an asynchronous notmuch command.
918 This starts and returns an asynchronous process running
919 `notmuch-command' with ARGS. The exit status is checked via
920 `notmuch-check-async-exit-status'. Output written to stderr is
921 redirected and displayed when the process exits (even if the
922 process exits successfully). NAME and BUFFER are the same as in
923 `start-process'. SENTINEL is a process sentinel function to call
924 when the process exits, or nil for none. The caller must *not*
925 invoke `set-process-sentinel' directly on the returned process,
926 as that will interfere with the handling of stderr and the exit
928 (let* ((command (or (executable-find notmuch-command)
929 (error "Command not found: %s" notmuch-command)))
930 (err-buffer (generate-new-buffer " *notmuch-stderr*"))
934 :command (cons command args)
935 :connection-type 'pipe
937 (err-proc (get-buffer-process err-buffer)))
938 (process-put proc 'err-buffer err-buffer)
939 (process-put proc 'sub-sentinel sentinel)
940 (set-process-sentinel proc #'notmuch-start-notmuch-sentinel)
941 (set-process-sentinel err-proc #'notmuch-start-notmuch-error-sentinel)
944 (defun notmuch-start-notmuch-sentinel (proc event)
945 "Process sentinel function used by `notmuch-start-notmuch'."
946 (let* ((err-buffer (process-get proc 'err-buffer))
947 (err (and (buffer-live-p err-buffer)
948 (not (zerop (buffer-size err-buffer)))
949 (with-current-buffer err-buffer (buffer-string))))
950 (sub-sentinel (process-get proc 'sub-sentinel)))
953 ;; Invoke the sub-sentinel, if any
955 (funcall sub-sentinel proc event))
956 ;; Check the exit status. This will signal an error if the
957 ;; exit status is non-zero. Don't do this if the process
958 ;; buffer is dead since that means Emacs killed the process
959 ;; and there's no point in telling the user that (but we
960 ;; still check for and report stderr output below).
961 (when (buffer-live-p (process-buffer proc))
962 (notmuch-check-async-exit-status proc event nil err))
963 ;; If that didn't signal an error, then any error output was
964 ;; really warning output. Show warnings, if any.
967 (with-current-buffer err-buffer
968 (goto-char (point-min))
970 ;; Show first line; stuff remaining lines in the
972 (let ((l1 (buffer-substring (point-min) (point))))
973 (skip-chars-forward "\n")
974 (cons l1 (and (not (eobp))
975 (buffer-substring (point)
978 (notmuch-logged-error (car warnings) (cdr warnings)))))
980 ;; Emacs behaves strangely if an error escapes from a sentinel,
981 ;; so turn errors into messages.
982 (message "%s" (error-message-string err))))))
984 (defun notmuch-start-notmuch-error-sentinel (proc _event)
985 (unless (process-live-p proc)
986 (let ((buffer (process-buffer proc)))
987 (when (buffer-live-p buffer)
988 (kill-buffer buffer)))))
990 (defvar-local notmuch-show-process-crypto nil)
992 ;;; Generic Utilities
994 (defun notmuch-interactive-region ()
995 "Return the bounds of the current interactive region.
997 This returns (BEG END), where BEG and END are the bounds of the
998 region if the region is active, or both `point' otherwise."
999 (if (region-active-p)
1000 (list (region-beginning) (region-end))
1001 (list (point) (point))))
1003 (define-obsolete-function-alias
1004 'notmuch-search-interactive-region
1005 'notmuch-interactive-region
1010 (provide 'notmuch-lib)
1012 ;;; notmuch-lib.el ends here