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