]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-lib.el
emacs: add support for reversing notmuch-search-archive-thread tag changes
[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 'json)
27 (require 'cl)
28
29 (defvar notmuch-command "notmuch"
30   "Command to run the notmuch binary.")
31
32 (defgroup notmuch nil
33   "Notmuch mail reader for Emacs."
34   :group 'mail)
35
36 (defgroup notmuch-hello nil
37   "Overview of saved searches, tags, etc."
38   :group 'notmuch)
39
40 (defgroup notmuch-search nil
41   "Searching and sorting mail."
42   :group 'notmuch)
43
44 (defgroup notmuch-show nil
45   "Showing messages and threads."
46   :group 'notmuch)
47
48 (defgroup notmuch-send nil
49   "Sending messages from Notmuch."
50   :group 'notmuch)
51
52 (custom-add-to-group 'notmuch-send 'message 'custom-group)
53
54 (defgroup notmuch-crypto nil
55   "Processing and display of cryptographic MIME parts."
56   :group 'notmuch)
57
58 (defgroup notmuch-hooks nil
59   "Running custom code on well-defined occasions."
60   :group 'notmuch)
61
62 (defgroup notmuch-external nil
63   "Running external commands from within Notmuch."
64   :group 'notmuch)
65
66 (defgroup notmuch-faces nil
67   "Graphical attributes for displaying text"
68   :group 'notmuch)
69
70 (defcustom notmuch-search-oldest-first t
71   "Show the oldest mail first when searching."
72   :type 'boolean
73   :group 'notmuch-search)
74
75 ;;
76
77 (defvar notmuch-search-history nil
78   "Variable to store notmuch searches history.")
79
80 (defcustom notmuch-saved-searches nil
81   "A list of saved searches to display."
82   :type '(alist :key-type string :value-type string)
83   :group 'notmuch-hello)
84
85 (defcustom notmuch-archive-tags '("-inbox")
86   "List of tag changes to apply to a message or a thread when it is archived.
87
88 Tags starting with \"+\" (or not starting with either \"+\" or
89 \"-\") in the list will be added, and tags starting with \"-\"
90 will be removed from the message or thread being archived.
91
92 For example, if you wanted to remove an \"inbox\" tag and add an
93 \"archived\" tag, you would set:
94     (\"-inbox\" \"+archived\")"
95   :type '(repeat string)
96   :group 'notmuch-search
97   :group 'notmuch-show)
98
99 (defvar notmuch-folders nil
100   "Deprecated name for what is now known as `notmuch-saved-searches'.")
101
102 (defun notmuch-saved-searches ()
103   "Common function for querying the notmuch-saved-searches variable.
104
105 We do this as a function to support the old name of the
106 variable (`notmuch-folders') as well as for the default value if
107 the user hasn't set this variable with the old or new value."
108   (if notmuch-saved-searches
109       notmuch-saved-searches
110     (if notmuch-folders
111         notmuch-folders
112       '(("inbox" . "tag:inbox")
113         ("unread" . "tag:unread")))))
114
115 (defun notmuch-version ()
116   "Return a string with the notmuch version number."
117   (let ((long-string
118          ;; Trim off the trailing newline.
119          (substring (shell-command-to-string
120                      (concat notmuch-command " --version"))
121                     0 -1)))
122     (if (string-match "^notmuch\\( version\\)? \\(.*\\)$"
123                       long-string)
124         (match-string 2 long-string)
125       "unknown")))
126
127 (defun notmuch-config-get (item)
128   "Return a value from the notmuch configuration."
129   ;; Trim off the trailing newline
130   (substring (shell-command-to-string
131               (concat notmuch-command " config get " item))
132               0 -1))
133
134 (defun notmuch-database-path ()
135   "Return the database.path value from the notmuch configuration."
136   (notmuch-config-get "database.path"))
137
138 (defun notmuch-user-name ()
139   "Return the user.name value from the notmuch configuration."
140   (notmuch-config-get "user.name"))
141
142 (defun notmuch-user-primary-email ()
143   "Return the user.primary_email value from the notmuch configuration."
144   (notmuch-config-get "user.primary_email"))
145
146 (defun notmuch-user-other-email ()
147   "Return the user.other_email value (as a list) from the notmuch configuration."
148   (split-string (notmuch-config-get "user.other_email") "\n"))
149
150 (defun notmuch-kill-this-buffer ()
151   "Kill the current buffer."
152   (interactive)
153   (kill-buffer (current-buffer)))
154
155 (defun notmuch-prettify-subject (subject)
156   ;; This function is used by `notmuch-search-process-filter' which
157   ;; requires that we not disrupt its' matching state.
158   (save-match-data
159     (if (and subject
160              (string-match "^[ \t]*$" subject))
161         "[No Subject]"
162       subject)))
163
164 (defun notmuch-id-to-query (id)
165   "Return a query that matches the message with id ID."
166   (concat "id:\"" (replace-regexp-in-string "\"" "\"\"" id t t) "\""))
167
168 ;;
169
170 (defun notmuch-common-do-stash (text)
171   "Common function to stash text in kill ring, and display in minibuffer."
172   (kill-new text)
173   (message "Stashed: %s" text))
174
175 ;;
176
177 (defun notmuch-remove-if-not (predicate list)
178   "Return a copy of LIST with all items not satisfying PREDICATE removed."
179   (let (out)
180     (while list
181       (when (funcall predicate (car list))
182         (push (car list) out))
183       (setq list (cdr list)))
184     (nreverse out)))
185
186 ;; This lets us avoid compiling these replacement functions when emacs
187 ;; is sufficiently new enough to supply them alone. We do the macro
188 ;; treatment rather than just wrapping our defun calls in a when form
189 ;; specifically so that the compiler never sees the code on new emacs,
190 ;; (since the code is triggering warnings that we don't know how to get
191 ;; rid of.
192 ;;
193 ;; A more clever macro here would accept a condition and a list of forms.
194 (defmacro compile-on-emacs-prior-to-23 (form)
195   "Conditionally evaluate form only on emacs < emacs-23."
196   (list 'when (< emacs-major-version 23)
197         form))
198
199 (defun notmuch-split-content-type (content-type)
200   "Split content/type into 'content' and 'type'"
201   (split-string content-type "/"))
202
203 (defun notmuch-match-content-type (t1 t2)
204   "Return t if t1 and t2 are matching content types, taking wildcards into account"
205   (let ((st1 (notmuch-split-content-type t1))
206         (st2 (notmuch-split-content-type t2)))
207     (if (or (string= (cadr st1) "*")
208             (string= (cadr st2) "*"))
209         ;; Comparison of content types should be case insensitive.
210         (string= (downcase (car st1)) (downcase (car st2)))
211       (string= (downcase t1) (downcase t2)))))
212
213 (defvar notmuch-multipart/alternative-discouraged
214   '(
215     ;; Avoid HTML parts.
216     "text/html"
217     ;; multipart/related usually contain a text/html part and some associated graphics.
218     "multipart/related"
219     ))
220
221 (defun notmuch-multipart/alternative-choose (types)
222   "Return a list of preferred types from the given list of types"
223   ;; Based on `mm-preferred-alternative-precedence'.
224   (let ((seq types))
225     (dolist (pref (reverse notmuch-multipart/alternative-discouraged))
226       (dolist (elem (copy-sequence seq))
227         (when (string-match pref elem)
228           (setq seq (nconc (delete elem seq) (list elem))))))
229     seq))
230
231 (defun notmuch-parts-filter-by-type (parts type)
232   "Given a list of message parts, return a list containing the ones matching
233 the given type."
234   (remove-if-not
235    (lambda (part) (notmuch-match-content-type (plist-get part :content-type) type))
236    parts))
237
238 ;; Helper for parts which are generally not included in the default
239 ;; JSON output.
240 (defun notmuch-get-bodypart-internal (query part-number process-crypto)
241   (let ((args '("show" "--format=raw"))
242         (part-arg (format "--part=%s" part-number)))
243     (setq args (append args (list part-arg)))
244     (if process-crypto
245         (setq args (append args '("--decrypt"))))
246     (setq args (append args (list query)))
247     (with-temp-buffer
248       (let ((coding-system-for-read 'no-conversion))
249         (progn
250           (apply 'call-process (append (list notmuch-command nil (list t nil) nil) args))
251           (buffer-string))))))
252
253 (defun notmuch-get-bodypart-content (msg part nth process-crypto)
254   (or (plist-get part :content)
255       (notmuch-get-bodypart-internal (notmuch-id-to-query (plist-get msg :id)) nth process-crypto)))
256
257 (defun notmuch-mm-display-part-inline (msg part nth content-type process-crypto)
258   "Use the mm-decode/mm-view functions to display a part in the
259 current buffer, if possible."
260   (let ((display-buffer (current-buffer)))
261     (with-temp-buffer
262       ;; In case there is :content, the content string is already converted
263       ;; into emacs internal format. `gnus-decoded' is a fake charset,
264       ;; which means no further decoding (to be done by mm- functions).
265       (let* ((charset (if (plist-member part :content)
266                           'gnus-decoded
267                         (plist-get part :content-charset)))
268              (handle (mm-make-handle (current-buffer) `(,content-type (charset . ,charset)))))
269         ;; If the user wants the part inlined, insert the content and
270         ;; test whether we are able to inline it (which includes both
271         ;; capability and suitability tests).
272         (when (mm-inlined-p handle)
273           (insert (notmuch-get-bodypart-content msg part nth process-crypto))
274           (when (mm-inlinable-p handle)
275             (set-buffer display-buffer)
276             (mm-display-part handle)
277             t))))))
278
279 ;; Converts a plist of headers to an alist of headers. The input plist should
280 ;; have symbols of the form :Header as keys, and the resulting alist will have
281 ;; symbols of the form 'Header as keys.
282 (defun notmuch-headers-plist-to-alist (plist)
283   (loop for (key value . rest) on plist by #'cddr
284         collect (cons (intern (substring (symbol-name key) 1)) value)))
285
286 (defun notmuch-combine-face-text-property (start end face)
287   "Combine FACE into the 'face text property between START and END.
288
289 This function combines FACE with any existing faces between START
290 and END.  Attributes specified by FACE take precedence over
291 existing attributes.  FACE must be a face name (a symbol or
292 string), a property list of face attributes, or a list of these."
293
294   (let ((pos start))
295     (while (< pos end)
296       (let ((cur (get-text-property pos 'face))
297             (next (next-single-property-change pos 'face nil end)))
298         (put-text-property pos next 'face (cons face cur))
299         (setq pos next)))))
300
301 ;; Compatibility functions for versions of emacs before emacs 23.
302 ;;
303 ;; Both functions here were copied from emacs 23 with the following copyright:
304 ;;
305 ;; Copyright (C) 1985, 1986, 1992, 1994, 1995, 1999, 2000, 2001, 2002, 2003,
306 ;;   2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
307 ;;
308 ;; and under the GPL version 3 (or later) exactly as notmuch itself.
309 (compile-on-emacs-prior-to-23
310  (defun apply-partially (fun &rest args)
311    "Return a function that is a partial application of FUN to ARGS.
312 ARGS is a list of the first N arguments to pass to FUN.
313 The result is a new function which does the same as FUN, except that
314 the first N arguments are fixed at the values with which this function
315 was called."
316    (lexical-let ((fun fun) (args1 args))
317      (lambda (&rest args2) (apply fun (append args1 args2))))))
318
319 (compile-on-emacs-prior-to-23
320  (defun mouse-event-p (object)
321    "Return non-nil if OBJECT is a mouse click event."
322    (memq (event-basic-type object) '(mouse-1 mouse-2 mouse-3 mouse-movement))))
323
324 ;; This variable is used only buffer local, but it needs to be
325 ;; declared globally first to avoid compiler warnings.
326 (defvar notmuch-show-process-crypto nil)
327 (make-variable-buffer-local 'notmuch-show-process-crypto)
328
329 ;; Incremental JSON parsing
330
331 (defun notmuch-json-create-parser (buffer)
332   "Return a streaming JSON parser that consumes input from BUFFER.
333
334 This parser is designed to read streaming JSON whose structure is
335 known to the caller.  Like a typical JSON parsing interface, it
336 provides a function to read a complete JSON value from the input.
337 However, it extends this with an additional function that
338 requires the next value in the input to be a compound value and
339 descends into it, allowing its elements to be read one at a time
340 or further descended into.  Both functions can return 'retry to
341 indicate that not enough input is available.
342
343 The parser always consumes input from BUFFER's point.  Hence, the
344 caller is allowed to delete and data before point and may
345 resynchronize after an error by moving point."
346
347   (list buffer
348         ;; Terminator stack: a stack of characters that indicate the
349         ;; end of the compound values enclosing point
350         '()
351         ;; Next: One of
352         ;; * 'expect-value if the next token must be a value, but a
353         ;;   value has not yet been reached
354         ;; * 'value if point is at the beginning of a value
355         ;; * 'expect-comma if the next token must be a comma
356         'expect-value
357         ;; Allow terminator: non-nil if the next token may be a
358         ;; terminator
359         nil
360         ;; Partial parse position: If state is 'value, a marker for
361         ;; the position of the partial parser or nil if no partial
362         ;; parsing has happened yet
363         nil
364         ;; Partial parse state: If state is 'value, the current
365         ;; `parse-partial-sexp' state
366         nil))
367
368 (defmacro notmuch-json-buffer (jp) `(first ,jp))
369 (defmacro notmuch-json-term-stack (jp) `(second ,jp))
370 (defmacro notmuch-json-next (jp) `(third ,jp))
371 (defmacro notmuch-json-allow-term (jp) `(fourth ,jp))
372 (defmacro notmuch-json-partial-pos (jp) `(fifth ,jp))
373 (defmacro notmuch-json-partial-state (jp) `(sixth ,jp))
374
375 (defvar notmuch-json-syntax-table
376   (let ((table (make-syntax-table)))
377     ;; The standard syntax table is what we need except that "." needs
378     ;; to have word syntax instead of punctuation syntax.
379     (modify-syntax-entry ?. "w" table)
380     table)
381   "Syntax table used for incremental JSON parsing.")
382
383 (defun notmuch-json-scan-to-value (jp)
384   ;; Helper function that consumes separators, terminators, and
385   ;; whitespace from point.  Returns nil if it successfully reached
386   ;; the beginning of a value, 'end if it consumed a terminator, or
387   ;; 'retry if not enough input was available to reach a value.  Upon
388   ;; nil return, (notmuch-json-next jp) is always 'value.
389
390   (if (eq (notmuch-json-next jp) 'value)
391       ;; We're already at a value
392       nil
393     ;; Drive the state toward 'expect-value
394     (skip-chars-forward " \t\r\n")
395     (or (when (eobp) 'retry)
396         ;; Test for the terminator for the current compound
397         (when (and (notmuch-json-allow-term jp)
398                    (eq (char-after) (car (notmuch-json-term-stack jp))))
399           ;; Consume it and expect a comma or terminator next
400           (forward-char)
401           (setf (notmuch-json-term-stack jp) (cdr (notmuch-json-term-stack jp))
402                 (notmuch-json-next jp) 'expect-comma
403                 (notmuch-json-allow-term jp) t)
404           'end)
405         ;; Test for a separator
406         (when (eq (notmuch-json-next jp) 'expect-comma)
407           (when (/= (char-after) ?,)
408             (signal 'json-readtable-error (list "expected ','")))
409           ;; Consume it, switch to 'expect-value, and disallow a
410           ;; terminator
411           (forward-char)
412           (skip-chars-forward " \t\r\n")
413           (setf (notmuch-json-next jp) 'expect-value
414                 (notmuch-json-allow-term jp) nil)
415           ;; We moved point, so test for eobp again and fall through
416           ;; to the next test if there's more input
417           (when (eobp) 'retry))
418         ;; Next must be 'expect-value and we know this isn't
419         ;; whitespace, EOB, or a terminator, so point must be on a
420         ;; value
421         (progn
422           (assert (eq (notmuch-json-next jp) 'expect-value))
423           (setf (notmuch-json-next jp) 'value)
424           nil))))
425
426 (defun notmuch-json-begin-compound (jp)
427   "Parse the beginning of a compound value and traverse inside it.
428
429 Returns 'retry if there is insufficient input to parse the
430 beginning of the compound.  If this is able to parse the
431 beginning of a compound, it moves point past the token that opens
432 the compound and returns t.  Later calls to `notmuch-json-read'
433 will return the compound's elements.
434
435 Entering JSON objects is currently unimplemented."
436
437   (with-current-buffer (notmuch-json-buffer jp)
438     ;; Disallow terminators
439     (setf (notmuch-json-allow-term jp) nil)
440     (or (notmuch-json-scan-to-value jp)
441         (if (/= (char-after) ?\[)
442             (signal 'json-readtable-error (list "expected '['"))
443           (forward-char)
444           (push ?\] (notmuch-json-term-stack jp))
445           ;; Expect a value or terminator next
446           (setf (notmuch-json-next jp) 'expect-value
447                 (notmuch-json-allow-term jp) t)
448           t))))
449
450 (defun notmuch-json-read (jp)
451   "Parse the value at point in JP's buffer.
452
453 Returns 'retry if there is insufficient input to parse a complete
454 JSON value (though it may still move point over separators or
455 whitespace).  If the parser is currently inside a compound value
456 and the next token ends the list or object, this moves point just
457 past the terminator and returns 'end.  Otherwise, this moves
458 point to just past the end of the value and returns the value."
459
460   (with-current-buffer (notmuch-json-buffer jp)
461     (or
462      ;; Get to a value state
463      (notmuch-json-scan-to-value jp)
464
465      ;; Can we parse a complete value?
466      (let ((complete
467             (if (looking-at "[-+0-9tfn]")
468                 ;; This is a number or a keyword, so the partial
469                 ;; parser isn't going to help us because a truncated
470                 ;; number or keyword looks like a complete symbol to
471                 ;; it.  Look for something that clearly ends it.
472                 (save-excursion
473                   (skip-chars-forward "^]},: \t\r\n")
474                   (not (eobp)))
475
476               ;; We're looking at a string, object, or array, which we
477               ;; can partial parse.  If we just reached the value, set
478               ;; up the partial parser.
479               (when (null (notmuch-json-partial-state jp))
480                 (setf (notmuch-json-partial-pos jp) (point-marker)))
481
482               ;; Extend the partial parse until we either reach EOB or
483               ;; get the whole value
484               (save-excursion
485                 (let ((pstate
486                        (with-syntax-table notmuch-json-syntax-table
487                          (parse-partial-sexp
488                           (notmuch-json-partial-pos jp) (point-max) 0 nil
489                           (notmuch-json-partial-state jp)))))
490                   ;; A complete value is available if we've reached
491                   ;; depth 0 or less and encountered a complete
492                   ;; subexpression.
493                   (if (and (<= (first pstate) 0) (third pstate))
494                       t
495                     ;; Not complete.  Update the partial parser state
496                     (setf (notmuch-json-partial-pos jp) (point-marker)
497                           (notmuch-json-partial-state jp) pstate)
498                     nil))))))
499
500        (if (not complete)
501            'retry
502          ;; We have a value.  Reset the partial parse state and expect
503          ;; a comma or terminator after the value.
504          (setf (notmuch-json-next jp) 'expect-comma
505                (notmuch-json-allow-term jp) t
506                (notmuch-json-partial-pos jp) nil
507                (notmuch-json-partial-state jp) nil)
508          ;; Parse the value
509          (let ((json-object-type 'plist)
510                (json-array-type 'list)
511                (json-false nil))
512            (json-read)))))))
513
514 (defun notmuch-json-eof (jp)
515   "Signal a json-error if there is more data in JP's buffer.
516
517 Moves point to the beginning of any trailing data or to the end
518 of the buffer if there is only trailing whitespace."
519
520   (with-current-buffer (notmuch-json-buffer jp)
521     (skip-chars-forward " \t\r\n")
522     (unless (eobp)
523       (signal 'json-error (list "Trailing garbage following JSON data")))))
524
525 (provide 'notmuch-lib)
526
527 ;; Local Variables:
528 ;; byte-compile-warnings: (not cl-functions)
529 ;; End: