Improve responsiveness while in 'replace-buffer-contents'
[emacs.git] / doc / lispref / syntax.texi
blob71c97fdae8ceed37ba9de68be56e9ae8663bf53d
1 @c -*-texinfo-*-
2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990-1995, 1998-1999, 2001-2018 Free Software
4 @c Foundation, Inc.
5 @c See the file elisp.texi for copying conditions.
6 @node Syntax Tables
7 @chapter Syntax Tables
8 @cindex parsing buffer text
9 @cindex syntax table
10 @cindex text parsing
12   A @dfn{syntax table} specifies the syntactic role of each character
13 in a buffer.  It can be used to determine where words, symbols, and
14 other syntactic constructs begin and end.  This information is used by
15 many Emacs facilities, including Font Lock mode (@pxref{Font Lock
16 Mode}) and the various complex movement commands (@pxref{Motion}).
18 @menu
19 * Basics: Syntax Basics.     Basic concepts of syntax tables.
20 * Syntax Descriptors::       How characters are classified.
21 * Syntax Table Functions::   How to create, examine and alter syntax tables.
22 * Syntax Properties::        Overriding syntax with text properties.
23 * Motion and Syntax::        Moving over characters with certain syntaxes.
24 * Parsing Expressions::      Parsing balanced expressions
25                                 using the syntax table.
26 * Syntax Table Internals::   How syntax table information is stored.
27 * Categories::               Another way of classifying character syntax.
28 @end menu
30 @node Syntax Basics
31 @section Syntax Table Concepts
33   A syntax table is a data structure which can be used to look up the
34 @dfn{syntax class} and other syntactic properties of each character.
35 Syntax tables are used by Lisp programs for scanning and moving across
36 text.
38   Internally, a syntax table is a char-table (@pxref{Char-Tables}).
39 The element at index @var{c} describes the character with code
40 @var{c}; its value is a cons cell which specifies the syntax of the
41 character in question.  @xref{Syntax Table Internals}, for details.
42 However, instead of using @code{aset} and @code{aref} to modify and
43 inspect syntax table contents, you should usually use the higher-level
44 functions @code{char-syntax} and @code{modify-syntax-entry}, which are
45 described in @ref{Syntax Table Functions}.
47 @defun syntax-table-p object
48 This function returns @code{t} if @var{object} is a syntax table.
49 @end defun
51   Each buffer has its own major mode, and each major mode has its own
52 idea of the syntax class of various characters.  For example, in Lisp
53 mode, the character @samp{;} begins a comment, but in C mode, it
54 terminates a statement.  To support these variations, the syntax table
55 is local to each buffer.  Typically, each major mode has its own
56 syntax table, which it installs in all buffers that use that mode.
57 For example, the variable @code{emacs-lisp-mode-syntax-table} holds
58 the syntax table used by Emacs Lisp mode, and
59 @code{c-mode-syntax-table} holds the syntax table used by C mode.
60 Changing a major mode's syntax table alters the syntax in all of that
61 mode's buffers, as well as in any buffers subsequently put in that
62 mode.  Occasionally, several similar modes share one syntax table.
63 @xref{Example Major Modes}, for an example of how to set up a syntax
64 table.
66 @cindex standard syntax table
67 @cindex inheritance, syntax table
68   A syntax table can @dfn{inherit} from another syntax table, which is
69 called its @dfn{parent syntax table}.  A syntax table can leave the
70 syntax class of some characters unspecified, by giving them the
71 ``inherit'' syntax class; such a character then acquires the syntax
72 class specified by the parent syntax table (@pxref{Syntax Class
73 Table}).  Emacs defines a @dfn{standard syntax table}, which is the
74 default parent syntax table, and is also the syntax table used by
75 Fundamental mode.
77 @defun standard-syntax-table
78 This function returns the standard syntax table, which is the syntax
79 table used in Fundamental mode.
80 @end defun
82   Syntax tables are not used by the Emacs Lisp reader, which has its
83 own built-in syntactic rules which cannot be changed.  (Some Lisp
84 systems provide ways to redefine the read syntax, but we decided to
85 leave this feature out of Emacs Lisp for simplicity.)
87 @node Syntax Descriptors
88 @section Syntax Descriptors
89 @cindex syntax class
91   The @dfn{syntax class} of a character describes its syntactic role.
92 Each syntax table specifies the syntax class of each character.  There
93 is no necessary relationship between the class of a character in one
94 syntax table and its class in any other table.
96   Each syntax class is designated by a mnemonic character, which
97 serves as the name of the class when you need to specify a class.
98 Usually, this designator character is one that is often assigned that
99 class; however, its meaning as a designator is unvarying and
100 independent of what syntax that character currently has.  Thus,
101 @samp{\} as a designator character always stands for escape character
102 syntax, regardless of whether the @samp{\} character actually has that
103 syntax in the current syntax table.
104 @ifnottex
105 @xref{Syntax Class Table}, for a list of syntax classes and their
106 designator characters.
107 @end ifnottex
109 @cindex syntax descriptor
110   A @dfn{syntax descriptor} is a Lisp string that describes the syntax
111 class and other syntactic properties of a character.  When you want to
112 modify the syntax of a character, that is done by calling the function
113 @code{modify-syntax-entry} and passing a syntax descriptor as one of
114 its arguments (@pxref{Syntax Table Functions}).
116   The first character in a syntax descriptor must be a syntax class
117 designator character.  The second character, if present, specifies a
118 matching character (e.g., in Lisp, the matching character for
119 @samp{(} is @samp{)}); a space specifies that there is no matching
120 character.  Then come characters specifying additional syntax
121 properties (@pxref{Syntax Flags}).
123   If no matching character or flags are needed, only one character
124 (specifying the syntax class) is sufficient.
126   For example, the syntax descriptor for the character @samp{*} in C
127 mode is @code{". 23"} (i.e., punctuation, matching character slot
128 unused, second character of a comment-starter, first character of a
129 comment-ender), and the entry for @samp{/} is @samp{@w{. 14}} (i.e.,
130 punctuation, matching character slot unused, first character of a
131 comment-starter, second character of a comment-ender).
133   Emacs also defines @dfn{raw syntax descriptors}, which are used to
134 describe syntax classes at a lower level.  @xref{Syntax Table
135 Internals}.
137 @menu
138 * Syntax Class Table::      Table of syntax classes.
139 * Syntax Flags::            Additional flags each character can have.
140 @end menu
142 @node Syntax Class Table
143 @subsection Table of Syntax Classes
144 @cindex syntax class table
146   Here is a table of syntax classes, the characters that designate
147 them, their meanings, and examples of their use.
149 @table @asis
150 @item Whitespace characters: @samp{@ } or @samp{-}
151 Characters that separate symbols and words from each other.
152 Typically, whitespace characters have no other syntactic significance,
153 and multiple whitespace characters are syntactically equivalent to a
154 single one.  Space, tab, and formfeed are classified as whitespace in
155 almost all major modes.
157 This syntax class can be designated by either @w{@samp{@ }} or
158 @samp{-}.  Both designators are equivalent.
160 @item Word constituents: @samp{w}
161 Parts of words in human languages.  These are typically used in
162 variable and command names in programs.  All upper- and lower-case
163 letters, and the digits, are typically word constituents.
165 @item Symbol constituents: @samp{_}
166 Extra characters used in variable and command names along with word
167 constituents.  Examples include the characters @samp{$&*+-_<>} in Lisp
168 mode, which may be part of a symbol name even though they are not part
169 of English words.  In standard C, the only non-word-constituent
170 character that is valid in symbols is underscore (@samp{_}).
172 @item Punctuation characters: @samp{.}
173 Characters used as punctuation in a human language, or used in a
174 programming language to separate symbols from one another.  Some
175 programming language modes, such as Emacs Lisp mode, have no
176 characters in this class since the few characters that are not symbol
177 or word constituents all have other uses.  Other programming language
178 modes, such as C mode, use punctuation syntax for operators.
180 @item Open parenthesis characters: @samp{(}
181 @itemx Close parenthesis characters: @samp{)}
182 Characters used in dissimilar pairs to surround sentences or
183 expressions.  Such a grouping is begun with an open parenthesis
184 character and terminated with a close.  Each open parenthesis
185 character matches a particular close parenthesis character, and vice
186 versa.  Normally, Emacs indicates momentarily the matching open
187 parenthesis when you insert a close parenthesis.  @xref{Blinking}.
189 In human languages, and in C code, the parenthesis pairs are
190 @samp{()}, @samp{[]}, and @samp{@{@}}.  In Emacs Lisp, the delimiters
191 for lists and vectors (@samp{()} and @samp{[]}) are classified as
192 parenthesis characters.
194 @item String quotes: @samp{"}
195 Characters used to delimit string constants.  The same string quote
196 character appears at the beginning and the end of a string.  Such
197 quoted strings do not nest.
199 The parsing facilities of Emacs consider a string as a single token.
200 The usual syntactic meanings of the characters in the string are
201 suppressed.
203 The Lisp modes have two string quote characters: double-quote (@samp{"})
204 and vertical bar (@samp{|}).  @samp{|} is not used in Emacs Lisp, but it
205 is used in Common Lisp.  C also has two string quote characters:
206 double-quote for strings, and apostrophe (@samp{'}) for character
207 constants.
209 Human text has no string quote characters.  We do not want quotation
210 marks to turn off the usual syntactic properties of other characters
211 in the quotation.
213 @item Escape-syntax characters: @samp{\}
214 Characters that start an escape sequence, such as is used in string
215 and character constants.  The character @samp{\} belongs to this class
216 in both C and Lisp.  (In C, it is used thus only inside strings, but
217 it turns out to cause no trouble to treat it this way throughout C
218 code.)
220 Characters in this class count as part of words if
221 @code{words-include-escapes} is non-@code{nil}.  @xref{Word Motion}.
223 @item Character quotes: @samp{/}
224 Characters used to quote the following character so that it loses its
225 normal syntactic meaning.  This differs from an escape character in
226 that only the character immediately following is ever affected.
228 Characters in this class count as part of words if
229 @code{words-include-escapes} is non-@code{nil}.  @xref{Word Motion}.
231 This class is used for backslash in @TeX{} mode.
233 @item Paired delimiters: @samp{$}
234 Similar to string quote characters, except that the syntactic
235 properties of the characters between the delimiters are not
236 suppressed.  Only @TeX{} mode uses a paired delimiter presently---the
237 @samp{$} that both enters and leaves math mode.
239 @item Expression prefixes: @samp{'}
240 Characters used for syntactic operators that are considered as part of
241 an expression if they appear next to one.  In Lisp modes, these
242 characters include the apostrophe, @samp{'} (used for quoting), the
243 comma, @samp{,} (used in macros), and @samp{#} (used in the read
244 syntax for certain data types).
246 @item Comment starters: @samp{<}
247 @itemx Comment enders: @samp{>}
248 @cindex comment syntax
249 Characters used in various languages to delimit comments.  Human text
250 has no comment characters.  In Lisp, the semicolon (@samp{;}) starts a
251 comment and a newline or formfeed ends one.
253 @item Inherit standard syntax: @samp{@@}
254 This syntax class does not specify a particular syntax.  It says to
255 look in the standard syntax table to find the syntax of this
256 character.
258 @item Generic comment delimiters: @samp{!}
259 Characters that start or end a special kind of comment.  @emph{Any}
260 generic comment delimiter matches @emph{any} generic comment
261 delimiter, but they cannot match a comment starter or comment ender;
262 generic comment delimiters can only match each other.
264 This syntax class is primarily meant for use with the
265 @code{syntax-table} text property (@pxref{Syntax Properties}).  You
266 can mark any range of characters as forming a comment, by giving the
267 first and last characters of the range @code{syntax-table} properties
268 identifying them as generic comment delimiters.
270 @item Generic string delimiters: @samp{|}
271 Characters that start or end a string.  This class differs from the
272 string quote class in that @emph{any} generic string delimiter can
273 match any other generic string delimiter; but they do not match
274 ordinary string quote characters.
276 This syntax class is primarily meant for use with the
277 @code{syntax-table} text property (@pxref{Syntax Properties}).  You
278 can mark any range of characters as forming a string constant, by
279 giving the first and last characters of the range @code{syntax-table}
280 properties identifying them as generic string delimiters.
281 @end table
283 @node Syntax Flags
284 @subsection Syntax Flags
285 @cindex syntax flags
287   In addition to the classes, entries for characters in a syntax table
288 can specify flags.  There are eight possible flags, represented by the
289 characters @samp{1}, @samp{2}, @samp{3}, @samp{4}, @samp{b}, @samp{c},
290 @samp{n}, and @samp{p}.
292   All the flags except @samp{p} are used to describe comment
293 delimiters.  The digit flags are used for comment delimiters made up
294 of 2 characters.  They indicate that a character can @emph{also} be
295 part of a comment sequence, in addition to the syntactic properties
296 associated with its character class.  The flags are independent of the
297 class and each other for the sake of characters such as @samp{*} in
298 C mode, which is a punctuation character, @emph{and} the second
299 character of a start-of-comment sequence (@samp{/*}), @emph{and} the
300 first character of an end-of-comment sequence (@samp{*/}).  The flags
301 @samp{b}, @samp{c}, and @samp{n} are used to qualify the corresponding
302 comment delimiter.
304   Here is a table of the possible flags for a character @var{c},
305 and what they mean:
307 @itemize @bullet
308 @item
309 @samp{1} means @var{c} is the start of a two-character comment-start
310 sequence.
312 @item
313 @samp{2} means @var{c} is the second character of such a sequence.
315 @item
316 @samp{3} means @var{c} is the start of a two-character comment-end
317 sequence.
319 @item
320 @samp{4} means @var{c} is the second character of such a sequence.
322 @item
323 @samp{b} means that @var{c} as a comment delimiter belongs to the
324 alternative ``b'' comment style.  For a two-character comment starter,
325 this flag is only significant on the second char, and for a 2-character
326 comment ender it is only significant on the first char.
328 @item
329 @samp{c} means that @var{c} as a comment delimiter belongs to the
330 alternative ``c'' comment style.  For a two-character comment
331 delimiter, @samp{c} on either character makes it of style ``c''.
333 @item
334 @samp{n} on a comment delimiter character specifies that this kind of
335 comment can be nested.  Inside such a comment, only comments of the
336 same style will be recognized.  For a two-character comment delimiter,
337 @samp{n} on either character makes it nestable.
339 @cindex comment style
340 Emacs supports several comment styles simultaneously in any one syntax
341 table.  A comment style is a set of flags @samp{b}, @samp{c}, and
342 @samp{n}, so there can be up to 8 different comment styles, each one
343 named by the set of its flags.  Each comment delimiter has a style and
344 only matches comment delimiters of the same style.  Thus if a comment
345 starts with the comment-start sequence of style ``bn'', it will extend
346 until the next matching comment-end sequence of style ``bn''.  When
347 the set of flags has neither flag @samp{b} nor flag @samp{c} set, the
348 resulting style is called the ``a'' style.
350 The appropriate comment syntax settings for C++ can be as follows:
352 @table @asis
353 @item @samp{/}
354 @samp{124}
355 @item @samp{*}
356 @samp{23b}
357 @item newline
358 @samp{>}
359 @end table
361 This defines four comment-delimiting sequences:
363 @table @asis
364 @item @samp{/*}
365 This is a comment-start sequence for ``b'' style because the
366 second character, @samp{*}, has the @samp{b} flag.
368 @item @samp{//}
369 This is a comment-start sequence for ``a'' style because the second
370 character, @samp{/}, does not have the @samp{b} flag.
372 @item @samp{*/}
373 This is a comment-end sequence for ``b'' style because the first
374 character, @samp{*}, has the @samp{b} flag.
376 @item newline
377 This is a comment-end sequence for ``a'' style, because the newline
378 character does not have the @samp{b} flag.
379 @end table
381 @item
382 @samp{p} identifies an additional prefix character for Lisp syntax.
383 These characters are treated as whitespace when they appear between
384 expressions.  When they appear within an expression, they are handled
385 according to their usual syntax classes.
387 The function @code{backward-prefix-chars} moves back over these
388 characters, as well as over characters whose primary syntax class is
389 prefix (@samp{'}).  @xref{Motion and Syntax}.
390 @end itemize
392 @node Syntax Table Functions
393 @section Syntax Table Functions
395   In this section we describe functions for creating, accessing and
396 altering syntax tables.
398 @defun make-syntax-table &optional table
399 This function creates a new syntax table.  If @var{table} is
400 non-@code{nil}, the parent of the new syntax table is @var{table};
401 otherwise, the parent is the standard syntax table.
403 In the new syntax table, all characters are initially given the
404 ``inherit'' (@samp{@@}) syntax class, i.e., their syntax is inherited
405 from the parent table (@pxref{Syntax Class Table}).
406 @end defun
408 @defun copy-syntax-table &optional table
409 This function constructs a copy of @var{table} and returns it.  If
410 @var{table} is omitted or @code{nil}, it returns a copy of the
411 standard syntax table.  Otherwise, an error is signaled if @var{table}
412 is not a syntax table.
413 @end defun
415 @deffn Command modify-syntax-entry char syntax-descriptor  &optional table
416 @cindex syntax entry, setting
417 This function sets the syntax entry for @var{char} according to
418 @var{syntax-descriptor}.  @var{char} must be a character, or a cons
419 cell of the form @code{(@var{min} . @var{max})}; in the latter case,
420 the function sets the syntax entries for all characters in the range
421 between @var{min} and @var{max}, inclusive.
423 The syntax is changed only for @var{table}, which defaults to the
424 current buffer's syntax table, and not in any other syntax table.
426 The argument @var{syntax-descriptor} is a syntax descriptor, i.e., a
427 string whose first character is a syntax class designator and whose
428 second and subsequent characters optionally specify a matching
429 character and syntax flags.  @xref{Syntax Descriptors}.  An error is
430 signaled if @var{syntax-descriptor} is not a valid syntax descriptor.
432 This function always returns @code{nil}.  The old syntax information in
433 the table for this character is discarded.
435 @example
436 @group
437 @exdent @r{Examples:}
439 ;; @r{Put the space character in class whitespace.}
440 (modify-syntax-entry ?\s " ")
441      @result{} nil
442 @end group
444 @group
445 ;; @r{Make @samp{$} an open parenthesis character,}
446 ;;   @r{with @samp{^} as its matching close.}
447 (modify-syntax-entry ?$ "(^")
448      @result{} nil
449 @end group
451 @group
452 ;; @r{Make @samp{^} a close parenthesis character,}
453 ;;   @r{with @samp{$} as its matching open.}
454 (modify-syntax-entry ?^ ")$")
455      @result{} nil
456 @end group
458 @group
459 ;; @r{Make @samp{/} a punctuation character,}
460 ;;   @r{the first character of a start-comment sequence,}
461 ;;   @r{and the second character of an end-comment sequence.}
462 ;;   @r{This is used in C mode.}
463 (modify-syntax-entry ?/ ". 14")
464      @result{} nil
465 @end group
466 @end example
467 @end deffn
469 @defun char-syntax character
470 This function returns the syntax class of @var{character}, represented
471 by its designator character (@pxref{Syntax Class Table}).  This
472 returns @emph{only} the class, not its matching character or syntax
473 flags.
475 The following examples apply to C mode.  (We use @code{string} to make
476 it easier to see the character returned by @code{char-syntax}.)
478 @example
479 @group
480 ;; Space characters have whitespace syntax class.
481 (string (char-syntax ?\s))
482      @result{} " "
483 @end group
485 @group
486 ;; Forward slash characters have punctuation syntax.
487 ;; Note that this @code{char-syntax} call does not reveal
488 ;; that it is also part of comment-start and -end sequences.
489 (string (char-syntax ?/))
490      @result{} "."
491 @end group
493 @group
494 ;; Open parenthesis characters have open parenthesis syntax.
495 ;; Note that this @code{char-syntax} call does not reveal that
496 ;; it has a matching character, @samp{)}.
497 (string (char-syntax ?\())
498      @result{} "("
499 @end group
500 @end example
502 @end defun
504 @defun set-syntax-table table
505 This function makes @var{table} the syntax table for the current buffer.
506 It returns @var{table}.
507 @end defun
509 @defun syntax-table
510 This function returns the current syntax table, which is the table for
511 the current buffer.
512 @end defun
514 @deffn Command describe-syntax &optional buffer
515 This command displays the contents of the syntax table of
516 @var{buffer} (by default, the current buffer) in a help buffer.
517 @end deffn
519 @defmac with-syntax-table table body@dots{}
520 This macro executes @var{body} using @var{table} as the current syntax
521 table.  It returns the value of the last form in @var{body}, after
522 restoring the old current syntax table.
524 Since each buffer has its own current syntax table, we should make that
525 more precise: @code{with-syntax-table} temporarily alters the current
526 syntax table of whichever buffer is current at the time the macro
527 execution starts.  Other buffers are not affected.
528 @end defmac
530 @node Syntax Properties
531 @section Syntax Properties
532 @kindex syntax-table @r{(text property)}
534 When the syntax table is not flexible enough to specify the syntax of
535 a language, you can override the syntax table for specific character
536 occurrences in the buffer, by applying a @code{syntax-table} text
537 property.  @xref{Text Properties}, for how to apply text properties.
539   The valid values of @code{syntax-table} text property are:
541 @table @asis
542 @item @var{syntax-table}
543 If the property value is a syntax table, that table is used instead of
544 the current buffer's syntax table to determine the syntax for the
545 underlying text character.
547 @item @code{(@var{syntax-code} . @var{matching-char})}
548 A cons cell of this format is a raw syntax descriptor (@pxref{Syntax
549 Table Internals}), which directly specifies a syntax class for the
550 underlying text character.
552 @item @code{nil}
553 If the property is @code{nil}, the character's syntax is determined from
554 the current syntax table in the usual way.
555 @end table
557 @defvar parse-sexp-lookup-properties
558 If this is non-@code{nil}, the syntax scanning functions, like
559 @code{forward-sexp}, pay attention to syntax text properties.
560 Otherwise they use only the current syntax table.
561 @end defvar
563 @defvar syntax-propertize-function
564 This variable, if non-@code{nil}, should store a function for applying
565 @code{syntax-table} properties to a specified stretch of text.  It is
566 intended to be used by major modes to install a function which applies
567 @code{syntax-table} properties in some mode-appropriate way.
569 The function is called by @code{syntax-ppss} (@pxref{Position Parse}),
570 and by Font Lock mode during syntactic fontification (@pxref{Syntactic
571 Font Lock}).  It is called with two arguments, @var{start} and
572 @var{end}, which are the starting and ending positions of the text on
573 which it should act.  It is allowed to call @code{syntax-ppss} on any
574 position before @var{end}.  However, it should not call
575 @code{syntax-ppss-flush-cache}; so, it is not allowed to call
576 @code{syntax-ppss} on some position and later modify the buffer at an
577 earlier position.
578 @end defvar
580 @defvar syntax-propertize-extend-region-functions
581 This abnormal hook is run by the syntax parsing code prior to calling
582 @code{syntax-propertize-function}.  Its role is to help locate safe
583 starting and ending buffer positions for passing to
584 @code{syntax-propertize-function}.  For example, a major mode can add
585 a function to this hook to identify multi-line syntactic constructs,
586 and ensure that the boundaries do not fall in the middle of one.
588 Each function in this hook should accept two arguments, @var{start}
589 and @var{end}.  It should return either a cons cell of two adjusted
590 buffer positions, @code{(@var{new-start} . @var{new-end})}, or
591 @code{nil} if no adjustment is necessary.  The hook functions are run
592 in turn, repeatedly, until they all return @code{nil}.
593 @end defvar
595 @node Motion and Syntax
596 @section Motion and Syntax
597 @cindex moving across syntax classes
598 @cindex skipping characters of certain syntax
600   This section describes functions for moving across characters that
601 have certain syntax classes.
603 @defun skip-syntax-forward syntaxes &optional limit
604 This function moves point forward across characters having syntax
605 classes mentioned in @var{syntaxes} (a string of syntax class
606 characters).  It stops when it encounters the end of the buffer, or
607 position @var{limit} (if specified), or a character it is not supposed
608 to skip.
610 If @var{syntaxes} starts with @samp{^}, then the function skips
611 characters whose syntax is @emph{not} in @var{syntaxes}.
613 The return value is the distance traveled, which is a nonnegative
614 integer.
615 @end defun
617 @defun skip-syntax-backward syntaxes &optional limit
618 This function moves point backward across characters whose syntax
619 classes are mentioned in @var{syntaxes}.  It stops when it encounters
620 the beginning of the buffer, or position @var{limit} (if specified), or
621 a character it is not supposed to skip.
623 If @var{syntaxes} starts with @samp{^}, then the function skips
624 characters whose syntax is @emph{not} in @var{syntaxes}.
626 The return value indicates the distance traveled.  It is an integer that
627 is zero or less.
628 @end defun
630 @defun backward-prefix-chars
631 This function moves point backward over any number of characters with
632 expression prefix syntax.  This includes both characters in the
633 expression prefix syntax class, and characters with the @samp{p} flag.
634 @end defun
636 @node Parsing Expressions
637 @section Parsing Expressions
638 @cindex parsing expressions
639 @cindex scanning expressions
641   This section describes functions for parsing and scanning balanced
642 expressions.  We will refer to such expressions as @dfn{sexps},
643 following the terminology of Lisp, even though these functions can act
644 on languages other than Lisp.  Basically, a sexp is either a balanced
645 parenthetical grouping, a string, or a symbol (i.e., a sequence
646 of characters whose syntax is either word constituent or symbol
647 constituent).  However, characters in the expression prefix syntax
648 class (@pxref{Syntax Class Table}) are treated as part of the sexp if
649 they appear next to it.
651   The syntax table controls the interpretation of characters, so these
652 functions can be used for Lisp expressions when in Lisp mode and for C
653 expressions when in C mode.  @xref{List Motion}, for convenient
654 higher-level functions for moving over balanced expressions.
656   A character's syntax controls how it changes the state of the
657 parser, rather than describing the state itself.  For example, a
658 string delimiter character toggles the parser state between
659 in-string and in-code, but the syntax of characters does not
660 directly say whether they are inside a string.  For example (note that
661 15 is the syntax code for generic string delimiters),
663 @example
664 (put-text-property 1 9 'syntax-table '(15 . nil))
665 @end example
667 @noindent
668 does not tell Emacs that the first eight chars of the current buffer
669 are a string, but rather that they are all string delimiters.  As a
670 result, Emacs treats them as four consecutive empty string constants.
672 @menu
673 * Motion via Parsing::       Motion functions that work by parsing.
674 * Position Parse::           Determining the syntactic state of a position.
675 * Parser State::             How Emacs represents a syntactic state.
676 * Low-Level Parsing::        Parsing across a specified region.
677 * Control Parsing::          Parameters that affect parsing.
678 @end menu
680 @node Motion via Parsing
681 @subsection Motion Commands Based on Parsing
682 @cindex motion based on parsing
684   This section describes simple point-motion functions that operate
685 based on parsing expressions.
687 @defun scan-lists from count depth
688 This function scans forward @var{count} balanced parenthetical
689 groupings from position @var{from}.  It returns the position where the
690 scan stops.  If @var{count} is negative, the scan moves backwards.
692 If @var{depth} is nonzero, treat the starting position as being
693 @var{depth} parentheses deep.  The scanner moves forward or backward
694 through the buffer until the depth changes to zero @var{count} times.
695 Hence, a positive value for @var{depth} has the effect of moving out
696 @var{depth} levels of parenthesis from the starting position, while a
697 negative @var{depth} has the effect of moving deeper by @var{-depth}
698 levels of parenthesis.
700 Scanning ignores comments if @code{parse-sexp-ignore-comments} is
701 non-@code{nil}.
703 If the scan reaches the beginning or end of the accessible part of the
704 buffer before it has scanned over @var{count} parenthetical groupings,
705 the return value is @code{nil} if the depth at that point is zero; if
706 the depth is non-zero, a @code{scan-error} error is signaled.
707 @end defun
709 @defun scan-sexps from count
710 This function scans forward @var{count} sexps from position @var{from}.
711 It returns the position where the scan stops.  If @var{count} is
712 negative, the scan moves backwards.
714 Scanning ignores comments if @code{parse-sexp-ignore-comments} is
715 non-@code{nil}.
717 If the scan reaches the beginning or end of (the accessible part of) the
718 buffer while in the middle of a parenthetical grouping, an error is
719 signaled.  If it reaches the beginning or end between groupings but
720 before count is used up, @code{nil} is returned.
721 @end defun
723 @defun forward-comment count
724 This function moves point forward across @var{count} complete comments
725      (that is, including the starting delimiter and the terminating
726 delimiter if any), plus any whitespace encountered on the way.  It
727 moves backward if @var{count} is negative.  If it encounters anything
728 other than a comment or whitespace, it stops, leaving point at the
729 place where it stopped.  This includes (for instance) finding the end
730 of a comment when moving forward and expecting the beginning of one.
731 The function also stops immediately after moving over the specified
732 number of complete comments.  If @var{count} comments are found as
733 expected, with nothing except whitespace between them, it returns
734 @code{t}; otherwise it returns @code{nil}.
736 This function cannot tell whether the comments it traverses are
737 embedded within a string.  If they look like comments, it treats them
738 as comments.
740 To move forward over all comments and whitespace following point, use
741 @code{(forward-comment (buffer-size))}.  @code{(buffer-size)} is a
742 good argument to use, because the number of comments in the buffer
743 cannot exceed that many.
744 @end defun
746 @node Position Parse
747 @subsection Finding the Parse State for a Position
748 @cindex parse state for a position
750   For syntactic analysis, such as in indentation, often the useful
751 thing is to compute the syntactic state corresponding to a given buffer
752 position.  This function does that conveniently.
754 @defun syntax-ppss &optional pos
755 This function returns the parser state that the parser would reach at
756 position @var{pos} starting from the beginning of the visible portion
757 of the buffer.
758 @iftex
759 See the next section for
760 @end iftex
761 @ifnottex
762 @xref{Parser State},
763 @end ifnottex
764 for a description of the parser state.
766 The return value is the same as if you call the low-level parsing
767 function @code{parse-partial-sexp} to parse from the beginning of the
768 visible portion of the buffer to @var{pos} (@pxref{Low-Level
769 Parsing}).  However, @code{syntax-ppss} uses caches to speed up the
770 computation.  Due to this optimization, the second value (previous
771 complete subexpression) and sixth value (minimum parenthesis depth) in
772 the returned parser state are not meaningful.
774 This function has a side effect: it adds a buffer-local entry to
775 @code{before-change-functions} (@pxref{Change Hooks}) for
776 @code{syntax-ppss-flush-cache} (see below).  This entry keeps the
777 cache consistent as the buffer is modified.  However, the cache might
778 not be updated if @code{syntax-ppss} is called while
779 @code{before-change-functions} is temporarily let-bound, or if the
780 buffer is modified without running the hook, such as when using
781 @code{inhibit-modification-hooks}.  In those cases, it is necessary to
782 call @code{syntax-ppss-flush-cache} explicitly.
783 @end defun
785 @defun syntax-ppss-flush-cache beg &rest ignored-args
786 This function flushes the cache used by @code{syntax-ppss}, starting
787 at position @var{beg}.  The remaining arguments, @var{ignored-args},
788 are ignored; this function accepts them so that it can be directly
789 used on hooks such as @code{before-change-functions} (@pxref{Change
790 Hooks}).
791 @end defun
793 @node Parser State
794 @subsection Parser State
795 @cindex parser state
797   A @dfn{parser state} is a list of (currently) eleven elements
798 describing the state of the syntactic parser, after it parses the text
799 between a specified starting point and a specified end point in the
800 buffer.  Parsing functions such as @code{syntax-ppss}
801 @ifnottex
802 (@pxref{Position Parse})
803 @end ifnottex
804 return a parser state as the value.  Some parsing functions accept a
805 parser state as an argument, for resuming parsing.
807   Here are the meanings of the elements of the parser state:
809 @enumerate 0
810 @item
811 The depth in parentheses, counting from 0.  @strong{Warning:} this can
812 be negative if there are more close parens than open parens between
813 the parser's starting point and end point.
815 @item
816 @cindex innermost containing parentheses
817 The character position of the start of the innermost parenthetical
818 grouping containing the stopping point; @code{nil} if none.
820 @item
821 @cindex previous complete subexpression
822 The character position of the start of the last complete subexpression
823 terminated; @code{nil} if none.
825 @item
826 @cindex inside string
827 Non-@code{nil} if inside a string.  More precisely, this is the
828 character that will terminate the string, or @code{t} if a generic
829 string delimiter character should terminate it.
831 @item
832 @cindex inside comment
833 @code{t} if inside a non-nestable comment (of any comment style;
834 @pxref{Syntax Flags}); or the comment nesting level if inside a
835 comment that can be nested.
837 @item
838 @cindex quote character
839 @code{t} if the end point is just after a quote character.
841 @item
842 The minimum parenthesis depth encountered during this scan.
844 @item
845 What kind of comment is active: @code{nil} if not in a comment or in a
846 comment of style @samp{a}; 1 for a comment of style @samp{b}; 2 for a
847 comment of style @samp{c}; and @code{syntax-table} for a comment that
848 should be ended by a generic comment delimiter character.
850 @item
851 The string or comment start position.  While inside a comment, this is
852 the position where the comment began; while inside a string, this is the
853 position where the string began.  When outside of strings and comments,
854 this element is @code{nil}.
856 @item
857 The list of the positions of the currently open parentheses, starting
858 with the outermost.
860 @item
861 When the last buffer position scanned was the (potential) first
862 character of a two character construct (comment delimiter or
863 escaped/char-quoted character pair), the @var{syntax-code}
864 (@pxref{Syntax Table Internals}) of that position.  Otherwise
865 @code{nil}.
866 @end enumerate
868   Elements 1, 2, and 6 are ignored in a state which you pass as an
869 argument to continue parsing.  Elements 9 and 10 are mainly used
870 internally by the parser code.
872   One additional piece of useful information is available from a
873 parser state using this function:
875 @defun syntax-ppss-toplevel-pos state
876 This function extracts, from parser state @var{state}, the last
877 position scanned in the parse which was at top level in grammatical
878 structure.  ``At top level'' means outside of any parentheses,
879 comments, or strings.
881 The value is @code{nil} if @var{state} represents a parse which has
882 arrived at a top level position.
883 @end defun
885 @node Low-Level Parsing
886 @subsection Low-Level Parsing
888   The most basic way to use the expression parser is to tell it
889 to start at a given position with a certain state, and parse up to
890 a specified end position.
892 @defun parse-partial-sexp start limit &optional target-depth stop-before state stop-comment
893 This function parses a sexp in the current buffer starting at
894 @var{start}, not scanning past @var{limit}.  It stops at position
895 @var{limit} or when certain criteria described below are met, and sets
896 point to the location where parsing stops.  It returns a parser state
897 @ifinfo
898 (@pxref{Parser State})
899 @end ifinfo
900 describing the status of the parse at the point where it stops.
902 @cindex parenthesis depth
903 If the third argument @var{target-depth} is non-@code{nil}, parsing
904 stops if the depth in parentheses becomes equal to @var{target-depth}.
905 The depth starts at 0, or at whatever is given in @var{state}.
907 If the fourth argument @var{stop-before} is non-@code{nil}, parsing
908 stops when it comes to any character that starts a sexp.  If
909 @var{stop-comment} is non-@code{nil}, parsing stops after the start of
910 an unnested comment.  If @var{stop-comment} is the symbol
911 @code{syntax-table}, parsing stops after the start of an unnested
912 comment or a string, or after the end of an unnested comment or a
913 string, whichever comes first.
915 If @var{state} is @code{nil}, @var{start} is assumed to be at the top
916 level of parenthesis structure, such as the beginning of a function
917 definition.  Alternatively, you might wish to resume parsing in the
918 middle of the structure.  To do this, you must provide a @var{state}
919 argument that describes the initial status of parsing.  The value
920 returned by a previous call to @code{parse-partial-sexp} will do
921 nicely.
922 @end defun
924 @node Control Parsing
925 @subsection Parameters to Control Parsing
926 @cindex parsing, control parameters
928 @defvar multibyte-syntax-as-symbol
929 If this variable is non-@code{nil}, @code{scan-sexps} treats all
930 non-@acronym{ASCII} characters as symbol constituents regardless
931 of what the syntax table says about them.  (However, text properties
932 can still override the syntax.)
933 @end defvar
935 @defopt parse-sexp-ignore-comments
936 @cindex skipping comments
937 If the value is non-@code{nil}, then comments are treated as
938 whitespace by the functions in this section and by @code{forward-sexp},
939 @code{scan-lists} and @code{scan-sexps}.
940 @end defopt
942 @vindex parse-sexp-lookup-properties
943 The behavior of @code{parse-partial-sexp} is also affected by
944 @code{parse-sexp-lookup-properties} (@pxref{Syntax Properties}).
946 @defvar comment-end-can-be-escaped
947 If this buffer local variable is non-@code{nil}, a single character
948 which usually terminates a comment doesn't do so when that character
949 is escaped.  This is used in C and C++ Modes, where line comments
950 starting with @samp{//} can be continued onto the next line by
951 escaping the newline with @samp{\}.
952 @end defvar
954 You can use @code{forward-comment} to move forward or backward over
955 one comment or several comments.
957 @node Syntax Table Internals
958 @section Syntax Table Internals
959 @cindex syntax table internals
961   Syntax tables are implemented as char-tables (@pxref{Char-Tables}),
962 but most Lisp programs don't work directly with their elements.
963 Syntax tables do not store syntax data as syntax descriptors
964 (@pxref{Syntax Descriptors}); they use an internal format, which is
965 documented in this section.  This internal format can also be assigned
966 as syntax properties (@pxref{Syntax Properties}).
968 @cindex syntax code
969 @cindex raw syntax descriptor
970   Each entry in a syntax table is a @dfn{raw syntax descriptor}: a
971 cons cell of the form @code{(@var{syntax-code}
972 . @var{matching-char})}.  @var{syntax-code} is an integer which
973 encodes the syntax class and syntax flags, according to the table
974 below.  @var{matching-char}, if non-@code{nil}, specifies a matching
975 character (similar to the second character in a syntax descriptor).
977 @cindex syntax tables (accessing elements of)
978 Use @code{aref} (@pxref{Array Functions}) to get the raw syntax
979 descriptor of a character, e.g. @w{@code{(aref (syntax-table) ch)}}.
981   Here are the syntax codes corresponding to the various syntax
982 classes:
984 @multitable @columnfractions .2 .3 .2 .3
985 @item
986 @i{Code} @tab @i{Class} @tab @i{Code} @tab @i{Class}
987 @item
988 0 @tab whitespace @tab 8 @tab paired delimiter
989 @item
990 1 @tab punctuation @tab 9 @tab escape
991 @item
992 2 @tab word @tab 10 @tab character quote
993 @item
994 3 @tab symbol @tab 11 @tab comment-start
995 @item
996 4 @tab open parenthesis @tab 12 @tab comment-end
997 @item
998 5 @tab close parenthesis @tab 13 @tab inherit
999 @item
1000 6 @tab expression prefix @tab 14 @tab generic comment
1001 @item
1002 7 @tab string quote @tab 15 @tab generic string
1003 @end multitable
1005 @noindent
1006 For example, in the standard syntax table, the entry for @samp{(} is
1007 @code{(4 . 41)}.  41 is the character code for @samp{)}.
1009   Syntax flags are encoded in higher order bits, starting 16 bits from
1010 the least significant bit.  This table gives the power of two which
1011 corresponds to each syntax flag.
1013 @multitable @columnfractions .15 .3 .15 .3
1014 @item
1015 @i{Prefix} @tab @i{Flag} @tab @i{Prefix} @tab @i{Flag}
1016 @item
1017 @samp{1} @tab @code{(lsh 1 16)} @tab @samp{p} @tab @code{(lsh 1 20)}
1018 @item
1019 @samp{2} @tab @code{(lsh 1 17)} @tab @samp{b} @tab @code{(lsh 1 21)}
1020 @item
1021 @samp{3} @tab @code{(lsh 1 18)} @tab @samp{n} @tab @code{(lsh 1 22)}
1022 @item
1023 @samp{4} @tab @code{(lsh 1 19)} @tab @samp{c} @tab @code{(lsh 1 23)}
1024 @end multitable
1026 @defun string-to-syntax desc
1027 Given a syntax descriptor @var{desc} (a string), this function returns
1028 the corresponding raw syntax descriptor.
1029 @end defun
1031 @defun syntax-after pos
1032 This function returns the raw syntax descriptor for the character in
1033 the buffer after position @var{pos}, taking account of syntax
1034 properties as well as the syntax table.  If @var{pos} is outside the
1035 buffer's accessible portion (@pxref{Narrowing, accessible portion}),
1036 the return value is @code{nil}.
1037 @end defun
1039 @defun syntax-class syntax
1040 This function returns the syntax code for the raw syntax descriptor
1041 @var{syntax}.  More precisely, it takes the raw syntax descriptor's
1042 @var{syntax-code} component, masks off the high 16 bits which record
1043 the syntax flags, and returns the resulting integer.
1045 If @var{syntax} is @code{nil}, the return value is returns @code{nil}.
1046 This is so that the expression
1048 @example
1049 (syntax-class (syntax-after pos))
1050 @end example
1052 @noindent
1053 evaluates to @code{nil} if @code{pos} is outside the buffer's
1054 accessible portion, without throwing errors or returning an incorrect
1055 code.
1056 @end defun
1058 @node Categories
1059 @section Categories
1060 @cindex categories of characters
1061 @cindex character categories
1063   @dfn{Categories} provide an alternate way of classifying characters
1064 syntactically.  You can define several categories as needed, then
1065 independently assign each character to one or more categories.  Unlike
1066 syntax classes, categories are not mutually exclusive; it is normal for
1067 one character to belong to several categories.
1069 @cindex category table
1070   Each buffer has a @dfn{category table} which records which categories
1071 are defined and also which characters belong to each category.  Each
1072 category table defines its own categories, but normally these are
1073 initialized by copying from the standard categories table, so that the
1074 standard categories are available in all modes.
1076   Each category has a name, which is an @acronym{ASCII} printing character in
1077 the range @w{@samp{ }} to @samp{~}.  You specify the name of a category
1078 when you define it with @code{define-category}.
1080 @cindex category set
1081   The category table is actually a char-table (@pxref{Char-Tables}).
1082 The element of the category table at index @var{c} is a @dfn{category
1083 set}---a bool-vector---that indicates which categories character @var{c}
1084 belongs to.  In this category set, if the element at index @var{cat} is
1085 @code{t}, that means category @var{cat} is a member of the set, and that
1086 character @var{c} belongs to category @var{cat}.
1088 For the next three functions, the optional argument @var{table}
1089 defaults to the current buffer's category table.
1091 @defun define-category char docstring &optional table
1092 This function defines a new category, with name @var{char} and
1093 documentation @var{docstring}, for the category table @var{table}.
1095 Here's an example of defining a new category for characters that have
1096 strong right-to-left directionality (@pxref{Bidirectional Display})
1097 and using it in a special category table.  To obtain the information
1098 about the directionality of characters, the example code uses the
1099 @samp{bidi-class} Unicode property (@pxref{Character Properties,
1100 bidi-class}).
1102 @example
1103 (defvar special-category-table-for-bidi
1104   ;;     Make an empty category-table.
1105   (let ((category-table (make-category-table))
1106         ;; Create a char-table which gives the 'bidi-class' Unicode
1107         ;; property for each character.
1108         (uniprop-table
1109          (unicode-property-table-internal 'bidi-class)))
1110     (define-category ?R "Characters of bidi-class R, AL, or RLO"
1111                      category-table)
1112     ;; Modify the category entry of each character whose
1113     ;; 'bidi-class' Unicode property is R, AL, or RLO --
1114     ;; these have a right-to-left directionality.
1115     (map-char-table
1116      #'(lambda (key val)
1117          (if (memq val '(R AL RLO))
1118              (modify-category-entry key ?R category-table)))
1119      uniprop-table)
1120     category-table))
1121 @end example
1122 @end defun
1124 @defun category-docstring category &optional table
1125 This function returns the documentation string of category @var{category}
1126 in category table @var{table}.
1128 @example
1129 (category-docstring ?a)
1130      @result{} "ASCII"
1131 (category-docstring ?l)
1132      @result{} "Latin"
1133 @end example
1134 @end defun
1136 @defun get-unused-category &optional table
1137 This function returns a category name (a character) which is not
1138 currently defined in @var{table}.  If all possible categories are in use
1139 in @var{table}, it returns @code{nil}.
1140 @end defun
1142 @defun category-table
1143 This function returns the current buffer's category table.
1144 @end defun
1146 @defun category-table-p object
1147 This function returns @code{t} if @var{object} is a category table,
1148 otherwise @code{nil}.
1149 @end defun
1151 @defun standard-category-table
1152 This function returns the standard category table.
1153 @end defun
1155 @defun copy-category-table &optional table
1156 This function constructs a copy of @var{table} and returns it.  If
1157 @var{table} is not supplied (or is @code{nil}), it returns a copy of the
1158 standard category table.  Otherwise, an error is signaled if @var{table}
1159 is not a category table.
1160 @end defun
1162 @defun set-category-table table
1163 This function makes @var{table} the category table for the current
1164 buffer.  It returns @var{table}.
1165 @end defun
1167 @defun make-category-table
1168 This creates and returns an empty category table.  In an empty category
1169 table, no categories have been allocated, and no characters belong to
1170 any categories.
1171 @end defun
1173 @defun make-category-set categories
1174 This function returns a new category set---a bool-vector---whose initial
1175 contents are the categories listed in the string @var{categories}.  The
1176 elements of @var{categories} should be category names; the new category
1177 set has @code{t} for each of those categories, and @code{nil} for all
1178 other categories.
1180 @example
1181 (make-category-set "al")
1182      @result{} #&128"\0\0\0\0\0\0\0\0\0\0\0\0\2\20\0\0"
1183 @end example
1184 @end defun
1186 @defun char-category-set char
1187 This function returns the category set for character @var{char} in the
1188 current buffer's category table.  This is the bool-vector which
1189 records which categories the character @var{char} belongs to.  The
1190 function @code{char-category-set} does not allocate storage, because
1191 it returns the same bool-vector that exists in the category table.
1193 @example
1194 (char-category-set ?a)
1195      @result{} #&128"\0\0\0\0\0\0\0\0\0\0\0\0\2\20\0\0"
1196 @end example
1197 @end defun
1199 @defun category-set-mnemonics category-set
1200 This function converts the category set @var{category-set} into a string
1201 containing the characters that designate the categories that are members
1202 of the set.
1204 @example
1205 (category-set-mnemonics (char-category-set ?a))
1206      @result{} "al"
1207 @end example
1208 @end defun
1210 @defun modify-category-entry char category &optional table reset
1211 This function modifies the category set of @var{char} in category
1212 table @var{table} (which defaults to the current buffer's category
1213 table).  @var{char} can be a character, or a cons cell of the form
1214 @code{(@var{min} . @var{max})}; in the latter case, the function
1215 modifies the category sets of all characters in the range between
1216 @var{min} and @var{max}, inclusive.
1218 Normally, it modifies a category set by adding @var{category} to it.
1219 But if @var{reset} is non-@code{nil}, then it deletes @var{category}
1220 instead.
1221 @end defun
1223 @deffn Command describe-categories &optional buffer-or-name
1224 This function describes the category specifications in the current
1225 category table.  It inserts the descriptions in a buffer, and then
1226 displays that buffer.  If @var{buffer-or-name} is non-@code{nil}, it
1227 describes the category table of that buffer instead.
1228 @end deffn