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.
29 "Notmuch mail reader for Emacs."
32 (defgroup notmuch-hello nil
33 "Overview of saved searches, tags, etc."
36 (defgroup notmuch-search nil
37 "Searching and sorting mail."
40 (defgroup notmuch-show nil
41 "Showing messages and threads."
44 (defgroup notmuch-send nil
45 "Sending messages from Notmuch."
48 (custom-add-to-group 'notmuch-send 'message 'custom-group)
50 (defgroup notmuch-crypto nil
51 "Processing and display of cryptographic MIME parts."
54 (defgroup notmuch-hooks nil
55 "Running custom code on well-defined occasions."
58 (defgroup notmuch-external nil
59 "Running external commands from within Notmuch."
62 (defgroup notmuch-faces nil
63 "Graphical attributes for displaying text"
66 (defcustom notmuch-command "notmuch"
67 "Name of the notmuch binary.
69 This can be a relative or absolute path to the notmuch binary.
70 If this is a relative path, it will be searched for in all of the
71 directories given in `exec-path' (which is, by default, based on
74 :group 'notmuch-external)
76 (defcustom notmuch-search-oldest-first t
77 "Show the oldest mail first when searching.
79 This variable defines the default sort order for displaying
80 search results. Note that any filtered searches created by
81 `notmuch-search-filter' retain the search order of the parent
84 :group 'notmuch-search)
86 (defcustom notmuch-poll-script nil
87 "[Deprecated] Command to run to incorporate new mail into the notmuch database.
89 This option has been deprecated in favor of \"notmuch new\"
90 hooks (see man notmuch-hooks). To change the path to the notmuch
91 binary, customize `notmuch-command'.
93 This variable controls the action invoked by
94 `notmuch-poll-and-refresh-this-buffer' (bound by default to 'G')
95 to incorporate new mail into the notmuch database.
97 If set to nil (the default), new mail is processed by invoking
98 \"notmuch new\". Otherwise, this should be set to a string that
99 gives the name of an external script that processes new mail. If
100 set to the empty string, no command will be run.
102 The external script could do any of the following depending on
105 1. Invoke a program to transfer mail to the local mail store
106 2. Invoke \"notmuch new\" to incorporate the new mail
107 3. Invoke one or more \"notmuch tag\" commands to classify the mail"
108 :type '(choice (const :tag "notmuch new" nil)
109 (const :tag "Disabled" "")
110 (string :tag "Custom script"))
111 :group 'notmuch-external)
115 (defvar notmuch-search-history nil
116 "Variable to store notmuch searches history.")
118 (defcustom notmuch-archive-tags '("-inbox")
119 "List of tag changes to apply to a message or a thread when it is archived.
121 Tags starting with \"+\" (or not starting with either \"+\" or
122 \"-\") in the list will be added, and tags starting with \"-\"
123 will be removed from the message or thread being archived.
125 For example, if you wanted to remove an \"inbox\" tag and add an
126 \"archived\" tag, you would set:
127 (\"-inbox\" \"+archived\")"
128 :type '(repeat string)
129 :group 'notmuch-search
130 :group 'notmuch-show)
132 (defvar notmuch-common-keymap
133 (let ((map (make-sparse-keymap)))
134 (define-key map "?" 'notmuch-help)
135 (define-key map "q" 'notmuch-kill-this-buffer)
136 (define-key map "s" 'notmuch-search)
137 (define-key map "z" 'notmuch-tree)
138 (define-key map "m" 'notmuch-mua-new-mail)
139 (define-key map "=" 'notmuch-refresh-this-buffer)
140 (define-key map "G" 'notmuch-poll-and-refresh-this-buffer)
142 "Keymap shared by all notmuch modes.")
144 ;; By default clicking on a button does not select the window
145 ;; containing the button (as opposed to clicking on a widget which
146 ;; does). This means that the button action is then executed in the
147 ;; current selected window which can cause problems if the button
148 ;; changes the buffer (e.g., id: links) or moves point.
150 ;; This provides a button type which overrides mouse-action so that
151 ;; the button's window is selected before the action is run. Other
152 ;; notmuch buttons can get the same behaviour by inheriting from this
154 (define-button-type 'notmuch-button-type
155 'mouse-action (lambda (button)
156 (select-window (posn-window (event-start last-input-event)))
157 (button-activate button)))
159 (defun notmuch-command-to-string (&rest args)
160 "Synchronously invoke \"notmuch\" with the given list of arguments.
162 If notmuch exits with a non-zero status, output from the process
163 will appear in a buffer named \"*Notmuch errors*\" and an error
166 Otherwise the output will be returned"
168 (let* ((status (apply #'call-process notmuch-command nil t nil args))
169 (output (buffer-string)))
170 (notmuch-check-exit-status status (cons notmuch-command args) output)
173 (defvar notmuch--cli-sane-p nil
174 "Cache whether the CLI seems to be configured sanely.")
176 (defun notmuch-cli-sane-p ()
177 "Return t if the cli seems to be configured sanely."
178 (unless notmuch--cli-sane-p
179 (let ((status (call-process notmuch-command nil nil nil
180 "config" "get" "user.primary_email")))
181 (setq notmuch--cli-sane-p (= status 0))))
184 (defun notmuch-assert-cli-sane ()
185 (unless (notmuch-cli-sane-p)
186 (notmuch-logged-error
187 "notmuch cli seems misconfigured or unconfigured."
188 "Perhaps you haven't run \"notmuch setup\" yet? Try running this
189 on the command line, and then retry your notmuch command")))
191 (defun notmuch-version ()
192 "Return a string with the notmuch version number."
194 ;; Trim off the trailing newline.
195 (substring (notmuch-command-to-string "--version") 0 -1)))
196 (if (string-match "^notmuch\\( version\\)? \\(.*\\)$"
198 (match-string 2 long-string)
201 (defun notmuch-config-get (item)
202 "Return a value from the notmuch configuration."
203 (let* ((val (notmuch-command-to-string "config" "get" item))
205 ;; Trim off the trailing newline (if the value is empty or not
206 ;; configured, there will be no newline)
207 (if (and (> len 0) (= (aref val (- len 1)) ?\n))
211 (defun notmuch-database-path ()
212 "Return the database.path value from the notmuch configuration."
213 (notmuch-config-get "database.path"))
215 (defun notmuch-user-name ()
216 "Return the user.name value from the notmuch configuration."
217 (notmuch-config-get "user.name"))
219 (defun notmuch-user-primary-email ()
220 "Return the user.primary_email value from the notmuch configuration."
221 (notmuch-config-get "user.primary_email"))
223 (defun notmuch-user-other-email ()
224 "Return the user.other_email value (as a list) from the notmuch configuration."
225 (split-string (notmuch-config-get "user.other_email") "\n" t))
227 (defun notmuch-poll ()
228 "Run \"notmuch new\" or an external script to import mail.
230 Invokes `notmuch-poll-script', \"notmuch new\", or does nothing
231 depending on the value of `notmuch-poll-script'."
233 (if (stringp notmuch-poll-script)
234 (unless (string= notmuch-poll-script "")
235 (call-process notmuch-poll-script nil nil))
236 (call-process notmuch-command nil nil nil "new")))
238 (defun notmuch-kill-this-buffer ()
239 "Kill the current buffer."
241 (kill-buffer (current-buffer)))
243 (defun notmuch-documentation-first-line (symbol)
244 "Return the first line of the documentation string for SYMBOL."
245 (let ((doc (documentation symbol)))
248 (insert (documentation symbol t))
249 (goto-char (point-min))
252 (buffer-substring beg (point))))
255 (defun notmuch-prefix-key-description (key)
256 "Given a prefix key code, return a human-readable string representation.
258 This is basically just `format-kbd-macro' but we also convert ESC to M-."
259 (let* ((key-vector (if (vectorp key) key (vector key)))
260 (desc (format-kbd-macro key-vector)))
261 (if (string= desc "ESC")
266 (defun notmuch-describe-key (actual-key binding prefix ua-keys tail)
267 "Prepend cons cells describing prefix-arg ACTUAL-KEY and ACTUAL-KEY to TAIL
269 It does not prepend if ACTUAL-KEY is already listed in TAIL."
270 (let ((key-string (concat prefix (format-kbd-macro actual-key))))
271 ;; We don't include documentation if the key-binding is
272 ;; over-ridden. Note, over-riding a binding automatically hides the
273 ;; prefixed version too.
274 (unless (assoc key-string tail)
275 (when (and ua-keys (symbolp binding)
276 (get binding 'notmuch-prefix-doc))
277 ;; Documentation for prefixed command
278 (let ((ua-desc (key-description ua-keys)))
279 (push (cons (concat ua-desc " " prefix (format-kbd-macro actual-key))
280 (get binding 'notmuch-prefix-doc))
282 ;; Documentation for command
283 (push (cons key-string
284 (or (and (symbolp binding) (get binding 'notmuch-doc))
285 (notmuch-documentation-first-line binding)))
289 (defun notmuch-describe-remaps (remap-keymap ua-keys base-keymap prefix tail)
290 ;; Remappings are represented as a binding whose first "event" is
291 ;; 'remap. Hence, if the keymap has any remappings, it will have a
292 ;; binding whose "key" is 'remap, and whose "binding" is itself a
293 ;; keymap that maps not from keys to commands, but from old (remapped)
294 ;; functions to the commands to use in their stead.
296 (lambda (command binding)
299 (setq tail (notmuch-describe-key actual-key binding prefix ua-keys tail)))
300 (where-is-internal command base-keymap)))
304 (defun notmuch-describe-keymap (keymap ua-keys base-keymap &optional prefix tail)
305 "Return a list of cons cells, each describing one binding in KEYMAP.
307 Each cons cell consists of a string giving a human-readable
308 description of the key, and a one-line description of the bound
309 function. See `notmuch-help' for an overview of how this
310 documentation is extracted.
312 UA-KEYS should be a key sequence bound to `universal-argument'.
313 It will be used to describe bindings of commands that support a
314 prefix argument. PREFIX and TAIL are used internally."
316 (lambda (key binding)
317 (cond ((mouse-event-p key) nil)
321 (notmuch-describe-remaps
322 binding ua-keys base-keymap prefix tail)
323 (notmuch-describe-keymap
324 binding ua-keys base-keymap (notmuch-prefix-key-description key) tail))))
326 (setq tail (notmuch-describe-key (vector key) binding prefix ua-keys tail)))))
330 (defun notmuch-substitute-command-keys (doc)
331 "Like `substitute-command-keys' but with documentation, not function names."
333 (while (string-match "\\\\{\\([^}[:space:]]*\\)}" doc beg)
336 (let* ((keymap-name (substring doc (match-beginning 1) (match-end 1)))
337 (keymap (symbol-value (intern keymap-name)))
338 (ua-keys (where-is-internal 'universal-argument keymap t))
339 (desc-alist (notmuch-describe-keymap keymap ua-keys keymap))
340 (desc-list (mapcar (lambda (arg) (concat (car arg) "\t" (cdr arg))) desc-alist)))
341 (mapconcat #'identity desc-list "\n")))))
342 (setq doc (replace-match desc 1 1 doc)))
343 (setq beg (match-end 0)))
346 (defun notmuch-help ()
347 "Display help for the current notmuch mode.
349 This is similar to `describe-function' for the current major
350 mode, but bindings tables are shown with documentation strings
351 rather than command names. By default, this uses the first line
352 of each command's documentation string. A command can override
353 this by setting the 'notmuch-doc property of its command symbol.
354 A command that supports a prefix argument can explicitly document
355 its prefixed behavior by setting the 'notmuch-prefix-doc property
356 of its command symbol."
358 (let* ((mode major-mode)
359 (doc (substitute-command-keys (notmuch-substitute-command-keys (documentation mode t)))))
360 (with-current-buffer (generate-new-buffer "*notmuch-help*")
362 (goto-char (point-min))
363 (set-buffer-modified-p nil)
364 (view-buffer (current-buffer) 'kill-buffer-if-not-modified))))
366 (defun notmuch-subkeymap-help ()
367 "Show help for a subkeymap."
369 (let* ((key (this-command-keys-vector))
370 (prefix (make-vector (1- (length key)) nil))
372 (while (< i (length prefix))
373 (aset prefix i (aref key i))
376 (let* ((subkeymap (key-binding prefix))
377 (ua-keys (where-is-internal 'universal-argument nil t))
378 (prefix-string (notmuch-prefix-key-description prefix))
379 (desc-alist (notmuch-describe-keymap subkeymap ua-keys subkeymap prefix-string))
380 (desc-list (mapcar (lambda (arg) (concat (car arg) "\t" (cdr arg))) desc-alist))
381 (desc (mapconcat #'identity desc-list "\n")))
382 (with-help-window (help-buffer)
383 (with-current-buffer standard-output
384 (insert "\nPress 'q' to quit this window.\n\n")
386 (pop-to-buffer (help-buffer)))))
388 (defvar notmuch-buffer-refresh-function nil
389 "Function to call to refresh the current buffer.")
390 (make-variable-buffer-local 'notmuch-buffer-refresh-function)
392 (defun notmuch-refresh-this-buffer ()
393 "Refresh the current buffer."
395 (when notmuch-buffer-refresh-function
396 (if (commandp notmuch-buffer-refresh-function)
397 ;; Pass prefix argument, etc.
398 (call-interactively notmuch-buffer-refresh-function)
399 (funcall notmuch-buffer-refresh-function))))
401 (defun notmuch-poll-and-refresh-this-buffer ()
402 "Invoke `notmuch-poll' to import mail, then refresh the current buffer."
405 (notmuch-refresh-this-buffer))
407 (defun notmuch-prettify-subject (subject)
408 ;; This function is used by `notmuch-search-process-filter' which
409 ;; requires that we not disrupt its' matching state.
412 (string-match "^[ \t]*$" subject))
416 (defun notmuch-sanitize (str)
417 "Sanitize control character in STR.
419 This includes newlines, tabs, and other funny characters."
420 (replace-regexp-in-string "[[:cntrl:]\x7f\u2028\u2029]+" " " str))
422 (defun notmuch-escape-boolean-term (term)
423 "Escape a boolean term for use in a query.
425 The caller is responsible for prepending the term prefix and a
426 colon. This performs minimal escaping in order to produce
427 user-friendly queries."
430 (if (or (equal term "")
431 ;; To be pessimistic, only pass through terms composed
432 ;; entirely of ASCII printing characters other than ", (,
434 (string-match "[^!#-'*-~]" term))
436 (concat "\"" (replace-regexp-in-string "\"" "\"\"" term t t) "\"")
439 (defun notmuch-id-to-query (id)
440 "Return a query that matches the message with id ID."
441 (concat "id:" (notmuch-escape-boolean-term id)))
443 (defun notmuch-hex-encode (str)
444 "Hex-encode STR (e.g., as used by batch tagging).
446 This replaces spaces, percents, and double quotes in STR with
447 %NN where NN is the hexadecimal value of the character."
448 (replace-regexp-in-string
449 "[ %\"]" (lambda (match) (format "%%%02x" (aref match 0))) str))
453 (defun notmuch-common-do-stash (text)
454 "Common function to stash text in kill ring, and display in minibuffer."
458 (message "Stashed: %s" text))
459 ;; There is nothing to stash so stash an empty string so the user
460 ;; doesn't accidentally paste something else somewhere.
462 (message "Nothing to stash!")))
466 (defun notmuch-remove-if-not (predicate list)
467 "Return a copy of LIST with all items not satisfying PREDICATE removed."
470 (when (funcall predicate (car list))
471 (push (car list) out))
472 (setq list (cdr list)))
475 (defun notmuch-split-content-type (content-type)
476 "Split content/type into 'content' and 'type'"
477 (split-string content-type "/"))
479 (defun notmuch-match-content-type (t1 t2)
480 "Return t if t1 and t2 are matching content types, taking wildcards into account"
481 (let ((st1 (notmuch-split-content-type t1))
482 (st2 (notmuch-split-content-type t2)))
483 (if (or (string= (cadr st1) "*")
484 (string= (cadr st2) "*"))
485 ;; Comparison of content types should be case insensitive.
486 (string= (downcase (car st1)) (downcase (car st2)))
487 (string= (downcase t1) (downcase t2)))))
489 (defvar notmuch-multipart/alternative-discouraged
493 ;; multipart/related usually contain a text/html part and some associated graphics.
497 (defun notmuch-multipart/alternative-choose (types)
498 "Return a list of preferred types from the given list of types"
499 ;; Based on `mm-preferred-alternative-precedence'.
501 (dolist (pref (reverse notmuch-multipart/alternative-discouraged))
502 (dolist (elem (copy-sequence seq))
503 (when (string-match pref elem)
504 (setq seq (nconc (delete elem seq) (list elem))))))
507 (defun notmuch-parts-filter-by-type (parts type)
508 "Given a list of message parts, return a list containing the ones matching
511 (lambda (part) (notmuch-match-content-type (plist-get part :content-type) type))
514 ;; Helper for parts which are generally not included in the default
516 (defun notmuch-get-bodypart-internal (query part-number process-crypto)
517 (let ((args '("show" "--format=raw"))
518 (part-arg (format "--part=%s" part-number)))
519 (setq args (append args (list part-arg)))
521 (setq args (append args '("--decrypt"))))
522 (setq args (append args (list query)))
524 (let ((coding-system-for-read 'no-conversion))
526 (apply 'call-process (append (list notmuch-command nil (list t nil) nil) args))
529 (defun notmuch-get-bodypart-content (msg part nth process-crypto)
530 (or (plist-get part :content)
531 (notmuch-get-bodypart-internal (notmuch-id-to-query (plist-get msg :id)) nth process-crypto)))
533 ;; Workaround: The call to `mm-display-part' below triggers a bug in
534 ;; Emacs 24 if it attempts to use the shr renderer to display an HTML
535 ;; part with images in it (demonstrated in 24.1 and 24.2 on Debian and
536 ;; Fedora 17, though unreproducable in other configurations).
537 ;; `mm-shr' references the variable `gnus-inhibit-images' without
538 ;; first loading gnus-art, which defines it, resulting in a
539 ;; void-variable error. Hence, we advise `mm-shr' to ensure gnus-art
541 (if (>= emacs-major-version 24)
542 (defadvice mm-shr (before load-gnus-arts activate)
543 (require 'gnus-art nil t)
544 (ad-disable-advice 'mm-shr 'before 'load-gnus-arts)
545 (ad-activate 'mm-shr)))
547 (defun notmuch-mm-display-part-inline (msg part nth content-type process-crypto)
548 "Use the mm-decode/mm-view functions to display a part in the
549 current buffer, if possible."
550 (let ((display-buffer (current-buffer)))
552 ;; In case there is :content, the content string is already converted
553 ;; into emacs internal format. `gnus-decoded' is a fake charset,
554 ;; which means no further decoding (to be done by mm- functions).
555 (let* ((charset (if (plist-member part :content)
557 (plist-get part :content-charset)))
558 (handle (mm-make-handle (current-buffer) `(,content-type (charset . ,charset)))))
559 ;; If the user wants the part inlined, insert the content and
560 ;; test whether we are able to inline it (which includes both
561 ;; capability and suitability tests).
562 (when (mm-inlined-p handle)
563 (insert (notmuch-get-bodypart-content msg part nth process-crypto))
564 (when (mm-inlinable-p handle)
565 (set-buffer display-buffer)
566 (mm-display-part handle)
569 ;; Converts a plist of headers to an alist of headers. The input plist should
570 ;; have symbols of the form :Header as keys, and the resulting alist will have
571 ;; symbols of the form 'Header as keys.
572 (defun notmuch-headers-plist-to-alist (plist)
573 (loop for (key value . rest) on plist by #'cddr
574 collect (cons (intern (substring (symbol-name key) 1)) value)))
576 (defun notmuch-face-ensure-list-form (face)
577 "Return FACE in face list form.
579 If FACE is already a face list, it will be returned as-is. If
580 FACE is a face name or face plist, it will be returned as a
581 single element face list."
582 (if (and (listp face) (not (keywordp (car face))))
586 (defun notmuch-apply-face (object face &optional below start end)
587 "Combine FACE into the 'face text property of OBJECT between START and END.
589 This function combines FACE with any existing faces between START
590 and END in OBJECT. Attributes specified by FACE take precedence
591 over existing attributes unless BELOW is non-nil.
593 OBJECT may be a string, a buffer, or nil (which means the current
594 buffer). If object is a string, START and END are 0-based;
595 otherwise they are buffer positions (integers or markers). FACE
596 must be a face name (a symbol or string), a property list of face
597 attributes, or a list of these. If START and/or END are omitted,
598 they default to the beginning/end of OBJECT. For convenience
599 when applied to strings, this returns OBJECT."
601 ;; A face property can have three forms: a face name (a string or
602 ;; symbol), a property list, or a list of these two forms. In the
603 ;; list case, the faces will be combined, with the earlier faces
604 ;; taking precedent. Here we canonicalize everything to list form
605 ;; to make it easy to combine.
606 (let ((pos (cond (start start)
610 ((stringp object) (length object))
611 (t (1+ (buffer-size object)))))
612 (face-list (notmuch-face-ensure-list-form face)))
614 (let* ((cur (get-text-property pos 'face object))
615 (cur-list (notmuch-face-ensure-list-form cur))
616 (new (cond ((null cur-list) face)
617 (below (append cur-list face-list))
618 (t (append face-list cur-list))))
619 (next (next-single-property-change pos 'face object end)))
620 (put-text-property pos next 'face new object)
624 (defun notmuch-map-text-property (start end prop func &optional object)
625 "Transform text property PROP using FUNC.
627 Applies FUNC to each distinct value of the text property PROP
628 between START and END of OBJECT, setting PROP to the value
631 (let ((value (get-text-property start prop object))
632 (next (next-single-property-change start prop object end)))
633 (put-text-property start next prop (funcall func value) object)
636 (defun notmuch-logged-error (msg &optional extra)
637 "Log MSG and EXTRA to *Notmuch errors* and signal MSG.
639 This logs MSG and EXTRA to the *Notmuch errors* buffer and
640 signals MSG as an error. If EXTRA is non-nil, text referring the
641 user to the *Notmuch errors* buffer will be appended to the
642 signaled error. This function does not return."
644 (with-current-buffer (get-buffer-create "*Notmuch errors*")
645 (goto-char (point-max))
649 (insert "[" (current-time-string) "]\n" msg)
656 (error "%s" (concat msg (when extra
657 " (see *Notmuch errors* for more details)"))))
659 (defun notmuch-check-async-exit-status (proc msg &optional command err-file)
660 "If PROC exited abnormally, pop up an error buffer and signal an error.
662 This is a wrapper around `notmuch-check-exit-status' for
663 asynchronous process sentinels. PROC and MSG must be the
664 arguments passed to the sentinel. COMMAND and ERR-FILE, if
665 provided, are passed to `notmuch-check-exit-status'. If COMMAND
666 is not provided, it is taken from `process-command'."
668 (case (process-status proc)
669 ((exit) (process-exit-status proc))
672 (notmuch-check-exit-status exit-status (or command (process-command proc))
675 (defun notmuch-check-exit-status (exit-status command &optional output err-file)
676 "If EXIT-STATUS is non-zero, pop up an error buffer and signal an error.
678 If EXIT-STATUS is non-zero, pop up a notmuch error buffer
679 describing the error and signal an Elisp error. EXIT-STATUS must
680 be a number indicating the exit status code of a process or a
681 string describing the signal that terminated the process (such as
682 returned by `call-process'). COMMAND must be a list giving the
683 command and its arguments. OUTPUT, if provided, is a string
684 giving the output of command. ERR-FILE, if provided, is the name
685 of a file containing the error output of command. OUTPUT and the
686 contents of ERR-FILE will be included in the error message."
689 ((eq exit-status 0) t)
691 (notmuch-logged-error "notmuch CLI version mismatch
692 Emacs requested an older output format than supported by the notmuch CLI.
693 You may need to restart Emacs or upgrade your notmuch Emacs package."))
695 (notmuch-logged-error "notmuch CLI version mismatch
696 Emacs requested a newer output format than supported by the notmuch CLI.
697 You may need to restart Emacs or upgrade your notmuch package."))
699 (let* ((err (when err-file
701 (insert-file-contents err-file)
706 "command: " (mapconcat #'shell-quote-argument command " ") "\n"
707 (if (integerp exit-status)
708 (format "exit status: %s\n" exit-status)
709 (format "exit signal: %s\n" exit-status))
711 (concat "stderr:\n" err))
713 (concat "stdout:\n" output)))))
715 ;; We have an error message straight from the CLI.
716 (notmuch-logged-error
717 (replace-regexp-in-string "[ \n\r\t\f]*\\'" "" err) extra)
718 ;; We only have combined output from the CLI; don't inundate
719 ;; the user with it. Mimic `process-lines'.
720 (notmuch-logged-error (format "%s exited with status %s"
721 (car command) exit-status)
723 ;; `notmuch-logged-error' does not return.
726 (defun notmuch-call-notmuch--helper (destination args)
727 "Helper for synchronous notmuch invocation commands.
729 This wraps `call-process'. DESTINATION has the same meaning as
730 for `call-process'. ARGS is as described for
731 `notmuch-call-notmuch-process'."
734 (while (keywordp (car args))
736 (:stdin-string (setq stdin-string (cadr args)
739 (error "Unknown keyword argument: %s" (car args)))))
740 (if (null stdin-string)
741 (apply #'call-process notmuch-command nil destination nil args)
742 (insert stdin-string)
743 (apply #'call-process-region (point-min) (point-max)
744 notmuch-command t destination nil args))))
746 (defun notmuch-call-notmuch-process (&rest args)
747 "Synchronously invoke `notmuch-command' with ARGS.
749 The caller may provide keyword arguments before ARGS. Currently
750 supported keyword arguments are:
752 :stdin-string STRING - Write STRING to stdin
754 If notmuch exits with a non-zero status, output from the process
755 will appear in a buffer named \"*Notmuch errors*\" and an error
758 (let ((status (notmuch-call-notmuch--helper t args)))
759 (notmuch-check-exit-status status (cons notmuch-command args)
762 (defun notmuch-call-notmuch-sexp (&rest args)
763 "Invoke `notmuch-command' with ARGS and return the parsed S-exp output.
765 This is equivalent to `notmuch-call-notmuch-process', but parses
766 notmuch's output as an S-expression and returns the parsed value.
767 Like `notmuch-call-notmuch-process', if notmuch exits with a
768 non-zero status, this will report its output and signal an
772 (let ((err-file (make-temp-file "nmerr")))
774 (let ((status (notmuch-call-notmuch--helper (list t err-file) args)))
775 (notmuch-check-exit-status status (cons notmuch-command args)
776 (buffer-string) err-file)
777 (goto-char (point-min))
778 (read (current-buffer)))
779 (delete-file err-file)))))
781 (defun notmuch-start-notmuch (name buffer sentinel &rest args)
782 "Start and return an asynchronous notmuch command.
784 This starts and returns an asynchronous process running
785 `notmuch-command' with ARGS. The exit status is checked via
786 `notmuch-check-async-exit-status'. Output written to stderr is
787 redirected and displayed when the process exits (even if the
788 process exits successfully). NAME and BUFFER are the same as in
789 `start-process'. SENTINEL is a process sentinel function to call
790 when the process exits, or nil for none. The caller must *not*
791 invoke `set-process-sentinel' directly on the returned process,
792 as that will interfere with the handling of stderr and the exit
795 ;; There is no way (as of Emacs 24.3) to capture stdout and stderr
796 ;; separately for asynchronous processes, or even to redirect stderr
797 ;; to a file, so we use a trivial shell wrapper to send stderr to a
798 ;; temporary file and clean things up in the sentinel.
799 (let* ((err-file (make-temp-file "nmerr"))
801 (process-connection-type nil)
802 ;; Find notmuch using Emacs' `exec-path'
803 (command (or (executable-find notmuch-command)
804 (error "command not found: %s" notmuch-command)))
805 (proc (apply #'start-process name buffer
807 "exec 2>\"$1\"; shift; exec \"$0\" \"$@\""
808 command err-file args)))
809 (process-put proc 'err-file err-file)
810 (process-put proc 'sub-sentinel sentinel)
811 (process-put proc 'real-command (cons notmuch-command args))
812 (set-process-sentinel proc #'notmuch-start-notmuch-sentinel)
815 (defun notmuch-start-notmuch-sentinel (proc event)
816 (let ((err-file (process-get proc 'err-file))
817 (sub-sentinel (process-get proc 'sub-sentinel))
818 (real-command (process-get proc 'real-command)))
821 ;; Invoke the sub-sentinel, if any
823 (funcall sub-sentinel proc event))
824 ;; Check the exit status. This will signal an error if the
825 ;; exit status is non-zero. Don't do this if the process
826 ;; buffer is dead since that means Emacs killed the process
827 ;; and there's no point in telling the user that (but we
828 ;; still check for and report stderr output below).
829 (when (buffer-live-p (process-buffer proc))
830 (notmuch-check-async-exit-status proc event real-command err-file))
831 ;; If that didn't signal an error, then any error output was
832 ;; really warning output. Show warnings, if any.
835 (unless (= (second (insert-file-contents err-file)) 0)
837 ;; Show first line; stuff remaining lines in the
839 (let ((l1 (buffer-substring (point-min) (point))))
840 (skip-chars-forward "\n")
841 (cons l1 (unless (eobp)
842 (buffer-substring (point) (point-max)))))))))
844 (notmuch-logged-error (car warnings) (cdr warnings)))))
846 ;; Emacs behaves strangely if an error escapes from a sentinel,
847 ;; so turn errors into messages.
848 (message "%s" (error-message-string err))))
849 (ignore-errors (delete-file err-file))))
851 ;; This variable is used only buffer local, but it needs to be
852 ;; declared globally first to avoid compiler warnings.
853 (defvar notmuch-show-process-crypto nil)
854 (make-variable-buffer-local 'notmuch-show-process-crypto)
856 (provide 'notmuch-lib)
859 ;; byte-compile-warnings: (not cl-functions)