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