Document reserved keys
[emacs.git] / lisp / emacs-lisp / syntax.el
blob6106720f7a56047ff8f73b7ac0073a0aa81fb25e
1 ;;; syntax.el --- helper functions to find syntactic context -*- lexical-binding: t -*-
3 ;; Copyright (C) 2000-2018 Free Software Foundation, Inc.
5 ;; Maintainer: emacs-devel@gnu.org
6 ;; Keywords: internal
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; The main exported function is `syntax-ppss'. You might also need
26 ;; to call `syntax-ppss-flush-cache' or to add it to
27 ;; before-change-functions'(although this is automatically done by
28 ;; syntax-ppss when needed, but that might fail if syntax-ppss is
29 ;; called in a context where before-change-functions is temporarily
30 ;; let-bound to nil).
32 ;;; Todo:
34 ;; - do something about the case where the syntax-table is changed.
35 ;; This typically happens with tex-mode and its `$' operator.
36 ;; - new functions `syntax-state', ... to replace uses of parse-partial-state
37 ;; with something higher-level (similar to syntax-ppss-context).
38 ;; - interaction with mmm-mode.
40 ;;; Code:
42 ;; Note: PPSS stands for `parse-partial-sexp state'
44 (eval-when-compile (require 'cl-lib))
46 ;;; Applying syntax-table properties where needed.
48 (defvar syntax-propertize-function nil
49 ;; Rather than a -functions hook, this is a -function because it's easier
50 ;; to do a single scan than several scans: with multiple scans, one cannot
51 ;; assume that the text before point has been propertized, so syntax-ppss
52 ;; gives unreliable results (and stores them in its cache to boot, so we'd
53 ;; have to flush that cache between each function, and we couldn't use
54 ;; syntax-ppss-flush-cache since that would not only flush the cache but also
55 ;; reset syntax-propertize--done which should not be done in this case).
56 "Mode-specific function to apply `syntax-table' text properties.
57 It is the work horse of `syntax-propertize', which is called by things like
58 Font-Lock and indentation.
60 It is given two arguments, START and END: the start and end of the text to
61 which `syntax-table' might need to be applied. Major modes can use this to
62 override the buffer's syntax table for special syntactic constructs that
63 cannot be handled just by the buffer's syntax-table.
65 The specified function may call `syntax-ppss' on any position
66 before END, but it should not call `syntax-ppss-flush-cache',
67 which means that it should not call `syntax-ppss' on some
68 position and later modify the buffer on some earlier position.")
70 (defvar syntax-propertize-chunk-size 500)
72 (defvar syntax-propertize-extend-region-functions
73 '(syntax-propertize-wholelines)
74 "Special hook run just before proceeding to propertize a region.
75 This is used to allow major modes to help `syntax-propertize' find safe buffer
76 positions as beginning and end of the propertized region. Its most common use
77 is to solve the problem of /identification/ of multiline elements by providing
78 a function that tries to find such elements and move the boundaries such that
79 they do not fall in the middle of one.
80 Each function is called with two arguments (START and END) and it should return
81 either a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
82 These functions are run in turn repeatedly until they all return nil.
83 Put first the functions more likely to cause a change and cheaper to compute.")
84 ;; Mark it as a special hook which doesn't use any global setting
85 ;; (i.e. doesn't obey the element t in the buffer-local value).
86 (make-variable-buffer-local 'syntax-propertize-extend-region-functions)
88 (defun syntax-propertize-wholelines (start end)
89 (goto-char start)
90 (cons (line-beginning-position)
91 (progn (goto-char end)
92 (if (bolp) (point) (line-beginning-position 2)))))
94 (defun syntax-propertize-multiline (beg end)
95 "Let `syntax-propertize' pay attention to the syntax-multiline property."
96 (when (and (> beg (point-min))
97 (get-text-property (1- beg) 'syntax-multiline))
98 (setq beg (or (previous-single-property-change beg 'syntax-multiline)
99 (point-min))))
101 (when (get-text-property end 'syntax-multiline)
102 (setq end (or (text-property-any end (point-max)
103 'syntax-multiline nil)
104 (point-max))))
105 (cons beg end))
107 (defun syntax-propertize--shift-groups (re n)
108 (replace-regexp-in-string
109 "\\\\(\\?\\([0-9]+\\):"
110 (lambda (s)
111 (replace-match
112 (number-to-string (+ n (string-to-number (match-string 1 s))))
113 t t s 1))
114 re t t))
116 (defmacro syntax-propertize-precompile-rules (&rest rules)
117 "Return a precompiled form of RULES to pass to `syntax-propertize-rules'.
118 The arg RULES can be of the same form as in `syntax-propertize-rules'.
119 The return value is an object that can be passed as a rule to
120 `syntax-propertize-rules'.
121 I.e. this is useful only when you want to share rules among several
122 `syntax-propertize-function's."
123 (declare (debug syntax-propertize-rules))
124 ;; Precompile? Yeah, right!
125 ;; Seriously, tho, this is a macro for 2 reasons:
126 ;; - we could indeed do some pre-compilation at some point in the future,
127 ;; e.g. fi/when we switch to a DFA-based implementation of
128 ;; syntax-propertize-rules.
129 ;; - this lets Edebug properly annotate the expressions inside RULES.
130 `',rules)
132 (defmacro syntax-propertize-rules (&rest rules)
133 "Make a function that applies RULES for use in `syntax-propertize-function'.
134 The function will scan the buffer, applying the rules where they match.
135 The buffer is scanned a single time, like \"lex\" would, rather than once
136 per rule.
138 Each RULE can be a symbol, in which case that symbol's value should be,
139 at macro-expansion time, a precompiled set of rules, as returned
140 by `syntax-propertize-precompile-rules'.
142 Otherwise, RULE should have the form (REGEXP HIGHLIGHT1 ... HIGHLIGHTn), where
143 REGEXP is an expression (evaluated at time of macro-expansion) that returns
144 a regexp, and where HIGHLIGHTs have the form (NUMBER SYNTAX) which means to
145 apply the property SYNTAX to the chars matched by the subgroup NUMBER
146 of the regular expression, if NUMBER did match.
147 SYNTAX is an expression that returns a value to apply as `syntax-table'
148 property. Some expressions are handled specially:
149 - if SYNTAX is a string, then it is converted with `string-to-syntax';
150 - if SYNTAX has the form (prog1 EXP . EXPS) then the value returned by EXP
151 will be applied to the buffer before running EXPS and if EXP is a string it
152 is also converted with `string-to-syntax'.
153 The SYNTAX expression is responsible to save the `match-data' if needed
154 for subsequent HIGHLIGHTs.
155 Also SYNTAX is free to move point, in which case RULES may not be applied to
156 some parts of the text or may be applied several times to other parts.
158 Note: back-references in REGEXPs do not work."
159 (declare (debug (&rest &or symbolp ;FIXME: edebug this eval step.
160 (form &rest
161 (numberp
162 [&or stringp ;FIXME: Use &wrap
163 ("prog1" [&or stringp def-form] def-body)
164 def-form])))))
165 (let ((newrules nil))
166 (while rules
167 (if (symbolp (car rules))
168 (setq rules (append (symbol-value (pop rules)) rules))
169 (push (pop rules) newrules)))
170 (setq rules (nreverse newrules)))
171 (let* ((offset 0)
172 (branches '())
173 ;; We'd like to use a real DFA-based lexer, usually, but since Emacs
174 ;; doesn't have one yet, we fallback on building one large regexp
175 ;; and use groups to determine which branch of the regexp matched.
177 (mapconcat
178 (lambda (rule)
179 (let* ((orig-re (eval (car rule)))
180 (re orig-re))
181 (when (and (assq 0 rule) (cdr rules))
182 ;; If there's more than 1 rule, and the rule want to apply
183 ;; highlight to match 0, create an extra group to be able to
184 ;; tell when *this* match 0 has succeeded.
185 (cl-incf offset)
186 (setq re (concat "\\(" re "\\)")))
187 (setq re (syntax-propertize--shift-groups re offset))
188 (let ((code '())
189 (condition
190 (cond
191 ((assq 0 rule) (if (zerop offset) t
192 `(match-beginning ,offset)))
193 ((null (cddr rule))
194 `(match-beginning ,(+ offset (car (cadr rule)))))
196 `(or ,@(mapcar
197 (lambda (case)
198 `(match-beginning ,(+ offset (car case))))
199 (cdr rule))))))
200 (nocode t)
201 (offset offset))
202 ;; If some of the subgroup rules include Elisp code, then we
203 ;; need to set the match-data so it's consistent with what the
204 ;; code expects. If not, then we can simply use shifted
205 ;; offset in our own code.
206 (unless (zerop offset)
207 (dolist (case (cdr rule))
208 (unless (stringp (cadr case))
209 (setq nocode nil)))
210 (unless nocode
211 (push `(let ((md (match-data 'ints)))
212 ;; Keep match 0 as is, but shift everything else.
213 (setcdr (cdr md) (nthcdr ,(* (1+ offset) 2) md))
214 (set-match-data md))
215 code)
216 (setq offset 0)))
217 ;; Now construct the code for each subgroup rules.
218 (dolist (case (cdr rule))
219 (cl-assert (null (cddr case)))
220 (let* ((gn (+ offset (car case)))
221 (action (nth 1 case))
222 (thiscode
223 (cond
224 ((stringp action)
225 `((put-text-property
226 (match-beginning ,gn) (match-end ,gn)
227 'syntax-table
228 ',(string-to-syntax action))))
229 ((eq (car-safe action) 'ignore)
230 (cdr action))
231 ((eq (car-safe action) 'prog1)
232 (if (stringp (nth 1 action))
233 `((put-text-property
234 (match-beginning ,gn) (match-end ,gn)
235 'syntax-table
236 ',(string-to-syntax (nth 1 action)))
237 ,@(nthcdr 2 action))
238 `((let ((mb (match-beginning ,gn))
239 (me (match-end ,gn))
240 (syntax ,(nth 1 action)))
241 (if syntax
242 (put-text-property
243 mb me 'syntax-table syntax))
244 ,@(nthcdr 2 action)))))
246 `((let ((mb (match-beginning ,gn))
247 (me (match-end ,gn))
248 (syntax ,action))
249 (if syntax
250 (put-text-property
251 mb me 'syntax-table syntax))))))))
253 (if (or (not (cddr rule)) (zerop gn))
254 (setq code (nconc (nreverse thiscode) code))
255 (push `(if (match-beginning ,gn)
256 ;; Try and generate clean code with no
257 ;; extraneous progn.
258 ,(if (null (cdr thiscode))
259 (car thiscode)
260 `(progn ,@thiscode)))
261 code))))
262 (push (cons condition (nreverse code))
263 branches))
264 (cl-incf offset (regexp-opt-depth orig-re))
265 re))
266 rules
267 "\\|")))
268 `(lambda (start end)
269 (goto-char start)
270 (while (and (< (point) end)
271 (re-search-forward ,re end t))
272 (cond ,@(nreverse branches))))))
274 (defun syntax-propertize-via-font-lock (keywords)
275 "Propertize for syntax using font-lock syntax.
276 KEYWORDS obeys the format used in `font-lock-syntactic-keywords'.
277 The return value is a function (with two parameters, START and
278 END) suitable for `syntax-propertize-function'."
279 (lambda (start end)
280 (with-no-warnings
281 (let ((font-lock-syntactic-keywords keywords))
282 (font-lock-fontify-syntactic-keywords-region start end)
283 ;; In case it was eval'd/compiled.
284 (setq keywords font-lock-syntactic-keywords)))))
286 (defun syntax-propertize (pos)
287 "Ensure that syntax-table properties are set until POS (a buffer point)."
288 (when (< syntax-propertize--done pos)
289 (if (null syntax-propertize-function)
290 (setq syntax-propertize--done (max (point-max) pos))
291 ;; (message "Needs to syntax-propertize from %s to %s"
292 ;; syntax-propertize--done pos)
293 (set (make-local-variable 'parse-sexp-lookup-properties) t)
294 (when (< syntax-propertize--done (point-min))
295 ;; *Usually* syntax-propertize is called via syntax-ppss which
296 ;; takes care of adding syntax-ppss-flush-cache to b-c-f, but this
297 ;; is not *always* the case, so since we share a single "flush" function
298 ;; between syntax-ppss and syntax-propertize, we also have to make
299 ;; sure the flush function is installed here (bug#29767).
300 (add-hook 'before-change-functions
301 #'syntax-ppss-flush-cache t t))
302 (save-excursion
303 (with-silent-modifications
304 (make-local-variable 'syntax-propertize--done) ;Just in case!
305 (let* ((start (max (min syntax-propertize--done (point-max))
306 (point-min)))
307 (end (max pos
308 (min (point-max)
309 (+ start syntax-propertize-chunk-size))))
310 (funs syntax-propertize-extend-region-functions))
311 (while funs
312 (let ((new (funcall (pop funs) start end))
313 ;; Avoid recursion!
314 (syntax-propertize--done most-positive-fixnum))
315 (if (or (null new)
316 (and (>= (car new) start) (<= (cdr new) end)))
318 (setq start (car new))
319 (setq end (cdr new))
320 ;; If there's been a change, we should go through the
321 ;; list again since this new position may
322 ;; warrant a different answer from one of the funs we've
323 ;; already seen.
324 (unless (eq funs
325 (cdr syntax-propertize-extend-region-functions))
326 (setq funs syntax-propertize-extend-region-functions)))))
327 ;; Flush ppss cache between the original value of `start' and that
328 ;; set above by syntax-propertize-extend-region-functions.
329 (syntax-ppss-flush-cache start)
330 ;; Move the limit before calling the function, so the function
331 ;; can use syntax-ppss.
332 (setq syntax-propertize--done end)
333 ;; (message "syntax-propertizing from %s to %s" start end)
334 (remove-text-properties start end
335 '(syntax-table nil syntax-multiline nil))
336 ;; Avoid recursion!
337 (let ((syntax-propertize--done most-positive-fixnum))
338 (funcall syntax-propertize-function start end))))))))
340 ;;; Link syntax-propertize with syntax.c.
342 (defvar syntax-propertize-chunks
343 ;; We're not sure how far we'll go. In my tests, using chunks of 2000
344 ;; brings to overhead to something negligible. Passing ‘charpos’ directly
345 ;; also works (basically works line-by-line) but results in an overhead which
346 ;; I thought was a bit too high (like around 50%).
347 2000)
349 (defun internal--syntax-propertize (charpos)
350 ;; FIXME: Called directly from C.
351 (save-match-data
352 (syntax-propertize (min (+ syntax-propertize-chunks charpos) (point-max)))))
354 ;;; Incrementally compute and memoize parser state.
356 (defsubst syntax-ppss-depth (ppss)
357 (nth 0 ppss))
359 (defun syntax-ppss-toplevel-pos (ppss)
360 "Get the latest syntactically outermost position found in a syntactic scan.
361 PPSS is a scan state, as returned by `parse-partial-sexp' or `syntax-ppss'.
362 An \"outermost position\" means one that it is outside of any syntactic entity:
363 outside of any parentheses, comments, or strings encountered in the scan.
364 If no such position is recorded in PPSS (because the end of the scan was
365 itself at the outermost level), return nil."
366 ;; BEWARE! We rely on the undocumented 9th field. The 9th field currently
367 ;; contains the list of positions of the enclosing open-parens.
368 ;; I.e. those positions are outside of any string/comment and the first of
369 ;; those is outside of any paren (i.e. corresponds to a nil ppss).
370 ;; If this list is empty but we are in a string or comment, then the 8th
371 ;; field contains a similar "toplevel" position.
372 (or (car (nth 9 ppss))
373 (nth 8 ppss)))
375 (defsubst syntax-ppss-context (ppss)
376 (cond
377 ((nth 3 ppss) 'string)
378 ((nth 4 ppss) 'comment)
379 (t nil)))
381 (defvar syntax-ppss-max-span 20000
382 "Threshold below which cache info is deemed unnecessary.
383 We try to make sure that cache entries are at least this far apart
384 from each other, to avoid keeping too much useless info.")
386 (defvar syntax-begin-function nil
387 "Function to move back outside of any comment/string/paren.
388 This function should move the cursor back to some syntactically safe
389 point (where the PPSS is equivalent to nil).")
390 (make-obsolete-variable 'syntax-begin-function nil "25.1")
392 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
393 ;; Several caches.
395 ;; Because `syntax-ppss' is equivalent to (parse-partial-sexp
396 ;; (POINT-MIN) x), we need either to empty the cache when we narrow
397 ;; the buffer, which is suboptimal, or we need to use several caches.
398 ;; We use two of them, one for widened buffer, and one for narrowing.
399 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
401 (defvar-local syntax-ppss-wide nil
402 "Cons of two elements (LAST . CACHE).
403 Where LAST is a pair (LAST-POS . LAST-PPS) caching the last invocation
404 and CACHE is a list of (POS . PPSS) pairs, in decreasing POS order.
405 These are valid when the buffer has no restriction.")
407 (defvar-local syntax-ppss-narrow nil
408 "Same as `syntax-ppss-wide' but for a narrowed buffer.")
410 (defvar-local syntax-ppss-narrow-start nil
411 "Start position of the narrowing for `syntax-ppss-narrow'.")
413 (defalias 'syntax-ppss-after-change-function 'syntax-ppss-flush-cache)
414 (defun syntax-ppss-flush-cache (beg &rest ignored)
415 "Flush the cache of `syntax-ppss' starting at position BEG."
416 ;; Set syntax-propertize to refontify anything past beg.
417 (setq syntax-propertize--done (min beg syntax-propertize--done))
418 ;; Flush invalid cache entries.
419 (dolist (cell (list syntax-ppss-wide syntax-ppss-narrow))
420 (pcase cell
421 (`(,last . ,cache)
422 (while (and cache (> (caar cache) beg))
423 (setq cache (cdr cache)))
424 ;; Throw away `last' value if made invalid.
425 (when (< beg (or (car last) 0))
426 ;; If syntax-begin-function jumped to BEG, then the old state at BEG can
427 ;; depend on the text after BEG (which is presumably changed). So if
428 ;; BEG=(car (nth 10 syntax-ppss-last)) don't reuse that data because the
429 ;; assumed nil state at BEG may not be valid any more.
430 (if (<= beg (or (syntax-ppss-toplevel-pos (cdr last))
431 (nth 3 last)
433 (setq last nil)
434 (setcar last nil)))
435 ;; Unregister if there's no cache left. Sadly this doesn't work
436 ;; because `before-change-functions' is temporarily bound to nil here.
437 ;; (unless cache
438 ;; (remove-hook 'before-change-functions 'syntax-ppss-flush-cache t))
439 (setcar cell last)
440 (setcdr cell cache)))
443 (defvar syntax-ppss-stats
444 [(0 . 0.0) (0 . 0.0) (0 . 0.0) (0 . 0.0) (0 . 0.0) (1 . 2500.0)])
445 (defun syntax-ppss-stats ()
446 (mapcar (lambda (x)
447 (condition-case nil
448 (cons (car x) (truncate (/ (cdr x) (car x))))
449 (error nil)))
450 syntax-ppss-stats))
452 (defvar-local syntax-ppss-table nil
453 "Syntax-table to use during `syntax-ppss', if any.")
455 (defun syntax-ppss--data ()
456 (if (eq (point-min) 1)
457 (progn
458 (unless syntax-ppss-wide
459 (setq syntax-ppss-wide (cons nil nil)))
460 syntax-ppss-wide)
461 (unless (eq syntax-ppss-narrow-start (point-min))
462 (setq syntax-ppss-narrow-start (point-min))
463 (setq syntax-ppss-narrow (cons nil nil)))
464 syntax-ppss-narrow))
466 (defun syntax-ppss (&optional pos)
467 "Parse-Partial-Sexp State at POS, defaulting to point.
468 The returned value is the same as that of `parse-partial-sexp'
469 run from `point-min' to POS except that values at positions 2 and 6
470 in the returned list (counting from 0) cannot be relied upon.
471 Point is at POS when this function returns.
473 It is necessary to call `syntax-ppss-flush-cache' explicitly if
474 this function is called while `before-change-functions' is
475 temporarily let-bound, or if the buffer is modified without
476 running the hook."
477 ;; Default values.
478 (unless pos (setq pos (point)))
479 (syntax-propertize pos)
481 (with-syntax-table (or syntax-ppss-table (syntax-table))
482 (let* ((cell (syntax-ppss--data))
483 (ppss-last (car cell))
484 (ppss-cache (cdr cell))
485 (old-ppss (cdr ppss-last))
486 (old-pos (car ppss-last))
487 (ppss nil)
488 (pt-min (point-min)))
489 (if (and old-pos (> old-pos pos)) (setq old-pos nil))
490 ;; Use the OLD-POS if usable and close. Don't update the `last' cache.
491 (condition-case nil
492 (if (and old-pos (< (- pos old-pos)
493 ;; The time to use syntax-begin-function and
494 ;; find PPSS is assumed to be about 2 * distance.
495 (* 2 (/ (cdr (aref syntax-ppss-stats 5))
496 (1+ (car (aref syntax-ppss-stats 5)))))))
497 (progn
498 (cl-incf (car (aref syntax-ppss-stats 0)))
499 (cl-incf (cdr (aref syntax-ppss-stats 0)) (- pos old-pos))
500 (parse-partial-sexp old-pos pos nil nil old-ppss))
502 (cond
503 ;; Use OLD-PPSS if possible and close enough.
504 ((and (not old-pos) old-ppss
505 ;; If `pt-min' is too far from `pos', we could try to use
506 ;; other positions in (nth 9 old-ppss), but that doesn't
507 ;; seem to happen in practice and it would complicate this
508 ;; code (and the before-change-function code even more).
509 ;; But maybe it would be useful in "degenerate" cases such
510 ;; as when the whole file is wrapped in a set
511 ;; of parentheses.
512 (setq pt-min (or (syntax-ppss-toplevel-pos old-ppss)
513 (nth 2 old-ppss)))
514 (<= pt-min pos) (< (- pos pt-min) syntax-ppss-max-span))
515 (cl-incf (car (aref syntax-ppss-stats 1)))
516 (cl-incf (cdr (aref syntax-ppss-stats 1)) (- pos pt-min))
517 (setq ppss (parse-partial-sexp pt-min pos)))
518 ;; The OLD-* data can't be used. Consult the cache.
520 (let ((cache-pred nil)
521 (cache ppss-cache)
522 (pt-min (point-min))
523 ;; I differentiate between PT-MIN and PT-BEST because
524 ;; I feel like it might be important to ensure that the
525 ;; cache is only filled with 100% sure data (whereas
526 ;; syntax-begin-function might return incorrect data).
527 ;; Maybe that's just stupid.
528 (pt-best (point-min))
529 (ppss-best nil))
530 ;; look for a usable cache entry.
531 (while (and cache (< pos (caar cache)))
532 (setq cache-pred cache)
533 (setq cache (cdr cache)))
534 (if cache (setq pt-min (caar cache) ppss (cdar cache)))
536 ;; Setup the before-change function if necessary.
537 (unless (or ppss-cache ppss-last)
538 (add-hook 'before-change-functions
539 'syntax-ppss-flush-cache t t))
541 ;; Use the best of OLD-POS and CACHE.
542 (if (or (not old-pos) (< old-pos pt-min))
543 (setq pt-best pt-min ppss-best ppss)
544 (cl-incf (car (aref syntax-ppss-stats 4)))
545 (cl-incf (cdr (aref syntax-ppss-stats 4)) (- pos old-pos))
546 (setq pt-best old-pos ppss-best old-ppss))
548 ;; Use the `syntax-begin-function' if available.
549 ;; We could try using that function earlier, but:
550 ;; - The result might not be 100% reliable, so it's better to use
551 ;; the cache if available.
552 ;; - The function might be slow.
553 ;; - If this function almost always finds a safe nearby spot,
554 ;; the cache won't be populated, so consulting it is cheap.
555 (when (and syntax-begin-function
556 (progn (goto-char pos)
557 (funcall syntax-begin-function)
558 ;; Make sure it's better.
559 (> (point) pt-best))
560 ;; Simple sanity checks.
561 (< (point) pos) ; backward-paragraph can fail here.
562 (not (memq (get-text-property (point) 'face)
563 '(font-lock-string-face font-lock-doc-face
564 font-lock-comment-face))))
565 (cl-incf (car (aref syntax-ppss-stats 5)))
566 (cl-incf (cdr (aref syntax-ppss-stats 5)) (- pos (point)))
567 (setq pt-best (point) ppss-best nil))
569 (cond
570 ;; Quick case when we found a nearby pos.
571 ((< (- pos pt-best) syntax-ppss-max-span)
572 (cl-incf (car (aref syntax-ppss-stats 2)))
573 (cl-incf (cdr (aref syntax-ppss-stats 2)) (- pos pt-best))
574 (setq ppss (parse-partial-sexp pt-best pos nil nil ppss-best)))
575 ;; Slow case: compute the state from some known position and
576 ;; populate the cache so we won't need to do it again soon.
578 (cl-incf (car (aref syntax-ppss-stats 3)))
579 (cl-incf (cdr (aref syntax-ppss-stats 3)) (- pos pt-min))
581 ;; If `pt-min' is too far, add a few intermediate entries.
582 (while (> (- pos pt-min) (* 2 syntax-ppss-max-span))
583 (setq ppss (parse-partial-sexp
584 pt-min (setq pt-min (/ (+ pt-min pos) 2))
585 nil nil ppss))
586 (push (cons pt-min ppss)
587 (if cache-pred (cdr cache-pred) ppss-cache)))
589 ;; Compute the actual return value.
590 (setq ppss (parse-partial-sexp pt-min pos nil nil ppss))
592 ;; Debugging check.
593 ;; (let ((real-ppss (parse-partial-sexp (point-min) pos)))
594 ;; (setcar (last ppss 4) 0)
595 ;; (setcar (last real-ppss 4) 0)
596 ;; (setcar (last ppss 8) nil)
597 ;; (setcar (last real-ppss 8) nil)
598 ;; (unless (equal ppss real-ppss)
599 ;; (message "!!Syntax: %s != %s" ppss real-ppss)
600 ;; (setq ppss real-ppss)))
602 ;; Store it in the cache.
603 (let ((pair (cons pos ppss)))
604 (if cache-pred
605 (if (> (- (caar cache-pred) pos) syntax-ppss-max-span)
606 (push pair (cdr cache-pred))
607 (setcar cache-pred pair))
608 (if (or (null ppss-cache)
609 (> (- (caar ppss-cache) pos)
610 syntax-ppss-max-span))
611 (push pair ppss-cache)
612 (setcar ppss-cache pair)))))))))
614 (setq ppss-last (cons pos ppss))
615 (setcar cell ppss-last)
616 (setcdr cell ppss-cache)
617 ppss)
618 (args-out-of-range
619 ;; If the buffer is more narrowed than when we built the cache,
620 ;; we may end up calling parse-partial-sexp with a position before
621 ;; point-min. In that case, just parse from point-min assuming
622 ;; a nil state.
623 (parse-partial-sexp (point-min) pos))))))
625 ;; Debugging functions
627 (defun syntax-ppss-debug ()
628 (let ((pt nil)
629 (min-diffs nil))
630 (dolist (x (append (cdr (syntax-ppss--data)) (list (cons (point-min) nil))))
631 (when pt (push (- pt (car x)) min-diffs))
632 (setq pt (car x)))
633 min-diffs))
635 ;; XEmacs compatibility functions
637 ;; (defun buffer-syntactic-context (&optional buffer)
638 ;; "Syntactic context at point in BUFFER.
639 ;; Either of `string', `comment' or nil.
640 ;; This is an XEmacs compatibility function."
641 ;; (with-current-buffer (or buffer (current-buffer))
642 ;; (syntax-ppss-context (syntax-ppss))))
644 ;; (defun buffer-syntactic-context-depth (&optional buffer)
645 ;; "Syntactic parenthesis depth at point in BUFFER.
646 ;; This is an XEmacs compatibility function."
647 ;; (with-current-buffer (or buffer (current-buffer))
648 ;; (syntax-ppss-depth (syntax-ppss))))
650 (provide 'syntax)
652 ;;; syntax.el ends here