]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-lib.el
emacs: dropped rest of now-unused JSON functionality
[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 <http://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 (require 'mm-view)
25 (require 'mm-decode)
26 (require 'cl)
27
28 (defvar notmuch-command "notmuch"
29   "Command to run the notmuch binary.")
30
31 (defgroup notmuch nil
32   "Notmuch mail reader for Emacs."
33   :group 'mail)
34
35 (defgroup notmuch-hello nil
36   "Overview of saved searches, tags, etc."
37   :group 'notmuch)
38
39 (defgroup notmuch-search nil
40   "Searching and sorting mail."
41   :group 'notmuch)
42
43 (defgroup notmuch-show nil
44   "Showing messages and threads."
45   :group 'notmuch)
46
47 (defgroup notmuch-send nil
48   "Sending messages from Notmuch."
49   :group 'notmuch)
50
51 (custom-add-to-group 'notmuch-send 'message 'custom-group)
52
53 (defgroup notmuch-crypto nil
54   "Processing and display of cryptographic MIME parts."
55   :group 'notmuch)
56
57 (defgroup notmuch-hooks nil
58   "Running custom code on well-defined occasions."
59   :group 'notmuch)
60
61 (defgroup notmuch-external nil
62   "Running external commands from within Notmuch."
63   :group 'notmuch)
64
65 (defgroup notmuch-faces nil
66   "Graphical attributes for displaying text"
67   :group 'notmuch)
68
69 (defcustom notmuch-search-oldest-first t
70   "Show the oldest mail first when searching.
71
72 This variable defines the default sort order for displaying
73 search results. Note that any filtered searches created by
74 `notmuch-search-filter' retain the search order of the parent
75 search."
76   :type 'boolean
77   :group 'notmuch-search)
78
79 ;;
80
81 (defvar notmuch-search-history nil
82   "Variable to store notmuch searches history.")
83
84 (defcustom notmuch-saved-searches '(("inbox" . "tag:inbox")
85                                     ("unread" . "tag:unread"))
86   "A list of saved searches to display."
87   :type '(alist :key-type string :value-type string)
88   :group 'notmuch-hello)
89
90 (defcustom notmuch-archive-tags '("-inbox")
91   "List of tag changes to apply to a message or a thread when it is archived.
92
93 Tags starting with \"+\" (or not starting with either \"+\" or
94 \"-\") in the list will be added, and tags starting with \"-\"
95 will be removed from the message or thread being archived.
96
97 For example, if you wanted to remove an \"inbox\" tag and add an
98 \"archived\" tag, you would set:
99     (\"-inbox\" \"+archived\")"
100   :type '(repeat string)
101   :group 'notmuch-search
102   :group 'notmuch-show)
103
104 ;; By default clicking on a button does not select the window
105 ;; containing the button (as opposed to clicking on a widget which
106 ;; does). This means that the button action is then executed in the
107 ;; current selected window which can cause problems if the button
108 ;; changes the buffer (e.g., id: links) or moves point.
109 ;;
110 ;; This provides a button type which overrides mouse-action so that
111 ;; the button's window is selected before the action is run. Other
112 ;; notmuch buttons can get the same behaviour by inheriting from this
113 ;; button type.
114 (define-button-type 'notmuch-button-type
115   'mouse-action (lambda (button)
116                   (select-window (posn-window (event-start last-input-event)))
117                   (button-activate button)))
118
119 (defun notmuch-command-to-string (&rest args)
120   "Synchronously invoke \"notmuch\" with the given list of arguments.
121
122 If notmuch exits with a non-zero status, output from the process
123 will appear in a buffer named \"*Notmuch errors*\" and an error
124 will be signaled.
125
126 Otherwise the output will be returned"
127   (with-temp-buffer
128     (let* ((status (apply #'call-process notmuch-command nil t nil args))
129            (output (buffer-string)))
130       (notmuch-check-exit-status status (cons notmuch-command args) output)
131       output)))
132
133 (defun notmuch-version ()
134   "Return a string with the notmuch version number."
135   (let ((long-string
136          ;; Trim off the trailing newline.
137          (substring (notmuch-command-to-string "--version") 0 -1)))
138     (if (string-match "^notmuch\\( version\\)? \\(.*\\)$"
139                       long-string)
140         (match-string 2 long-string)
141       "unknown")))
142
143 (defun notmuch-config-get (item)
144   "Return a value from the notmuch configuration."
145   ;; Trim off the trailing newline
146   (substring (notmuch-command-to-string "config" "get" item) 0 -1))
147
148 (defun notmuch-database-path ()
149   "Return the database.path value from the notmuch configuration."
150   (notmuch-config-get "database.path"))
151
152 (defun notmuch-user-name ()
153   "Return the user.name value from the notmuch configuration."
154   (notmuch-config-get "user.name"))
155
156 (defun notmuch-user-primary-email ()
157   "Return the user.primary_email value from the notmuch configuration."
158   (notmuch-config-get "user.primary_email"))
159
160 (defun notmuch-user-other-email ()
161   "Return the user.other_email value (as a list) from the notmuch configuration."
162   (split-string (notmuch-config-get "user.other_email") "\n"))
163
164 (defun notmuch-kill-this-buffer ()
165   "Kill the current buffer."
166   (interactive)
167   (kill-buffer (current-buffer)))
168
169 (defun notmuch-prettify-subject (subject)
170   ;; This function is used by `notmuch-search-process-filter' which
171   ;; requires that we not disrupt its' matching state.
172   (save-match-data
173     (if (and subject
174              (string-match "^[ \t]*$" subject))
175         "[No Subject]"
176       subject)))
177
178 (defun notmuch-escape-boolean-term (term)
179   "Escape a boolean term for use in a query.
180
181 The caller is responsible for prepending the term prefix and a
182 colon.  This performs minimal escaping in order to produce
183 user-friendly queries."
184
185   (save-match-data
186     (if (or (equal term "")
187             (string-match "[ ()]\\|^\"" term))
188         ;; Requires escaping
189         (concat "\"" (replace-regexp-in-string "\"" "\"\"" term t t) "\"")
190       term)))
191
192 (defun notmuch-id-to-query (id)
193   "Return a query that matches the message with id ID."
194   (concat "id:" (notmuch-escape-boolean-term id)))
195
196 ;;
197
198 (defun notmuch-common-do-stash (text)
199   "Common function to stash text in kill ring, and display in minibuffer."
200   (if text
201       (progn
202         (kill-new text)
203         (message "Stashed: %s" text))
204     ;; There is nothing to stash so stash an empty string so the user
205     ;; doesn't accidentally paste something else somewhere.
206     (kill-new "")
207     (message "Nothing to stash!")))
208
209 ;;
210
211 (defun notmuch-remove-if-not (predicate list)
212   "Return a copy of LIST with all items not satisfying PREDICATE removed."
213   (let (out)
214     (while list
215       (when (funcall predicate (car list))
216         (push (car list) out))
217       (setq list (cdr list)))
218     (nreverse out)))
219
220 (defun notmuch-split-content-type (content-type)
221   "Split content/type into 'content' and 'type'"
222   (split-string content-type "/"))
223
224 (defun notmuch-match-content-type (t1 t2)
225   "Return t if t1 and t2 are matching content types, taking wildcards into account"
226   (let ((st1 (notmuch-split-content-type t1))
227         (st2 (notmuch-split-content-type t2)))
228     (if (or (string= (cadr st1) "*")
229             (string= (cadr st2) "*"))
230         ;; Comparison of content types should be case insensitive.
231         (string= (downcase (car st1)) (downcase (car st2)))
232       (string= (downcase t1) (downcase t2)))))
233
234 (defvar notmuch-multipart/alternative-discouraged
235   '(
236     ;; Avoid HTML parts.
237     "text/html"
238     ;; multipart/related usually contain a text/html part and some associated graphics.
239     "multipart/related"
240     ))
241
242 (defun notmuch-multipart/alternative-choose (types)
243   "Return a list of preferred types from the given list of types"
244   ;; Based on `mm-preferred-alternative-precedence'.
245   (let ((seq types))
246     (dolist (pref (reverse notmuch-multipart/alternative-discouraged))
247       (dolist (elem (copy-sequence seq))
248         (when (string-match pref elem)
249           (setq seq (nconc (delete elem seq) (list elem))))))
250     seq))
251
252 (defun notmuch-parts-filter-by-type (parts type)
253   "Given a list of message parts, return a list containing the ones matching
254 the given type."
255   (remove-if-not
256    (lambda (part) (notmuch-match-content-type (plist-get part :content-type) type))
257    parts))
258
259 ;; Helper for parts which are generally not included in the default
260 ;; SEXP output.
261 (defun notmuch-get-bodypart-internal (query part-number process-crypto)
262   (let ((args '("show" "--format=raw"))
263         (part-arg (format "--part=%s" part-number)))
264     (setq args (append args (list part-arg)))
265     (if process-crypto
266         (setq args (append args '("--decrypt"))))
267     (setq args (append args (list query)))
268     (with-temp-buffer
269       (let ((coding-system-for-read 'no-conversion))
270         (progn
271           (apply 'call-process (append (list notmuch-command nil (list t nil) nil) args))
272           (buffer-string))))))
273
274 (defun notmuch-get-bodypart-content (msg part nth process-crypto)
275   (or (plist-get part :content)
276       (notmuch-get-bodypart-internal (notmuch-id-to-query (plist-get msg :id)) nth process-crypto)))
277
278 ;; Workaround: The call to `mm-display-part' below triggers a bug in
279 ;; Emacs 24 if it attempts to use the shr renderer to display an HTML
280 ;; part with images in it (demonstrated in 24.1 and 24.2 on Debian and
281 ;; Fedora 17, though unreproducable in other configurations).
282 ;; `mm-shr' references the variable `gnus-inhibit-images' without
283 ;; first loading gnus-art, which defines it, resulting in a
284 ;; void-variable error.  Hence, we advise `mm-shr' to ensure gnus-art
285 ;; is loaded.
286 (if (>= emacs-major-version 24)
287     (defadvice mm-shr (before load-gnus-arts activate)
288       (require 'gnus-art nil t)
289       (ad-disable-advice 'mm-shr 'before 'load-gnus-arts)))
290
291 (defun notmuch-mm-display-part-inline (msg part nth content-type process-crypto)
292   "Use the mm-decode/mm-view functions to display a part in the
293 current buffer, if possible."
294   (let ((display-buffer (current-buffer)))
295     (with-temp-buffer
296       ;; In case there is :content, the content string is already converted
297       ;; into emacs internal format. `gnus-decoded' is a fake charset,
298       ;; which means no further decoding (to be done by mm- functions).
299       (let* ((charset (if (plist-member part :content)
300                           'gnus-decoded
301                         (plist-get part :content-charset)))
302              (handle (mm-make-handle (current-buffer) `(,content-type (charset . ,charset)))))
303         ;; If the user wants the part inlined, insert the content and
304         ;; test whether we are able to inline it (which includes both
305         ;; capability and suitability tests).
306         (when (mm-inlined-p handle)
307           (insert (notmuch-get-bodypart-content msg part nth process-crypto))
308           (when (mm-inlinable-p handle)
309             (set-buffer display-buffer)
310             (mm-display-part handle)
311             t))))))
312
313 ;; Converts a plist of headers to an alist of headers. The input plist should
314 ;; have symbols of the form :Header as keys, and the resulting alist will have
315 ;; symbols of the form 'Header as keys.
316 (defun notmuch-headers-plist-to-alist (plist)
317   (loop for (key value . rest) on plist by #'cddr
318         collect (cons (intern (substring (symbol-name key) 1)) value)))
319
320 (defun notmuch-face-ensure-list-form (face)
321   "Return FACE in face list form.
322
323 If FACE is already a face list, it will be returned as-is.  If
324 FACE is a face name or face plist, it will be returned as a
325 single element face list."
326   (if (and (listp face) (not (keywordp (car face))))
327       face
328     (list face)))
329
330 (defun notmuch-combine-face-text-property (start end face &optional below object)
331   "Combine FACE into the 'face text property between START and END.
332
333 This function combines FACE with any existing faces between START
334 and END in OBJECT (which defaults to the current buffer).
335 Attributes specified by FACE take precedence over existing
336 attributes unless BELOW is non-nil.  FACE must be a face name (a
337 symbol or string), a property list of face attributes, or a list
338 of these.  For convenience when applied to strings, this returns
339 OBJECT."
340
341   ;; A face property can have three forms: a face name (a string or
342   ;; symbol), a property list, or a list of these two forms.  In the
343   ;; list case, the faces will be combined, with the earlier faces
344   ;; taking precedent.  Here we canonicalize everything to list form
345   ;; to make it easy to combine.
346   (let ((pos start)
347         (face-list (notmuch-face-ensure-list-form face)))
348     (while (< pos end)
349       (let* ((cur (get-text-property pos 'face object))
350              (cur-list (notmuch-face-ensure-list-form cur))
351              (new (cond ((null cur-list) face)
352                         (below (append cur-list face-list))
353                         (t (append face-list cur-list))))
354              (next (next-single-property-change pos 'face object end)))
355         (put-text-property pos next 'face new object)
356         (setq pos next))))
357   object)
358
359 (defun notmuch-combine-face-text-property-string (string face &optional below)
360   (notmuch-combine-face-text-property
361    0
362    (length string)
363    face
364    below
365    string))
366
367 (defun notmuch-map-text-property (start end prop func &optional object)
368   "Transform text property PROP using FUNC.
369
370 Applies FUNC to each distinct value of the text property PROP
371 between START and END of OBJECT, setting PROP to the value
372 returned by FUNC."
373   (while (< start end)
374     (let ((value (get-text-property start prop object))
375           (next (next-single-property-change start prop object end)))
376       (put-text-property start next prop (funcall func value) object)
377       (setq start next))))
378
379 (defun notmuch-logged-error (msg &optional extra)
380   "Log MSG and EXTRA to *Notmuch errors* and signal MSG.
381
382 This logs MSG and EXTRA to the *Notmuch errors* buffer and
383 signals MSG as an error.  If EXTRA is non-nil, text referring the
384 user to the *Notmuch errors* buffer will be appended to the
385 signaled error.  This function does not return."
386
387   (with-current-buffer (get-buffer-create "*Notmuch errors*")
388     (goto-char (point-max))
389     (unless (bobp)
390       (newline))
391     (save-excursion
392       (insert "[" (current-time-string) "]\n" msg)
393       (unless (bolp)
394         (newline))
395       (when extra
396         (insert extra)
397         (unless (bolp)
398           (newline)))))
399   (error "%s" (concat msg (when extra
400                             " (see *Notmuch errors* for more details)"))))
401
402 (defun notmuch-check-async-exit-status (proc msg &optional command err-file)
403   "If PROC exited abnormally, pop up an error buffer and signal an error.
404
405 This is a wrapper around `notmuch-check-exit-status' for
406 asynchronous process sentinels.  PROC and MSG must be the
407 arguments passed to the sentinel.  COMMAND and ERR-FILE, if
408 provided, are passed to `notmuch-check-exit-status'.  If COMMAND
409 is not provided, it is taken from `process-command'."
410   (let ((exit-status
411          (case (process-status proc)
412            ((exit) (process-exit-status proc))
413            ((signal) msg))))
414     (when exit-status
415       (notmuch-check-exit-status exit-status (or command (process-command proc))
416                                  nil err-file))))
417
418 (defun notmuch-check-exit-status (exit-status command &optional output err-file)
419   "If EXIT-STATUS is non-zero, pop up an error buffer and signal an error.
420
421 If EXIT-STATUS is non-zero, pop up a notmuch error buffer
422 describing the error and signal an Elisp error.  EXIT-STATUS must
423 be a number indicating the exit status code of a process or a
424 string describing the signal that terminated the process (such as
425 returned by `call-process').  COMMAND must be a list giving the
426 command and its arguments.  OUTPUT, if provided, is a string
427 giving the output of command.  ERR-FILE, if provided, is the name
428 of a file containing the error output of command.  OUTPUT and the
429 contents of ERR-FILE will be included in the error message."
430
431   (cond
432    ((eq exit-status 0) t)
433    ((eq exit-status 20)
434     (notmuch-logged-error "notmuch CLI version mismatch
435 Emacs requested an older output format than supported by the notmuch CLI.
436 You may need to restart Emacs or upgrade your notmuch Emacs package."))
437    ((eq exit-status 21)
438     (notmuch-logged-error "notmuch CLI version mismatch
439 Emacs requested a newer output format than supported by the notmuch CLI.
440 You may need to restart Emacs or upgrade your notmuch package."))
441    (t
442     (let* ((err (when err-file
443                   (with-temp-buffer
444                     (insert-file-contents err-file)
445                     (unless (eobp)
446                       (buffer-string)))))
447            (extra
448             (concat
449              "command: " (mapconcat #'shell-quote-argument command " ") "\n"
450              (if (integerp exit-status)
451                  (format "exit status: %s\n" exit-status)
452                (format "exit signal: %s\n" exit-status))
453              (when err
454                (concat "stderr:\n" err))
455              (when output
456                (concat "stdout:\n" output)))))
457         (if err
458             ;; We have an error message straight from the CLI.
459             (notmuch-logged-error
460              (replace-regexp-in-string "[ \n\r\t\f]*\\'" "" err) extra)
461           ;; We only have combined output from the CLI; don't inundate
462           ;; the user with it.  Mimic `process-lines'.
463           (notmuch-logged-error (format "%s exited with status %s"
464                                         (car command) exit-status)
465                                 extra))
466         ;; `notmuch-logged-error' does not return.
467         ))))
468
469 (defun notmuch-call-notmuch-sexp (&rest args)
470   "Invoke `notmuch-command' with ARGS and return the parsed S-exp output.
471
472 If notmuch exits with a non-zero status, this will pop up a
473 buffer containing notmuch's output and signal an error."
474
475   (with-temp-buffer
476     (let ((err-file (make-temp-file "nmerr")))
477       (unwind-protect
478           (let ((status (apply #'call-process
479                                notmuch-command nil (list t err-file) nil args)))
480             (notmuch-check-exit-status status (cons notmuch-command args)
481                                        (buffer-string) err-file)
482             (goto-char (point-min))
483             (read (current-buffer)))
484         (delete-file err-file)))))
485
486 (defun notmuch-start-notmuch (name buffer sentinel &rest args)
487   "Start and return an asynchronous notmuch command.
488
489 This starts and returns an asynchronous process running
490 `notmuch-command' with ARGS.  The exit status is checked via
491 `notmuch-check-async-exit-status'.  Output written to stderr is
492 redirected and displayed when the process exits (even if the
493 process exits successfully).  NAME and BUFFER are the same as in
494 `start-process'.  SENTINEL is a process sentinel function to call
495 when the process exits, or nil for none.  The caller must *not*
496 invoke `set-process-sentinel' directly on the returned process,
497 as that will interfere with the handling of stderr and the exit
498 status."
499
500   ;; There is no way (as of Emacs 24.3) to capture stdout and stderr
501   ;; separately for asynchronous processes, or even to redirect stderr
502   ;; to a file, so we use a trivial shell wrapper to send stderr to a
503   ;; temporary file and clean things up in the sentinel.
504   (let* ((err-file (make-temp-file "nmerr"))
505          ;; Use a pipe
506          (process-connection-type nil)
507          ;; Find notmuch using Emacs' `exec-path'
508          (command (or (executable-find notmuch-command)
509                       (error "command not found: %s" notmuch-command)))
510          (proc (apply #'start-process name buffer
511                       "/bin/sh" "-c"
512                       "exec 2>\"$1\"; shift; exec \"$0\" \"$@\""
513                       command err-file args)))
514     (process-put proc 'err-file err-file)
515     (process-put proc 'sub-sentinel sentinel)
516     (process-put proc 'real-command (cons notmuch-command args))
517     (set-process-sentinel proc #'notmuch-start-notmuch-sentinel)
518     proc))
519
520 (defun notmuch-start-notmuch-sentinel (proc event)
521   (let ((err-file (process-get proc 'err-file))
522         (sub-sentinel (process-get proc 'sub-sentinel))
523         (real-command (process-get proc 'real-command)))
524     (condition-case err
525         (progn
526           ;; Invoke the sub-sentinel, if any
527           (when sub-sentinel
528             (funcall sub-sentinel proc event))
529           ;; Check the exit status.  This will signal an error if the
530           ;; exit status is non-zero.  Don't do this if the process
531           ;; buffer is dead since that means Emacs killed the process
532           ;; and there's no point in telling the user that (but we
533           ;; still check for and report stderr output below).
534           (when (buffer-live-p (process-buffer proc))
535             (notmuch-check-async-exit-status proc event real-command err-file))
536           ;; If that didn't signal an error, then any error output was
537           ;; really warning output.  Show warnings, if any.
538           (let ((warnings
539                  (with-temp-buffer
540                    (unless (= (second (insert-file-contents err-file)) 0)
541                      (end-of-line)
542                      ;; Show first line; stuff remaining lines in the
543                      ;; errors buffer.
544                      (let ((l1 (buffer-substring (point-min) (point))))
545                        (skip-chars-forward "\n")
546                        (cons l1 (unless (eobp)
547                                   (buffer-substring (point) (point-max)))))))))
548             (when warnings
549               (notmuch-logged-error (car warnings) (cdr warnings)))))
550       (error
551        ;; Emacs behaves strangely if an error escapes from a sentinel,
552        ;; so turn errors into messages.
553        (message "%s" (error-message-string err))))
554     (ignore-errors (delete-file err-file))))
555
556 ;; This variable is used only buffer local, but it needs to be
557 ;; declared globally first to avoid compiler warnings.
558 (defvar notmuch-show-process-crypto nil)
559 (make-variable-buffer-local 'notmuch-show-process-crypto)
560
561
562 (provide 'notmuch-lib)
563
564 ;; Local Variables:
565 ;; byte-compile-warnings: (not cl-functions)
566 ;; End: