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