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