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