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>
32 (require 'notmuch-compat)
34 (unless (require 'notmuch-version nil t)
35 (defconst notmuch-emacs-version "unknown"
36 "Placeholder variable when notmuch-version.el[c] is not available."))
41 "Notmuch mail reader for Emacs."
44 (defgroup notmuch-hello nil
45 "Overview of saved searches, tags, etc."
48 (defgroup notmuch-search nil
49 "Searching and sorting mail."
52 (defgroup notmuch-show nil
53 "Showing messages and threads."
56 (defgroup notmuch-send nil
57 "Sending messages from Notmuch."
61 (defgroup notmuch-tag nil
62 "Tags and tagging in Notmuch."
65 (defgroup notmuch-crypto nil
66 "Processing and display of cryptographic MIME parts."
69 (defgroup notmuch-hooks nil
70 "Running custom code on well-defined occasions."
73 (defgroup notmuch-external nil
74 "Running external commands from within Notmuch."
77 (defgroup notmuch-address nil
81 (defgroup notmuch-faces nil
82 "Graphical attributes for displaying text"
87 (defcustom notmuch-command "notmuch"
88 "Name of the notmuch binary.
90 This can be a relative or absolute path to the notmuch binary.
91 If this is a relative path, it will be searched for in all of the
92 directories given in `exec-path' (which is, by default, based on
95 :group 'notmuch-external)
97 (defcustom notmuch-search-oldest-first t
98 "Show the oldest mail first when searching.
100 This variable defines the default sort order for displaying
101 search results. Note that any filtered searches created by
102 `notmuch-search-filter' retain the search order of the parent
105 :group 'notmuch-search)
106 (make-variable-buffer-local 'notmuch-search-oldest-first)
108 (defcustom notmuch-poll-script nil
109 "[Deprecated] Command to run to incorporate new mail into the notmuch database.
111 This option has been deprecated in favor of \"notmuch new\"
112 hooks (see man notmuch-hooks). To change the path to the notmuch
113 binary, customize `notmuch-command'.
115 This variable controls the action invoked by
116 `notmuch-poll-and-refresh-this-buffer' (bound by default to 'G')
117 to incorporate new mail into the notmuch database.
119 If set to nil (the default), new mail is processed by invoking
120 \"notmuch new\". Otherwise, this should be set to a string that
121 gives the name of an external script that processes new mail. If
122 set to the empty string, no command will be run.
124 The external script could do any of the following depending on
127 1. Invoke a program to transfer mail to the local mail store
128 2. Invoke \"notmuch new\" to incorporate the new mail
129 3. Invoke one or more \"notmuch tag\" commands to classify the mail"
130 :type '(choice (const :tag "notmuch new" nil)
131 (const :tag "Disabled" "")
132 (string :tag "Custom script"))
133 :group 'notmuch-external)
135 (defcustom notmuch-archive-tags '("-inbox")
136 "List of tag changes to apply to a message or a thread when it is archived.
138 Tags starting with \"+\" (or not starting with either \"+\" or
139 \"-\") in the list will be added, and tags starting with \"-\"
140 will be removed from the message or thread being archived.
142 For example, if you wanted to remove an \"inbox\" tag and add an
143 \"archived\" tag, you would set:
144 (\"-inbox\" \"+archived\")"
145 :type '(repeat string)
146 :group 'notmuch-search
147 :group 'notmuch-show)
151 (defvar notmuch-search-history nil
152 "Variable to store notmuch searches history.")
154 (defvar notmuch-common-keymap
155 (let ((map (make-sparse-keymap)))
156 (define-key map "?" 'notmuch-help)
157 (define-key map "v" 'notmuch-version)
158 (define-key map "q" 'notmuch-bury-or-kill-this-buffer)
159 (define-key map "s" 'notmuch-search)
160 (define-key map "t" 'notmuch-search-by-tag)
161 (define-key map "z" 'notmuch-tree)
162 (define-key map "u" 'notmuch-unthreaded)
163 (define-key map "m" 'notmuch-mua-new-mail)
164 (define-key map "g" 'notmuch-refresh-this-buffer)
165 (define-key map "=" 'notmuch-refresh-this-buffer)
166 (define-key map (kbd "M-=") 'notmuch-refresh-all-buffers)
167 (define-key map "G" 'notmuch-poll-and-refresh-this-buffer)
168 (define-key map "j" 'notmuch-jump-search)
169 (define-key map [remap undo] 'notmuch-tag-undo)
171 "Keymap shared by all notmuch modes.")
173 ;; By default clicking on a button does not select the window
174 ;; containing the button (as opposed to clicking on a widget which
175 ;; does). This means that the button action is then executed in the
176 ;; current selected window which can cause problems if the button
177 ;; changes the buffer (e.g., id: links) or moves point.
179 ;; This provides a button type which overrides mouse-action so that
180 ;; the button's window is selected before the action is run. Other
181 ;; notmuch buttons can get the same behaviour by inheriting from this
183 (define-button-type 'notmuch-button-type
184 'mouse-action (lambda (button)
185 (select-window (posn-window (event-start last-input-event)))
186 (button-activate button)))
190 (defun notmuch-command-to-string (&rest args)
191 "Synchronously invoke \"notmuch\" with the given list of arguments.
193 If notmuch exits with a non-zero status, output from the process
194 will appear in a buffer named \"*Notmuch errors*\" and an error
197 Otherwise the output will be returned."
199 (let ((status (apply #'notmuch--call-process notmuch-command nil t nil args))
200 (output (buffer-string)))
201 (notmuch-check-exit-status status (cons notmuch-command args) output)
204 (defvar notmuch--cli-sane-p nil
205 "Cache whether the CLI seems to be configured sanely.")
207 (defun notmuch-cli-sane-p ()
208 "Return t if the cli seems to be configured sanely."
209 (unless notmuch--cli-sane-p
210 (let ((status (notmuch--call-process notmuch-command nil nil nil
211 "config" "get" "user.primary_email")))
212 (setq notmuch--cli-sane-p (= status 0))))
215 (defun notmuch-assert-cli-sane ()
216 (unless (notmuch-cli-sane-p)
217 (notmuch-logged-error
218 "notmuch cli seems misconfigured or unconfigured."
219 "Perhaps you haven't run \"notmuch setup\" yet? Try running this
220 on the command line, and then retry your notmuch command")))
222 (defun notmuch-cli-version ()
223 "Return a string with the notmuch cli command version number."
225 ;; Trim off the trailing newline.
226 (substring (notmuch-command-to-string "--version") 0 -1)))
227 (if (string-match "^notmuch\\( version\\)? \\(.*\\)$"
229 (match-string 2 long-string)
232 (defvar notmuch-emacs-version)
234 (defun notmuch-version ()
235 "Display the notmuch version.
236 The versions of the Emacs package and the `notmuch' executable
237 should match, but if and only if they don't, then this command
238 displays both values separately."
240 (let ((cli-version (notmuch-cli-version)))
241 (message "notmuch version %s"
242 (if (string= notmuch-emacs-version cli-version)
245 " (emacs mua version " notmuch-emacs-version ")")))))
247 ;;; Notmuch Configuration
249 (defun notmuch-config-get (item)
250 "Return a value from the notmuch configuration."
251 (let* ((val (notmuch-command-to-string "config" "get" item))
253 ;; Trim off the trailing newline (if the value is empty or not
254 ;; configured, there will be no newline).
256 (= (aref val (- len 1)) ?\n))
260 (defun notmuch-database-path ()
261 "Return the database.path value from the notmuch configuration."
262 (notmuch-config-get "database.path"))
264 (defun notmuch-user-name ()
265 "Return the user.name value from the notmuch configuration."
266 (notmuch-config-get "user.name"))
268 (defun notmuch-user-primary-email ()
269 "Return the user.primary_email value from the notmuch configuration."
270 (notmuch-config-get "user.primary_email"))
272 (defun notmuch-user-other-email ()
273 "Return the user.other_email value (as a list) from the notmuch configuration."
274 (split-string (notmuch-config-get "user.other_email") "\n" t))
276 (defun notmuch-user-emails ()
277 (cons (notmuch-user-primary-email) (notmuch-user-other-email)))
281 (defun notmuch-poll ()
282 "Run \"notmuch new\" or an external script to import mail.
284 Invokes `notmuch-poll-script', \"notmuch new\", or does nothing
285 depending on the value of `notmuch-poll-script'."
287 (message "Polling mail...")
288 (if (stringp notmuch-poll-script)
289 (unless (string-empty-p notmuch-poll-script)
290 (unless (equal (notmuch--call-process notmuch-poll-script nil nil) 0)
291 (error "Notmuch: poll script `%s' failed!" notmuch-poll-script)))
292 (notmuch-call-notmuch-process "new"))
293 (message "Polling mail...done"))
295 (defun notmuch-bury-or-kill-this-buffer ()
296 "Undisplay the current buffer.
298 Bury the current buffer, unless there is only one window showing
299 it, in which case it is killed."
301 (if (> (length (get-buffer-window-list nil nil t)) 1)
305 ;;; Describe Key Bindings
307 (defun notmuch-prefix-key-description (key)
308 "Given a prefix key code, return a human-readable string representation.
310 This is basically just `format-kbd-macro' but we also convert ESC to M-."
311 (let* ((key-vector (if (vectorp key) key (vector key)))
312 (desc (format-kbd-macro key-vector)))
313 (if (string= desc "ESC")
317 (defun notmuch-describe-key (actual-key binding prefix ua-keys tail)
318 "Prepend cons cells describing prefix-arg ACTUAL-KEY and ACTUAL-KEY to TAIL.
320 It does not prepend if ACTUAL-KEY is already listed in TAIL."
321 (let ((key-string (concat prefix (key-description actual-key))))
322 ;; We don't include documentation if the key-binding is
323 ;; over-ridden. Note, over-riding a binding automatically hides the
324 ;; prefixed version too.
325 (unless (assoc key-string tail)
326 (when (and ua-keys (symbolp binding)
327 (get binding 'notmuch-prefix-doc))
328 ;; Documentation for prefixed command
329 (let ((ua-desc (key-description ua-keys)))
330 (push (cons (concat ua-desc " " prefix (format-kbd-macro actual-key))
331 (get binding 'notmuch-prefix-doc))
333 ;; Documentation for command
334 (push (cons key-string
335 (or (and (symbolp binding)
336 (get binding 'notmuch-doc))
337 (and (functionp binding)
338 (let ((doc (documentation binding)))
340 (string-match "\\`.+" doc)
341 (match-string 0 doc))))))
345 (defun notmuch-describe-remaps (remap-keymap ua-keys base-keymap prefix tail)
346 ;; Remappings are represented as a binding whose first "event" is
347 ;; 'remap. Hence, if the keymap has any remappings, it will have a
348 ;; binding whose "key" is 'remap, and whose "binding" is itself a
349 ;; keymap that maps not from keys to commands, but from old (remapped)
350 ;; functions to the commands to use in their stead.
351 (map-keymap (lambda (command binding)
352 (mapc (lambda (actual-key)
354 (notmuch-describe-key actual-key binding
355 prefix ua-keys tail)))
356 (where-is-internal command base-keymap)))
360 (defun notmuch-describe-keymap (keymap ua-keys base-keymap &optional prefix tail)
361 "Return a list of cons cells, each describing one binding in KEYMAP.
363 Each cons cell consists of a string giving a human-readable
364 description of the key, and a one-line description of the bound
365 function. See `notmuch-help' for an overview of how this
366 documentation is extracted.
368 UA-KEYS should be a key sequence bound to `universal-argument'.
369 It will be used to describe bindings of commands that support a
370 prefix argument. PREFIX and TAIL are used internally."
372 (lambda (key binding)
373 (cond ((mouse-event-p key) nil)
377 (notmuch-describe-remaps
378 binding ua-keys base-keymap prefix tail)
379 (notmuch-describe-keymap
380 binding ua-keys base-keymap
381 (notmuch-prefix-key-description key)
385 (notmuch-describe-key (vector key)
386 binding prefix ua-keys tail)))))
390 (defun notmuch-substitute-command-keys (doc)
391 "Like `substitute-command-keys' but with documentation, not function names."
393 (while (string-match "\\\\{\\([^}[:space:]]*\\)}" doc beg)
396 (let* ((keymap-name (substring doc
399 (keymap (symbol-value (intern keymap-name)))
400 (ua-keys (where-is-internal 'universal-argument keymap t))
401 (desc-alist (notmuch-describe-keymap keymap ua-keys keymap))
402 (desc-list (mapcar (lambda (arg)
403 (concat (car arg) "\t" (cdr arg)))
405 (mapconcat #'identity desc-list "\n")))))
406 (setq doc (replace-match desc 1 1 doc)))
407 (setq beg (match-end 0)))
410 (defun notmuch-help ()
411 "Display help for the current notmuch mode.
413 This is similar to `describe-function' for the current major
414 mode, but bindings tables are shown with documentation strings
415 rather than command names. By default, this uses the first line
416 of each command's documentation string. A command can override
417 this by setting the 'notmuch-doc property of its command symbol.
418 A command that supports a prefix argument can explicitly document
419 its prefixed behavior by setting the 'notmuch-prefix-doc property
420 of its command symbol."
422 (let ((doc (substitute-command-keys
423 (notmuch-substitute-command-keys
424 (documentation major-mode t)))))
425 (with-current-buffer (generate-new-buffer "*notmuch-help*")
427 (goto-char (point-min))
428 (set-buffer-modified-p nil)
429 (view-buffer (current-buffer) 'kill-buffer-if-not-modified))))
431 (defun notmuch-subkeymap-help ()
432 "Show help for a subkeymap."
434 (let* ((key (this-command-keys-vector))
435 (prefix (make-vector (1- (length key)) nil))
437 (while (< i (length prefix))
438 (aset prefix i (aref key i))
440 (let* ((subkeymap (key-binding prefix))
441 (ua-keys (where-is-internal 'universal-argument nil t))
442 (prefix-string (notmuch-prefix-key-description prefix))
443 (desc-alist (notmuch-describe-keymap
444 subkeymap ua-keys subkeymap prefix-string))
445 (desc-list (mapcar (lambda (arg) (concat (car arg) "\t" (cdr arg)))
447 (desc (mapconcat #'identity desc-list "\n")))
448 (with-help-window (help-buffer)
449 (with-current-buffer standard-output
450 (insert "\nPress 'q' to quit this window.\n\n")
452 (pop-to-buffer (help-buffer)))))
454 ;;; Refreshing Buffers
456 (defvar-local notmuch-buffer-refresh-function nil
457 "Function to call to refresh the current buffer.")
459 (defun notmuch-refresh-this-buffer ()
460 "Refresh the current buffer."
462 (when notmuch-buffer-refresh-function
463 ;; Pass prefix argument, etc.
464 (call-interactively notmuch-buffer-refresh-function)))
466 (defun notmuch-poll-and-refresh-this-buffer ()
467 "Invoke `notmuch-poll' to import mail, then refresh the current buffer."
470 (notmuch-refresh-this-buffer))
472 (defun notmuch-refresh-all-buffers ()
473 "Invoke `notmuch-refresh-this-buffer' on all notmuch major-mode buffers.
475 The buffers are silently refreshed, i.e. they are not forced to
478 (dolist (buffer (buffer-list))
479 (let ((buffer-mode (buffer-local-value 'major-mode buffer)))
480 (when (memq buffer-mode '(notmuch-show-mode
484 (with-current-buffer buffer
485 (notmuch-refresh-this-buffer))))))
489 (defun notmuch-prettify-subject (subject)
490 ;; This function is used by `notmuch-search-process-filter',
491 ;; which requires that we not disrupt its matching state.
494 (string-match "^[ \t]*$" subject))
498 (defun notmuch-sanitize (str)
499 "Sanitize control character in STR.
501 This includes newlines, tabs, and other funny characters."
502 (replace-regexp-in-string "[[:cntrl:]\x7f\u2028\u2029]+" " " str))
504 (defun notmuch-escape-boolean-term (term)
505 "Escape a boolean term for use in a query.
507 The caller is responsible for prepending the term prefix and a
508 colon. This performs minimal escaping in order to produce
509 user-friendly queries."
511 (if (or (equal term "")
512 ;; To be pessimistic, only pass through terms composed
513 ;; entirely of ASCII printing characters other than ", (,
515 (string-match "[^!#-'*-~]" term))
517 (concat "\"" (replace-regexp-in-string "\"" "\"\"" term t t) "\"")
520 (defun notmuch-id-to-query (id)
521 "Return a query that matches the message with id ID."
522 (concat "id:" (notmuch-escape-boolean-term id)))
524 (defun notmuch-hex-encode (str)
525 "Hex-encode STR (e.g., as used by batch tagging).
527 This replaces spaces, percents, and double quotes in STR with
528 %NN where NN is the hexadecimal value of the character."
529 (replace-regexp-in-string
530 "[ %\"]" (lambda (match) (format "%%%02x" (aref match 0))) str))
532 (defun notmuch-common-do-stash (text)
533 "Common function to stash text in kill ring, and display in minibuffer."
537 (message "Stashed: %s" text))
538 ;; There is nothing to stash so stash an empty string so the user
539 ;; doesn't accidentally paste something else somewhere.
541 (message "Nothing to stash!")))
543 ;;; Generic Utilities
545 (defun notmuch-plist-delete (plist property)
548 (unless (eq property (car plist))
549 (setq p (plist-put p (car plist) (cadr plist))))
550 (setq plist (cddr plist)))
555 (defun notmuch-match-content-type (t1 t2)
556 "Return t if t1 and t2 are matching content types.
557 Take wildcards into account."
560 (let ((st1 (split-string t1 "/"))
561 (st2 (split-string t2 "/")))
562 (if (or (string= (cadr st1) "*")
563 (string= (cadr st2) "*"))
564 ;; Comparison of content types should be case insensitive.
565 (string= (downcase (car st1))
566 (downcase (car st2)))
567 (string= (downcase t1)
570 (defvar notmuch-multipart/alternative-discouraged
571 '(;; Avoid HTML parts.
573 ;; multipart/related usually contain a text/html part and some
574 ;; associated graphics.
575 "multipart/related"))
577 (defun notmuch-multipart/alternative-determine-discouraged (msg)
578 "Return the discouraged alternatives for the specified message."
579 ;; If a function, return the result of calling it.
580 (if (functionp notmuch-multipart/alternative-discouraged)
581 (funcall notmuch-multipart/alternative-discouraged msg)
582 ;; Otherwise simply return the value of the variable, which is
583 ;; assumed to be a list of discouraged alternatives. This is the
584 ;; default behaviour.
585 notmuch-multipart/alternative-discouraged))
587 (defun notmuch-multipart/alternative-choose (msg types)
588 "Return a list of preferred types from the given list of types
589 for this message, if present."
590 ;; Based on `mm-preferred-alternative-precedence'.
591 (let ((discouraged (notmuch-multipart/alternative-determine-discouraged msg))
593 (dolist (pref (reverse discouraged))
594 (dolist (elem (copy-sequence seq))
595 (when (string-match pref elem)
596 (setq seq (nconc (delete elem seq) (list elem))))))
599 (defun notmuch-parts-filter-by-type (parts type)
600 "Given a list of message parts, return a list containing the ones matching
603 (lambda (part) (notmuch-match-content-type (plist-get part :content-type) type))
606 (defun notmuch--get-bodypart-raw (msg part process-crypto binaryp cache)
607 (let* ((plist-elem (if binaryp :content-binary :content))
608 (data (or (plist-get part plist-elem)
610 ;; Emacs internally uses a UTF-8-like multibyte string
611 ;; representation by default (regardless of the coding
612 ;; system, which only affects how it goes from outside data
613 ;; to this internal representation). This *almost* never
614 ;; matters. Annoyingly, it does matter if we use this data
615 ;; in an image descriptor, since Emacs will use its internal
616 ;; data buffer directly and this multibyte representation
617 ;; corrupts binary image formats. Since the caller is
618 ;; asking for binary data, a unibyte string is a more
619 ;; appropriate representation anyway.
621 (set-buffer-multibyte nil))
622 (let ((args `("show" "--format=raw"
623 ,(format "--part=%s" (plist-get part :id))
624 ,@(and process-crypto '("--decrypt=true"))
625 ,(notmuch-id-to-query (plist-get msg :id))))
626 (coding-system-for-read
630 (mm-charset-to-coding-system
631 (plist-get part :content-charset))))
633 ;; `mm-charset-to-coding-system' seems
634 ;; to return things that are not
635 ;; considered acceptable values for
636 ;; `coding-system-for-read'.
637 (if (coding-system-p coding-system)
639 ;; RFC 2047 says that the default
640 ;; charset is US-ASCII. RFC6657
641 ;; complicates this somewhat.
643 (apply #'notmuch--call-process
644 notmuch-command nil '(t nil) nil args)
646 (when (and cache data)
647 (plist-put part plist-elem data))
650 (defun notmuch-get-bodypart-binary (msg part process-crypto &optional cache)
651 "Return the unprocessed content of PART in MSG as a unibyte string.
653 This returns the \"raw\" content of the given part after content
654 transfer decoding, but with no further processing (see the
655 discussion of --format=raw in man notmuch-show). In particular,
656 this does no charset conversion.
658 If CACHE is non-nil, the content of this part will be saved in
659 MSG (if it isn't already)."
660 (notmuch--get-bodypart-raw msg part process-crypto t cache))
662 (defun notmuch-get-bodypart-text (msg part process-crypto &optional cache)
663 "Return the text content of PART in MSG.
665 This returns the content of the given part as a multibyte Lisp
666 string after performing content transfer decoding and any
667 necessary charset decoding.
669 If CACHE is non-nil, the content of this part will be saved in
670 MSG (if it isn't already)."
671 (notmuch--get-bodypart-raw msg part process-crypto nil cache))
673 (defun notmuch-mm-display-part-inline (msg part content-type process-crypto)
674 "Use the mm-decode/mm-view functions to display a part in the
675 current buffer, if possible."
676 (let ((display-buffer (current-buffer)))
678 ;; In case we already have :content, use it and tell mm-* that
679 ;; it's already been charset-decoded by using the fake
680 ;; `gnus-decoded' charset. Otherwise, we'll fetch the binary
681 ;; part content and let mm-* decode it.
682 (let* ((have-content (plist-member part :content))
683 (charset (if have-content
685 (plist-get part :content-charset)))
686 (handle (mm-make-handle (current-buffer)
687 `(,content-type (charset . ,charset)))))
688 ;; If the user wants the part inlined, insert the content and
689 ;; test whether we are able to inline it (which includes both
690 ;; capability and suitability tests).
691 (when (mm-inlined-p handle)
693 (insert (notmuch-get-bodypart-text msg part process-crypto))
694 (insert (notmuch-get-bodypart-binary msg part process-crypto)))
695 (when (mm-inlinable-p handle)
696 (set-buffer display-buffer)
697 (mm-display-part handle)
700 ;;; Generic Utilities
702 ;; Converts a plist of headers to an alist of headers. The input plist should
703 ;; have symbols of the form :Header as keys, and the resulting alist will have
704 ;; symbols of the form 'Header as keys.
705 (defun notmuch-headers-plist-to-alist (plist)
706 (cl-loop for (key value . rest) on plist by #'cddr
707 collect (cons (intern (substring (symbol-name key) 1)) value)))
709 (defun notmuch-face-ensure-list-form (face)
710 "Return FACE in face list form.
712 If FACE is already a face list, it will be returned as-is. If
713 FACE is a face name or face plist, it will be returned as a
714 single element face list."
715 (if (and (listp face) (not (keywordp (car face))))
719 (defun notmuch-apply-face (object face &optional below start end)
720 "Combine FACE into the 'face text property of OBJECT between START and END.
722 This function combines FACE with any existing faces between START
723 and END in OBJECT. Attributes specified by FACE take precedence
724 over existing attributes unless BELOW is non-nil.
726 OBJECT may be a string, a buffer, or nil (which means the current
727 buffer). If object is a string, START and END are 0-based;
728 otherwise they are buffer positions (integers or markers). FACE
729 must be a face name (a symbol or string), a property list of face
730 attributes, or a list of these. If START and/or END are omitted,
731 they default to the beginning/end of OBJECT. For convenience
732 when applied to strings, this returns OBJECT."
733 ;; A face property can have three forms: a face name (a string or
734 ;; symbol), a property list, or a list of these two forms. In the
735 ;; list case, the faces will be combined, with the earlier faces
736 ;; taking precedent. Here we canonicalize everything to list form
737 ;; to make it easy to combine.
738 (let ((pos (cond (start start)
742 ((stringp object) (length object))
743 (t (1+ (buffer-size object)))))
744 (face-list (notmuch-face-ensure-list-form face)))
746 (let* ((cur (get-text-property pos 'face object))
747 (cur-list (notmuch-face-ensure-list-form cur))
748 (new (cond ((null cur-list) face)
749 (below (append cur-list face-list))
750 (t (append face-list cur-list))))
751 (next (next-single-property-change pos 'face object end)))
752 (put-text-property pos next 'face new object)
756 (defun notmuch-map-text-property (start end prop func &optional object)
757 "Transform text property PROP using FUNC.
759 Applies FUNC to each distinct value of the text property PROP
760 between START and END of OBJECT, setting PROP to the value
763 (let ((value (get-text-property start prop object))
764 (next (next-single-property-change start prop object end)))
765 (put-text-property start next prop (funcall func value) object)
770 (defun notmuch-logged-error (msg &optional extra)
771 "Log MSG and EXTRA to *Notmuch errors* and signal MSG.
773 This logs MSG and EXTRA to the *Notmuch errors* buffer and
774 signals MSG as an error. If EXTRA is non-nil, text referring the
775 user to the *Notmuch errors* buffer will be appended to the
776 signaled error. This function does not return."
777 (with-current-buffer (get-buffer-create "*Notmuch errors*")
778 (goto-char (point-max))
782 (insert "[" (current-time-string) "]\n" msg)
789 (error "%s%s" msg (if extra " (see *Notmuch errors* for more details)" "")))
791 (defun notmuch-check-async-exit-status (proc msg &optional command err)
792 "If PROC exited abnormally, pop up an error buffer and signal an error.
794 This is a wrapper around `notmuch-check-exit-status' for
795 asynchronous process sentinels. PROC and MSG must be the
796 arguments passed to the sentinel. COMMAND and ERR, if provided,
797 are passed to `notmuch-check-exit-status'. If COMMAND is not
798 provided, it is taken from `process-command'."
800 (cl-case (process-status proc)
801 ((exit) (process-exit-status proc))
804 (notmuch-check-exit-status exit-status
805 (or command (process-command proc))
808 (defun notmuch-check-exit-status (exit-status command &optional output err)
809 "If EXIT-STATUS is non-zero, pop up an error buffer and signal an error.
811 If EXIT-STATUS is non-zero, pop up a notmuch error buffer
812 describing the error and signal an Elisp error. EXIT-STATUS must
813 be a number indicating the exit status code of a process or a
814 string describing the signal that terminated the process (such as
815 returned by `call-process'). COMMAND must be a list giving the
816 command and its arguments. OUTPUT, if provided, is a string
817 giving the output of command. ERR, if provided, is the error
818 output of command. OUTPUT and ERR will be included in the error
821 ((eq exit-status 0) t)
823 (notmuch-logged-error "notmuch CLI version mismatch
824 Emacs requested an older output format than supported by the notmuch CLI.
825 You may need to restart Emacs or upgrade your notmuch Emacs package."))
827 (notmuch-logged-error "notmuch CLI version mismatch
828 Emacs requested a newer output format than supported by the notmuch CLI.
829 You may need to restart Emacs or upgrade your notmuch package."))
832 ((`(,command . ,args) command)
833 (command (if (equal (file-name-nondirectory command)
838 (mapconcat (lambda (arg)
839 (shell-quote-argument
840 (cond ((stringp arg) arg)
841 ((symbolp arg) (symbol-name arg))
842 (t "*UNKNOWN ARGUMENT*"))))
846 (concat "command: " command-string "\n"
847 (if (integerp exit-status)
848 (format "exit status: %s\n" exit-status)
849 (format "exit signal: %s\n" exit-status))
850 (and err (concat "stderr:\n" err))
851 (and output (concat "stdout:\n" output)))))
853 ;; We have an error message straight from the CLI.
854 (notmuch-logged-error
855 (replace-regexp-in-string "[ \n\r\t\f]*\\'" "" err) extra)
856 ;; We only have combined output from the CLI; don't inundate
857 ;; the user with it. Mimic `process-lines'.
858 (notmuch-logged-error (format "%s exited with status %s"
861 ;; `notmuch-logged-error' does not return.
864 (defmacro notmuch--apply-with-env (func &rest args)
865 `(let ((default-directory "~"))
866 (apply ,func ,@args)))
868 (defun notmuch--process-lines (program &rest args)
869 "Wrap process-lines, binding DEFAULT-DIRECTORY to a safe
871 (notmuch--apply-with-env #'process-lines program args))
873 (defun notmuch--make-process (&rest args)
874 "Wrap make-process, binding DEFAULT-DIRECTORY to a safe
876 (notmuch--apply-with-env #'make-process args))
878 (defun notmuch--call-process-region (start end program
879 &optional delete buffer display
881 "Wrap call-process-region, binding DEFAULT-DIRECTORY to a safe
883 (notmuch--apply-with-env
884 #'call-process-region start end program delete buffer display args))
886 (defun notmuch--call-process (program &optional infile destination display &rest args)
887 "Wrap call-process, binding DEFAULT-DIRECTORY to a safe default"
888 (notmuch--apply-with-env #'call-process program infile destination display args))
890 (defun notmuch-call-notmuch--helper (destination args)
891 "Helper for synchronous notmuch invocation commands.
893 This wraps `call-process'. DESTINATION has the same meaning as
894 for `call-process'. ARGS is as described for
895 `notmuch-call-notmuch-process'."
897 (while (keywordp (car args))
899 (:stdin-string (setq stdin-string (cadr args))
900 (setq args (cddr args)))
902 (error "Unknown keyword argument: %s" (car args)))))
903 (if (null stdin-string)
904 (apply #'notmuch--call-process notmuch-command nil destination nil args)
905 (insert stdin-string)
906 (apply #'notmuch--call-process-region (point-min) (point-max)
907 notmuch-command t destination nil args))))
909 (defun notmuch-call-notmuch-process (&rest args)
910 "Synchronously invoke `notmuch-command' with ARGS.
912 The caller may provide keyword arguments before ARGS. Currently
913 supported keyword arguments are:
915 :stdin-string STRING - Write STRING to stdin
917 If notmuch exits with a non-zero status, output from the process
918 will appear in a buffer named \"*Notmuch errors*\" and an error
921 (let ((status (notmuch-call-notmuch--helper t args)))
922 (notmuch-check-exit-status status (cons notmuch-command args)
925 (defun notmuch-call-notmuch-sexp (&rest args)
926 "Invoke `notmuch-command' with ARGS and return the parsed S-exp output.
928 This is equivalent to `notmuch-call-notmuch-process', but parses
929 notmuch's output as an S-expression and returns the parsed value.
930 Like `notmuch-call-notmuch-process', if notmuch exits with a
931 non-zero status, this will report its output and signal an
934 (let ((err-file (make-temp-file "nmerr")))
936 (let ((status (notmuch-call-notmuch--helper (list t err-file) args))
937 (err (with-temp-buffer
938 (insert-file-contents err-file)
941 (notmuch-check-exit-status status (cons notmuch-command args)
943 (goto-char (point-min))
944 (read (current-buffer)))
945 (delete-file err-file)))))
947 (defun notmuch-start-notmuch (name buffer sentinel &rest args)
948 "Start and return an asynchronous notmuch command.
950 This starts and returns an asynchronous process running
951 `notmuch-command' with ARGS. The exit status is checked via
952 `notmuch-check-async-exit-status'. Output written to stderr is
953 redirected and displayed when the process exits (even if the
954 process exits successfully). NAME and BUFFER are the same as in
955 `start-process'. SENTINEL is a process sentinel function to call
956 when the process exits, or nil for none. The caller must *not*
957 invoke `set-process-sentinel' directly on the returned process,
958 as that will interfere with the handling of stderr and the exit
960 (let* ((command (or (executable-find notmuch-command)
961 (error "Command not found: %s" notmuch-command)))
962 (err-buffer (generate-new-buffer " *notmuch-stderr*"))
963 (proc (notmuch--make-process
966 :command (cons command args)
967 :connection-type 'pipe
969 (err-proc (get-buffer-process err-buffer)))
970 (process-put proc 'err-buffer err-buffer)
971 (process-put proc 'sub-sentinel sentinel)
972 (set-process-sentinel proc #'notmuch-start-notmuch-sentinel)
973 (set-process-sentinel err-proc #'notmuch-start-notmuch-error-sentinel)
976 (defun notmuch-start-notmuch-sentinel (proc event)
977 "Process sentinel function used by `notmuch-start-notmuch'."
978 (let* ((err-buffer (process-get proc 'err-buffer))
979 (err (and (buffer-live-p err-buffer)
980 (not (zerop (buffer-size err-buffer)))
981 (with-current-buffer err-buffer (buffer-string))))
982 (sub-sentinel (process-get proc 'sub-sentinel)))
985 ;; Invoke the sub-sentinel, if any
987 (funcall sub-sentinel proc event))
988 ;; Check the exit status. This will signal an error if the
989 ;; exit status is non-zero. Don't do this if the process
990 ;; buffer is dead since that means Emacs killed the process
991 ;; and there's no point in telling the user that (but we
992 ;; still check for and report stderr output below).
993 (when (buffer-live-p (process-buffer proc))
994 (notmuch-check-async-exit-status proc event nil err))
995 ;; If that didn't signal an error, then any error output was
996 ;; really warning output. Show warnings, if any.
999 (with-current-buffer err-buffer
1000 (goto-char (point-min))
1002 ;; Show first line; stuff remaining lines in the
1004 (let ((l1 (buffer-substring (point-min) (point))))
1005 (skip-chars-forward "\n")
1006 (cons l1 (and (not (eobp))
1007 (buffer-substring (point)
1010 (notmuch-logged-error (car warnings) (cdr warnings)))))
1012 ;; Emacs behaves strangely if an error escapes from a sentinel,
1013 ;; so turn errors into messages.
1014 (message "%s" (error-message-string err))))))
1016 (defun notmuch-start-notmuch-error-sentinel (proc _event)
1017 (unless (process-live-p proc)
1018 (let ((buffer (process-buffer proc)))
1019 (when (buffer-live-p buffer)
1020 (kill-buffer buffer)))))
1022 (defvar-local notmuch-show-process-crypto nil)
1024 ;;; Generic Utilities
1026 (defun notmuch-interactive-region ()
1027 "Return the bounds of the current interactive region.
1029 This returns (BEG END), where BEG and END are the bounds of the
1030 region if the region is active, or both `point' otherwise."
1031 (if (region-active-p)
1032 (list (region-beginning) (region-end))
1033 (list (point) (point))))
1035 (define-obsolete-function-alias
1036 'notmuch-search-interactive-region
1037 'notmuch-interactive-region
1042 (provide 'notmuch-lib)
1044 ;;; notmuch-lib.el ends here