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.
32 (require 'notmuch-compat)
34 (unless (require 'notmuch-version nil t)
35 (defconst notmuch-emacs-version "unknown"
36 "Placeholder variable when notmuch-version.el[c] is not available."))
38 (autoload 'notmuch-jump-search "notmuch-jump"
39 "Jump to a saved search by shortcut key." t)
42 "Notmuch mail reader for Emacs."
45 (defgroup notmuch-hello nil
46 "Overview of saved searches, tags, etc."
49 (defgroup notmuch-search nil
50 "Searching and sorting mail."
53 (defgroup notmuch-show nil
54 "Showing messages and threads."
57 (defgroup notmuch-send nil
58 "Sending messages from Notmuch."
61 (custom-add-to-group 'notmuch-send 'message 'custom-group)
63 (defgroup notmuch-tag nil
64 "Tags and tagging in Notmuch."
67 (defgroup notmuch-crypto nil
68 "Processing and display of cryptographic MIME parts."
71 (defgroup notmuch-hooks nil
72 "Running custom code on well-defined occasions."
75 (defgroup notmuch-external nil
76 "Running external commands from within Notmuch."
79 (defgroup notmuch-address nil
83 (defgroup notmuch-faces nil
84 "Graphical attributes for displaying text"
87 (defcustom notmuch-command "notmuch"
88 "Name of the notmuch binary.
90 This can be a relative or absolute path to the notmuch binary.
91 If this is a relative path, it will be searched for in all of the
92 directories given in `exec-path' (which is, by default, based on
95 :group 'notmuch-external)
97 (defcustom notmuch-search-oldest-first t
98 "Show the oldest mail first when searching.
100 This variable defines the default sort order for displaying
101 search results. Note that any filtered searches created by
102 `notmuch-search-filter' retain the search order of the parent
105 :group 'notmuch-search)
107 (defcustom notmuch-poll-script nil
108 "[Deprecated] Command to run to incorporate new mail into the notmuch database.
110 This option has been deprecated in favor of \"notmuch new\"
111 hooks (see man notmuch-hooks). To change the path to the notmuch
112 binary, customize `notmuch-command'.
114 This variable controls the action invoked by
115 `notmuch-poll-and-refresh-this-buffer' (bound by default to 'G')
116 to incorporate new mail into the notmuch database.
118 If set to nil (the default), new mail is processed by invoking
119 \"notmuch new\". Otherwise, this should be set to a string that
120 gives the name of an external script that processes new mail. If
121 set to the empty string, no command will be run.
123 The external script could do any of the following depending on
126 1. Invoke a program to transfer mail to the local mail store
127 2. Invoke \"notmuch new\" to incorporate the new mail
128 3. Invoke one or more \"notmuch tag\" commands to classify the mail"
129 :type '(choice (const :tag "notmuch new" nil)
130 (const :tag "Disabled" "")
131 (string :tag "Custom script"))
132 :group 'notmuch-external)
136 (defvar notmuch-search-history nil
137 "Variable to store notmuch searches history.")
139 (defcustom notmuch-archive-tags '("-inbox")
140 "List of tag changes to apply to a message or a thread when it is archived.
142 Tags starting with \"+\" (or not starting with either \"+\" or
143 \"-\") in the list will be added, and tags starting with \"-\"
144 will be removed from the message or thread being archived.
146 For example, if you wanted to remove an \"inbox\" tag and add an
147 \"archived\" tag, you would set:
148 (\"-inbox\" \"+archived\")"
149 :type '(repeat string)
150 :group 'notmuch-search
151 :group 'notmuch-show)
153 (defvar notmuch-common-keymap
154 (let ((map (make-sparse-keymap)))
155 (define-key map "?" 'notmuch-help)
156 (define-key map "q" 'notmuch-bury-or-kill-this-buffer)
157 (define-key map "s" 'notmuch-search)
158 (define-key map "t" 'notmuch-search-by-tag)
159 (define-key map "z" 'notmuch-tree)
160 (define-key map "u" 'notmuch-unthreaded)
161 (define-key map "m" 'notmuch-mua-new-mail)
162 (define-key map "g" 'notmuch-refresh-this-buffer)
163 (define-key map "=" 'notmuch-refresh-this-buffer)
164 (define-key map (kbd "M-=") 'notmuch-refresh-all-buffers)
165 (define-key map "G" 'notmuch-poll-and-refresh-this-buffer)
166 (define-key map "j" 'notmuch-jump-search)
168 "Keymap shared by all notmuch modes.")
170 ;; By default clicking on a button does not select the window
171 ;; containing the button (as opposed to clicking on a widget which
172 ;; does). This means that the button action is then executed in the
173 ;; current selected window which can cause problems if the button
174 ;; changes the buffer (e.g., id: links) or moves point.
176 ;; This provides a button type which overrides mouse-action so that
177 ;; the button's window is selected before the action is run. Other
178 ;; notmuch buttons can get the same behaviour by inheriting from this
180 (define-button-type 'notmuch-button-type
181 'mouse-action (lambda (button)
182 (select-window (posn-window (event-start last-input-event)))
183 (button-activate button)))
185 (defun notmuch-command-to-string (&rest args)
186 "Synchronously invoke \"notmuch\" with the given list of arguments.
188 If notmuch exits with a non-zero status, output from the process
189 will appear in a buffer named \"*Notmuch errors*\" and an error
192 Otherwise the output will be returned."
194 (let* ((status (apply #'call-process notmuch-command nil t nil args))
195 (output (buffer-string)))
196 (notmuch-check-exit-status status (cons notmuch-command args) output)
199 (defvar notmuch--cli-sane-p nil
200 "Cache whether the CLI seems to be configured sanely.")
202 (defun notmuch-cli-sane-p ()
203 "Return t if the cli seems to be configured sanely."
204 (unless notmuch--cli-sane-p
205 (let ((status (call-process notmuch-command nil nil nil
206 "config" "get" "user.primary_email")))
207 (setq notmuch--cli-sane-p (= status 0))))
210 (defun notmuch-assert-cli-sane ()
211 (unless (notmuch-cli-sane-p)
212 (notmuch-logged-error
213 "notmuch cli seems misconfigured or unconfigured."
214 "Perhaps you haven't run \"notmuch setup\" yet? Try running this
215 on the command line, and then retry your notmuch command")))
217 (defun notmuch-cli-version ()
218 "Return a string with the notmuch cli command version number."
220 ;; Trim off the trailing newline.
221 (substring (notmuch-command-to-string "--version") 0 -1)))
222 (if (string-match "^notmuch\\( version\\)? \\(.*\\)$"
224 (match-string 2 long-string)
227 (defun notmuch-config-get (item)
228 "Return a value from the notmuch configuration."
229 (let* ((val (notmuch-command-to-string "config" "get" item))
231 ;; Trim off the trailing newline (if the value is empty or not
232 ;; configured, there will be no newline)
233 (if (and (> len 0) (= (aref val (- len 1)) ?\n))
237 (defun notmuch-database-path ()
238 "Return the database.path value from the notmuch configuration."
239 (notmuch-config-get "database.path"))
241 (defun notmuch-user-name ()
242 "Return the user.name value from the notmuch configuration."
243 (notmuch-config-get "user.name"))
245 (defun notmuch-user-primary-email ()
246 "Return the user.primary_email value from the notmuch configuration."
247 (notmuch-config-get "user.primary_email"))
249 (defun notmuch-user-other-email ()
250 "Return the user.other_email value (as a list) from the notmuch configuration."
251 (split-string (notmuch-config-get "user.other_email") "\n" t))
253 (defun notmuch-user-emails ()
254 (cons (notmuch-user-primary-email) (notmuch-user-other-email)))
256 (defun notmuch-poll ()
257 "Run \"notmuch new\" or an external script to import mail.
259 Invokes `notmuch-poll-script', \"notmuch new\", or does nothing
260 depending on the value of `notmuch-poll-script'."
262 (if (stringp notmuch-poll-script)
263 (unless (string= notmuch-poll-script "")
264 (unless (equal (call-process notmuch-poll-script nil nil) 0)
265 (error "Notmuch: poll script `%s' failed!" notmuch-poll-script)))
266 (notmuch-call-notmuch-process "new")))
268 (defun notmuch-bury-or-kill-this-buffer ()
269 "Undisplay the current buffer.
271 Bury the current buffer, unless there is only one window showing
272 it, in which case it is killed."
274 (if (> (length (get-buffer-window-list nil nil t)) 1)
278 (defun notmuch-documentation-first-line (symbol)
279 "Return the first line of the documentation string for SYMBOL."
280 (let ((doc (documentation symbol)))
283 (insert (documentation symbol t))
284 (goto-char (point-min))
287 (buffer-substring beg (point))))
290 (defun notmuch-prefix-key-description (key)
291 "Given a prefix key code, return a human-readable string representation.
293 This is basically just `format-kbd-macro' but we also convert ESC to M-."
294 (let* ((key-vector (if (vectorp key) key (vector key)))
295 (desc (format-kbd-macro key-vector)))
296 (if (string= desc "ESC")
301 (defun notmuch-describe-key (actual-key binding prefix ua-keys tail)
302 "Prepend cons cells describing prefix-arg ACTUAL-KEY and ACTUAL-KEY to TAIL.
304 It does not prepend if ACTUAL-KEY is already listed in TAIL."
305 (let ((key-string (concat prefix (key-description actual-key))))
306 ;; We don't include documentation if the key-binding is
307 ;; over-ridden. Note, over-riding a binding automatically hides the
308 ;; prefixed version too.
309 (unless (assoc key-string tail)
310 (when (and ua-keys (symbolp binding)
311 (get binding 'notmuch-prefix-doc))
312 ;; Documentation for prefixed command
313 (let ((ua-desc (key-description ua-keys)))
314 (push (cons (concat ua-desc " " prefix (format-kbd-macro actual-key))
315 (get binding 'notmuch-prefix-doc))
317 ;; Documentation for command
318 (push (cons key-string
319 (or (and (symbolp binding) (get binding 'notmuch-doc))
320 (and (functionp binding) (notmuch-documentation-first-line binding))))
324 (defun notmuch-describe-remaps (remap-keymap ua-keys base-keymap prefix tail)
325 ;; Remappings are represented as a binding whose first "event" is
326 ;; 'remap. Hence, if the keymap has any remappings, it will have a
327 ;; binding whose "key" is 'remap, and whose "binding" is itself a
328 ;; keymap that maps not from keys to commands, but from old (remapped)
329 ;; functions to the commands to use in their stead.
331 (lambda (command binding)
334 (setq tail (notmuch-describe-key actual-key binding prefix ua-keys tail)))
335 (where-is-internal command base-keymap)))
339 (defun notmuch-describe-keymap (keymap ua-keys base-keymap &optional prefix tail)
340 "Return a list of cons cells, each describing one binding in KEYMAP.
342 Each cons cell consists of a string giving a human-readable
343 description of the key, and a one-line description of the bound
344 function. See `notmuch-help' for an overview of how this
345 documentation is extracted.
347 UA-KEYS should be a key sequence bound to `universal-argument'.
348 It will be used to describe bindings of commands that support a
349 prefix argument. PREFIX and TAIL are used internally."
351 (lambda (key binding)
352 (cond ((mouse-event-p key) nil)
356 (notmuch-describe-remaps
357 binding ua-keys base-keymap prefix tail)
358 (notmuch-describe-keymap
359 binding ua-keys base-keymap (notmuch-prefix-key-description key) tail))))
361 (setq tail (notmuch-describe-key (vector key) binding prefix ua-keys tail)))))
365 (defun notmuch-substitute-command-keys (doc)
366 "Like `substitute-command-keys' but with documentation, not function names."
368 (while (string-match "\\\\{\\([^}[:space:]]*\\)}" doc beg)
371 (let* ((keymap-name (substring doc (match-beginning 1) (match-end 1)))
372 (keymap (symbol-value (intern keymap-name)))
373 (ua-keys (where-is-internal 'universal-argument keymap t))
374 (desc-alist (notmuch-describe-keymap keymap ua-keys keymap))
375 (desc-list (mapcar (lambda (arg) (concat (car arg) "\t" (cdr arg))) desc-alist)))
376 (mapconcat #'identity desc-list "\n")))))
377 (setq doc (replace-match desc 1 1 doc)))
378 (setq beg (match-end 0)))
381 (defun notmuch-help ()
382 "Display help for the current notmuch mode.
384 This is similar to `describe-function' for the current major
385 mode, but bindings tables are shown with documentation strings
386 rather than command names. By default, this uses the first line
387 of each command's documentation string. A command can override
388 this by setting the 'notmuch-doc property of its command symbol.
389 A command that supports a prefix argument can explicitly document
390 its prefixed behavior by setting the 'notmuch-prefix-doc property
391 of its command symbol."
393 (let* ((mode major-mode)
394 (doc (substitute-command-keys (notmuch-substitute-command-keys (documentation mode t)))))
395 (with-current-buffer (generate-new-buffer "*notmuch-help*")
397 (goto-char (point-min))
398 (set-buffer-modified-p nil)
399 (view-buffer (current-buffer) 'kill-buffer-if-not-modified))))
401 (defun notmuch-subkeymap-help ()
402 "Show help for a subkeymap."
404 (let* ((key (this-command-keys-vector))
405 (prefix (make-vector (1- (length key)) nil))
407 (while (< i (length prefix))
408 (aset prefix i (aref key i))
411 (let* ((subkeymap (key-binding prefix))
412 (ua-keys (where-is-internal 'universal-argument nil t))
413 (prefix-string (notmuch-prefix-key-description prefix))
414 (desc-alist (notmuch-describe-keymap subkeymap ua-keys subkeymap prefix-string))
415 (desc-list (mapcar (lambda (arg) (concat (car arg) "\t" (cdr arg))) desc-alist))
416 (desc (mapconcat #'identity desc-list "\n")))
417 (with-help-window (help-buffer)
418 (with-current-buffer standard-output
419 (insert "\nPress 'q' to quit this window.\n\n")
421 (pop-to-buffer (help-buffer)))))
423 (defvar notmuch-buffer-refresh-function nil
424 "Function to call to refresh the current buffer.")
425 (make-variable-buffer-local 'notmuch-buffer-refresh-function)
427 (defun notmuch-refresh-this-buffer ()
428 "Refresh the current buffer."
430 (when notmuch-buffer-refresh-function
431 ;; Pass prefix argument, etc.
432 (call-interactively notmuch-buffer-refresh-function)))
434 (defun notmuch-poll-and-refresh-this-buffer ()
435 "Invoke `notmuch-poll' to import mail, then refresh the current buffer."
438 (notmuch-refresh-this-buffer))
440 (defun notmuch-refresh-all-buffers ()
441 "Invoke `notmuch-refresh-this-buffer' on all notmuch major-mode buffers.
443 The buffers are silently refreshed, i.e. they are not forced to
446 (dolist (buffer (buffer-list))
447 (let ((buffer-mode (buffer-local-value 'major-mode buffer)))
448 (when (memq buffer-mode '(notmuch-show-mode
452 (with-current-buffer buffer
453 (notmuch-refresh-this-buffer))))))
455 (defun notmuch-prettify-subject (subject)
456 ;; This function is used by `notmuch-search-process-filter' which
457 ;; requires that we not disrupt its' matching state.
460 (string-match "^[ \t]*$" subject))
464 (defun notmuch-sanitize (str)
465 "Sanitize control character in STR.
467 This includes newlines, tabs, and other funny characters."
468 (replace-regexp-in-string "[[:cntrl:]\x7f\u2028\u2029]+" " " str))
470 (defun notmuch-escape-boolean-term (term)
471 "Escape a boolean term for use in a query.
473 The caller is responsible for prepending the term prefix and a
474 colon. This performs minimal escaping in order to produce
475 user-friendly queries."
478 (if (or (equal term "")
479 ;; To be pessimistic, only pass through terms composed
480 ;; entirely of ASCII printing characters other than ", (,
482 (string-match "[^!#-'*-~]" term))
484 (concat "\"" (replace-regexp-in-string "\"" "\"\"" term t t) "\"")
487 (defun notmuch-id-to-query (id)
488 "Return a query that matches the message with id ID."
489 (concat "id:" (notmuch-escape-boolean-term id)))
491 (defun notmuch-hex-encode (str)
492 "Hex-encode STR (e.g., as used by batch tagging).
494 This replaces spaces, percents, and double quotes in STR with
495 %NN where NN is the hexadecimal value of the character."
496 (replace-regexp-in-string
497 "[ %\"]" (lambda (match) (format "%%%02x" (aref match 0))) str))
501 (defun notmuch-common-do-stash (text)
502 "Common function to stash text in kill ring, and display in minibuffer."
506 (message "Stashed: %s" text))
507 ;; There is nothing to stash so stash an empty string so the user
508 ;; doesn't accidentally paste something else somewhere.
510 (message "Nothing to stash!")))
514 (defun notmuch-remove-if-not (predicate list)
515 "Return a copy of LIST with all items not satisfying PREDICATE removed."
518 (when (funcall predicate (car list))
519 (push (car list) out))
520 (setq list (cdr list)))
523 (defun notmuch-plist-delete (plist property)
524 (let* ((xplist (cons nil plist))
527 (when (eq (cadr pred) property)
528 (setcdr pred (cdddr pred)))
529 (setq pred (cddr pred)))
532 (defun notmuch-split-content-type (content-type)
533 "Split content/type into 'content' and 'type'."
534 (split-string content-type "/"))
536 (defun notmuch-match-content-type (t1 t2)
537 "Return t if t1 and t2 are matching content types, taking wildcards into account."
538 (let ((st1 (notmuch-split-content-type t1))
539 (st2 (notmuch-split-content-type t2)))
540 (if (or (string= (cadr st1) "*")
541 (string= (cadr st2) "*"))
542 ;; Comparison of content types should be case insensitive.
543 (string= (downcase (car st1)) (downcase (car st2)))
544 (string= (downcase t1) (downcase t2)))))
546 (defvar notmuch-multipart/alternative-discouraged
550 ;; multipart/related usually contain a text/html part and some associated graphics.
554 (defun notmuch-multipart/alternative-determine-discouraged (msg)
555 "Return the discouraged alternatives for the specified message."
556 ;; If a function, return the result of calling it.
557 (if (functionp notmuch-multipart/alternative-discouraged)
558 (funcall notmuch-multipart/alternative-discouraged msg)
559 ;; Otherwise simply return the value of the variable, which is
560 ;; assumed to be a list of discouraged alternatives. This is the
561 ;; default behaviour.
562 notmuch-multipart/alternative-discouraged))
564 (defun notmuch-multipart/alternative-choose (msg types)
565 "Return a list of preferred types from the given list of types
566 for this message, if present."
567 ;; Based on `mm-preferred-alternative-precedence'.
568 (let ((discouraged (notmuch-multipart/alternative-determine-discouraged msg))
570 (dolist (pref (reverse discouraged))
571 (dolist (elem (copy-sequence seq))
572 (when (string-match pref elem)
573 (setq seq (nconc (delete elem seq) (list elem))))))
576 (defun notmuch-parts-filter-by-type (parts type)
577 "Given a list of message parts, return a list containing the ones matching
580 (lambda (part) (notmuch-match-content-type (plist-get part :content-type) type))
583 (defun notmuch--get-bodypart-raw (msg part process-crypto binaryp cache)
584 (let* ((plist-elem (if binaryp :content-binary :content))
585 (data (or (plist-get part plist-elem)
587 ;; Emacs internally uses a UTF-8-like multibyte string
588 ;; representation by default (regardless of the coding
589 ;; system, which only affects how it goes from outside data
590 ;; to this internal representation). This *almost* never
591 ;; matters. Annoyingly, it does matter if we use this data
592 ;; in an image descriptor, since Emacs will use its internal
593 ;; data buffer directly and this multibyte representation
594 ;; corrupts binary image formats. Since the caller is
595 ;; asking for binary data, a unibyte string is a more
596 ;; appropriate representation anyway.
598 (set-buffer-multibyte nil))
599 (let ((args `("show" "--format=raw"
600 ,(format "--part=%s" (plist-get part :id))
601 ,@(when process-crypto '("--decrypt=true"))
602 ,(notmuch-id-to-query (plist-get msg :id))))
603 (coding-system-for-read
604 (if binaryp 'no-conversion
605 (let ((coding-system (mm-charset-to-coding-system
606 (plist-get part :content-charset))))
608 ;; `mm-charset-to-coding-system' seems
609 ;; to return things that are not
610 ;; considered acceptable values for
611 ;; `coding-system-for-read'.
612 (if (coding-system-p coding-system)
614 ;; RFC 2047 says that the default
615 ;; charset is US-ASCII. RFC6657
616 ;; complicates this somewhat.
618 (apply #'call-process notmuch-command nil '(t nil) nil args)
620 (when (and cache data)
621 (plist-put part plist-elem data))
624 (defun notmuch-get-bodypart-binary (msg part process-crypto &optional cache)
625 "Return the unprocessed content of PART in MSG as a unibyte string.
627 This returns the \"raw\" content of the given part after content
628 transfer decoding, but with no further processing (see the
629 discussion of --format=raw in man notmuch-show). In particular,
630 this does no charset conversion.
632 If CACHE is non-nil, the content of this part will be saved in
633 MSG (if it isn't already)."
634 (notmuch--get-bodypart-raw msg part process-crypto t cache))
636 (defun notmuch-get-bodypart-text (msg part process-crypto &optional cache)
637 "Return the text content of PART in MSG.
639 This returns the content of the given part as a multibyte Lisp
640 string after performing content transfer decoding and any
641 necessary charset decoding.
643 If CACHE is non-nil, the content of this part will be saved in
644 MSG (if it isn't already)."
645 (notmuch--get-bodypart-raw msg part process-crypto nil cache))
647 ;; Workaround: The call to `mm-display-part' below triggers a bug in
648 ;; Emacs 24 if it attempts to use the shr renderer to display an HTML
649 ;; part with images in it (demonstrated in 24.1 and 24.2 on Debian and
650 ;; Fedora 17, though unreproducable in other configurations).
651 ;; `mm-shr' references the variable `gnus-inhibit-images' without
652 ;; first loading gnus-art, which defines it, resulting in a
653 ;; void-variable error. Hence, we advise `mm-shr' to ensure gnus-art
655 (if (>= emacs-major-version 24)
656 (defadvice mm-shr (before load-gnus-arts activate)
657 (require 'gnus-art nil t)
658 (ad-disable-advice 'mm-shr 'before 'load-gnus-arts)
659 (ad-activate 'mm-shr)))
661 (defun notmuch-mm-display-part-inline (msg part content-type process-crypto)
662 "Use the mm-decode/mm-view functions to display a part in the
663 current buffer, if possible."
664 (let ((display-buffer (current-buffer)))
666 ;; In case we already have :content, use it and tell mm-* that
667 ;; it's already been charset-decoded by using the fake
668 ;; `gnus-decoded' charset. Otherwise, we'll fetch the binary
669 ;; part content and let mm-* decode it.
670 (let* ((have-content (plist-member part :content))
671 (charset (if have-content 'gnus-decoded
672 (plist-get part :content-charset)))
673 (handle (mm-make-handle (current-buffer) `(,content-type (charset . ,charset)))))
674 ;; If the user wants the part inlined, insert the content and
675 ;; test whether we are able to inline it (which includes both
676 ;; capability and suitability tests).
677 (when (mm-inlined-p handle)
679 (insert (notmuch-get-bodypart-text msg part process-crypto))
680 (insert (notmuch-get-bodypart-binary msg part process-crypto)))
681 (when (mm-inlinable-p handle)
682 (set-buffer display-buffer)
683 (mm-display-part handle)
686 ;; Converts a plist of headers to an alist of headers. The input plist should
687 ;; have symbols of the form :Header as keys, and the resulting alist will have
688 ;; symbols of the form 'Header as keys.
689 (defun notmuch-headers-plist-to-alist (plist)
690 (cl-loop for (key value . rest) on plist by #'cddr
691 collect (cons (intern (substring (symbol-name key) 1)) value)))
693 (defun notmuch-face-ensure-list-form (face)
694 "Return FACE in face list form.
696 If FACE is already a face list, it will be returned as-is. If
697 FACE is a face name or face plist, it will be returned as a
698 single element face list."
699 (if (and (listp face) (not (keywordp (car face))))
703 (defun notmuch-apply-face (object face &optional below start end)
704 "Combine FACE into the 'face text property of OBJECT between START and END.
706 This function combines FACE with any existing faces between START
707 and END in OBJECT. Attributes specified by FACE take precedence
708 over existing attributes unless BELOW is non-nil.
710 OBJECT may be a string, a buffer, or nil (which means the current
711 buffer). If object is a string, START and END are 0-based;
712 otherwise they are buffer positions (integers or markers). FACE
713 must be a face name (a symbol or string), a property list of face
714 attributes, or a list of these. If START and/or END are omitted,
715 they default to the beginning/end of OBJECT. For convenience
716 when applied to strings, this returns OBJECT."
718 ;; A face property can have three forms: a face name (a string or
719 ;; symbol), a property list, or a list of these two forms. In the
720 ;; list case, the faces will be combined, with the earlier faces
721 ;; taking precedent. Here we canonicalize everything to list form
722 ;; to make it easy to combine.
723 (let ((pos (cond (start start)
727 ((stringp object) (length object))
728 (t (1+ (buffer-size object)))))
729 (face-list (notmuch-face-ensure-list-form face)))
731 (let* ((cur (get-text-property pos 'face object))
732 (cur-list (notmuch-face-ensure-list-form cur))
733 (new (cond ((null cur-list) face)
734 (below (append cur-list face-list))
735 (t (append face-list cur-list))))
736 (next (next-single-property-change pos 'face object end)))
737 (put-text-property pos next 'face new object)
741 (defun notmuch-map-text-property (start end prop func &optional object)
742 "Transform text property PROP using FUNC.
744 Applies FUNC to each distinct value of the text property PROP
745 between START and END of OBJECT, setting PROP to the value
748 (let ((value (get-text-property start prop object))
749 (next (next-single-property-change start prop object end)))
750 (put-text-property start next prop (funcall func value) object)
753 (defun notmuch-logged-error (msg &optional extra)
754 "Log MSG and EXTRA to *Notmuch errors* and signal MSG.
756 This logs MSG and EXTRA to the *Notmuch errors* buffer and
757 signals MSG as an error. If EXTRA is non-nil, text referring the
758 user to the *Notmuch errors* buffer will be appended to the
759 signaled error. This function does not return."
761 (with-current-buffer (get-buffer-create "*Notmuch errors*")
762 (goto-char (point-max))
766 (insert "[" (current-time-string) "]\n" msg)
773 (error "%s" (concat msg (when extra
774 " (see *Notmuch errors* for more details)"))))
776 (defun notmuch-check-async-exit-status (proc msg &optional command err)
777 "If PROC exited abnormally, pop up an error buffer and signal an error.
779 This is a wrapper around `notmuch-check-exit-status' for
780 asynchronous process sentinels. PROC and MSG must be the
781 arguments passed to the sentinel. COMMAND and ERR, if provided,
782 are passed to `notmuch-check-exit-status'. If COMMAND is not
783 provided, it is taken from `process-command'."
785 (cl-case (process-status proc)
786 ((exit) (process-exit-status proc))
789 (notmuch-check-exit-status exit-status (or command (process-command proc))
792 (defun notmuch-check-exit-status (exit-status command &optional output err)
793 "If EXIT-STATUS is non-zero, pop up an error buffer and signal an error.
795 If EXIT-STATUS is non-zero, pop up a notmuch error buffer
796 describing the error and signal an Elisp error. EXIT-STATUS must
797 be a number indicating the exit status code of a process or a
798 string describing the signal that terminated the process (such as
799 returned by `call-process'). COMMAND must be a list giving the
800 command and its arguments. OUTPUT, if provided, is a string
801 giving the output of command. ERR, if provided, is the error
802 output of command. OUTPUT and ERR will be included in the error
806 ((eq exit-status 0) t)
808 (notmuch-logged-error "notmuch CLI version mismatch
809 Emacs requested an older output format than supported by the notmuch CLI.
810 You may need to restart Emacs or upgrade your notmuch Emacs package."))
812 (notmuch-logged-error "notmuch CLI version mismatch
813 Emacs requested a newer output format than supported by the notmuch CLI.
814 You may need to restart Emacs or upgrade your notmuch package."))
816 (let* ((command-string
817 (mapconcat (lambda (arg)
818 (shell-quote-argument
819 (cond ((stringp arg) arg)
820 ((symbolp arg) (symbol-name arg))
821 (t "*UNKNOWN ARGUMENT*"))))
824 (concat "command: " command-string "\n"
825 (if (integerp exit-status)
826 (format "exit status: %s\n" exit-status)
827 (format "exit signal: %s\n" exit-status))
829 (concat "stderr:\n" err))
831 (concat "stdout:\n" output)))))
833 ;; We have an error message straight from the CLI.
834 (notmuch-logged-error
835 (replace-regexp-in-string "[ \n\r\t\f]*\\'" "" err) extra)
836 ;; We only have combined output from the CLI; don't inundate
837 ;; the user with it. Mimic `process-lines'.
838 (notmuch-logged-error (format "%s exited with status %s"
839 (car command) exit-status)
841 ;; `notmuch-logged-error' does not return.
844 (defun notmuch-call-notmuch--helper (destination args)
845 "Helper for synchronous notmuch invocation commands.
847 This wraps `call-process'. DESTINATION has the same meaning as
848 for `call-process'. ARGS is as described for
849 `notmuch-call-notmuch-process'."
852 (while (keywordp (car args))
854 (:stdin-string (setq stdin-string (cadr args)
857 (error "Unknown keyword argument: %s" (car args)))))
858 (if (null stdin-string)
859 (apply #'call-process notmuch-command nil destination nil args)
860 (insert stdin-string)
861 (apply #'call-process-region (point-min) (point-max)
862 notmuch-command t destination nil args))))
864 (defun notmuch-call-notmuch-process (&rest args)
865 "Synchronously invoke `notmuch-command' with ARGS.
867 The caller may provide keyword arguments before ARGS. Currently
868 supported keyword arguments are:
870 :stdin-string STRING - Write STRING to stdin
872 If notmuch exits with a non-zero status, output from the process
873 will appear in a buffer named \"*Notmuch errors*\" and an error
876 (let ((status (notmuch-call-notmuch--helper t args)))
877 (notmuch-check-exit-status status (cons notmuch-command args)
880 (defun notmuch-call-notmuch-sexp (&rest args)
881 "Invoke `notmuch-command' with ARGS and return the parsed S-exp output.
883 This is equivalent to `notmuch-call-notmuch-process', but parses
884 notmuch's output as an S-expression and returns the parsed value.
885 Like `notmuch-call-notmuch-process', if notmuch exits with a
886 non-zero status, this will report its output and signal an
890 (let ((err-file (make-temp-file "nmerr")))
892 (let ((status (notmuch-call-notmuch--helper (list t err-file) args))
893 (err (with-temp-buffer
894 (insert-file-contents err-file)
897 (notmuch-check-exit-status status (cons notmuch-command args)
899 (goto-char (point-min))
900 (read (current-buffer)))
901 (delete-file err-file)))))
903 (defun notmuch-start-notmuch (name buffer sentinel &rest args)
904 "Start and return an asynchronous notmuch command.
906 This starts and returns an asynchronous process running
907 `notmuch-command' with ARGS. The exit status is checked via
908 `notmuch-check-async-exit-status'. Output written to stderr is
909 redirected and displayed when the process exits (even if the
910 process exits successfully). NAME and BUFFER are the same as in
911 `start-process'. SENTINEL is a process sentinel function to call
912 when the process exits, or nil for none. The caller must *not*
913 invoke `set-process-sentinel' directly on the returned process,
914 as that will interfere with the handling of stderr and the exit
917 (let (err-file err-buffer proc err-proc
918 ;; Find notmuch using Emacs' `exec-path'
919 (command (or (executable-find notmuch-command)
920 (error "Command not found: %s" notmuch-command))))
921 (if (fboundp 'make-process)
923 (setq err-buffer (generate-new-buffer " *notmuch-stderr*"))
924 ;; Emacs 25 and newer has `make-process', which allows
925 ;; redirecting stderr independently from stdout to a
926 ;; separate buffer. As this allows us to avoid using a
927 ;; temporary file and shell invocation, use it when
929 (setq proc (make-process
932 :command (cons command args)
933 :connection-type 'pipe
935 err-proc (get-buffer-process err-buffer))
936 (process-put proc 'err-buffer err-buffer)
938 (process-put err-proc 'err-file err-file)
939 (process-put err-proc 'err-buffer err-buffer)
940 (set-process-sentinel err-proc #'notmuch-start-notmuch-error-sentinel))
942 ;; On Emacs versions before 25, there is no way to capture
943 ;; stdout and stderr separately for asynchronous processes, or
944 ;; even to redirect stderr to a file, so we use a trivial shell
945 ;; wrapper to send stderr to a temporary file and clean things
946 ;; up in the sentinel.
947 (setq err-file (make-temp-file "nmerr"))
948 (let ((process-connection-type nil)) ;; Use a pipe
949 (setq proc (apply #'start-process name buffer
951 "exec 2>\"$1\"; shift; exec \"$0\" \"$@\""
952 command err-file args)))
953 (process-put proc 'err-file err-file))
955 (process-put proc 'sub-sentinel sentinel)
956 (process-put proc 'real-command (cons notmuch-command args))
957 (set-process-sentinel proc #'notmuch-start-notmuch-sentinel)
960 (defun notmuch-start-notmuch-sentinel (proc event)
961 "Process sentinel function used by `notmuch-start-notmuch'."
962 (let* ((err-file (process-get proc 'err-file))
963 (err-buffer (or (process-get proc 'err-buffer)
964 (find-file-noselect err-file)))
965 (err (when (not (zerop (buffer-size err-buffer)))
966 (with-current-buffer err-buffer (buffer-string))))
967 (sub-sentinel (process-get proc 'sub-sentinel))
968 (real-command (process-get proc 'real-command)))
971 ;; Invoke the sub-sentinel, if any
973 (funcall sub-sentinel proc event))
974 ;; Check the exit status. This will signal an error if the
975 ;; exit status is non-zero. Don't do this if the process
976 ;; buffer is dead since that means Emacs killed the process
977 ;; and there's no point in telling the user that (but we
978 ;; still check for and report stderr output below).
979 (when (buffer-live-p (process-buffer proc))
980 (notmuch-check-async-exit-status proc event real-command err))
981 ;; If that didn't signal an error, then any error output was
982 ;; really warning output. Show warnings, if any.
985 (with-current-buffer err-buffer
986 (goto-char (point-min))
988 ;; Show first line; stuff remaining lines in the
990 (let ((l1 (buffer-substring (point-min) (point))))
991 (skip-chars-forward "\n")
992 (cons l1 (unless (eobp)
993 (buffer-substring (point) (point-max)))))))))
995 (notmuch-logged-error (car warnings) (cdr warnings)))))
997 ;; Emacs behaves strangely if an error escapes from a sentinel,
998 ;; so turn errors into messages.
999 (message "%s" (error-message-string err))))
1000 (when err-file (ignore-errors (delete-file err-file)))))
1002 (defun notmuch-start-notmuch-error-sentinel (proc event)
1003 (let* ((err-file (process-get proc 'err-file))
1004 ;; When `make-process' is available, use the error buffer
1005 ;; associated with the process, otherwise the error file.
1006 (err-buffer (or (process-get proc 'err-buffer)
1007 (find-file-noselect err-file))))
1008 (when err-buffer (kill-buffer err-buffer))))
1010 ;; This variable is used only buffer local, but it needs to be
1011 ;; declared globally first to avoid compiler warnings.
1012 (defvar notmuch-show-process-crypto nil)
1013 (make-variable-buffer-local 'notmuch-show-process-crypto)
1015 (defun notmuch-interactive-region ()
1016 "Return the bounds of the current interactive region.
1018 This returns (BEG END), where BEG and END are the bounds of the
1019 region if the region is active, or both `point' otherwise."
1020 (if (region-active-p)
1021 (list (region-beginning) (region-end))
1022 (list (point) (point))))
1024 (define-obsolete-function-alias
1025 'notmuch-search-interactive-region
1026 'notmuch-interactive-region
1029 (provide 'notmuch-lib)
1031 ;;; notmuch-lib.el ends here