]> git.notmuchmail.org Git - notmuch/blob - emacs/notmuch-lib.el
emacs: Combine string faces and combine under existing faces
[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 '(("inbox" . "tag:inbox")
81                                     ("unread" . "tag:unread"))
82   "A list of saved searches to display."
83   :type '(alist :key-type string :value-type string)
84   :group 'notmuch-hello)
85
86 (defcustom notmuch-archive-tags '("-inbox")
87   "List of tag changes to apply to a message or a thread when it is archived.
88
89 Tags starting with \"+\" (or not starting with either \"+\" or
90 \"-\") in the list will be added, and tags starting with \"-\"
91 will be removed from the message or thread being archived.
92
93 For example, if you wanted to remove an \"inbox\" tag and add an
94 \"archived\" tag, you would set:
95     (\"-inbox\" \"+archived\")"
96   :type '(repeat string)
97   :group 'notmuch-search
98   :group 'notmuch-show)
99
100 ;; By default clicking on a button does not select the window
101 ;; containing the button (as opposed to clicking on a widget which
102 ;; does). This means that the button action is then executed in the
103 ;; current selected window which can cause problems if the button
104 ;; changes the buffer (e.g., id: links) or moves point.
105 ;;
106 ;; This provides a button type which overrides mouse-action so that
107 ;; the button's window is selected before the action is run. Other
108 ;; notmuch buttons can get the same behaviour by inheriting from this
109 ;; button type.
110 (define-button-type 'notmuch-button-type
111   'mouse-action (lambda (button)
112                   (select-window (posn-window (event-start last-input-event)))
113                   (button-activate button)))
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-escape-boolean-term (term)
165   "Escape a boolean term for use in a query.
166
167 The caller is responsible for prepending the term prefix and a
168 colon.  This performs minimal escaping in order to produce
169 user-friendly queries."
170
171   (save-match-data
172     (if (or (equal term "")
173             (string-match "[ ()]\\|^\"" term))
174         ;; Requires escaping
175         (concat "\"" (replace-regexp-in-string "\"" "\"\"" term t t) "\"")
176       term)))
177
178 (defun notmuch-id-to-query (id)
179   "Return a query that matches the message with id ID."
180   (concat "id:" (notmuch-escape-boolean-term id)))
181
182 ;;
183
184 (defun notmuch-common-do-stash (text)
185   "Common function to stash text in kill ring, and display in minibuffer."
186   (if text
187       (progn
188         (kill-new text)
189         (message "Stashed: %s" text))
190     ;; There is nothing to stash so stash an empty string so the user
191     ;; doesn't accidentally paste something else somewhere.
192     (kill-new "")
193     (message "Nothing to stash!")))
194
195 ;;
196
197 (defun notmuch-remove-if-not (predicate list)
198   "Return a copy of LIST with all items not satisfying PREDICATE removed."
199   (let (out)
200     (while list
201       (when (funcall predicate (car list))
202         (push (car list) out))
203       (setq list (cdr list)))
204     (nreverse out)))
205
206 ;; This lets us avoid compiling these replacement functions when emacs
207 ;; is sufficiently new enough to supply them alone. We do the macro
208 ;; treatment rather than just wrapping our defun calls in a when form
209 ;; specifically so that the compiler never sees the code on new emacs,
210 ;; (since the code is triggering warnings that we don't know how to get
211 ;; rid of.
212 ;;
213 ;; A more clever macro here would accept a condition and a list of forms.
214 (defmacro compile-on-emacs-prior-to-23 (form)
215   "Conditionally evaluate form only on emacs < emacs-23."
216   (list 'when (< emacs-major-version 23)
217         form))
218
219 (defun notmuch-split-content-type (content-type)
220   "Split content/type into 'content' and 'type'"
221   (split-string content-type "/"))
222
223 (defun notmuch-match-content-type (t1 t2)
224   "Return t if t1 and t2 are matching content types, taking wildcards into account"
225   (let ((st1 (notmuch-split-content-type t1))
226         (st2 (notmuch-split-content-type t2)))
227     (if (or (string= (cadr st1) "*")
228             (string= (cadr st2) "*"))
229         ;; Comparison of content types should be case insensitive.
230         (string= (downcase (car st1)) (downcase (car st2)))
231       (string= (downcase t1) (downcase t2)))))
232
233 (defvar notmuch-multipart/alternative-discouraged
234   '(
235     ;; Avoid HTML parts.
236     "text/html"
237     ;; multipart/related usually contain a text/html part and some associated graphics.
238     "multipart/related"
239     ))
240
241 (defun notmuch-multipart/alternative-choose (types)
242   "Return a list of preferred types from the given list of types"
243   ;; Based on `mm-preferred-alternative-precedence'.
244   (let ((seq types))
245     (dolist (pref (reverse notmuch-multipart/alternative-discouraged))
246       (dolist (elem (copy-sequence seq))
247         (when (string-match pref elem)
248           (setq seq (nconc (delete elem seq) (list elem))))))
249     seq))
250
251 (defun notmuch-parts-filter-by-type (parts type)
252   "Given a list of message parts, return a list containing the ones matching
253 the given type."
254   (remove-if-not
255    (lambda (part) (notmuch-match-content-type (plist-get part :content-type) type))
256    parts))
257
258 ;; Helper for parts which are generally not included in the default
259 ;; JSON output.
260 (defun notmuch-get-bodypart-internal (query part-number process-crypto)
261   (let ((args '("show" "--format=raw"))
262         (part-arg (format "--part=%s" part-number)))
263     (setq args (append args (list part-arg)))
264     (if process-crypto
265         (setq args (append args '("--decrypt"))))
266     (setq args (append args (list query)))
267     (with-temp-buffer
268       (let ((coding-system-for-read 'no-conversion))
269         (progn
270           (apply 'call-process (append (list notmuch-command nil (list t nil) nil) args))
271           (buffer-string))))))
272
273 (defun notmuch-get-bodypart-content (msg part nth process-crypto)
274   (or (plist-get part :content)
275       (notmuch-get-bodypart-internal (notmuch-id-to-query (plist-get msg :id)) nth process-crypto)))
276
277 ;; Workaround: The call to `mm-display-part' below triggers a bug in
278 ;; Emacs 24 if it attempts to use the shr renderer to display an HTML
279 ;; part with images in it (demonstrated in 24.1 and 24.2 on Debian and
280 ;; Fedora 17, though unreproducable in other configurations).
281 ;; `mm-shr' references the variable `gnus-inhibit-images' without
282 ;; first loading gnus-art, which defines it, resulting in a
283 ;; void-variable error.  Hence, we advise `mm-shr' to ensure gnus-art
284 ;; is loaded.
285 (if (>= emacs-major-version 24)
286     (defadvice mm-shr (before load-gnus-arts activate)
287       (require 'gnus-art nil t)
288       (ad-disable-advice 'mm-shr 'before 'load-gnus-arts)))
289
290 (defun notmuch-mm-display-part-inline (msg part nth content-type process-crypto)
291   "Use the mm-decode/mm-view functions to display a part in the
292 current buffer, if possible."
293   (let ((display-buffer (current-buffer)))
294     (with-temp-buffer
295       ;; In case there is :content, the content string is already converted
296       ;; into emacs internal format. `gnus-decoded' is a fake charset,
297       ;; which means no further decoding (to be done by mm- functions).
298       (let* ((charset (if (plist-member part :content)
299                           'gnus-decoded
300                         (plist-get part :content-charset)))
301              (handle (mm-make-handle (current-buffer) `(,content-type (charset . ,charset)))))
302         ;; If the user wants the part inlined, insert the content and
303         ;; test whether we are able to inline it (which includes both
304         ;; capability and suitability tests).
305         (when (mm-inlined-p handle)
306           (insert (notmuch-get-bodypart-content msg part nth process-crypto))
307           (when (mm-inlinable-p handle)
308             (set-buffer display-buffer)
309             (mm-display-part handle)
310             t))))))
311
312 ;; Converts a plist of headers to an alist of headers. The input plist should
313 ;; have symbols of the form :Header as keys, and the resulting alist will have
314 ;; symbols of the form 'Header as keys.
315 (defun notmuch-headers-plist-to-alist (plist)
316   (loop for (key value . rest) on plist by #'cddr
317         collect (cons (intern (substring (symbol-name key) 1)) value)))
318
319 (defun notmuch-face-ensure-list-form (face)
320   "Return FACE in face list form.
321
322 If FACE is already a face list, it will be returned as-is.  If
323 FACE is a face name or face plist, it will be returned as a
324 single element face list."
325   (if (and (listp face) (not (keywordp (car face))))
326       face
327     (list face)))
328
329 (defun notmuch-combine-face-text-property (start end face &optional below object)
330   "Combine FACE into the 'face text property between START and END.
331
332 This function combines FACE with any existing faces between START
333 and END in OBJECT (which defaults to the current buffer).
334 Attributes specified by FACE take precedence over existing
335 attributes unless BELOW is non-nil.  FACE must be a face name (a
336 symbol or string), a property list of face attributes, or a list
337 of these.  For convenience when applied to strings, this returns
338 OBJECT."
339
340   ;; A face property can have three forms: a face name (a string or
341   ;; symbol), a property list, or a list of these two forms.  In the
342   ;; list case, the faces will be combined, with the earlier faces
343   ;; taking precedent.  Here we canonicalize everything to list form
344   ;; to make it easy to combine.
345   (let ((pos start)
346         (face-list (notmuch-face-ensure-list-form face)))
347     (while (< pos end)
348       (let* ((cur (get-text-property pos 'face object))
349              (cur-list (notmuch-face-ensure-list-form cur))
350              (new (cond ((null cur-list) face)
351                         (below (append cur-list face-list))
352                         (t (append face-list cur-list))))
353              (next (next-single-property-change pos 'face object end)))
354         (put-text-property pos next 'face new object)
355         (setq pos next))))
356   object)
357
358 (defun notmuch-logged-error (msg &optional extra)
359   "Log MSG and EXTRA to *Notmuch errors* and signal MSG.
360
361 This logs MSG and EXTRA to the *Notmuch errors* buffer and
362 signals MSG as an error.  If EXTRA is non-nil, text referring the
363 user to the *Notmuch errors* buffer will be appended to the
364 signaled error.  This function does not return."
365
366   (with-current-buffer (get-buffer-create "*Notmuch errors*")
367     (goto-char (point-max))
368     (unless (bobp)
369       (newline))
370     (save-excursion
371       (insert "[" (current-time-string) "]\n" msg)
372       (unless (bolp)
373         (newline))
374       (when extra
375         (insert extra)
376         (unless (bolp)
377           (newline)))))
378   (error "%s" (concat msg (when extra
379                             " (see *Notmuch errors* for more details)"))))
380
381 (defun notmuch-check-async-exit-status (proc msg)
382   "If PROC exited abnormally, pop up an error buffer and signal an error.
383
384 This is a wrapper around `notmuch-check-exit-status' for
385 asynchronous process sentinels.  PROC and MSG must be the
386 arguments passed to the sentinel."
387   (let ((exit-status
388          (case (process-status proc)
389            ((exit) (process-exit-status proc))
390            ((signal) msg))))
391     (when exit-status
392       (notmuch-check-exit-status exit-status (process-command proc)))))
393
394 (defun notmuch-check-exit-status (exit-status command &optional output err-file)
395   "If EXIT-STATUS is non-zero, pop up an error buffer and signal an error.
396
397 If EXIT-STATUS is non-zero, pop up a notmuch error buffer
398 describing the error and signal an Elisp error.  EXIT-STATUS must
399 be a number indicating the exit status code of a process or a
400 string describing the signal that terminated the process (such as
401 returned by `call-process').  COMMAND must be a list giving the
402 command and its arguments.  OUTPUT, if provided, is a string
403 giving the output of command.  ERR-FILE, if provided, is the name
404 of a file containing the error output of command.  OUTPUT and the
405 contents of ERR-FILE will be included in the error message."
406
407   (cond
408    ((eq exit-status 0) t)
409    ((eq exit-status 20)
410     (notmuch-logged-error "notmuch CLI version mismatch
411 Emacs requested an older output format than supported by the notmuch CLI.
412 You may need to restart Emacs or upgrade your notmuch Emacs package."))
413    ((eq exit-status 21)
414     (notmuch-logged-error "notmuch CLI version mismatch
415 Emacs requested a newer output format than supported by the notmuch CLI.
416 You may need to restart Emacs or upgrade your notmuch package."))
417    (t
418     (let* ((err (when err-file
419                   (with-temp-buffer
420                     (insert-file-contents err-file)
421                     (unless (eobp)
422                       (buffer-string)))))
423            (extra
424             (concat
425              "command: " (mapconcat #'shell-quote-argument command " ") "\n"
426              (if (integerp exit-status)
427                  (format "exit status: %s\n" exit-status)
428                (format "exit signal: %s\n" exit-status))
429              (when err
430                (concat "stderr:\n" err))
431              (when output
432                (concat "stdout:\n" output)))))
433         (if err
434             ;; We have an error message straight from the CLI.
435             (notmuch-logged-error
436              (replace-regexp-in-string "\\s $" "" err) extra)
437           ;; We only have combined output from the CLI; don't inundate
438           ;; the user with it.  Mimic `process-lines'.
439           (notmuch-logged-error (format "%s exited with status %s"
440                                         (car command) exit-status)
441                                 extra))
442         ;; `notmuch-logged-error' does not return.
443         ))))
444
445 (defun notmuch-call-notmuch-json (&rest args)
446   "Invoke `notmuch-command' with `args' and return the parsed JSON output.
447
448 The returned output will represent objects using property lists
449 and arrays as lists.  If notmuch exits with a non-zero status,
450 this will pop up a buffer containing notmuch's output and signal
451 an error."
452
453   (with-temp-buffer
454     (let ((err-file (make-temp-file "nmerr")))
455       (unwind-protect
456           (let ((status (apply #'call-process
457                                notmuch-command nil (list t err-file) nil args)))
458             (notmuch-check-exit-status status (cons notmuch-command args)
459                                        (buffer-string) err-file)
460             (goto-char (point-min))
461             (let ((json-object-type 'plist)
462                   (json-array-type 'list)
463                   (json-false 'nil))
464               (json-read)))
465         (delete-file err-file)))))
466
467 ;; Compatibility functions for versions of emacs before emacs 23.
468 ;;
469 ;; Both functions here were copied from emacs 23 with the following copyright:
470 ;;
471 ;; Copyright (C) 1985, 1986, 1992, 1994, 1995, 1999, 2000, 2001, 2002, 2003,
472 ;;   2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
473 ;;
474 ;; and under the GPL version 3 (or later) exactly as notmuch itself.
475 (compile-on-emacs-prior-to-23
476  (defun apply-partially (fun &rest args)
477    "Return a function that is a partial application of FUN to ARGS.
478 ARGS is a list of the first N arguments to pass to FUN.
479 The result is a new function which does the same as FUN, except that
480 the first N arguments are fixed at the values with which this function
481 was called."
482    (lexical-let ((fun fun) (args1 args))
483      (lambda (&rest args2) (apply fun (append args1 args2))))))
484
485 (compile-on-emacs-prior-to-23
486  (defun mouse-event-p (object)
487    "Return non-nil if OBJECT is a mouse click event."
488    (memq (event-basic-type object) '(mouse-1 mouse-2 mouse-3 mouse-movement))))
489
490 ;; This variable is used only buffer local, but it needs to be
491 ;; declared globally first to avoid compiler warnings.
492 (defvar notmuch-show-process-crypto nil)
493 (make-variable-buffer-local 'notmuch-show-process-crypto)
494
495 ;; Incremental JSON parsing
496
497 ;; These two variables are internal variables to the parsing
498 ;; routines. They are always used buffer local but need to be declared
499 ;; globally to avoid compiler warnings.
500
501 (defvar notmuch-json-parser nil
502   "Internal incremental JSON parser object: local to the buffer being parsed.")
503
504 (defvar notmuch-json-state nil
505   "State of the internal JSON parser: local to the buffer being parsed.")
506
507 (defun notmuch-json-create-parser (buffer)
508   "Return a streaming JSON parser that consumes input from BUFFER.
509
510 This parser is designed to read streaming JSON whose structure is
511 known to the caller.  Like a typical JSON parsing interface, it
512 provides a function to read a complete JSON value from the input.
513 However, it extends this with an additional function that
514 requires the next value in the input to be a compound value and
515 descends into it, allowing its elements to be read one at a time
516 or further descended into.  Both functions can return 'retry to
517 indicate that not enough input is available.
518
519 The parser always consumes input from BUFFER's point.  Hence, the
520 caller is allowed to delete and data before point and may
521 resynchronize after an error by moving point."
522
523   (list buffer
524         ;; Terminator stack: a stack of characters that indicate the
525         ;; end of the compound values enclosing point
526         '()
527         ;; Next: One of
528         ;; * 'expect-value if the next token must be a value, but a
529         ;;   value has not yet been reached
530         ;; * 'value if point is at the beginning of a value
531         ;; * 'expect-comma if the next token must be a comma
532         'expect-value
533         ;; Allow terminator: non-nil if the next token may be a
534         ;; terminator
535         nil
536         ;; Partial parse position: If state is 'value, a marker for
537         ;; the position of the partial parser or nil if no partial
538         ;; parsing has happened yet
539         nil
540         ;; Partial parse state: If state is 'value, the current
541         ;; `parse-partial-sexp' state
542         nil))
543
544 (defmacro notmuch-json-buffer (jp) `(first ,jp))
545 (defmacro notmuch-json-term-stack (jp) `(second ,jp))
546 (defmacro notmuch-json-next (jp) `(third ,jp))
547 (defmacro notmuch-json-allow-term (jp) `(fourth ,jp))
548 (defmacro notmuch-json-partial-pos (jp) `(fifth ,jp))
549 (defmacro notmuch-json-partial-state (jp) `(sixth ,jp))
550
551 (defvar notmuch-json-syntax-table
552   (let ((table (make-syntax-table)))
553     ;; The standard syntax table is what we need except that "." needs
554     ;; to have word syntax instead of punctuation syntax.
555     (modify-syntax-entry ?. "w" table)
556     table)
557   "Syntax table used for incremental JSON parsing.")
558
559 (defun notmuch-json-scan-to-value (jp)
560   ;; Helper function that consumes separators, terminators, and
561   ;; whitespace from point.  Returns nil if it successfully reached
562   ;; the beginning of a value, 'end if it consumed a terminator, or
563   ;; 'retry if not enough input was available to reach a value.  Upon
564   ;; nil return, (notmuch-json-next jp) is always 'value.
565
566   (if (eq (notmuch-json-next jp) 'value)
567       ;; We're already at a value
568       nil
569     ;; Drive the state toward 'expect-value
570     (skip-chars-forward " \t\r\n")
571     (or (when (eobp) 'retry)
572         ;; Test for the terminator for the current compound
573         (when (and (notmuch-json-allow-term jp)
574                    (eq (char-after) (car (notmuch-json-term-stack jp))))
575           ;; Consume it and expect a comma or terminator next
576           (forward-char)
577           (setf (notmuch-json-term-stack jp) (cdr (notmuch-json-term-stack jp))
578                 (notmuch-json-next jp) 'expect-comma
579                 (notmuch-json-allow-term jp) t)
580           'end)
581         ;; Test for a separator
582         (when (eq (notmuch-json-next jp) 'expect-comma)
583           (when (/= (char-after) ?,)
584             (signal 'json-readtable-error (list "expected ','")))
585           ;; Consume it, switch to 'expect-value, and disallow a
586           ;; terminator
587           (forward-char)
588           (skip-chars-forward " \t\r\n")
589           (setf (notmuch-json-next jp) 'expect-value
590                 (notmuch-json-allow-term jp) nil)
591           ;; We moved point, so test for eobp again and fall through
592           ;; to the next test if there's more input
593           (when (eobp) 'retry))
594         ;; Next must be 'expect-value and we know this isn't
595         ;; whitespace, EOB, or a terminator, so point must be on a
596         ;; value
597         (progn
598           (assert (eq (notmuch-json-next jp) 'expect-value))
599           (setf (notmuch-json-next jp) 'value)
600           nil))))
601
602 (defun notmuch-json-begin-compound (jp)
603   "Parse the beginning of a compound value and traverse inside it.
604
605 Returns 'retry if there is insufficient input to parse the
606 beginning of the compound.  If this is able to parse the
607 beginning of a compound, it moves point past the token that opens
608 the compound and returns t.  Later calls to `notmuch-json-read'
609 will return the compound's elements.
610
611 Entering JSON objects is currently unimplemented."
612
613   (with-current-buffer (notmuch-json-buffer jp)
614     ;; Disallow terminators
615     (setf (notmuch-json-allow-term jp) nil)
616     ;; Save "next" so we can restore it if there's a syntax error
617     (let ((saved-next (notmuch-json-next jp)))
618       (or (notmuch-json-scan-to-value jp)
619           (if (/= (char-after) ?\[)
620               (progn
621                 (setf (notmuch-json-next jp) saved-next)
622                 (signal 'json-readtable-error (list "expected '['")))
623             (forward-char)
624             (push ?\] (notmuch-json-term-stack jp))
625             ;; Expect a value or terminator next
626             (setf (notmuch-json-next jp) 'expect-value
627                   (notmuch-json-allow-term jp) t)
628             t)))))
629
630 (defun notmuch-json-read (jp)
631   "Parse the value at point in JP's buffer.
632
633 Returns 'retry if there is insufficient input to parse a complete
634 JSON value (though it may still move point over separators or
635 whitespace).  If the parser is currently inside a compound value
636 and the next token ends the list or object, this moves point just
637 past the terminator and returns 'end.  Otherwise, this moves
638 point to just past the end of the value and returns the value."
639
640   (with-current-buffer (notmuch-json-buffer jp)
641     (or
642      ;; Get to a value state
643      (notmuch-json-scan-to-value jp)
644
645      ;; Can we parse a complete value?
646      (let ((complete
647             (if (looking-at "[-+0-9tfn]")
648                 ;; This is a number or a keyword, so the partial
649                 ;; parser isn't going to help us because a truncated
650                 ;; number or keyword looks like a complete symbol to
651                 ;; it.  Look for something that clearly ends it.
652                 (save-excursion
653                   (skip-chars-forward "^]},: \t\r\n")
654                   (not (eobp)))
655
656               ;; We're looking at a string, object, or array, which we
657               ;; can partial parse.  If we just reached the value, set
658               ;; up the partial parser.
659               (when (null (notmuch-json-partial-state jp))
660                 (setf (notmuch-json-partial-pos jp) (point-marker)))
661
662               ;; Extend the partial parse until we either reach EOB or
663               ;; get the whole value
664               (save-excursion
665                 (let ((pstate
666                        (with-syntax-table notmuch-json-syntax-table
667                          (parse-partial-sexp
668                           (notmuch-json-partial-pos jp) (point-max) 0 nil
669                           (notmuch-json-partial-state jp)))))
670                   ;; A complete value is available if we've reached
671                   ;; depth 0 or less and encountered a complete
672                   ;; subexpression.
673                   (if (and (<= (first pstate) 0) (third pstate))
674                       t
675                     ;; Not complete.  Update the partial parser state
676                     (setf (notmuch-json-partial-pos jp) (point-marker)
677                           (notmuch-json-partial-state jp) pstate)
678                     nil))))))
679
680        (if (not complete)
681            'retry
682          ;; We have a value.  Reset the partial parse state and expect
683          ;; a comma or terminator after the value.
684          (setf (notmuch-json-next jp) 'expect-comma
685                (notmuch-json-allow-term jp) t
686                (notmuch-json-partial-pos jp) nil
687                (notmuch-json-partial-state jp) nil)
688          ;; Parse the value
689          (let ((json-object-type 'plist)
690                (json-array-type 'list)
691                (json-false nil))
692            (json-read)))))))
693
694 (defun notmuch-json-eof (jp)
695   "Signal a json-error if there is more data in JP's buffer.
696
697 Moves point to the beginning of any trailing data or to the end
698 of the buffer if there is only trailing whitespace."
699
700   (with-current-buffer (notmuch-json-buffer jp)
701     (skip-chars-forward " \t\r\n")
702     (unless (eobp)
703       (signal 'json-error (list "Trailing garbage following JSON data")))))
704
705 (defun notmuch-json-parse-partial-list (result-function error-function results-buf)
706   "Parse a partial JSON list from current buffer.
707
708 This function consumes a JSON list from the current buffer,
709 applying RESULT-FUNCTION in buffer RESULT-BUFFER to each complete
710 value in the list.  It operates incrementally and should be
711 called whenever the buffer has been extended with additional
712 data.
713
714 If there is a syntax error, this will attempt to resynchronize
715 with the input and will apply ERROR-FUNCTION in buffer
716 RESULT-BUFFER to any input that was skipped.
717
718 It sets up all the needed internal variables: the caller just
719 needs to call it with point in the same place that the parser
720 left it."
721   (let (done)
722     (unless (local-variable-p 'notmuch-json-parser)
723       (set (make-local-variable 'notmuch-json-parser)
724            (notmuch-json-create-parser (current-buffer)))
725       (set (make-local-variable 'notmuch-json-state) 'begin))
726     (while (not done)
727       (condition-case nil
728           (case notmuch-json-state
729                 ((begin)
730                  ;; Enter the results list
731                  (if (eq (notmuch-json-begin-compound
732                           notmuch-json-parser) 'retry)
733                      (setq done t)
734                    (setq notmuch-json-state 'result)))
735                 ((result)
736                  ;; Parse a result
737                  (let ((result (notmuch-json-read notmuch-json-parser)))
738                    (case result
739                          ((retry) (setq done t))
740                          ((end) (setq notmuch-json-state 'end))
741                          (otherwise (with-current-buffer results-buf
742                                       (funcall result-function result))))))
743                 ((end)
744                  ;; Any trailing data is unexpected
745                  (notmuch-json-eof notmuch-json-parser)
746                  (setq done t)))
747         (json-error
748          ;; Do our best to resynchronize and ensure forward
749          ;; progress
750          (let ((bad (buffer-substring (line-beginning-position)
751                                       (line-end-position))))
752            (forward-line)
753            (with-current-buffer results-buf
754              (funcall error-function "%s" bad))))))
755     ;; Clear out what we've parsed
756     (delete-region (point-min) (point))))
757
758
759
760
761 (provide 'notmuch-lib)
762
763 ;; Local Variables:
764 ;; byte-compile-warnings: (not cl-functions)
765 ;; End: