1 ;;; notmuch-lib.el --- common variables, functions and function declarations
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>
22 ;; This is an part of an emacs-based interface to the notmuch mail system.
31 (unless (require 'notmuch-version nil t)
32 (defconst notmuch-emacs-version "unknown"
33 "Placeholder variable when notmuch-version.el[c] is not available."))
35 (autoload 'notmuch-jump-search "notmuch-jump"
36 "Jump to a saved search by shortcut key." t)
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."
58 (custom-add-to-group 'notmuch-send 'message 'custom-group)
60 (defgroup notmuch-crypto nil
61 "Processing and display of cryptographic MIME parts."
64 (defgroup notmuch-hooks nil
65 "Running custom code on well-defined occasions."
68 (defgroup notmuch-external nil
69 "Running external commands from within Notmuch."
72 (defgroup notmuch-faces nil
73 "Graphical attributes for displaying text"
76 (defcustom notmuch-command "notmuch"
77 "Name of the notmuch binary.
79 This can be a relative or absolute path to the notmuch binary.
80 If this is a relative path, it will be searched for in all of the
81 directories given in `exec-path' (which is, by default, based on
84 :group 'notmuch-external)
86 (defcustom notmuch-search-oldest-first t
87 "Show the oldest mail first when searching.
89 This variable defines the default sort order for displaying
90 search results. Note that any filtered searches created by
91 `notmuch-search-filter' retain the search order of the parent
94 :group 'notmuch-search)
96 (defcustom notmuch-poll-script nil
97 "[Deprecated] Command to run to incorporate new mail into the notmuch database.
99 This option has been deprecated in favor of \"notmuch new\"
100 hooks (see man notmuch-hooks). To change the path to the notmuch
101 binary, customize `notmuch-command'.
103 This variable controls the action invoked by
104 `notmuch-poll-and-refresh-this-buffer' (bound by default to 'G')
105 to incorporate new mail into the notmuch database.
107 If set to nil (the default), new mail is processed by invoking
108 \"notmuch new\". Otherwise, this should be set to a string that
109 gives the name of an external script that processes new mail. If
110 set to the empty string, no command will be run.
112 The external script could do any of the following depending on
115 1. Invoke a program to transfer mail to the local mail store
116 2. Invoke \"notmuch new\" to incorporate the new mail
117 3. Invoke one or more \"notmuch tag\" commands to classify the mail"
118 :type '(choice (const :tag "notmuch new" nil)
119 (const :tag "Disabled" "")
120 (string :tag "Custom script"))
121 :group 'notmuch-external)
125 (defvar notmuch-search-history nil
126 "Variable to store notmuch searches history.")
128 (defcustom notmuch-archive-tags '("-inbox")
129 "List of tag changes to apply to a message or a thread when it is archived.
131 Tags starting with \"+\" (or not starting with either \"+\" or
132 \"-\") in the list will be added, and tags starting with \"-\"
133 will be removed from the message or thread being archived.
135 For example, if you wanted to remove an \"inbox\" tag and add an
136 \"archived\" tag, you would set:
137 (\"-inbox\" \"+archived\")"
138 :type '(repeat string)
139 :group 'notmuch-search
140 :group 'notmuch-show)
142 (defvar notmuch-common-keymap
143 (let ((map (make-sparse-keymap)))
144 (define-key map "?" 'notmuch-help)
145 (define-key map "q" 'notmuch-bury-or-kill-this-buffer)
146 (define-key map "s" 'notmuch-search)
147 (define-key map "z" 'notmuch-tree)
148 (define-key map "m" 'notmuch-mua-new-mail)
149 (define-key map "=" 'notmuch-refresh-this-buffer)
150 (define-key map "G" 'notmuch-poll-and-refresh-this-buffer)
151 (define-key map "j" 'notmuch-jump-search)
153 "Keymap shared by all notmuch modes.")
155 ;; By default clicking on a button does not select the window
156 ;; containing the button (as opposed to clicking on a widget which
157 ;; does). This means that the button action is then executed in the
158 ;; current selected window which can cause problems if the button
159 ;; changes the buffer (e.g., id: links) or moves point.
161 ;; This provides a button type which overrides mouse-action so that
162 ;; the button's window is selected before the action is run. Other
163 ;; notmuch buttons can get the same behaviour by inheriting from this
165 (define-button-type 'notmuch-button-type
166 'mouse-action (lambda (button)
167 (select-window (posn-window (event-start last-input-event)))
168 (button-activate button)))
170 (defun notmuch-command-to-string (&rest args)
171 "Synchronously invoke \"notmuch\" with the given list of arguments.
173 If notmuch exits with a non-zero status, output from the process
174 will appear in a buffer named \"*Notmuch errors*\" and an error
177 Otherwise the output will be returned"
179 (let* ((status (apply #'call-process notmuch-command nil t nil args))
180 (output (buffer-string)))
181 (notmuch-check-exit-status status (cons notmuch-command args) output)
184 (defvar notmuch--cli-sane-p nil
185 "Cache whether the CLI seems to be configured sanely.")
187 (defun notmuch-cli-sane-p ()
188 "Return t if the cli seems to be configured sanely."
189 (unless notmuch--cli-sane-p
190 (let ((status (call-process notmuch-command nil nil nil
191 "config" "get" "user.primary_email")))
192 (setq notmuch--cli-sane-p (= status 0))))
195 (defun notmuch-assert-cli-sane ()
196 (unless (notmuch-cli-sane-p)
197 (notmuch-logged-error
198 "notmuch cli seems misconfigured or unconfigured."
199 "Perhaps you haven't run \"notmuch setup\" yet? Try running this
200 on the command line, and then retry your notmuch command")))
202 (defun notmuch-cli-version ()
203 "Return a string with the notmuch cli command version number."
205 ;; Trim off the trailing newline.
206 (substring (notmuch-command-to-string "--version") 0 -1)))
207 (if (string-match "^notmuch\\( version\\)? \\(.*\\)$"
209 (match-string 2 long-string)
212 (defun notmuch-config-get (item)
213 "Return a value from the notmuch configuration."
214 (let* ((val (notmuch-command-to-string "config" "get" item))
216 ;; Trim off the trailing newline (if the value is empty or not
217 ;; configured, there will be no newline)
218 (if (and (> len 0) (= (aref val (- len 1)) ?\n))
222 (defun notmuch-database-path ()
223 "Return the database.path value from the notmuch configuration."
224 (notmuch-config-get "database.path"))
226 (defun notmuch-user-name ()
227 "Return the user.name value from the notmuch configuration."
228 (notmuch-config-get "user.name"))
230 (defun notmuch-user-primary-email ()
231 "Return the user.primary_email value from the notmuch configuration."
232 (notmuch-config-get "user.primary_email"))
234 (defun notmuch-user-other-email ()
235 "Return the user.other_email value (as a list) from the notmuch configuration."
236 (split-string (notmuch-config-get "user.other_email") "\n" t))
238 (defun notmuch-user-emails ()
239 (cons (notmuch-user-primary-email) (notmuch-user-other-email)))
241 (defun notmuch-poll ()
242 "Run \"notmuch new\" or an external script to import mail.
244 Invokes `notmuch-poll-script', \"notmuch new\", or does nothing
245 depending on the value of `notmuch-poll-script'."
247 (if (stringp notmuch-poll-script)
248 (unless (string= notmuch-poll-script "")
249 (unless (equal (call-process notmuch-poll-script nil nil) 0)
250 (error "Notmuch: poll script `%s' failed!" notmuch-poll-script)))
251 (notmuch-call-notmuch-process "new")))
253 (defun notmuch-bury-or-kill-this-buffer ()
254 "Undisplay the current buffer.
256 Bury the current buffer, unless there is only one window showing
257 it, in which case it is killed."
259 (if (> (length (get-buffer-window-list nil nil t)) 1)
263 (defun notmuch-documentation-first-line (symbol)
264 "Return the first line of the documentation string for SYMBOL."
265 (let ((doc (documentation symbol)))
268 (insert (documentation symbol t))
269 (goto-char (point-min))
272 (buffer-substring beg (point))))
275 (defun notmuch-prefix-key-description (key)
276 "Given a prefix key code, return a human-readable string representation.
278 This is basically just `format-kbd-macro' but we also convert ESC to M-."
279 (let* ((key-vector (if (vectorp key) key (vector key)))
280 (desc (format-kbd-macro key-vector)))
281 (if (string= desc "ESC")
286 (defun notmuch-describe-key (actual-key binding prefix ua-keys tail)
287 "Prepend cons cells describing prefix-arg ACTUAL-KEY and ACTUAL-KEY to TAIL
289 It does not prepend if ACTUAL-KEY is already listed in TAIL."
290 (let ((key-string (concat prefix (format-kbd-macro actual-key))))
291 ;; We don't include documentation if the key-binding is
292 ;; over-ridden. Note, over-riding a binding automatically hides the
293 ;; prefixed version too.
294 (unless (assoc key-string tail)
295 (when (and ua-keys (symbolp binding)
296 (get binding 'notmuch-prefix-doc))
297 ;; Documentation for prefixed command
298 (let ((ua-desc (key-description ua-keys)))
299 (push (cons (concat ua-desc " " prefix (format-kbd-macro actual-key))
300 (get binding 'notmuch-prefix-doc))
302 ;; Documentation for command
303 (push (cons key-string
304 (or (and (symbolp binding) (get binding 'notmuch-doc))
305 (notmuch-documentation-first-line binding)))
309 (defun notmuch-describe-remaps (remap-keymap ua-keys base-keymap prefix tail)
310 ;; Remappings are represented as a binding whose first "event" is
311 ;; 'remap. Hence, if the keymap has any remappings, it will have a
312 ;; binding whose "key" is 'remap, and whose "binding" is itself a
313 ;; keymap that maps not from keys to commands, but from old (remapped)
314 ;; functions to the commands to use in their stead.
316 (lambda (command binding)
319 (setq tail (notmuch-describe-key actual-key binding prefix ua-keys tail)))
320 (where-is-internal command base-keymap)))
324 (defun notmuch-describe-keymap (keymap ua-keys base-keymap &optional prefix tail)
325 "Return a list of cons cells, each describing one binding in KEYMAP.
327 Each cons cell consists of a string giving a human-readable
328 description of the key, and a one-line description of the bound
329 function. See `notmuch-help' for an overview of how this
330 documentation is extracted.
332 UA-KEYS should be a key sequence bound to `universal-argument'.
333 It will be used to describe bindings of commands that support a
334 prefix argument. PREFIX and TAIL are used internally."
336 (lambda (key binding)
337 (cond ((mouse-event-p key) nil)
341 (notmuch-describe-remaps
342 binding ua-keys base-keymap prefix tail)
343 (notmuch-describe-keymap
344 binding ua-keys base-keymap (notmuch-prefix-key-description key) tail))))
346 (setq tail (notmuch-describe-key (vector key) binding prefix ua-keys tail)))))
350 (defun notmuch-substitute-command-keys (doc)
351 "Like `substitute-command-keys' but with documentation, not function names."
353 (while (string-match "\\\\{\\([^}[:space:]]*\\)}" doc beg)
356 (let* ((keymap-name (substring doc (match-beginning 1) (match-end 1)))
357 (keymap (symbol-value (intern keymap-name)))
358 (ua-keys (where-is-internal 'universal-argument keymap t))
359 (desc-alist (notmuch-describe-keymap keymap ua-keys keymap))
360 (desc-list (mapcar (lambda (arg) (concat (car arg) "\t" (cdr arg))) desc-alist)))
361 (mapconcat #'identity desc-list "\n")))))
362 (setq doc (replace-match desc 1 1 doc)))
363 (setq beg (match-end 0)))
366 (defun notmuch-help ()
367 "Display help for the current notmuch mode.
369 This is similar to `describe-function' for the current major
370 mode, but bindings tables are shown with documentation strings
371 rather than command names. By default, this uses the first line
372 of each command's documentation string. A command can override
373 this by setting the 'notmuch-doc property of its command symbol.
374 A command that supports a prefix argument can explicitly document
375 its prefixed behavior by setting the 'notmuch-prefix-doc property
376 of its command symbol."
378 (let* ((mode major-mode)
379 (doc (substitute-command-keys (notmuch-substitute-command-keys (documentation mode t)))))
380 (with-current-buffer (generate-new-buffer "*notmuch-help*")
382 (goto-char (point-min))
383 (set-buffer-modified-p nil)
384 (view-buffer (current-buffer) 'kill-buffer-if-not-modified))))
386 (defun notmuch-subkeymap-help ()
387 "Show help for a subkeymap."
389 (let* ((key (this-command-keys-vector))
390 (prefix (make-vector (1- (length key)) nil))
392 (while (< i (length prefix))
393 (aset prefix i (aref key i))
396 (let* ((subkeymap (key-binding prefix))
397 (ua-keys (where-is-internal 'universal-argument nil t))
398 (prefix-string (notmuch-prefix-key-description prefix))
399 (desc-alist (notmuch-describe-keymap subkeymap ua-keys subkeymap prefix-string))
400 (desc-list (mapcar (lambda (arg) (concat (car arg) "\t" (cdr arg))) desc-alist))
401 (desc (mapconcat #'identity desc-list "\n")))
402 (with-help-window (help-buffer)
403 (with-current-buffer standard-output
404 (insert "\nPress 'q' to quit this window.\n\n")
406 (pop-to-buffer (help-buffer)))))
408 (defvar notmuch-buffer-refresh-function nil
409 "Function to call to refresh the current buffer.")
410 (make-variable-buffer-local 'notmuch-buffer-refresh-function)
412 (defun notmuch-refresh-this-buffer ()
413 "Refresh the current buffer."
415 (when notmuch-buffer-refresh-function
416 (if (commandp notmuch-buffer-refresh-function)
417 ;; Pass prefix argument, etc.
418 (call-interactively notmuch-buffer-refresh-function)
419 (funcall notmuch-buffer-refresh-function))))
421 (defun notmuch-poll-and-refresh-this-buffer ()
422 "Invoke `notmuch-poll' to import mail, then refresh the current buffer."
425 (notmuch-refresh-this-buffer))
427 (defun notmuch-prettify-subject (subject)
428 ;; This function is used by `notmuch-search-process-filter' which
429 ;; requires that we not disrupt its' matching state.
432 (string-match "^[ \t]*$" subject))
436 (defun notmuch-sanitize (str)
437 "Sanitize control character in STR.
439 This includes newlines, tabs, and other funny characters."
440 (replace-regexp-in-string "[[:cntrl:]\x7f\u2028\u2029]+" " " str))
442 (defun notmuch-escape-boolean-term (term)
443 "Escape a boolean term for use in a query.
445 The caller is responsible for prepending the term prefix and a
446 colon. This performs minimal escaping in order to produce
447 user-friendly queries."
450 (if (or (equal term "")
451 ;; To be pessimistic, only pass through terms composed
452 ;; entirely of ASCII printing characters other than ", (,
454 (string-match "[^!#-'*-~]" term))
456 (concat "\"" (replace-regexp-in-string "\"" "\"\"" term t t) "\"")
459 (defun notmuch-id-to-query (id)
460 "Return a query that matches the message with id ID."
461 (concat "id:" (notmuch-escape-boolean-term id)))
463 (defun notmuch-hex-encode (str)
464 "Hex-encode STR (e.g., as used by batch tagging).
466 This replaces spaces, percents, and double quotes in STR with
467 %NN where NN is the hexadecimal value of the character."
468 (replace-regexp-in-string
469 "[ %\"]" (lambda (match) (format "%%%02x" (aref match 0))) str))
473 (defun notmuch-common-do-stash (text)
474 "Common function to stash text in kill ring, and display in minibuffer."
478 (message "Stashed: %s" text))
479 ;; There is nothing to stash so stash an empty string so the user
480 ;; doesn't accidentally paste something else somewhere.
482 (message "Nothing to stash!")))
486 (defun notmuch-remove-if-not (predicate list)
487 "Return a copy of LIST with all items not satisfying PREDICATE removed."
490 (when (funcall predicate (car list))
491 (push (car list) out))
492 (setq list (cdr list)))
495 (defun notmuch-plist-delete (plist property)
496 (let* ((xplist (cons nil plist))
499 (when (eq (cadr pred) property)
500 (setcdr pred (cdddr pred)))
501 (setq pred (cddr pred)))
504 (defun notmuch-split-content-type (content-type)
505 "Split content/type into 'content' and 'type'"
506 (split-string content-type "/"))
508 (defun notmuch-match-content-type (t1 t2)
509 "Return t if t1 and t2 are matching content types, taking wildcards into account"
510 (let ((st1 (notmuch-split-content-type t1))
511 (st2 (notmuch-split-content-type t2)))
512 (if (or (string= (cadr st1) "*")
513 (string= (cadr st2) "*"))
514 ;; Comparison of content types should be case insensitive.
515 (string= (downcase (car st1)) (downcase (car st2)))
516 (string= (downcase t1) (downcase t2)))))
518 (defvar notmuch-multipart/alternative-discouraged
522 ;; multipart/related usually contain a text/html part and some associated graphics.
526 (defun notmuch-multipart/alternative-determine-discouraged (msg)
527 "Return the discouraged alternatives for the specified message."
528 ;; If a function, return the result of calling it.
529 (if (functionp notmuch-multipart/alternative-discouraged)
530 (funcall notmuch-multipart/alternative-discouraged msg)
531 ;; Otherwise simply return the value of the variable, which is
532 ;; assumed to be a list of discouraged alternatives. This is the
533 ;; default behaviour.
534 notmuch-multipart/alternative-discouraged))
536 (defun notmuch-multipart/alternative-choose (msg types)
537 "Return a list of preferred types from the given list of types
538 for this message, if present."
539 ;; Based on `mm-preferred-alternative-precedence'.
540 (let ((discouraged (notmuch-multipart/alternative-determine-discouraged msg))
542 (dolist (pref (reverse discouraged))
543 (dolist (elem (copy-sequence seq))
544 (when (string-match pref elem)
545 (setq seq (nconc (delete elem seq) (list elem))))))
548 (defun notmuch-parts-filter-by-type (parts type)
549 "Given a list of message parts, return a list containing the ones matching
552 (lambda (part) (notmuch-match-content-type (plist-get part :content-type) type))
555 (defun notmuch--get-bodypart-raw (msg part process-crypto binaryp cache)
556 (let* ((plist-elem (if binaryp :content-binary :content))
557 (data (or (plist-get part plist-elem)
559 ;; Emacs internally uses a UTF-8-like multibyte string
560 ;; representation by default (regardless of the coding
561 ;; system, which only affects how it goes from outside data
562 ;; to this internal representation). This *almost* never
563 ;; matters. Annoyingly, it does matter if we use this data
564 ;; in an image descriptor, since Emacs will use its internal
565 ;; data buffer directly and this multibyte representation
566 ;; corrupts binary image formats. Since the caller is
567 ;; asking for binary data, a unibyte string is a more
568 ;; appropriate representation anyway.
570 (set-buffer-multibyte nil))
571 (let ((args `("show" "--format=raw"
572 ,(format "--part=%s" (plist-get part :id))
573 ,@(when process-crypto '("--decrypt"))
574 ,(notmuch-id-to-query (plist-get msg :id))))
575 (coding-system-for-read
576 (if binaryp 'no-conversion
577 (let ((coding-system (mm-charset-to-coding-system
578 (plist-get part :content-charset))))
580 ;; `mm-charset-to-coding-system' seems
581 ;; to return things that are not
582 ;; considered acceptable values for
583 ;; `coding-system-for-read'.
584 (if (coding-system-p coding-system)
586 ;; RFC 2047 says that the default
587 ;; charset is US-ASCII. RFC6657
588 ;; complicates this somewhat.
590 (apply #'call-process notmuch-command nil '(t nil) nil args)
592 (when (and cache data)
593 (plist-put part plist-elem data))
596 (defun notmuch-get-bodypart-binary (msg part process-crypto &optional cache)
597 "Return the unprocessed content of PART in MSG as a unibyte string.
599 This returns the \"raw\" content of the given part after content
600 transfer decoding, but with no further processing (see the
601 discussion of --format=raw in man notmuch-show). In particular,
602 this does no charset conversion.
604 If CACHE is non-nil, the content of this part will be saved in
605 MSG (if it isn't already)."
606 (notmuch--get-bodypart-raw msg part process-crypto t cache))
608 (defun notmuch-get-bodypart-text (msg part process-crypto &optional cache)
609 "Return the text content of PART in MSG.
611 This returns the content of the given part as a multibyte Lisp
612 string after performing content transfer decoding and any
613 necessary charset decoding.
615 If CACHE is non-nil, the content of this part will be saved in
616 MSG (if it isn't already)."
617 (notmuch--get-bodypart-raw msg part process-crypto nil cache))
619 ;; Workaround: The call to `mm-display-part' below triggers a bug in
620 ;; Emacs 24 if it attempts to use the shr renderer to display an HTML
621 ;; part with images in it (demonstrated in 24.1 and 24.2 on Debian and
622 ;; Fedora 17, though unreproducable in other configurations).
623 ;; `mm-shr' references the variable `gnus-inhibit-images' without
624 ;; first loading gnus-art, which defines it, resulting in a
625 ;; void-variable error. Hence, we advise `mm-shr' to ensure gnus-art
627 (if (>= emacs-major-version 24)
628 (defadvice mm-shr (before load-gnus-arts activate)
629 (require 'gnus-art nil t)
630 (ad-disable-advice 'mm-shr 'before 'load-gnus-arts)
631 (ad-activate 'mm-shr)))
633 (defun notmuch-mm-display-part-inline (msg part content-type process-crypto)
634 "Use the mm-decode/mm-view functions to display a part in the
635 current buffer, if possible."
636 (let ((display-buffer (current-buffer)))
638 ;; In case we already have :content, use it and tell mm-* that
639 ;; it's already been charset-decoded by using the fake
640 ;; `gnus-decoded' charset. Otherwise, we'll fetch the binary
641 ;; part content and let mm-* decode it.
642 (let* ((have-content (plist-member part :content))
643 (charset (if have-content 'gnus-decoded
644 (plist-get part :content-charset)))
645 (handle (mm-make-handle (current-buffer) `(,content-type (charset . ,charset)))))
646 ;; If the user wants the part inlined, insert the content and
647 ;; test whether we are able to inline it (which includes both
648 ;; capability and suitability tests).
649 (when (mm-inlined-p handle)
651 (insert (notmuch-get-bodypart-text msg part process-crypto))
652 (insert (notmuch-get-bodypart-binary msg part process-crypto)))
653 (when (mm-inlinable-p handle)
654 (set-buffer display-buffer)
655 (mm-display-part handle)
658 ;; Converts a plist of headers to an alist of headers. The input plist should
659 ;; have symbols of the form :Header as keys, and the resulting alist will have
660 ;; symbols of the form 'Header as keys.
661 (defun notmuch-headers-plist-to-alist (plist)
662 (loop for (key value . rest) on plist by #'cddr
663 collect (cons (intern (substring (symbol-name key) 1)) value)))
665 (defun notmuch-face-ensure-list-form (face)
666 "Return FACE in face list form.
668 If FACE is already a face list, it will be returned as-is. If
669 FACE is a face name or face plist, it will be returned as a
670 single element face list."
671 (if (and (listp face) (not (keywordp (car face))))
675 (defun notmuch-apply-face (object face &optional below start end)
676 "Combine FACE into the 'face text property of OBJECT between START and END.
678 This function combines FACE with any existing faces between START
679 and END in OBJECT. Attributes specified by FACE take precedence
680 over existing attributes unless BELOW is non-nil.
682 OBJECT may be a string, a buffer, or nil (which means the current
683 buffer). If object is a string, START and END are 0-based;
684 otherwise they are buffer positions (integers or markers). FACE
685 must be a face name (a symbol or string), a property list of face
686 attributes, or a list of these. If START and/or END are omitted,
687 they default to the beginning/end of OBJECT. For convenience
688 when applied to strings, this returns OBJECT."
690 ;; A face property can have three forms: a face name (a string or
691 ;; symbol), a property list, or a list of these two forms. In the
692 ;; list case, the faces will be combined, with the earlier faces
693 ;; taking precedent. Here we canonicalize everything to list form
694 ;; to make it easy to combine.
695 (let ((pos (cond (start start)
699 ((stringp object) (length object))
700 (t (1+ (buffer-size object)))))
701 (face-list (notmuch-face-ensure-list-form face)))
703 (let* ((cur (get-text-property pos 'face object))
704 (cur-list (notmuch-face-ensure-list-form cur))
705 (new (cond ((null cur-list) face)
706 (below (append cur-list face-list))
707 (t (append face-list cur-list))))
708 (next (next-single-property-change pos 'face object end)))
709 (put-text-property pos next 'face new object)
713 (defun notmuch-map-text-property (start end prop func &optional object)
714 "Transform text property PROP using FUNC.
716 Applies FUNC to each distinct value of the text property PROP
717 between START and END of OBJECT, setting PROP to the value
720 (let ((value (get-text-property start prop object))
721 (next (next-single-property-change start prop object end)))
722 (put-text-property start next prop (funcall func value) object)
725 (defun notmuch-logged-error (msg &optional extra)
726 "Log MSG and EXTRA to *Notmuch errors* and signal MSG.
728 This logs MSG and EXTRA to the *Notmuch errors* buffer and
729 signals MSG as an error. If EXTRA is non-nil, text referring the
730 user to the *Notmuch errors* buffer will be appended to the
731 signaled error. This function does not return."
733 (with-current-buffer (get-buffer-create "*Notmuch errors*")
734 (goto-char (point-max))
738 (insert "[" (current-time-string) "]\n" msg)
745 (error "%s" (concat msg (when extra
746 " (see *Notmuch errors* for more details)"))))
748 (defun notmuch-check-async-exit-status (proc msg &optional command err-file)
749 "If PROC exited abnormally, pop up an error buffer and signal an error.
751 This is a wrapper around `notmuch-check-exit-status' for
752 asynchronous process sentinels. PROC and MSG must be the
753 arguments passed to the sentinel. COMMAND and ERR-FILE, if
754 provided, are passed to `notmuch-check-exit-status'. If COMMAND
755 is not provided, it is taken from `process-command'."
757 (case (process-status proc)
758 ((exit) (process-exit-status proc))
761 (notmuch-check-exit-status exit-status (or command (process-command proc))
764 (defun notmuch-check-exit-status (exit-status command &optional output err-file)
765 "If EXIT-STATUS is non-zero, pop up an error buffer and signal an error.
767 If EXIT-STATUS is non-zero, pop up a notmuch error buffer
768 describing the error and signal an Elisp error. EXIT-STATUS must
769 be a number indicating the exit status code of a process or a
770 string describing the signal that terminated the process (such as
771 returned by `call-process'). COMMAND must be a list giving the
772 command and its arguments. OUTPUT, if provided, is a string
773 giving the output of command. ERR-FILE, if provided, is the name
774 of a file containing the error output of command. OUTPUT and the
775 contents of ERR-FILE will be included in the error message."
778 ((eq exit-status 0) t)
780 (notmuch-logged-error "notmuch CLI version mismatch
781 Emacs requested an older output format than supported by the notmuch CLI.
782 You may need to restart Emacs or upgrade your notmuch Emacs package."))
784 (notmuch-logged-error "notmuch CLI version mismatch
785 Emacs requested a newer output format than supported by the notmuch CLI.
786 You may need to restart Emacs or upgrade your notmuch package."))
788 (let* ((err (when err-file
790 (insert-file-contents err-file)
795 "command: " (mapconcat #'shell-quote-argument command " ") "\n"
796 (if (integerp exit-status)
797 (format "exit status: %s\n" exit-status)
798 (format "exit signal: %s\n" exit-status))
800 (concat "stderr:\n" err))
802 (concat "stdout:\n" output)))))
804 ;; We have an error message straight from the CLI.
805 (notmuch-logged-error
806 (replace-regexp-in-string "[ \n\r\t\f]*\\'" "" err) extra)
807 ;; We only have combined output from the CLI; don't inundate
808 ;; the user with it. Mimic `process-lines'.
809 (notmuch-logged-error (format "%s exited with status %s"
810 (car command) exit-status)
812 ;; `notmuch-logged-error' does not return.
815 (defun notmuch-call-notmuch--helper (destination args)
816 "Helper for synchronous notmuch invocation commands.
818 This wraps `call-process'. DESTINATION has the same meaning as
819 for `call-process'. ARGS is as described for
820 `notmuch-call-notmuch-process'."
823 (while (keywordp (car args))
825 (:stdin-string (setq stdin-string (cadr args)
828 (error "Unknown keyword argument: %s" (car args)))))
829 (if (null stdin-string)
830 (apply #'call-process notmuch-command nil destination nil args)
831 (insert stdin-string)
832 (apply #'call-process-region (point-min) (point-max)
833 notmuch-command t destination nil args))))
835 (defun notmuch-call-notmuch-process (&rest args)
836 "Synchronously invoke `notmuch-command' with ARGS.
838 The caller may provide keyword arguments before ARGS. Currently
839 supported keyword arguments are:
841 :stdin-string STRING - Write STRING to stdin
843 If notmuch exits with a non-zero status, output from the process
844 will appear in a buffer named \"*Notmuch errors*\" and an error
847 (let ((status (notmuch-call-notmuch--helper t args)))
848 (notmuch-check-exit-status status (cons notmuch-command args)
851 (defun notmuch-call-notmuch-sexp (&rest args)
852 "Invoke `notmuch-command' with ARGS and return the parsed S-exp output.
854 This is equivalent to `notmuch-call-notmuch-process', but parses
855 notmuch's output as an S-expression and returns the parsed value.
856 Like `notmuch-call-notmuch-process', if notmuch exits with a
857 non-zero status, this will report its output and signal an
861 (let ((err-file (make-temp-file "nmerr")))
863 (let ((status (notmuch-call-notmuch--helper (list t err-file) args)))
864 (notmuch-check-exit-status status (cons notmuch-command args)
865 (buffer-string) err-file)
866 (goto-char (point-min))
867 (read (current-buffer)))
868 (delete-file err-file)))))
870 (defun notmuch-start-notmuch (name buffer sentinel &rest args)
871 "Start and return an asynchronous notmuch command.
873 This starts and returns an asynchronous process running
874 `notmuch-command' with ARGS. The exit status is checked via
875 `notmuch-check-async-exit-status'. Output written to stderr is
876 redirected and displayed when the process exits (even if the
877 process exits successfully). NAME and BUFFER are the same as in
878 `start-process'. SENTINEL is a process sentinel function to call
879 when the process exits, or nil for none. The caller must *not*
880 invoke `set-process-sentinel' directly on the returned process,
881 as that will interfere with the handling of stderr and the exit
884 ;; There is no way (as of Emacs 24.3) to capture stdout and stderr
885 ;; separately for asynchronous processes, or even to redirect stderr
886 ;; to a file, so we use a trivial shell wrapper to send stderr to a
887 ;; temporary file and clean things up in the sentinel.
888 (let* ((err-file (make-temp-file "nmerr"))
890 (process-connection-type nil)
891 ;; Find notmuch using Emacs' `exec-path'
892 (command (or (executable-find notmuch-command)
893 (error "command not found: %s" notmuch-command)))
894 (proc (apply #'start-process name buffer
896 "exec 2>\"$1\"; shift; exec \"$0\" \"$@\""
897 command err-file args)))
898 (process-put proc 'err-file err-file)
899 (process-put proc 'sub-sentinel sentinel)
900 (process-put proc 'real-command (cons notmuch-command args))
901 (set-process-sentinel proc #'notmuch-start-notmuch-sentinel)
904 (defun notmuch-start-notmuch-sentinel (proc event)
905 (let ((err-file (process-get proc 'err-file))
906 (sub-sentinel (process-get proc 'sub-sentinel))
907 (real-command (process-get proc 'real-command)))
910 ;; Invoke the sub-sentinel, if any
912 (funcall sub-sentinel proc event))
913 ;; Check the exit status. This will signal an error if the
914 ;; exit status is non-zero. Don't do this if the process
915 ;; buffer is dead since that means Emacs killed the process
916 ;; and there's no point in telling the user that (but we
917 ;; still check for and report stderr output below).
918 (when (buffer-live-p (process-buffer proc))
919 (notmuch-check-async-exit-status proc event real-command err-file))
920 ;; If that didn't signal an error, then any error output was
921 ;; really warning output. Show warnings, if any.
924 (unless (= (second (insert-file-contents err-file)) 0)
926 ;; Show first line; stuff remaining lines in the
928 (let ((l1 (buffer-substring (point-min) (point))))
929 (skip-chars-forward "\n")
930 (cons l1 (unless (eobp)
931 (buffer-substring (point) (point-max)))))))))
933 (notmuch-logged-error (car warnings) (cdr warnings)))))
935 ;; Emacs behaves strangely if an error escapes from a sentinel,
936 ;; so turn errors into messages.
937 (message "%s" (error-message-string err))))
938 (ignore-errors (delete-file err-file))))
940 ;; This variable is used only buffer local, but it needs to be
941 ;; declared globally first to avoid compiler warnings.
942 (defvar notmuch-show-process-crypto nil)
943 (make-variable-buffer-local 'notmuch-show-process-crypto)
945 (provide 'notmuch-lib)
948 ;; byte-compile-warnings: (not cl-functions)
951 ;;; notmuch-lib.el ends here