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