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