Debian Codegraph @

doc/docs/lexerdevelopment.rst

raw
1 .. -*- mode: rst -*-
2
3 .. highlight:: python
4
5 ====================
6 Write your own lexer
7 ====================
8
9 If a lexer for your favorite language is missing in the Pygments package, you
10 can easily write your own and extend Pygments.
11
12 All you need can be found inside the :mod:`pygments.lexer` module. As you can
13 read in the :doc:`API documentation <api>`, a lexer is a class that is
14 initialized with some keyword arguments (the lexer options) and that provides a
15 :meth:`.get_tokens_unprocessed()` method which is given a string or unicode
16 object with the data to lex.
17
18 The :meth:`.get_tokens_unprocessed()` method must return an iterator or iterable
19 containing tuples in the form ``(index, token, value)``. Normally you don't
20 need to do this since there are base lexers that do most of the work and that
21 you can subclass.
22
23 How to add a lexer
24 ==================
25
26 To add a lexer, you have to perform the following steps:
27
28 * Select a matching module under ``pygments/lexers``, or create a new
29 module for your lexer class.
30
31 .. note::
32
33 We encourage you to put your lexer class into its own module, unless it's a
34 very small derivative of an already existing lexer.
35
36 * Next, make sure the lexer is known from outside the module. All modules
37 in the ``pygments.lexers`` package specify ``__all__``. For example,
38 ``automation.py`` sets::
39
40 __all__ = ['AutohotkeyLexer', 'AutoItLexer']
41
42 Add the name of your lexer class to this list (or create the list if your
43 lexer is the only class in the module).
44
45 * Finally the lexer can be made publicly known by rebuilding the lexer mapping.
46
47 .. code-block:: console
48
49 $ tox -e mapfiles
50
51 How to test your lexer
52 ======================
53
54 To add a new lexer test, create a file with just your code snippet
55 under ``tests/snippets/<lexer_alias>/``. Then run
56 ``tox -- --update-goldens <filename.txt>`` to auto-populate the
57 currently expected tokens. Check that they look good and check in the
58 file.
59
60 Lexer tests are run with ``tox``, like all other tests. While
61 working on a lexer, you can also run only the tests for that lexer
62 with ``tox -- tests/snippets/language-name/`` and/or
63 ``tox -- tests/examplefiles/language-name/``.
64
65 Running the test suite with ``tox`` will run lexers on the test
66 inputs, and check that the output matches the expected tokens. If you
67 are improving a lexer, it is normal that the token output changes. To
68 update the expected token output for the tests, again use
69 ``tox -- --update-goldens <filename.txt>``. Review the changes and
70 check that they are as intended, then commit them along with your
71 proposed code change.
72
73 Large test files should go in ``tests/examplefiles``. This works
74 similar to ``snippets``, but the token output is stored in a separate
75 file. Output can also be regenerated with ``--update-goldens``.
76
77 .. note::
78
79 When contributing a new lexer, you *must* provide an example file or test
80 snippet. Lexers which can't be tested will not be accepted.
81
82 RegexLexer
83 ==========
84
85 The lexer base class used by almost all of Pygments' lexers is the
86 :class:`RegexLexer <pygments.lexer.RegexLexer>`. This class allows you to define lexing rules in terms of
87 *regular expressions* for different *states*.
88
89 States are groups of regular expressions that are matched against the input
90 string at the *current position*. If one of these expressions matches, a
91 corresponding action is performed (such as yielding a token with a specific
92 type, or changing state), the current position is set to where the last match
93 ended and the matching process continues with the _first_ regex of the current
94 state.
95
96 .. note::
97
98 This means you're always jumping back to the first entry, i.e. you cannot match states in a particular order. For example, a state with the following rules won't work as intended:
99
100 .. code:: python
101
102 'state': [
103 (r'\w+', Name,),
104 (r'\s+', Whitespace,),
105 (r'\w+', Keyword,)
106 ]
107
108 In the example above, ``Keyword`` will never be matched. To match certain token types in order, see below for the `bygroups` helper.
109
110 Lexer states are kept on a stack: each time a new state is entered, the new
111 state is pushed onto the stack. The most basic lexers (like the `DiffLexer`)
112 just need one state.
113
114 Each state is defined as a list of tuples in the form (`regex`, `action`,
115 `new_state`) where the last item is optional. In the most basic form, `action`
116 is a token type (like `Name.Builtin`). That means: When `regex` matches, emit a
117 token with the match text and type `tokentype` and push `new_state` on the state
118 stack. If the new state is ``'#pop'``, the topmost state is popped from the
119 stack instead. To pop more than one state, use ``'#pop:2'`` and so on.
120 ``'#push'`` is a synonym for pushing a second time the current state on top of
121 the stack.
122
123 The following example shows the `DiffLexer` from the builtin lexers. Note that
124 it contains some additional attributes `name`, `aliases` and `filenames` which
125 aren't required for a lexer. They are used by the builtin lexer lookup
126 functions. ::
127
128 from pygments.lexer import RegexLexer
129 from pygments.token import *
130
131 class DiffLexer(RegexLexer):
132 name = 'Diff'
133 aliases = ['diff']
134 filenames = ['*.diff']
135
136 tokens = {
137 'root': [
138 (r' .*\n', Text),
139 (r'\+.*\n', Generic.Inserted),
140 (r'-.*\n', Generic.Deleted),
141 (r'@.*\n', Generic.Subheading),
142 (r'Index.*\n', Generic.Heading),
143 (r'=.*\n', Generic.Heading),
144 (r'.*\n', Text),
145 ]
146 }
147
148 As you can see this lexer only uses one state. When the lexer starts scanning
149 the text, it first checks if the current character is a space. If this is true
150 it scans everything until newline and returns the data as a `Text` token (which
151 is the "no special highlighting" token).
152
153 If this rule doesn't match, it checks if the current char is a plus sign. And
154 so on.
155
156 If no rule matches at the current position, the current char is emitted as an
157 `Error` token that indicates a lexing error, and the position is increased by
158 one.
159
160
161 Using a lexer
162 =============
163
164 The easiest way to use a new lexer is to use Pygments' support for loading
165 the lexer from a file relative to your current directory.
166
167 First, change the name of your lexer class to CustomLexer:
168
169 .. code-block:: python
170
171 from pygments.lexer import RegexLexer
172 from pygments.token import *
173
174 class CustomLexer(RegexLexer):
175 """All your lexer code goes here!"""
176
177 Then you can load and test the lexer from the command line with the additional
178 flag ``-x``:
179
180 .. code-block:: console
181
182 $ python -m pygments -x -l your_lexer_file.py <inputfile>
183
184 To specify a class name other than CustomLexer, append it with a colon:
185
186 .. code-block:: console
187
188 $ python -m pygments -x -l your_lexer.py:SomeLexer <inputfile>
189
190 Or, using the Python API:
191
192 .. code-block:: python
193
194 # For a lexer named CustomLexer
195 your_lexer = load_lexer_from_file(filename, **options)
196
197 # For a lexer named MyNewLexer
198 your_named_lexer = load_lexer_from_file(filename, "MyNewLexer", **options)
199
200 When loading custom lexers and formatters, be extremely careful to use only
201 trusted files; Pygments will perform the equivalent of ``eval`` on them.
202
203 If you only want to use your lexer with the Pygments API, you can import and
204 instantiate the lexer yourself, then pass it to :func:`pygments.highlight`.
205
206 Use the ``-f`` flag to select a different output format than terminal
207 escape sequences. The :class:`.HtmlFormatter` helps
208 you with debugging your lexer. You can use the ``debug_token_types`` option
209 to display the token types assigned to each part of your input file:
210
211 .. code-block:: console
212
213 $ python -m pygments -x -f html -Ofull,debug_token_types -l your_lexer.py:SomeLexer <inputfile>
214
215 Hover over each token to see the token type displayed as a tooltip.
216
217 If your lexer would be useful to other people, we would love if you
218 contributed it to Pygments. See :doc:`contributing` for advice.
219
220
221 Regex Flags
222 ===========
223
224 You can either define regex flags locally in the regex (``r'(?x)foo bar'``) or
225 globally by adding a `flags` attribute to your lexer class. If no attribute is
226 defined, it defaults to `re.MULTILINE`. For more information about regular
227 expression flags see the page about `regular expressions`_ in the Python
228 documentation.
229
230 .. _regular expressions: https://docs.python.org/library/re.html#regular-expression-syntax
231
232
233 Scanning multiple tokens at once
234 ================================
235
236 So far, the `action` element in the rule tuple of regex, action and state has
237 been a single token type. Now we look at the first of several other possible
238 values.
239
240 Here is a more complex lexer that highlights INI files. INI files consist of
241 sections, comments and ``key = value`` pairs::
242
243 from pygments.lexer import RegexLexer, bygroups
244 from pygments.token import *
245
246 class IniLexer(RegexLexer):
247 name = 'INI'
248 aliases = ['ini', 'cfg']
249 filenames = ['*.ini', '*.cfg']
250
251 tokens = {
252 'root': [
253 (r'\s+', Whitespace),
254 (r';.*', Comment),
255 (r'\[.*?\]$', Keyword),
256 (r'(.*?)(\s*)(=)(\s*)(.*)',
257 bygroups(Name.Attribute, Whitespace, Operator, Whitespace, String))
258 ]
259 }
260
261 The lexer first looks for whitespace, comments and section names. Later it
262 looks for a line that looks like a key, value pair, separated by an ``'='``
263 sign, and optional whitespace.
264
265 The `bygroups` helper yields each capturing group in the regex with a different
266 token type. First the `Name.Attribute` token, then a `Text` token for the
267 optional whitespace, after that a `Operator` token for the equals sign. Then a
268 `Text` token for the whitespace again. The rest of the line is returned as
269 `String`.
270
271 Note that for this to work, every part of the match must be inside a capturing
272 group (a ``(...)``), and there must not be any nested capturing groups. If you
273 nevertheless need a group, use a non-capturing group defined using this syntax:
274 ``(?:some|words|here)`` (note the ``?:`` after the beginning parenthesis).
275
276 If you find yourself needing a capturing group inside the regex which shouldn't
277 be part of the output but is used in the regular expressions for backreferencing
278 (eg: ``r'(<(foo|bar)>)(.*?)(</\2>)'``), you can pass `None` to the bygroups
279 function and that group will be skipped in the output.
280
281
282 Changing states
283 ===============
284
285 Many lexers need multiple states to work as expected. For example, some
286 languages allow multiline comments to be nested. Since this is a recursive
287 pattern it's impossible to lex just using regular expressions.
288
289 Here is a lexer that recognizes C++ style comments (multi-line with ``/* */``
290 and single-line with ``//`` until end of line)::
291
292 from pygments.lexer import RegexLexer
293 from pygments.token import *
294
295 class CppCommentLexer(RegexLexer):
296 name = 'Example Lexer with states'
297
298 tokens = {
299 'root': [
300 (r'[^/]+', Text),
301 (r'/\*', Comment.Multiline, 'comment'),
302 (r'//.*?$', Comment.Singleline),
303 (r'/', Text)
304 ],
305 'comment': [
306 (r'[^*/]+', Comment.Multiline),
307 (r'/\*', Comment.Multiline, '#push'),
308 (r'\*/', Comment.Multiline, '#pop'),
309 (r'[*/]', Comment.Multiline)
310 ]
311 }
312
313 This lexer starts lexing in the ``'root'`` state. It tries to match as much as
314 possible until it finds a slash (``'/'``). If the next character after the slash
315 is an asterisk (``'*'``) the `RegexLexer` sends those two characters to the
316 output stream marked as `Comment.Multiline` and continues lexing with the rules
317 defined in the ``'comment'`` state.
318
319 If there wasn't an asterisk after the slash, the `RegexLexer` checks if it's a
320 Singleline comment (i.e. followed by a second slash). If this also wasn't the
321 case it must be a single slash, which is not a comment starter (the separate
322 regex for a single slash must also be given, else the slash would be marked as
323 an error token).
324
325 Inside the ``'comment'`` state, we do the same thing again. Scan until the
326 lexer finds a star or slash. If it's the opening of a multiline comment, push
327 the ``'comment'`` state on the stack and continue scanning, again in the
328 ``'comment'`` state. Else, check if it's the end of the multiline comment. If
329 yes, pop one state from the stack.
330
331 Note: If you pop from an empty stack you'll get an `IndexError`. (There is an
332 easy way to prevent this from happening: don't ``'#pop'`` in the root state).
333
334 If the `RegexLexer` encounters a newline that is flagged as an error token, the
335 stack is emptied and the lexer continues scanning in the ``'root'`` state. This
336 can help producing error-tolerant highlighting for erroneous input, e.g. when a
337 single-line string is not closed.
338
339
340 Advanced state tricks
341 =====================
342
343 There are a few more things you can do with states:
344
345 - You can push multiple states onto the stack if you give a tuple instead of a
346 simple string as the third item in a rule tuple. For example, if you want to
347 match a comment containing a directive, something like:
348
349 .. code-block:: text
350
351 /* <processing directive> rest of comment */
352
353 you can use this rule::
354
355 tokens = {
356 'root': [
357 (r'/\* <', Comment, ('comment', 'directive')),
358 ...
359 ],
360 'directive': [
361 (r'[^>]+', Comment.Directive),
362 (r'>', Comment, '#pop'),
363 ],
364 'comment': [
365 (r'[^*]+', Comment),
366 (r'\*/', Comment, '#pop'),
367 (r'\*', Comment),
368 ]
369 }
370
371 When this encounters the above sample, first ``'comment'`` and ``'directive'``
372 are pushed onto the stack, then the lexer continues in the directive state
373 until it finds the closing ``>``, then it continues in the comment state until
374 the closing ``*/``. Then, both states are popped from the stack again and
375 lexing continues in the root state.
376
377 .. versionadded:: 0.9
378 The tuple can contain the special ``'#push'`` and ``'#pop'`` (but not
379 ``'#pop:n'``) directives.
380
381
382 - You can include the rules of a state in the definition of another. This is
383 done by using `include` from `pygments.lexer`::
384
385 from pygments.lexer import RegexLexer, bygroups, include
386 from pygments.token import *
387
388 class ExampleLexer(RegexLexer):
389 tokens = {
390 'comments': [
391 (r'(?s)/\*.*?\*/', Comment),
392 (r'//.*?\n', Comment),
393 ],
394 'root': [
395 include('comments'),
396 (r'(function)( )(\w+)( )({)',
397 bygroups(Keyword, Whitespace, Name, Whitespace, Punctuation), 'function'),
398 (r'.*\n', Text),
399 ],
400 'function': [
401 (r'[^}/]+', Text),
402 include('comments'),
403 (r'/', Text),
404 (r'\}', Punctuation, '#pop'),
405 ]
406 }
407
408 This is a hypothetical lexer for a language that consist of functions and
409 comments. Because comments can occur at toplevel and in functions, we need
410 rules for comments in both states. As you can see, the `include` helper saves
411 repeating rules that occur more than once (in this example, the state
412 ``'comment'`` will never be entered by the lexer, as it's only there to be
413 included in ``'root'`` and ``'function'``).
414
415 - Sometimes, you may want to "combine" a state from existing ones. This is
416 possible with the `combined` helper from `pygments.lexer`.
417
418 If you, instead of a new state, write ``combined('state1', 'state2')`` as the
419 third item of a rule tuple, a new anonymous state will be formed from state1
420 and state2 and if the rule matches, the lexer will enter this state.
421
422 This is not used very often, but can be helpful in some cases, such as the
423 `PythonLexer`'s string literal processing.
424
425 - If you want your lexer to start lexing in a different state you can modify the
426 stack by overriding the `get_tokens_unprocessed()` method::
427
428 from pygments.lexer import RegexLexer
429
430 class ExampleLexer(RegexLexer):
431 tokens = {...}
432
433 def get_tokens_unprocessed(self, text, stack=('root', 'otherstate')):
434 for item in RegexLexer.get_tokens_unprocessed(self, text, stack):
435 yield item
436
437 Some lexers like the `PhpLexer` use this to make the leading ``<?php``
438 preprocessor comments optional. Note that you can crash the lexer easily by
439 putting values into the stack that don't exist in the token map. Also
440 removing ``'root'`` from the stack can result in strange errors!
441
442 - In some lexers, a state should be popped if anything is encountered that isn't
443 matched by a rule in the state. You could use an empty regex at the end of
444 the state list, but Pygments provides a more obvious way of spelling that:
445 ``default('#pop')`` is equivalent to ``('', Text, '#pop')``.
446
447 .. versionadded:: 2.0
448
449
450 Subclassing lexers derived from RegexLexer
451 ==========================================
452
453 .. versionadded:: 1.6
454
455 Sometimes multiple languages are very similar, but should still be lexed by
456 different lexer classes.
457
458 When subclassing a lexer derived from RegexLexer, the ``tokens`` dictionaries
459 defined in the parent and child class are merged. For example::
460
461 from pygments.lexer import RegexLexer, inherit
462 from pygments.token import *
463
464 class BaseLexer(RegexLexer):
465 tokens = {
466 'root': [
467 ('[a-z]+', Name),
468 (r'/\*', Comment, 'comment'),
469 ('"', String, 'string'),
470 (r'\s+', Whitespace),
471 ],
472 'string': [
473 ('[^"]+', String),
474 ('"', String, '#pop'),
475 ],
476 'comment': [
477 ...
478 ],
479 }
480
481 class DerivedLexer(BaseLexer):
482 tokens = {
483 'root': [
484 ('[0-9]+', Number),
485 inherit,
486 ],
487 'string': [
488 (r'[^"\\]+', String),
489 (r'\\.', String.Escape),
490 ('"', String, '#pop'),
491 ],
492 }
493
494 The `BaseLexer` defines two states, lexing names and strings. The
495 `DerivedLexer` defines its own tokens dictionary, which extends the definitions
496 of the base lexer:
497
498 * The "root" state has an additional rule and then the special object `inherit`,
499 which tells Pygments to insert the token definitions of the parent class at
500 that point.
501
502 * The "string" state is replaced entirely, since there is not `inherit` rule.
503
504 * The "comment" state is inherited entirely.
505
506
507 Using multiple lexers
508 =====================
509
510 Using multiple lexers for the same input can be tricky. One of the easiest
511 combination techniques is shown here: You can replace the action entry in a rule
512 tuple with a lexer class. The matched text will then be lexed with that lexer,
513 and the resulting tokens will be yielded.
514
515 For example, look at this stripped-down HTML lexer::
516
517 from pygments.lexer import RegexLexer, bygroups, using
518 from pygments.token import *
519 from pygments.lexers.javascript import JavascriptLexer
520
521 class HtmlLexer(RegexLexer):
522 name = 'HTML'
523 aliases = ['html']
524 filenames = ['*.html', '*.htm']
525
526 flags = re.IGNORECASE | re.DOTALL
527 tokens = {
528 'root': [
529 ('[^<&]+', Text),
530 ('&.*?;', Name.Entity),
531 (r'<\s*script\s*', Name.Tag, ('script-content', 'tag')),
532 (r'<\s*[a-zA-Z0-9:]+', Name.Tag, 'tag'),
533 (r'<\s*/\s*[a-zA-Z0-9:]+\s*>', Name.Tag),
534 ],
535 'script-content': [
536 (r'(.+?)(<\s*/\s*script\s*>)',
537 bygroups(using(JavascriptLexer), Name.Tag),
538 '#pop'),
539 ]
540 }
541
542 Here the content of a ``<script>`` tag is passed to a newly created instance of
543 a `JavascriptLexer` and not processed by the `HtmlLexer`. This is done using
544 the `using` helper that takes the other lexer class as its parameter.
545
546 Note the combination of `bygroups` and `using`. This makes sure that the
547 content up to the ``</script>`` end tag is processed by the `JavascriptLexer`,
548 while the end tag is yielded as a normal token with the `Name.Tag` type.
549
550 Also note the ``(r'<\s*script\s*', Name.Tag, ('script-content', 'tag'))`` rule.
551 Here, two states are pushed onto the state stack, ``'script-content'`` and
552 ``'tag'``. That means that first ``'tag'`` is processed, which will lex
553 attributes and the closing ``>``, then the ``'tag'`` state is popped and the
554 next state on top of the stack will be ``'script-content'``.
555
556 Since you cannot refer to the class currently being defined, use `this`
557 (imported from `pygments.lexer`) to refer to the current lexer class, i.e.
558 ``using(this)``. This construct may seem unnecessary, but this is often the
559 most obvious way of lexing arbitrary syntax between fixed delimiters without
560 introducing deeply nested states.
561
562 The `using()` helper has a special keyword argument, `state`, which works as
563 follows: if given, the lexer to use initially is not in the ``"root"`` state,
564 but in the state given by this argument. This does not work with advanced
565 `RegexLexer` subclasses such as `ExtendedRegexLexer` (see below).
566
567 Any other keywords arguments passed to `using()` are added to the keyword
568 arguments used to create the lexer.
569
570
571 Delegating Lexer
572 ================
573
574 Another approach for nested lexers is the `DelegatingLexer` which is for example
575 used for the template engine lexers. It takes two lexers as arguments on
576 initialisation: a `root_lexer` and a `language_lexer`.
577
578 The input is processed as follows: First, the whole text is lexed with the
579 `language_lexer`. All tokens yielded with the special type of ``Other`` are
580 then concatenated and given to the `root_lexer`. The language tokens of the
581 `language_lexer` are then inserted into the `root_lexer`'s token stream at the
582 appropriate positions. ::
583
584 from pygments.lexer import DelegatingLexer
585 from pygments.lexers.web import HtmlLexer, PhpLexer
586
587 class HtmlPhpLexer(DelegatingLexer):
588 def __init__(self, **options):
589 super().__init__(HtmlLexer, PhpLexer, **options)
590
591 This procedure ensures that e.g. HTML with template tags in it is highlighted
592 correctly even if the template tags are put into HTML tags or attributes.
593
594 If you want to change the needle token ``Other`` to something else, you can give
595 the lexer another token type as the third parameter::
596
597 DelegatingLexer.__init__(MyLexer, OtherLexer, Text, **options)
598
599
600 Callbacks
601 =========
602
603 Sometimes the grammar of a language is so complex that a lexer would be unable
604 to process it just by using regular expressions and stacks.
605
606 For this, the `RegexLexer` allows callbacks to be given in rule tuples, instead
607 of token types (`bygroups` and `using` are nothing else but preimplemented
608 callbacks). The callback must be a function taking two arguments:
609
610 * the lexer itself
611 * the match object for the last matched rule
612
613 The callback must then return an iterable of (or simply yield) ``(index,
614 tokentype, value)`` tuples, which are then just passed through by
615 `get_tokens_unprocessed()`. The ``index`` here is the position of the token in
616 the input string, ``tokentype`` is the normal token type (like `Name.Builtin`),
617 and ``value`` the associated part of the input string.
618
619 You can see an example here::
620
621 from pygments.lexer import RegexLexer
622 from pygments.token import Generic
623
624 class HypotheticLexer(RegexLexer):
625
626 def headline_callback(lexer, match):
627 equal_signs = match.group(1)
628 text = match.group(2)
629 yield match.start(), Generic.Headline, equal_signs + text + equal_signs
630
631 tokens = {
632 'root': [
633 (r'(=+)(.*?)(\1)', headline_callback)
634 ]
635 }
636
637 If the regex for the `headline_callback` matches, the function is called with
638 the match object. Note that after the callback is done, processing continues
639 normally, that is, after the end of the previous match. The callback has no
640 possibility to influence the position.
641
642 There are not really any simple examples for lexer callbacks, but you can see
643 them in action e.g. in the `SMLLexer` class in `ml.py`_.
644
645 .. _ml.py: https://github.com/pygments/pygments/blob/master/pygments/lexers/ml.py
646
647
648 The ExtendedRegexLexer class
649 ============================
650
651 The `RegexLexer`, even with callbacks, unfortunately isn't powerful enough for
652 the funky syntax rules of languages such as Ruby.
653
654 But fear not; even then you don't have to abandon the regular expression
655 approach: Pygments has a subclass of `RegexLexer`, the `ExtendedRegexLexer`.
656 All features known from RegexLexers are available here too, and the tokens are
657 specified in exactly the same way, *except* for one detail:
658
659 The `get_tokens_unprocessed()` method holds its internal state data not as local
660 variables, but in an instance of the `pygments.lexer.LexerContext` class, and
661 that instance is passed to callbacks as a third argument. This means that you
662 can modify the lexer state in callbacks.
663
664 The `LexerContext` class has the following members:
665
666 * `text` -- the input text
667 * `pos` -- the current starting position that is used for matching regexes
668 * `stack` -- a list containing the state stack
669 * `end` -- the maximum position to which regexes are matched, this defaults to
670 the length of `text`
671
672 Additionally, the `get_tokens_unprocessed()` method can be given a
673 `LexerContext` instead of a string and will then process this context instead of
674 creating a new one for the string argument.
675
676 Note that because you can set the current position to anything in the callback,
677 it won't be automatically be set by the caller after the callback is finished.
678 For example, this is how the hypothetical lexer above would be written with the
679 `ExtendedRegexLexer`::
680
681 from pygments.lexer import ExtendedRegexLexer
682 from pygments.token import Generic
683
684 class ExHypotheticLexer(ExtendedRegexLexer):
685
686 def headline_callback(lexer, match, ctx):
687 equal_signs = match.group(1)
688 text = match.group(2)
689 yield match.start(), Generic.Headline, equal_signs + text + equal_signs
690 ctx.pos = match.end()
691
692 tokens = {
693 'root': [
694 (r'(=+)(.*?)(\1)', headline_callback)
695 ]
696 }
697
698 This might sound confusing (and it can really be). But it is needed, and for an
699 example look at the Ruby lexer in `ruby.py`_.
700
701 .. _ruby.py: https://github.com/pygments/pygments/blob/master/pygments/lexers/ruby.py
702
703
704 Handling Lists of Keywords
705 ==========================
706
707 For a relatively short list (hundreds) you can construct an optimized regular
708 expression directly using ``words()`` (longer lists, see next section). This
709 function handles a few things for you automatically, including escaping
710 metacharacters and Python's first-match rather than longest-match in
711 alternations. Feel free to put the lists themselves in
712 ``pygments/lexers/_$lang_builtins.py`` (see examples there), and generated by
713 code if possible.
714
715 An example of using ``words()`` is something like::
716
717 from pygments.lexer import RegexLexer, words, Name
718
719 class MyLexer(RegexLexer):
720
721 tokens = {
722 'root': [
723 (words(('else', 'elseif'), suffix=r'\b'), Name.Builtin),
724 (r'\w+', Name),
725 ],
726 }
727
728 As you can see, you can add ``prefix`` and ``suffix`` parts to the constructed
729 regex.
730
731
732 Modifying Token Streams
733 =======================
734
735 Some languages ship a lot of builtin functions (for example PHP). The total
736 amount of those functions differs from system to system because not everybody
737 has every extension installed. In the case of PHP there are over 3000 builtin
738 functions. That's an incredibly huge amount of functions, much more than you
739 want to put into a regular expression.
740
741 But because only `Name` tokens can be function names this is solvable by
742 overriding the ``get_tokens_unprocessed()`` method. The following lexer
743 subclasses the `PythonLexer` so that it highlights some additional names as
744 pseudo keywords::
745
746 from pygments.lexers.python import PythonLexer
747 from pygments.token import Name, Keyword
748
749 class MyPythonLexer(PythonLexer):
750 EXTRA_KEYWORDS = set(('foo', 'bar', 'foobar', 'barfoo', 'spam', 'eggs'))
751
752 def get_tokens_unprocessed(self, text):
753 for index, token, value in PythonLexer.get_tokens_unprocessed(self, text):
754 if token is Name and value in self.EXTRA_KEYWORDS:
755 yield index, Keyword.Pseudo, value
756 else:
757 yield index, token, value
758
759 The `PhpLexer` and `LuaLexer` use this method to resolve builtin functions.
760
761
762
763 .. _lexer-pitfalls:
764
765 Common pitfalls and best practices
766 ==================================
767
768 Regular expressions are ubiquitous in Pygments lexers. We have
769 written this section to warn about a few common mistakes you might do
770 when using them. There are also some tips on making your lexers easier
771 to read and review. You are asked to read this section if you want to
772 contribute a new lexer, but you might find it useful in any case.
773
774
775 * When writing rules, try to merge simple rules. For instance, combine::
776
777 (r"\(", token.Punctuation),
778 (r"\)", token.Punctuation),
779 (r"\[", token.Punctuation),
780 (r"\]", token.Punctuation),
781 ("{", token.Punctuation),
782 ("}", token.Punctuation),
783
784 into::
785
786 (r"[\(\)\[\]{}]+", token.Punctuation)
787
788 .. note::
789
790 We're using ``+`` here as well to match successive punctuation tokens together. See below for more information about this.
791
792
793 * Be careful with ``.*``. This matches greedily as much as it can. For instance,
794 a rule like ``@.*@`` will match the whole string ``@first@ second @third@``,
795 instead of matching ``@first@`` and ``@third@``. You can use ``@.*?@`` in
796 this case to stop early. The ``?`` tries to match *as few times* as possible.
797
798 * Beware of so-called "catastrophic backtracking". As a first example, consider
799 the regular expression ``(A+)*B``. This is equivalent to ``A*B`` regarding
800 what it matches, but *non*-matches will take very long. This is because
801 of the way the regular expression engine works. Suppose you feed it 50
802 'A's, and a 'C' at the end. It first matches the 'A's greedily in ``A+``,
803 but finds that it cannot match the end since 'B' is not the same as 'C'.
804 Then it backtracks, removing one 'A' from the first ``A+`` and trying to
805 match the rest as another ``(A+)*``. This fails again, so it backtracks
806 further left in the input string, etc. In effect, it tries all combinations
807
808 .. code-block:: text
809
810 (AAAAAAAAAAAAAAAAA)
811 (AAAAAAAAAAAAAAAA)(A)
812 (AAAAAAAAAAAAAAA)(AA)
813 (AAAAAAAAAAAAAAA)(A)(A)
814 (AAAAAAAAAAAAAA)(AAA)
815 (AAAAAAAAAAAAAA)(AA)(A)
816 ...
817
818 Thus, the matching has exponential complexity. In a lexer, the
819 effect is that Pygments will seemingly hang when parsing invalid
820 input. ::
821
822 >>> import re
823 >>> re.match('(A+)*B', 'A'*50 + 'C') # hangs
824
825 As a more subtle and real-life example, here is a badly written
826 regular expression to match strings::
827
828 r'"(\\?.)*?"'
829
830 If the ending quote is missing, the regular expression engine will
831 find that it cannot match at the end, and try to backtrack with fewer
832 matches in the ``*?``. When it finds a backslash, as it has already
833 tried the possibility ``\\.``, it tries ``.`` (recognizing it as a
834 simple character without meaning), which leads to the same
835 exponential backtracking problem if there are lots of backslashes in
836 the (invalid) input string. A good way to write this would be
837 ``r'"([^\\]|\\.)*?"'``, where the inner group can only match in one
838 way. Better yet is to use a dedicated state, which not only
839 sidesteps the issue without headaches, but allows you to highlight
840 string escapes. ::
841
842 'root': [
843 ...,
844 (r'"', String, 'string'),
845 ...
846 ],
847 'string': [
848 (r'\\.', String.Escape),
849 (r'"', String, '#pop'),
850 (r'[^\\"]+', String),
851 ]
852
853 * When writing rules for patterns such as comments or strings, match as many
854 characters as possible in each token. This is an example of what *not* to
855 do::
856
857 'comment': [
858 (r'\*/', Comment.Multiline, '#pop'),
859 (r'.', Comment.Multiline),
860 ]
861
862 This generates one token per character in the comment, which slows
863 down the lexing process, and also makes the raw token output (and in
864 particular the test output) hard to read. Do this instead::
865
866 'comment': [
867 (r'\*/', Comment.Multiline, '#pop'),
868 (r'[^*]+', Comment.Multiline),
869 (r'\*', Comment.Multiline),
870 ]