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 <http://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.
30 (unless (require 'notmuch-version nil t)
31 (defconst notmuch-emacs-version "unknown"
32 "Placeholder variable when notmuch-version.el[c] is not available."))
34 (autoload 'notmuch-jump-search "notmuch-jump"
35 "Jump to a saved search by shortcut key." t)
38 "Notmuch mail reader for Emacs."
41 (defgroup notmuch-hello nil
42 "Overview of saved searches, tags, etc."
45 (defgroup notmuch-search nil
46 "Searching and sorting mail."
49 (defgroup notmuch-show nil
50 "Showing messages and threads."
53 (defgroup notmuch-send nil
54 "Sending messages from Notmuch."
57 (custom-add-to-group 'notmuch-send 'message 'custom-group)
59 (defgroup notmuch-crypto nil
60 "Processing and display of cryptographic MIME parts."
63 (defgroup notmuch-hooks nil
64 "Running custom code on well-defined occasions."
67 (defgroup notmuch-external nil
68 "Running external commands from within Notmuch."
71 (defgroup notmuch-faces nil
72 "Graphical attributes for displaying text"
75 (defcustom notmuch-command "notmuch"
76 "Name of the notmuch binary.
78 This can be a relative or absolute path to the notmuch binary.
79 If this is a relative path, it will be searched for in all of the
80 directories given in `exec-path' (which is, by default, based on
83 :group 'notmuch-external)
85 (defcustom notmuch-search-oldest-first t
86 "Show the oldest mail first when searching.
88 This variable defines the default sort order for displaying
89 search results. Note that any filtered searches created by
90 `notmuch-search-filter' retain the search order of the parent
93 :group 'notmuch-search)
95 (defcustom notmuch-poll-script nil
96 "[Deprecated] Command to run to incorporate new mail into the notmuch database.
98 This option has been deprecated in favor of \"notmuch new\"
99 hooks (see man notmuch-hooks). To change the path to the notmuch
100 binary, customize `notmuch-command'.
102 This variable controls the action invoked by
103 `notmuch-poll-and-refresh-this-buffer' (bound by default to 'G')
104 to incorporate new mail into the notmuch database.
106 If set to nil (the default), new mail is processed by invoking
107 \"notmuch new\". Otherwise, this should be set to a string that
108 gives the name of an external script that processes new mail. If
109 set to the empty string, no command will be run.
111 The external script could do any of the following depending on
114 1. Invoke a program to transfer mail to the local mail store
115 2. Invoke \"notmuch new\" to incorporate the new mail
116 3. Invoke one or more \"notmuch tag\" commands to classify the mail"
117 :type '(choice (const :tag "notmuch new" nil)
118 (const :tag "Disabled" "")
119 (string :tag "Custom script"))
120 :group 'notmuch-external)
124 (defvar notmuch-search-history nil
125 "Variable to store notmuch searches history.")
127 (defcustom notmuch-archive-tags '("-inbox")
128 "List of tag changes to apply to a message or a thread when it is archived.
130 Tags starting with \"+\" (or not starting with either \"+\" or
131 \"-\") in the list will be added, and tags starting with \"-\"
132 will be removed from the message or thread being archived.
134 For example, if you wanted to remove an \"inbox\" tag and add an
135 \"archived\" tag, you would set:
136 (\"-inbox\" \"+archived\")"
137 :type '(repeat string)
138 :group 'notmuch-search
139 :group 'notmuch-show)
141 (defvar notmuch-common-keymap
142 (let ((map (make-sparse-keymap)))
143 (define-key map "?" 'notmuch-help)
144 (define-key map "q" 'notmuch-bury-or-kill-this-buffer)
145 (define-key map "s" 'notmuch-search)
146 (define-key map "z" 'notmuch-tree)
147 (define-key map "m" 'notmuch-mua-new-mail)
148 (define-key map "=" 'notmuch-refresh-this-buffer)
149 (define-key map "G" 'notmuch-poll-and-refresh-this-buffer)
150 (define-key map "j" 'notmuch-jump-search)
152 "Keymap shared by all notmuch modes.")
154 ;; By default clicking on a button does not select the window
155 ;; containing the button (as opposed to clicking on a widget which
156 ;; does). This means that the button action is then executed in the
157 ;; current selected window which can cause problems if the button
158 ;; changes the buffer (e.g., id: links) or moves point.
160 ;; This provides a button type which overrides mouse-action so that
161 ;; the button's window is selected before the action is run. Other
162 ;; notmuch buttons can get the same behaviour by inheriting from this
164 (define-button-type 'notmuch-button-type
165 'mouse-action (lambda (button)
166 (select-window (posn-window (event-start last-input-event)))
167 (button-activate button)))
169 (defun notmuch-command-to-string (&rest args)
170 "Synchronously invoke \"notmuch\" with the given list of arguments.
172 If notmuch exits with a non-zero status, output from the process
173 will appear in a buffer named \"*Notmuch errors*\" and an error
176 Otherwise the output will be returned"
178 (let* ((status (apply #'call-process notmuch-command nil t nil args))
179 (output (buffer-string)))
180 (notmuch-check-exit-status status (cons notmuch-command args) output)
183 (defvar notmuch--cli-sane-p nil
184 "Cache whether the CLI seems to be configured sanely.")
186 (defun notmuch-cli-sane-p ()
187 "Return t if the cli seems to be configured sanely."
188 (unless notmuch--cli-sane-p
189 (let ((status (call-process notmuch-command nil nil nil
190 "config" "get" "user.primary_email")))
191 (setq notmuch--cli-sane-p (= status 0))))
194 (defun notmuch-assert-cli-sane ()
195 (unless (notmuch-cli-sane-p)
196 (notmuch-logged-error
197 "notmuch cli seems misconfigured or unconfigured."
198 "Perhaps you haven't run \"notmuch setup\" yet? Try running this
199 on the command line, and then retry your notmuch command")))
201 (defun notmuch-cli-version ()
202 "Return a string with the notmuch cli command version number."
204 ;; Trim off the trailing newline.
205 (substring (notmuch-command-to-string "--version") 0 -1)))
206 (if (string-match "^notmuch\\( version\\)? \\(.*\\)$"
208 (match-string 2 long-string)
211 (defun notmuch-config-get (item)
212 "Return a value from the notmuch configuration."
213 (let* ((val (notmuch-command-to-string "config" "get" item))
215 ;; Trim off the trailing newline (if the value is empty or not
216 ;; configured, there will be no newline)
217 (if (and (> len 0) (= (aref val (- len 1)) ?\n))
221 (defun notmuch-database-path ()
222 "Return the database.path value from the notmuch configuration."
223 (notmuch-config-get "database.path"))
225 (defun notmuch-user-name ()
226 "Return the user.name value from the notmuch configuration."
227 (notmuch-config-get "user.name"))
229 (defun notmuch-user-primary-email ()
230 "Return the user.primary_email value from the notmuch configuration."
231 (notmuch-config-get "user.primary_email"))
233 (defun notmuch-user-other-email ()
234 "Return the user.other_email value (as a list) from the notmuch configuration."
235 (split-string (notmuch-config-get "user.other_email") "\n" t))
237 (defun notmuch-user-emails ()
238 (cons (notmuch-user-primary-email) (notmuch-user-other-email)))
240 (defun notmuch-poll ()
241 "Run \"notmuch new\" or an external script to import mail.
243 Invokes `notmuch-poll-script', \"notmuch new\", or does nothing
244 depending on the value of `notmuch-poll-script'."
246 (if (stringp notmuch-poll-script)
247 (unless (string= notmuch-poll-script "")
248 (unless (equal (call-process notmuch-poll-script nil nil) 0)
249 (error "Notmuch: poll script `%s' failed!" notmuch-poll-script)))
250 (notmuch-call-notmuch-process "new")))
252 (defun notmuch-bury-or-kill-this-buffer ()
253 "Undisplay the current buffer.
255 Bury the current buffer, unless there is only one window showing
256 it, in which case it is killed."
258 (if (> (length (get-buffer-window-list nil nil t)) 1)
262 (defun notmuch-documentation-first-line (symbol)
263 "Return the first line of the documentation string for SYMBOL."
264 (let ((doc (documentation symbol)))
267 (insert (documentation symbol t))
268 (goto-char (point-min))
271 (buffer-substring beg (point))))
274 (defun notmuch-prefix-key-description (key)
275 "Given a prefix key code, return a human-readable string representation.
277 This is basically just `format-kbd-macro' but we also convert ESC to M-."
278 (let* ((key-vector (if (vectorp key) key (vector key)))
279 (desc (format-kbd-macro key-vector)))
280 (if (string= desc "ESC")
285 (defun notmuch-describe-key (actual-key binding prefix ua-keys tail)
286 "Prepend cons cells describing prefix-arg ACTUAL-KEY and ACTUAL-KEY to TAIL
288 It does not prepend if ACTUAL-KEY is already listed in TAIL."
289 (let ((key-string (concat prefix (format-kbd-macro actual-key))))
290 ;; We don't include documentation if the key-binding is
291 ;; over-ridden. Note, over-riding a binding automatically hides the
292 ;; prefixed version too.
293 (unless (assoc key-string tail)
294 (when (and ua-keys (symbolp binding)
295 (get binding 'notmuch-prefix-doc))
296 ;; Documentation for prefixed command
297 (let ((ua-desc (key-description ua-keys)))
298 (push (cons (concat ua-desc " " prefix (format-kbd-macro actual-key))
299 (get binding 'notmuch-prefix-doc))
301 ;; Documentation for command
302 (push (cons key-string
303 (or (and (symbolp binding) (get binding 'notmuch-doc))
304 (notmuch-documentation-first-line binding)))
308 (defun notmuch-describe-remaps (remap-keymap ua-keys base-keymap prefix tail)
309 ;; Remappings are represented as a binding whose first "event" is
310 ;; 'remap. Hence, if the keymap has any remappings, it will have a
311 ;; binding whose "key" is 'remap, and whose "binding" is itself a
312 ;; keymap that maps not from keys to commands, but from old (remapped)
313 ;; functions to the commands to use in their stead.
315 (lambda (command binding)
318 (setq tail (notmuch-describe-key actual-key binding prefix ua-keys tail)))
319 (where-is-internal command base-keymap)))
323 (defun notmuch-describe-keymap (keymap ua-keys base-keymap &optional prefix tail)
324 "Return a list of cons cells, each describing one binding in KEYMAP.
326 Each cons cell consists of a string giving a human-readable
327 description of the key, and a one-line description of the bound
328 function. See `notmuch-help' for an overview of how this
329 documentation is extracted.
331 UA-KEYS should be a key sequence bound to `universal-argument'.
332 It will be used to describe bindings of commands that support a
333 prefix argument. PREFIX and TAIL are used internally."
335 (lambda (key binding)
336 (cond ((mouse-event-p key) nil)
340 (notmuch-describe-remaps
341 binding ua-keys base-keymap prefix tail)
342 (notmuch-describe-keymap
343 binding ua-keys base-keymap (notmuch-prefix-key-description key) tail))))
345 (setq tail (notmuch-describe-key (vector key) binding prefix ua-keys tail)))))
349 (defun notmuch-substitute-command-keys (doc)
350 "Like `substitute-command-keys' but with documentation, not function names."
352 (while (string-match "\\\\{\\([^}[:space:]]*\\)}" doc beg)
355 (let* ((keymap-name (substring doc (match-beginning 1) (match-end 1)))
356 (keymap (symbol-value (intern keymap-name)))
357 (ua-keys (where-is-internal 'universal-argument keymap t))
358 (desc-alist (notmuch-describe-keymap keymap ua-keys keymap))
359 (desc-list (mapcar (lambda (arg) (concat (car arg) "\t" (cdr arg))) desc-alist)))
360 (mapconcat #'identity desc-list "\n")))))
361 (setq doc (replace-match desc 1 1 doc)))
362 (setq beg (match-end 0)))
365 (defun notmuch-help ()
366 "Display help for the current notmuch mode.
368 This is similar to `describe-function' for the current major
369 mode, but bindings tables are shown with documentation strings
370 rather than command names. By default, this uses the first line
371 of each command's documentation string. A command can override
372 this by setting the 'notmuch-doc property of its command symbol.
373 A command that supports a prefix argument can explicitly document
374 its prefixed behavior by setting the 'notmuch-prefix-doc property
375 of its command symbol."
377 (let* ((mode major-mode)
378 (doc (substitute-command-keys (notmuch-substitute-command-keys (documentation mode t)))))
379 (with-current-buffer (generate-new-buffer "*notmuch-help*")
381 (goto-char (point-min))
382 (set-buffer-modified-p nil)
383 (view-buffer (current-buffer) 'kill-buffer-if-not-modified))))
385 (defun notmuch-subkeymap-help ()
386 "Show help for a subkeymap."
388 (let* ((key (this-command-keys-vector))
389 (prefix (make-vector (1- (length key)) nil))
391 (while (< i (length prefix))
392 (aset prefix i (aref key i))
395 (let* ((subkeymap (key-binding prefix))
396 (ua-keys (where-is-internal 'universal-argument nil t))
397 (prefix-string (notmuch-prefix-key-description prefix))
398 (desc-alist (notmuch-describe-keymap subkeymap ua-keys subkeymap prefix-string))
399 (desc-list (mapcar (lambda (arg) (concat (car arg) "\t" (cdr arg))) desc-alist))
400 (desc (mapconcat #'identity desc-list "\n")))
401 (with-help-window (help-buffer)
402 (with-current-buffer standard-output
403 (insert "\nPress 'q' to quit this window.\n\n")
405 (pop-to-buffer (help-buffer)))))
407 (defvar notmuch-buffer-refresh-function nil
408 "Function to call to refresh the current buffer.")
409 (make-variable-buffer-local 'notmuch-buffer-refresh-function)
411 (defun notmuch-refresh-this-buffer ()
412 "Refresh the current buffer."
414 (when notmuch-buffer-refresh-function
415 (if (commandp notmuch-buffer-refresh-function)
416 ;; Pass prefix argument, etc.
417 (call-interactively notmuch-buffer-refresh-function)
418 (funcall notmuch-buffer-refresh-function))))
420 (defun notmuch-poll-and-refresh-this-buffer ()
421 "Invoke `notmuch-poll' to import mail, then refresh the current buffer."
424 (notmuch-refresh-this-buffer))
426 (defun notmuch-prettify-subject (subject)
427 ;; This function is used by `notmuch-search-process-filter' which
428 ;; requires that we not disrupt its' matching state.
431 (string-match "^[ \t]*$" subject))
435 (defun notmuch-sanitize (str)
436 "Sanitize control character in STR.
438 This includes newlines, tabs, and other funny characters."
439 (replace-regexp-in-string "[[:cntrl:]\x7f\u2028\u2029]+" " " str))
441 (defun notmuch-escape-boolean-term (term)
442 "Escape a boolean term for use in a query.
444 The caller is responsible for prepending the term prefix and a
445 colon. This performs minimal escaping in order to produce
446 user-friendly queries."
449 (if (or (equal term "")
450 ;; To be pessimistic, only pass through terms composed
451 ;; entirely of ASCII printing characters other than ", (,
453 (string-match "[^!#-'*-~]" term))
455 (concat "\"" (replace-regexp-in-string "\"" "\"\"" term t t) "\"")
458 (defun notmuch-id-to-query (id)
459 "Return a query that matches the message with id ID."
460 (concat "id:" (notmuch-escape-boolean-term id)))
462 (defun notmuch-hex-encode (str)
463 "Hex-encode STR (e.g., as used by batch tagging).
465 This replaces spaces, percents, and double quotes in STR with
466 %NN where NN is the hexadecimal value of the character."
467 (replace-regexp-in-string
468 "[ %\"]" (lambda (match) (format "%%%02x" (aref match 0))) str))
472 (defun notmuch-common-do-stash (text)
473 "Common function to stash text in kill ring, and display in minibuffer."
477 (message "Stashed: %s" text))
478 ;; There is nothing to stash so stash an empty string so the user
479 ;; doesn't accidentally paste something else somewhere.
481 (message "Nothing to stash!")))
485 (defun notmuch-remove-if-not (predicate list)
486 "Return a copy of LIST with all items not satisfying PREDICATE removed."
489 (when (funcall predicate (car list))
490 (push (car list) out))
491 (setq list (cdr list)))
494 (defun notmuch-plist-delete (plist property)
495 (let* ((xplist (cons nil plist))
498 (when (eq (cadr pred) property)
499 (setcdr pred (cdddr pred)))
500 (setq pred (cddr pred)))
503 (defun notmuch-split-content-type (content-type)
504 "Split content/type into 'content' and 'type'"
505 (split-string content-type "/"))
507 (defun notmuch-match-content-type (t1 t2)
508 "Return t if t1 and t2 are matching content types, taking wildcards into account"
509 (let ((st1 (notmuch-split-content-type t1))
510 (st2 (notmuch-split-content-type t2)))
511 (if (or (string= (cadr st1) "*")
512 (string= (cadr st2) "*"))
513 ;; Comparison of content types should be case insensitive.
514 (string= (downcase (car st1)) (downcase (car st2)))
515 (string= (downcase t1) (downcase t2)))))
517 (defvar notmuch-multipart/alternative-discouraged
521 ;; multipart/related usually contain a text/html part and some associated graphics.
525 (defun notmuch-multipart/alternative-determine-discouraged (msg)
526 "Return the discouraged alternatives for the specified message."
527 ;; If a function, return the result of calling it.
528 (if (functionp notmuch-multipart/alternative-discouraged)
529 (funcall notmuch-multipart/alternative-discouraged msg)
530 ;; Otherwise simply return the value of the variable, which is
531 ;; assumed to be a list of discouraged alternatives. This is the
532 ;; default behaviour.
533 notmuch-multipart/alternative-discouraged))
535 (defun notmuch-multipart/alternative-choose (msg types)
536 "Return a list of preferred types from the given list of types
537 for this message, if present."
538 ;; Based on `mm-preferred-alternative-precedence'.
539 (let ((discouraged (notmuch-multipart/alternative-determine-discouraged msg))
541 (dolist (pref (reverse discouraged))
542 (dolist (elem (copy-sequence seq))
543 (when (string-match pref elem)
544 (setq seq (nconc (delete elem seq) (list elem))))))
547 (defun notmuch-parts-filter-by-type (parts type)
548 "Given a list of message parts, return a list containing the ones matching
551 (lambda (part) (notmuch-match-content-type (plist-get part :content-type) type))
554 (defun notmuch--get-bodypart-raw (msg part process-crypto binaryp cache)
555 (let* ((plist-elem (if binaryp :content-binary :content))
556 (data (or (plist-get part plist-elem)
558 ;; Emacs internally uses a UTF-8-like multibyte string
559 ;; representation by default (regardless of the coding
560 ;; system, which only affects how it goes from outside data
561 ;; to this internal representation). This *almost* never
562 ;; matters. Annoyingly, it does matter if we use this data
563 ;; in an image descriptor, since Emacs will use its internal
564 ;; data buffer directly and this multibyte representation
565 ;; corrupts binary image formats. Since the caller is
566 ;; asking for binary data, a unibyte string is a more
567 ;; appropriate representation anyway.
569 (set-buffer-multibyte nil))
570 (let ((args `("show" "--format=raw"
571 ,(format "--part=%s" (plist-get part :id))
572 ,@(when process-crypto '("--decrypt"))
573 ,(notmuch-id-to-query (plist-get msg :id))))
574 (coding-system-for-read
575 (if binaryp 'no-conversion 'utf-8)))
576 (apply #'call-process notmuch-command nil '(t nil) nil args)
578 (when (and cache data)
579 (plist-put part plist-elem data))
582 (defun notmuch-get-bodypart-binary (msg part process-crypto &optional cache)
583 "Return the unprocessed content of PART in MSG as a unibyte string.
585 This returns the \"raw\" content of the given part after content
586 transfer decoding, but with no further processing (see the
587 discussion of --format=raw in man notmuch-show). In particular,
588 this does no charset conversion.
590 If CACHE is non-nil, the content of this part will be saved in
591 MSG (if it isn't already)."
592 (notmuch--get-bodypart-raw msg part process-crypto t cache))
594 (defun notmuch-get-bodypart-text (msg part process-crypto &optional cache)
595 "Return the text content of PART in MSG.
597 This returns the content of the given part as a multibyte Lisp
598 string after performing content transfer decoding and any
599 necessary charset decoding.
601 If CACHE is non-nil, the content of this part will be saved in
602 MSG (if it isn't already)."
603 (notmuch--get-bodypart-raw msg part process-crypto nil cache))
605 ;; Workaround: The call to `mm-display-part' below triggers a bug in
606 ;; Emacs 24 if it attempts to use the shr renderer to display an HTML
607 ;; part with images in it (demonstrated in 24.1 and 24.2 on Debian and
608 ;; Fedora 17, though unreproducable in other configurations).
609 ;; `mm-shr' references the variable `gnus-inhibit-images' without
610 ;; first loading gnus-art, which defines it, resulting in a
611 ;; void-variable error. Hence, we advise `mm-shr' to ensure gnus-art
613 (if (>= emacs-major-version 24)
614 (defadvice mm-shr (before load-gnus-arts activate)
615 (require 'gnus-art nil t)
616 (ad-disable-advice 'mm-shr 'before 'load-gnus-arts)
617 (ad-activate 'mm-shr)))
619 (defun notmuch-mm-display-part-inline (msg part content-type process-crypto)
620 "Use the mm-decode/mm-view functions to display a part in the
621 current buffer, if possible."
622 (let ((display-buffer (current-buffer)))
624 ;; In case we already have :content, use it and tell mm-* that
625 ;; it's already been charset-decoded by using the fake
626 ;; `gnus-decoded' charset. Otherwise, we'll fetch the binary
627 ;; part content and let mm-* decode it.
628 (let* ((have-content (plist-member part :content))
629 (charset (if have-content 'gnus-decoded
630 (plist-get part :content-charset)))
631 (handle (mm-make-handle (current-buffer) `(,content-type (charset . ,charset)))))
632 ;; If the user wants the part inlined, insert the content and
633 ;; test whether we are able to inline it (which includes both
634 ;; capability and suitability tests).
635 (when (mm-inlined-p handle)
637 (insert (notmuch-get-bodypart-text msg part process-crypto))
638 (insert (notmuch-get-bodypart-binary msg part process-crypto)))
639 (when (mm-inlinable-p handle)
640 (set-buffer display-buffer)
641 (mm-display-part handle)
644 ;; Converts a plist of headers to an alist of headers. The input plist should
645 ;; have symbols of the form :Header as keys, and the resulting alist will have
646 ;; symbols of the form 'Header as keys.
647 (defun notmuch-headers-plist-to-alist (plist)
648 (loop for (key value . rest) on plist by #'cddr
649 collect (cons (intern (substring (symbol-name key) 1)) value)))
651 (defun notmuch-face-ensure-list-form (face)
652 "Return FACE in face list form.
654 If FACE is already a face list, it will be returned as-is. If
655 FACE is a face name or face plist, it will be returned as a
656 single element face list."
657 (if (and (listp face) (not (keywordp (car face))))
661 (defun notmuch-apply-face (object face &optional below start end)
662 "Combine FACE into the 'face text property of OBJECT between START and END.
664 This function combines FACE with any existing faces between START
665 and END in OBJECT. Attributes specified by FACE take precedence
666 over existing attributes unless BELOW is non-nil.
668 OBJECT may be a string, a buffer, or nil (which means the current
669 buffer). If object is a string, START and END are 0-based;
670 otherwise they are buffer positions (integers or markers). FACE
671 must be a face name (a symbol or string), a property list of face
672 attributes, or a list of these. If START and/or END are omitted,
673 they default to the beginning/end of OBJECT. For convenience
674 when applied to strings, this returns OBJECT."
676 ;; A face property can have three forms: a face name (a string or
677 ;; symbol), a property list, or a list of these two forms. In the
678 ;; list case, the faces will be combined, with the earlier faces
679 ;; taking precedent. Here we canonicalize everything to list form
680 ;; to make it easy to combine.
681 (let ((pos (cond (start start)
685 ((stringp object) (length object))
686 (t (1+ (buffer-size object)))))
687 (face-list (notmuch-face-ensure-list-form face)))
689 (let* ((cur (get-text-property pos 'face object))
690 (cur-list (notmuch-face-ensure-list-form cur))
691 (new (cond ((null cur-list) face)
692 (below (append cur-list face-list))
693 (t (append face-list cur-list))))
694 (next (next-single-property-change pos 'face object end)))
695 (put-text-property pos next 'face new object)
699 (defun notmuch-map-text-property (start end prop func &optional object)
700 "Transform text property PROP using FUNC.
702 Applies FUNC to each distinct value of the text property PROP
703 between START and END of OBJECT, setting PROP to the value
706 (let ((value (get-text-property start prop object))
707 (next (next-single-property-change start prop object end)))
708 (put-text-property start next prop (funcall func value) object)
711 (defun notmuch-logged-error (msg &optional extra)
712 "Log MSG and EXTRA to *Notmuch errors* and signal MSG.
714 This logs MSG and EXTRA to the *Notmuch errors* buffer and
715 signals MSG as an error. If EXTRA is non-nil, text referring the
716 user to the *Notmuch errors* buffer will be appended to the
717 signaled error. This function does not return."
719 (with-current-buffer (get-buffer-create "*Notmuch errors*")
720 (goto-char (point-max))
724 (insert "[" (current-time-string) "]\n" msg)
731 (error "%s" (concat msg (when extra
732 " (see *Notmuch errors* for more details)"))))
734 (defun notmuch-check-async-exit-status (proc msg &optional command err-file)
735 "If PROC exited abnormally, pop up an error buffer and signal an error.
737 This is a wrapper around `notmuch-check-exit-status' for
738 asynchronous process sentinels. PROC and MSG must be the
739 arguments passed to the sentinel. COMMAND and ERR-FILE, if
740 provided, are passed to `notmuch-check-exit-status'. If COMMAND
741 is not provided, it is taken from `process-command'."
743 (case (process-status proc)
744 ((exit) (process-exit-status proc))
747 (notmuch-check-exit-status exit-status (or command (process-command proc))
750 (defun notmuch-check-exit-status (exit-status command &optional output err-file)
751 "If EXIT-STATUS is non-zero, pop up an error buffer and signal an error.
753 If EXIT-STATUS is non-zero, pop up a notmuch error buffer
754 describing the error and signal an Elisp error. EXIT-STATUS must
755 be a number indicating the exit status code of a process or a
756 string describing the signal that terminated the process (such as
757 returned by `call-process'). COMMAND must be a list giving the
758 command and its arguments. OUTPUT, if provided, is a string
759 giving the output of command. ERR-FILE, if provided, is the name
760 of a file containing the error output of command. OUTPUT and the
761 contents of ERR-FILE will be included in the error message."
764 ((eq exit-status 0) t)
766 (notmuch-logged-error "notmuch CLI version mismatch
767 Emacs requested an older output format than supported by the notmuch CLI.
768 You may need to restart Emacs or upgrade your notmuch Emacs package."))
770 (notmuch-logged-error "notmuch CLI version mismatch
771 Emacs requested a newer output format than supported by the notmuch CLI.
772 You may need to restart Emacs or upgrade your notmuch package."))
774 (let* ((err (when err-file
776 (insert-file-contents err-file)
781 "command: " (mapconcat #'shell-quote-argument command " ") "\n"
782 (if (integerp exit-status)
783 (format "exit status: %s\n" exit-status)
784 (format "exit signal: %s\n" exit-status))
786 (concat "stderr:\n" err))
788 (concat "stdout:\n" output)))))
790 ;; We have an error message straight from the CLI.
791 (notmuch-logged-error
792 (replace-regexp-in-string "[ \n\r\t\f]*\\'" "" err) extra)
793 ;; We only have combined output from the CLI; don't inundate
794 ;; the user with it. Mimic `process-lines'.
795 (notmuch-logged-error (format "%s exited with status %s"
796 (car command) exit-status)
798 ;; `notmuch-logged-error' does not return.
801 (defun notmuch-call-notmuch--helper (destination args)
802 "Helper for synchronous notmuch invocation commands.
804 This wraps `call-process'. DESTINATION has the same meaning as
805 for `call-process'. ARGS is as described for
806 `notmuch-call-notmuch-process'."
809 (while (keywordp (car args))
811 (:stdin-string (setq stdin-string (cadr args)
814 (error "Unknown keyword argument: %s" (car args)))))
815 (if (null stdin-string)
816 (apply #'call-process notmuch-command nil destination nil args)
817 (insert stdin-string)
818 (apply #'call-process-region (point-min) (point-max)
819 notmuch-command t destination nil args))))
821 (defun notmuch-call-notmuch-process (&rest args)
822 "Synchronously invoke `notmuch-command' with ARGS.
824 The caller may provide keyword arguments before ARGS. Currently
825 supported keyword arguments are:
827 :stdin-string STRING - Write STRING to stdin
829 If notmuch exits with a non-zero status, output from the process
830 will appear in a buffer named \"*Notmuch errors*\" and an error
833 (let ((status (notmuch-call-notmuch--helper t args)))
834 (notmuch-check-exit-status status (cons notmuch-command args)
837 (defun notmuch-call-notmuch-sexp (&rest args)
838 "Invoke `notmuch-command' with ARGS and return the parsed S-exp output.
840 This is equivalent to `notmuch-call-notmuch-process', but parses
841 notmuch's output as an S-expression and returns the parsed value.
842 Like `notmuch-call-notmuch-process', if notmuch exits with a
843 non-zero status, this will report its output and signal an
847 (let ((err-file (make-temp-file "nmerr")))
849 (let ((status (notmuch-call-notmuch--helper (list t err-file) args)))
850 (notmuch-check-exit-status status (cons notmuch-command args)
851 (buffer-string) err-file)
852 (goto-char (point-min))
853 (read (current-buffer)))
854 (delete-file err-file)))))
856 (defun notmuch-start-notmuch (name buffer sentinel &rest args)
857 "Start and return an asynchronous notmuch command.
859 This starts and returns an asynchronous process running
860 `notmuch-command' with ARGS. The exit status is checked via
861 `notmuch-check-async-exit-status'. Output written to stderr is
862 redirected and displayed when the process exits (even if the
863 process exits successfully). NAME and BUFFER are the same as in
864 `start-process'. SENTINEL is a process sentinel function to call
865 when the process exits, or nil for none. The caller must *not*
866 invoke `set-process-sentinel' directly on the returned process,
867 as that will interfere with the handling of stderr and the exit
870 ;; There is no way (as of Emacs 24.3) to capture stdout and stderr
871 ;; separately for asynchronous processes, or even to redirect stderr
872 ;; to a file, so we use a trivial shell wrapper to send stderr to a
873 ;; temporary file and clean things up in the sentinel.
874 (let* ((err-file (make-temp-file "nmerr"))
876 (process-connection-type nil)
877 ;; Find notmuch using Emacs' `exec-path'
878 (command (or (executable-find notmuch-command)
879 (error "command not found: %s" notmuch-command)))
880 (proc (apply #'start-process name buffer
882 "exec 2>\"$1\"; shift; exec \"$0\" \"$@\""
883 command err-file args)))
884 (process-put proc 'err-file err-file)
885 (process-put proc 'sub-sentinel sentinel)
886 (process-put proc 'real-command (cons notmuch-command args))
887 (set-process-sentinel proc #'notmuch-start-notmuch-sentinel)
890 (defun notmuch-start-notmuch-sentinel (proc event)
891 (let ((err-file (process-get proc 'err-file))
892 (sub-sentinel (process-get proc 'sub-sentinel))
893 (real-command (process-get proc 'real-command)))
896 ;; Invoke the sub-sentinel, if any
898 (funcall sub-sentinel proc event))
899 ;; Check the exit status. This will signal an error if the
900 ;; exit status is non-zero. Don't do this if the process
901 ;; buffer is dead since that means Emacs killed the process
902 ;; and there's no point in telling the user that (but we
903 ;; still check for and report stderr output below).
904 (when (buffer-live-p (process-buffer proc))
905 (notmuch-check-async-exit-status proc event real-command err-file))
906 ;; If that didn't signal an error, then any error output was
907 ;; really warning output. Show warnings, if any.
910 (unless (= (second (insert-file-contents err-file)) 0)
912 ;; Show first line; stuff remaining lines in the
914 (let ((l1 (buffer-substring (point-min) (point))))
915 (skip-chars-forward "\n")
916 (cons l1 (unless (eobp)
917 (buffer-substring (point) (point-max)))))))))
919 (notmuch-logged-error (car warnings) (cdr warnings)))))
921 ;; Emacs behaves strangely if an error escapes from a sentinel,
922 ;; so turn errors into messages.
923 (message "%s" (error-message-string err))))
924 (ignore-errors (delete-file err-file))))
926 ;; This variable is used only buffer local, but it needs to be
927 ;; declared globally first to avoid compiler warnings.
928 (defvar notmuch-show-process-crypto nil)
929 (make-variable-buffer-local 'notmuch-show-process-crypto)
931 (provide 'notmuch-lib)
934 ;; byte-compile-warnings: (not cl-functions)
937 ;;; notmuch-lib.el ends here