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