1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
|
---input---
.. -*- mode: rst -*-
{+.. highlight:: python+}
====================
Write your own lexer
====================
If a lexer for your favorite language is missing in the Pygments package, you
can easily write your own and extend Pygments.
All you need can be found inside the :mod:`pygments.lexer` module. As you can
read in the :doc:`API documentation <api>`, a lexer is a class that is
initialized with some keyword arguments (the lexer options) and that provides a
:meth:`.get_tokens_unprocessed()` method which is given a string or unicode
object with the data to [-parse.-] {+lex.+}
The :meth:`.get_tokens_unprocessed()` method must return an iterator or iterable
containing tuples in the form ``(index, token, value)``. Normally you don't
need to do this since there are [-numerous-] base lexers {+that do most of the work and that+}
you can subclass.
RegexLexer
==========
[-A very powerful (but quite easy to use)-]
{+The+} lexer {+base class used by almost all of Pygments' lexers+} is the
:class:`RegexLexer`. This
[-lexer base-] class allows you to define lexing rules in terms of
*regular expressions* for different *states*.
States are groups of regular expressions that are matched against the input
string at the *current position*. If one of these expressions matches, a
corresponding action is performed [-(normally-] {+(such as+} yielding a token with a specific
[-type),-]
{+type, or changing state),+} the current position is set to where the last match
ended and the matching process continues with the first regex of the current
state.
Lexer states are kept [-in-] {+on+} a [-state-] stack: each time a new state is entered, the new
state is pushed onto the stack. The most basic lexers (like the `DiffLexer`)
just need one state.
Each state is defined as a list of tuples in the form (`regex`, `action`,
`new_state`) where the last item is optional. In the most basic form, `action`
is a token type (like `Name.Builtin`). That means: When `regex` matches, emit a
token with the match text and type `tokentype` and push `new_state` on the state
stack. If the new state is ``'#pop'``, the topmost state is popped from the
stack instead. [-(To-] {+To+} pop more than one state, use ``'#pop:2'`` and so [-on.)-] {+on.+}
``'#push'`` is a synonym for pushing the current state on the stack.
The following example shows the `DiffLexer` from the builtin lexers. Note that
it contains some additional attributes `name`, `aliases` and `filenames` which
aren't required for a lexer. They are used by the builtin lexer lookup
functions.
[-.. sourcecode:: python-] {+::+}
from pygments.lexer import RegexLexer
from pygments.token import *
class DiffLexer(RegexLexer):
name = 'Diff'
aliases = ['diff']
filenames = ['*.diff']
tokens = {
'root': [
(r' .*\n', Text),
(r'\+.*\n', Generic.Inserted),
(r'-.*\n', Generic.Deleted),
(r'@.*\n', Generic.Subheading),
(r'Index.*\n', Generic.Heading),
(r'=.*\n', Generic.Heading),
(r'.*\n', Text),
]
}
As you can see this lexer only uses one state. When the lexer starts scanning
the text, it first checks if the current character is a space. If this is true
it scans everything until newline and returns the [-parsed-] data as {+a+} `Text` [-token.-] {+token (which
is the "no special highlighting" token).+}
If this rule doesn't match, it checks if the current char is a plus sign. And
so on.
If no rule matches at the current position, the current char is emitted as an
`Error` token that indicates a [-parsing-] {+lexing+} error, and the position is increased by
[-1.-]
{+one.+}
Adding and testing a new lexer
==============================
To make [-pygments-] {+Pygments+} aware of your new lexer, you have to perform the following
steps:
First, change to the current directory containing the [-pygments-] {+Pygments+} source code:
.. [-sourcecode::-] {+code-block::+} console
$ cd .../pygments-main
{+Select a matching module under ``pygments/lexers``, or create a new module for
your lexer class.+}
Next, make sure the lexer is known from outside of the module. All modules in
the ``pygments.lexers`` specify ``__all__``. For example, [-``other.py`` sets:
.. sourcecode:: python-] {+``esoteric.py`` sets::+}
__all__ = ['BrainfuckLexer', 'BefungeLexer', ...]
Simply add the name of your lexer class to this list.
Finally the lexer can be made [-publically-] {+publicly+} known by rebuilding the lexer mapping:
.. [-sourcecode::-] {+code-block::+} console
$ make mapfiles
To test the new lexer, store an example file with the proper extension in
``tests/examplefiles``. For example, to test your ``DiffLexer``, add a
``tests/examplefiles/example.diff`` containing a sample diff output.
Now you can use pygmentize to render your example to HTML:
.. [-sourcecode::-] {+code-block::+} console
$ ./pygmentize -O full -f html -o /tmp/example.html tests/examplefiles/example.diff
Note that this [-explicitely-] {+explicitly+} calls the ``pygmentize`` in the current directory
by preceding it with ``./``. This ensures your modifications are used.
Otherwise a possibly already installed, unmodified version without your new
lexer would have been called from the system search path (``$PATH``).
To view the result, open ``/tmp/example.html`` in your browser.
Once the example renders as expected, you should run the complete test suite:
.. [-sourcecode::-] {+code-block::+} console
$ make test
{+It also tests that your lexer fulfills the lexer API and certain invariants,
such as that the concatenation of all token text is the same as the input text.+}
Regex Flags
===========
You can either define regex flags {+locally+} in the regex (``r'(?x)foo bar'``) or
{+globally+} by adding a `flags` attribute to your lexer class. If no attribute is
defined, it defaults to `re.MULTILINE`. For more [-informations-] {+information+} about regular
expression flags see the {+page about+} `regular expressions`_ [-help page-] in the [-python-] {+Python+}
documentation.
.. _regular expressions: [-http://docs.python.org/lib/re-syntax.html-] {+http://docs.python.org/library/re.html#regular-expression-syntax+}
Scanning multiple tokens at once
================================
{+So far, the `action` element in the rule tuple of regex, action and state has
been a single token type. Now we look at the first of several other possible
values.+}
Here is a more complex lexer that highlights INI files. INI files consist of
sections, comments and [-key-] {+``key+} = [-value pairs:
.. sourcecode:: python-] {+value`` pairs::+}
from pygments.lexer import RegexLexer, bygroups
from pygments.token import *
class IniLexer(RegexLexer):
name = 'INI'
aliases = ['ini', 'cfg']
filenames = ['*.ini', '*.cfg']
tokens = {
'root': [
(r'\s+', Text),
(r';.*?$', Comment),
(r'\[.*?\]$', Keyword),
(r'(.*?)(\s*)(=)(\s*)(.*?)$',
bygroups(Name.Attribute, Text, Operator, Text, String))
]
}
The lexer first looks for whitespace, comments and section names. [-And later-] {+Later+} it
looks for a line that looks like a key, value pair, separated by an ``'='``
sign, and optional whitespace.
The `bygroups` helper [-makes sure that-] {+yields+} each {+capturing+} group [-is yielded-] {+in the regex+} with a different
token type. First the `Name.Attribute` token, then a `Text` token for the
optional whitespace, after that a `Operator` token for the equals sign. Then a
`Text` token for the whitespace again. The rest of the line is returned as
`String`.
Note that for this to work, every part of the match must be inside a capturing
group (a ``(...)``), and there must not be any nested capturing groups. If you
nevertheless need a group, use a non-capturing group defined using this syntax:
[-``r'(?:some|words|here)'``-]
{+``(?:some|words|here)``+} (note the ``?:`` after the beginning parenthesis).
If you find yourself needing a capturing group inside the regex which shouldn't
be part of the output but is used in the regular expressions for backreferencing
(eg: ``r'(<(foo|bar)>)(.*?)(</\2>)'``), you can pass `None` to the bygroups
function and [-it will skip-] that group will be skipped in the output.
Changing states
===============
Many lexers need multiple states to work as expected. For example, some
languages allow multiline comments to be nested. Since this is a recursive
pattern it's impossible to lex just using regular expressions.
Here is [-the solution:
.. sourcecode:: python-] {+a lexer that recognizes C++ style comments (multi-line with ``/* */``
and single-line with ``//`` until end of line)::+}
from pygments.lexer import RegexLexer
from pygments.token import *
class [-ExampleLexer(RegexLexer):-] {+CppCommentLexer(RegexLexer):+}
name = 'Example Lexer with states'
tokens = {
'root': [
(r'[^/]+', Text),
(r'/\*', Comment.Multiline, 'comment'),
(r'//.*?$', Comment.Singleline),
(r'/', Text)
],
'comment': [
(r'[^*/]', Comment.Multiline),
(r'/\*', Comment.Multiline, '#push'),
(r'\*/', Comment.Multiline, '#pop'),
(r'[*/]', Comment.Multiline)
]
}
This lexer starts lexing in the ``'root'`` state. It tries to match as much as
possible until it finds a slash (``'/'``). If the next character after the slash
is [-a star-] {+an asterisk+} (``'*'``) the `RegexLexer` sends those two characters to the
output stream marked as `Comment.Multiline` and continues [-parsing-] {+lexing+} with the rules
defined in the ``'comment'`` state.
If there wasn't [-a star-] {+an asterisk+} after the slash, the `RegexLexer` checks if it's a
[-singleline-]
{+Singleline+} comment [-(eg:-] {+(i.e.+} followed by a second slash). If this also wasn't the
case it must be a single [-slash-] {+slash, which is not a comment starter+} (the separate
regex for a single slash must also be given, else the slash would be marked as
an error token).
Inside the ``'comment'`` state, we do the same thing again. Scan until the
lexer finds a star or slash. If it's the opening of a multiline comment, push
the ``'comment'`` state on the stack and continue scanning, again in the
``'comment'`` state. Else, check if it's the end of the multiline comment. If
yes, pop one state from the stack.
Note: If you pop from an empty stack you'll get an `IndexError`. (There is an
easy way to prevent this from happening: don't ``'#pop'`` in the root state).
If the `RegexLexer` encounters a newline that is flagged as an error token, the
stack is emptied and the lexer continues scanning in the ``'root'`` state. This
[-helps-]
{+can help+} producing error-tolerant highlighting for erroneous input, e.g. when a
single-line string is not closed.
Advanced state tricks
=====================
There are a few more things you can do with states:
- You can push multiple states onto the stack if you give a tuple instead of a
simple string as the third item in a rule tuple. For example, if you want to
match a comment containing a directive, something [-like::-] {+like:
.. code-block:: text+}
/* <processing directive> rest of comment */
you can use this [-rule:
.. sourcecode:: python-] {+rule::+}
tokens = {
'root': [
(r'/\* <', Comment, ('comment', 'directive')),
...
],
'directive': [
(r'[^>]*', Comment.Directive),
(r'>', Comment, '#pop'),
],
'comment': [
(r'[^*]+', Comment),
(r'\*/', Comment, '#pop'),
(r'\*', Comment),
]
}
When this encounters the above sample, first ``'comment'`` and ``'directive'``
are pushed onto the stack, then the lexer continues in the directive state
until it finds the closing ``>``, then it continues in the comment state until
the closing ``*/``. Then, both states are popped from the stack again and
lexing continues in the root state.
.. versionadded:: 0.9
The tuple can contain the special ``'#push'`` and ``'#pop'`` (but not
``'#pop:n'``) directives.
- You can include the rules of a state in the definition of another. This is
done by using `include` from [-`pygments.lexer`:
.. sourcecode:: python-] {+`pygments.lexer`::+}
from pygments.lexer import RegexLexer, bygroups, include
from pygments.token import *
class ExampleLexer(RegexLexer):
tokens = {
'comments': [
(r'/\*.*?\*/', Comment),
(r'//.*?\n', Comment),
],
'root': [
include('comments'),
(r'(function )(\w+)( {)',
bygroups(Keyword, Name, Keyword), 'function'),
(r'.', Text),
],
'function': [
(r'[^}/]+', Text),
include('comments'),
(r'/', Text),
[-(r'}',-]
{+(r'\}',+} Keyword, '#pop'),
]
}
This is a hypothetical lexer for a language that consist of functions and
comments. Because comments can occur at toplevel and in functions, we need
rules for comments in both states. As you can see, the `include` helper saves
repeating rules that occur more than once (in this example, the state
``'comment'`` will never be entered by the lexer, as it's only there to be
included in ``'root'`` and ``'function'``).
- Sometimes, you may want to "combine" a state from existing ones. This is
possible with the [-`combine`-] {+`combined`+} helper from `pygments.lexer`.
If you, instead of a new state, write ``combined('state1', 'state2')`` as the
third item of a rule tuple, a new anonymous state will be formed from state1
and state2 and if the rule matches, the lexer will enter this state.
This is not used very often, but can be helpful in some cases, such as the
`PythonLexer`'s string literal processing.
- If you want your lexer to start lexing in a different state you can modify the
stack by [-overloading-] {+overriding+} the `get_tokens_unprocessed()` [-method:
.. sourcecode:: python-] {+method::+}
from pygments.lexer import RegexLexer
class [-MyLexer(RegexLexer):-] {+ExampleLexer(RegexLexer):+}
tokens = {...}
def get_tokens_unprocessed(self, [-text):
stack = ['root', 'otherstate']-] {+text, stack=('root', 'otherstate')):+}
for item in RegexLexer.get_tokens_unprocessed(text, stack):
yield item
Some lexers like the `PhpLexer` use this to make the leading ``<?php``
preprocessor comments optional. Note that you can crash the lexer easily by
putting values into the stack that don't exist in the token map. Also
removing ``'root'`` from the stack can result in strange errors!
- [-An-] {+In some lexers, a state should be popped if anything is encountered that isn't
matched by a rule in the state. You could use an+} empty regex at the end of [-a-]
{+the+} state list, [-combined with ``'#pop'``, can
act as-] {+but Pygments provides+} a [-return point-] {+more obvious way of spelling that:
``default('#pop')`` is equivalent to ``('', Text, '#pop')``.
.. versionadded:: 2.0
Subclassing lexers derived+} from {+RegexLexer
==========================================
.. versionadded:: 1.6
Sometimes multiple languages are very similar, but should still be lexed by
different lexer classes.
When subclassing+} a {+lexer derived from RegexLexer, the ``tokens`` dictionaries
defined in the parent and child class are merged. For example::
from pygments.lexer import RegexLexer, inherit
from pygments.token import *
class BaseLexer(RegexLexer):
tokens = {
'root': [
('[a-z]+', Name),
(r'/\*', Comment, 'comment'),
('"', String, 'string'),
('\s+', Text),
],
'string': [
('[^"]+', String),
('"', String, '#pop'),
],
'comment': [
...
],
}
class DerivedLexer(BaseLexer):
tokens = {
'root': [
('[0-9]+', Number),
inherit,
],
'string': [
(r'[^"\\]+', String),
(r'\\.', String.Escape),
('"', String, '#pop'),
],
}
The `BaseLexer` defines two states, lexing names and strings. The
`DerivedLexer` defines its own tokens dictionary, which extends the definitions
of the base lexer:
* The "root"+} state {+has an additional rule and then the special object `inherit`,
which tells Pygments to insert the token definitions of the parent class at+}
that [-doesn't have a clear end marker.-] {+point.
* The "string" state is replaced entirely, since there is not `inherit` rule.
* The "comment" state is inherited entirely.+}
Using multiple lexers
=====================
Using multiple lexers for the same input can be tricky. One of the easiest
combination techniques is shown here: You can replace the [-token type-] {+action+} entry in a rule
tuple [-(the second item)-] with a lexer class. The matched text will then be lexed with that lexer,
and the resulting tokens will be yielded.
For example, look at this stripped-down HTML [-lexer:
.. sourcecode:: python-] {+lexer::+}
from pygments.lexer import RegexLexer, bygroups, using
from pygments.token import *
from [-pygments.lexers.web-] {+pygments.lexers.javascript+} import JavascriptLexer
class HtmlLexer(RegexLexer):
name = 'HTML'
aliases = ['html']
filenames = ['*.html', '*.htm']
flags = re.IGNORECASE | re.DOTALL
tokens = {
'root': [
('[^<&]+', Text),
('&.*?;', Name.Entity),
(r'<\s*script\s*', Name.Tag, ('script-content', 'tag')),
(r'<\s*[a-zA-Z0-9:]+', Name.Tag, 'tag'),
(r'<\s*/\s*[a-zA-Z0-9:]+\s*>', Name.Tag),
],
'script-content': [
(r'(.+?)(<\s*/\s*script\s*>)',
bygroups(using(JavascriptLexer), Name.Tag),
'#pop'),
]
}
Here the content of a ``<script>`` tag is passed to a newly created instance of
a `JavascriptLexer` and not processed by the `HtmlLexer`. This is done using
the `using` helper that takes the other lexer class as its parameter.
Note the combination of `bygroups` and `using`. This makes sure that the
content up to the ``</script>`` end tag is processed by the `JavascriptLexer`,
while the end tag is yielded as a normal token with the `Name.Tag` type.
[-As an additional goodie, if the lexer class is replaced by `this` (imported from
`pygments.lexer`), the "other" lexer will be the current one (because you cannot
refer to the current class within the code that runs at class definition time).-]
Also note the ``(r'<\s*script\s*', Name.Tag, ('script-content', 'tag'))`` rule.
Here, two states are pushed onto the state stack, ``'script-content'`` and
``'tag'``. That means that first ``'tag'`` is processed, which will [-parse-] {+lex+}
attributes and the closing ``>``, then the ``'tag'`` state is popped and the
next state on top of the stack will be ``'script-content'``.
{+Since you cannot refer to the class currently being defined, use `this`
(imported from `pygments.lexer`) to refer to the current lexer class, i.e.
``using(this)``. This construct may seem unnecessary, but this is often the
most obvious way of lexing arbitrary syntax between fixed delimiters without
introducing deeply nested states.+}
The `using()` helper has a special keyword argument, `state`, which works as
follows: if given, the lexer to use initially is not in the ``"root"`` state,
but in the state given by this argument. This [-*only* works-] {+does not work+} with [-a `RegexLexer`.-] {+advanced
`RegexLexer` subclasses such as `ExtendedRegexLexer` (see below).+}
Any other keywords arguments passed to `using()` are added to the keyword
arguments used to create the lexer.
Delegating Lexer
================
Another approach for nested lexers is the `DelegatingLexer` which is for example
used for the template engine lexers. It takes two lexers as arguments on
initialisation: a `root_lexer` and a `language_lexer`.
The input is processed as follows: First, the whole text is lexed with the
`language_lexer`. All tokens yielded with [-a-] {+the special+} type of ``Other`` are
then concatenated and given to the `root_lexer`. The language tokens of the
`language_lexer` are then inserted into the `root_lexer`'s token stream at the
appropriate positions.
[-.. sourcecode:: python-] {+::+}
from pygments.lexer import DelegatingLexer
from pygments.lexers.web import HtmlLexer, PhpLexer
class HtmlPhpLexer(DelegatingLexer):
def __init__(self, **options):
super(HtmlPhpLexer, self).__init__(HtmlLexer, PhpLexer, **options)
This procedure ensures that e.g. HTML with template tags in it is highlighted
correctly even if the template tags are put into HTML tags or attributes.
If you want to change the needle token ``Other`` to something else, you can give
the lexer another token type as the third [-parameter:
.. sourcecode:: python-] {+parameter::+}
DelegatingLexer.__init__(MyLexer, OtherLexer, Text, **options)
Callbacks
=========
Sometimes the grammar of a language is so complex that a lexer would be unable
to [-parse-] {+process+} it just by using regular expressions and stacks.
For this, the `RegexLexer` allows callbacks to be given in rule tuples, instead
of token types (`bygroups` and `using` are nothing else but preimplemented
callbacks). The callback must be a function taking two arguments:
* the lexer itself
* the match object for the last matched rule
The callback must then return an iterable of (or simply yield) ``(index,
tokentype, value)`` tuples, which are then just passed through by
`get_tokens_unprocessed()`. The ``index`` here is the position of the token in
the input string, ``tokentype`` is the normal token type (like `Name.Builtin`),
and ``value`` the associated part of the input string.
You can see an example [-here:
.. sourcecode:: python-] {+here::+}
from pygments.lexer import RegexLexer
from pygments.token import Generic
class HypotheticLexer(RegexLexer):
def headline_callback(lexer, match):
equal_signs = match.group(1)
text = match.group(2)
yield match.start(), Generic.Headline, equal_signs + text + equal_signs
tokens = {
'root': [
(r'(=+)(.*?)(\1)', headline_callback)
]
}
If the regex for the `headline_callback` matches, the function is called with
the match object. Note that after the callback is done, processing continues
normally, that is, after the end of the previous match. The callback has no
possibility to influence the position.
There are not really any simple examples for lexer callbacks, but you can see
them in action e.g. in the [-`compiled.py`_ source code-] {+`SMLLexer` class+} in [-the `CLexer` and
`JavaLexer` classes.-] {+`ml.py`_.+}
.. [-_compiled.py: http://bitbucket.org/birkenfeld/pygments-main/src/tip/pygments/lexers/compiled.py-] {+_ml.py: http://bitbucket.org/birkenfeld/pygments-main/src/tip/pygments/lexers/ml.py+}
The ExtendedRegexLexer class
============================
The `RegexLexer`, even with callbacks, unfortunately isn't powerful enough for
the funky syntax rules of [-some-] languages [-that will go unnamed,-] such as Ruby.
But fear not; even then you don't have to abandon the regular expression
[-approach. For-]
{+approach:+} Pygments has a subclass of `RegexLexer`, the `ExtendedRegexLexer`.
All features known from RegexLexers are available here too, and the tokens are
specified in exactly the same way, *except* for one detail:
The `get_tokens_unprocessed()` method holds its internal state data not as local
variables, but in an instance of the `pygments.lexer.LexerContext` class, and
that instance is passed to callbacks as a third argument. This means that you
can modify the lexer state in callbacks.
The `LexerContext` class has the following members:
* `text` -- the input text
* `pos` -- the current starting position that is used for matching regexes
* `stack` -- a list containing the state stack
* `end` -- the maximum position to which regexes are matched, this defaults to
the length of `text`
Additionally, the `get_tokens_unprocessed()` method can be given a
`LexerContext` instead of a string and will then process this context instead of
creating a new one for the string argument.
Note that because you can set the current position to anything in the callback,
it won't be automatically be set by the caller after the callback is finished.
For example, this is how the hypothetical lexer above would be written with the
[-`ExtendedRegexLexer`:
.. sourcecode:: python-]
{+`ExtendedRegexLexer`::+}
from pygments.lexer import ExtendedRegexLexer
from pygments.token import Generic
class ExHypotheticLexer(ExtendedRegexLexer):
def headline_callback(lexer, match, ctx):
equal_signs = match.group(1)
text = match.group(2)
yield match.start(), Generic.Headline, equal_signs + text + equal_signs
ctx.pos = match.end()
tokens = {
'root': [
(r'(=+)(.*?)(\1)', headline_callback)
]
}
This might sound confusing (and it can really be). But it is needed, and for an
example look at the Ruby lexer in [-`agile.py`_.-] {+`ruby.py`_.+}
.. [-_agile.py: https://bitbucket.org/birkenfeld/pygments-main/src/tip/pygments/lexers/agile.py
Filtering-] {+_ruby.py: https://bitbucket.org/birkenfeld/pygments-main/src/tip/pygments/lexers/ruby.py
Handling Lists of Keywords
==========================
For a relatively short list (hundreds) you can construct an optimized regular
expression directly using ``words()`` (longer lists, see next section). This
function handles a few things for you automatically, including escaping
metacharacters and Python's first-match rather than longest-match in
alternations. Feel free to put the lists themselves in
``pygments/lexers/_$lang_builtins.py`` (see examples there), and generated by
code if possible.
An example of using ``words()`` is something like::
from pygments.lexer import RegexLexer, words, Name
class MyLexer(RegexLexer):
tokens = {
'root': [
(words(('else', 'elseif'), suffix=r'\b'), Name.Builtin),
(r'\w+', Name),
],
}
As you can see, you can add ``prefix`` and ``suffix`` parts to the constructed
regex.
Modifying+} Token Streams
=======================
Some languages ship a lot of builtin functions (for example PHP). The total
amount of those functions differs from system to system because not everybody
has every extension installed. In the case of PHP there are over 3000 builtin
functions. That's an [-incredible-] {+incredibly+} huge amount of functions, much more than you
[-can-]
{+want to+} put into a regular expression.
But because only `Name` tokens can be function names [-it's-] {+this is+} solvable by
overriding the ``get_tokens_unprocessed()`` method. The following lexer
subclasses the `PythonLexer` so that it highlights some additional names as
pseudo [-keywords:
.. sourcecode:: python-] {+keywords::+}
from [-pygments.lexers.agile-] {+pygments.lexers.python+} import PythonLexer
from pygments.token import Name, Keyword
class MyPythonLexer(PythonLexer):
EXTRA_KEYWORDS = [-['foo',-] {+set(('foo',+} 'bar', 'foobar', 'barfoo', 'spam', [-'eggs']-] {+'eggs'))+}
def get_tokens_unprocessed(self, text):
for index, token, value in PythonLexer.get_tokens_unprocessed(self, text):
if token is Name and value in self.EXTRA_KEYWORDS:
yield index, Keyword.Pseudo, value
else:
yield index, token, value
The `PhpLexer` and `LuaLexer` use this method to resolve builtin functions.
[-.. note:: Do not confuse this with the :doc:`filter <filters>` system.-]
---tokens---
'.. ' Text
'-' Text
'*' Text
'-' Text
' mode: rst ' Text
'-' Text
'*' Text
'-' Text
'\n\n' Text
'{+' Generic.Inserted
'.. highlight:: python' Generic.Inserted
'+}' Generic.Inserted
'\n\n====================\nWrite your own lexer\n====================\n\nIf a lexer for your favorite language is missing in the Pygments package, you\ncan easily write your own and extend Pygments.\n\nAll you need can be found inside the :mod:`pygments.lexer` module. As you can\nread in the :doc:`API documentation <api>`, a lexer is a class that is\ninitialized with some keyword arguments (the lexer options) and that provides a\n:meth:`.get_tokens_unprocessed()` method which is given a string or unicode\nobject with the data to ' Text
'[-' Generic.Deleted
'parse.' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'lex.' Generic.Inserted
'+}' Generic.Inserted
"\n\nThe :meth:`.get_tokens_unprocessed()` method must return an iterator or iterable\ncontaining tuples in the form ``(index, token, value)``. Normally you don't\nneed to do this since there are " Text
'[-' Generic.Deleted
'numerous' Generic.Deleted
'-]' Generic.Deleted
' base lexers ' Text
'{+' Generic.Inserted
'that do most of the work and that' Generic.Inserted
'+}' Generic.Inserted
'\nyou can subclass.\n\n\nRegexLexer\n==========\n\n' Text
'[-' Generic.Deleted
'A very powerful (but quite easy to use)' Generic.Deleted
'-]' Generic.Deleted
'\n\n' Text
'{+' Generic.Inserted
'The' Generic.Inserted
'+}' Generic.Inserted
' lexer ' Text
'{+' Generic.Inserted
"base class used by almost all of Pygments' lexers" Generic.Inserted
'+}' Generic.Inserted
' is the\n:class:`RegexLexer`. This\n' Text
'[-' Generic.Deleted
'lexer base' Generic.Deleted
'-]' Generic.Deleted
' class allows you to define lexing rules in terms of\n*regular expressions* for different *states*.\n\nStates are groups of regular expressions that are matched against the input\nstring at the *current position*. If one of these expressions matches, a\ncorresponding action is performed ' Text
'[-' Generic.Deleted
'(normally' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'(such as' Generic.Inserted
'+}' Generic.Inserted
' yielding a token with a specific\n' Text
'[-' Generic.Deleted
'type),' Generic.Deleted
'-]' Generic.Deleted
'\n' Text
'{+' Generic.Inserted
'type, or changing state),' Generic.Inserted
'+}' Generic.Inserted
' the current position is set to where the last match\nended and the matching process continues with the first regex of the current\nstate.\n\nLexer states are kept ' Text
'[-' Generic.Deleted
'in' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'on' Generic.Inserted
'+}' Generic.Inserted
' a ' Text
'[-' Generic.Deleted
'state' Generic.Deleted
'-]' Generic.Deleted
" stack: each time a new state is entered, the new\nstate is pushed onto the stack. The most basic lexers (like the `DiffLexer`)\njust need one state.\n\nEach state is defined as a list of tuples in the form (`regex`, `action`,\n`new_state`) where the last item is optional. In the most basic form, `action`\nis a token type (like `Name.Builtin`). That means: When `regex` matches, emit a\ntoken with the match text and type `tokentype` and push `new_state` on the state\nstack. If the new state is ``'#pop'``, the topmost state is popped from the\nstack instead. " Text
'[-' Generic.Deleted
'(To' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'To' Generic.Inserted
'+}' Generic.Inserted
" pop more than one state, use ``'#pop:2'`` and so " Text
'[-' Generic.Deleted
'on.)' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'on.' Generic.Inserted
'+}' Generic.Inserted
"\n``'#push'`` is a synonym for pushing the current state on the stack.\n\nThe following example shows the `DiffLexer` from the builtin lexers. Note that\nit contains some additional attributes `name`, `aliases` and `filenames` which\naren't required for a lexer. They are used by the builtin lexer lookup\nfunctions.\n\n" Text
'[-' Generic.Deleted
'.. sourcecode:: python' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'::' Generic.Inserted
'+}' Generic.Inserted
"\n\n from pygments.lexer import RegexLexer\n from pygments.token import *\n\n class DiffLexer(RegexLexer):\n name = 'Diff'\n aliases = " Text
'[' Text
"'diff'" Text
']' Text
'\n filenames = ' Text
'[' Text
"'*.diff'" Text
']' Text
'\n\n tokens = ' Text
'{' Text
"\n 'root': " Text
'[' Text
"\n (r' .*\\n', Text),\n (r'\\" Text
'+' Text
".*\\n', Generic.Inserted),\n (r'" Text
'-' Text
".*\\n', Generic.Deleted),\n (r'@.*\\n', Generic.Subheading),\n (r'Index.*\\n', Generic.Heading),\n (r'=.*\\n', Generic.Heading),\n (r'.*\\n', Text),\n " Text
']' Text
'\n ' Text
'}' Text
'\n\nAs you can see this lexer only uses one state. When the lexer starts scanning\nthe text, it first checks if the current character is a space. If this is true\nit scans everything until newline and returns the ' Text
'[-' Generic.Deleted
'parsed' Generic.Deleted
'-]' Generic.Deleted
' data as ' Text
'{+' Generic.Inserted
'a' Generic.Inserted
'+}' Generic.Inserted
' `Text` ' Text
'[-' Generic.Deleted
'token.' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'token (which\nis the "no special highlighting" token).' Generic.Inserted
'+}' Generic.Inserted
"\n\nIf this rule doesn't match, it checks if the current char is a plus sign. And\nso on.\n\nIf no rule matches at the current position, the current char is emitted as an\n`Error` token that indicates a " Text
'[-' Generic.Deleted
'parsing' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'lexing' Generic.Inserted
'+}' Generic.Inserted
' error, and the position is increased by\n' Text
'[-' Generic.Deleted
'1.' Generic.Deleted
'-]' Generic.Deleted
'\n' Text
'{+' Generic.Inserted
'one.' Generic.Inserted
'+}' Generic.Inserted
'\n\n\nAdding and testing a new lexer\n==============================\n\nTo make ' Text
'[-' Generic.Deleted
'pygments' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'Pygments' Generic.Inserted
'+}' Generic.Inserted
' aware of your new lexer, you have to perform the following\nsteps:\n\nFirst, change to the current directory containing the ' Text
'[-' Generic.Deleted
'pygments' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'Pygments' Generic.Inserted
'+}' Generic.Inserted
' source code:\n\n.. ' Text
'[-' Generic.Deleted
'sourcecode::' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'code' Generic.Inserted
'-' Generic.Inserted
'block::' Generic.Inserted
'+}' Generic.Inserted
' console\n\n $ cd .../pygments' Text
'-' Text
'main\n\n' Text
'{+' Generic.Inserted
'Select a matching module under ``pygments/lexers``, or create a new module for\nyour lexer class.' Generic.Inserted
'+}' Generic.Inserted
'\n\nNext, make sure the lexer is known from outside of the module. All modules in\nthe ``pygments.lexers`` specify ``__all__``. For example, ' Text
'[-' Generic.Deleted
'``other.py`` sets:\n\n.. sourcecode:: python' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'``esoteric.py`` sets::' Generic.Inserted
'+}' Generic.Inserted
'\n\n __all__ = ' Text
'[' Text
"'BrainfuckLexer', 'BefungeLexer', ..." Text
']' Text
'\n\nSimply add the name of your lexer class to this list.\n\nFinally the lexer can be made ' Text
'[-' Generic.Deleted
'publically' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'publicly' Generic.Inserted
'+}' Generic.Inserted
' known by rebuilding the lexer mapping:\n\n.. ' Text
'[-' Generic.Deleted
'sourcecode::' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'code' Generic.Inserted
'-' Generic.Inserted
'block::' Generic.Inserted
'+}' Generic.Inserted
' console\n\n $ make mapfiles\n\nTo test the new lexer, store an example file with the proper extension in\n``tests/examplefiles``. For example, to test your ``DiffLexer``, add a\n``tests/examplefiles/example.diff`` containing a sample diff output.\n\nNow you can use pygmentize to render your example to HTML:\n\n.. ' Text
'[-' Generic.Deleted
'sourcecode::' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'code' Generic.Inserted
'-' Generic.Inserted
'block::' Generic.Inserted
'+}' Generic.Inserted
' console\n\n $ ./pygmentize ' Text
'-' Text
'O full ' Text
'-' Text
'f html ' Text
'-' Text
'o /tmp/example.html tests/examplefiles/example.diff\n\nNote that this ' Text
'[-' Generic.Deleted
'explicitely' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'explicitly' Generic.Inserted
'+}' Generic.Inserted
' calls the ``pygmentize`` in the current directory\nby preceding it with ``./``. This ensures your modifications are used.\nOtherwise a possibly already installed, unmodified version without your new\nlexer would have been called from the system search path (``$PATH``).\n\nTo view the result, open ``/tmp/example.html`` in your browser.\n\nOnce the example renders as expected, you should run the complete test suite:\n\n.. ' Text
'[-' Generic.Deleted
'sourcecode::' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'code' Generic.Inserted
'-' Generic.Inserted
'block::' Generic.Inserted
'+}' Generic.Inserted
' console\n\n $ make test\n\n' Text
'{+' Generic.Inserted
'It also tests that your lexer fulfills the lexer API and certain invariants,\nsuch as that the concatenation of all token text is the same as the input text.' Generic.Inserted
'+}' Generic.Inserted
'\n\n\nRegex Flags\n===========\n\nYou can either define regex flags ' Text
'{+' Generic.Inserted
'locally' Generic.Inserted
'+}' Generic.Inserted
" in the regex (``r'(?x)foo bar'``) or\n" Text
'{+' Generic.Inserted
'globally' Generic.Inserted
'+}' Generic.Inserted
' by adding a `flags` attribute to your lexer class. If no attribute is\ndefined, it defaults to `re.MULTILINE`. For more ' Text
'[-' Generic.Deleted
'informations' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'information' Generic.Inserted
'+}' Generic.Inserted
' about regular\nexpression flags see the ' Text
'{+' Generic.Inserted
'page about' Generic.Inserted
'+}' Generic.Inserted
' `regular expressions`_ ' Text
'[-' Generic.Deleted
'help page' Generic.Deleted
'-]' Generic.Deleted
' in the ' Text
'[-' Generic.Deleted
'python' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'Python' Generic.Inserted
'+}' Generic.Inserted
'\ndocumentation.\n\n.. _regular expressions: ' Text
'[-' Generic.Deleted
'http://docs.python.org/lib/re' Generic.Deleted
'-' Generic.Deleted
'syntax.html' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'http://docs.python.org/library/re.html#regular' Generic.Inserted
'-' Generic.Inserted
'expression' Generic.Inserted
'-' Generic.Inserted
'syntax' Generic.Inserted
'+}' Generic.Inserted
'\n\n\nScanning multiple tokens at once\n================================\n\n' Text
'{+' Generic.Inserted
'So far, the `action` element in the rule tuple of regex, action and state has\nbeen a single token type. Now we look at the first of several other possible\nvalues.' Generic.Inserted
'+}' Generic.Inserted
'\n\nHere is a more complex lexer that highlights INI files. INI files consist of\nsections, comments and ' Text
'[-' Generic.Deleted
'key' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'``key' Generic.Inserted
'+}' Generic.Inserted
' = ' Text
'[-' Generic.Deleted
'value pairs:\n\n.. sourcecode:: python' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'value`` pairs::' Generic.Inserted
'+}' Generic.Inserted
"\n\n from pygments.lexer import RegexLexer, bygroups\n from pygments.token import *\n\n class IniLexer(RegexLexer):\n name = 'INI'\n aliases = " Text
'[' Text
"'ini', 'cfg'" Text
']' Text
'\n filenames = ' Text
'[' Text
"'*.ini', '*.cfg'" Text
']' Text
'\n\n tokens = ' Text
'{' Text
"\n 'root': " Text
'[' Text
"\n (r'\\s" Text
'+' Text
"', Text),\n (r';.*?$', Comment),\n (r'\\" Text
'[' Text
'.*?\\' Text
']' Text
"$', Keyword),\n (r'(.*?)(\\s*)(=)(\\s*)(.*?)$',\n bygroups(Name.Attribute, Text, Operator, Text, String))\n " Text
']' Text
'\n ' Text
'}' Text
'\n\nThe lexer first looks for whitespace, comments and section names. ' Text
'[-' Generic.Deleted
'And later' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'Later' Generic.Inserted
'+}' Generic.Inserted
" it\nlooks for a line that looks like a key, value pair, separated by an ``'='``\nsign, and optional whitespace.\n\nThe `bygroups` helper " Text
'[-' Generic.Deleted
'makes sure that' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'yields' Generic.Inserted
'+}' Generic.Inserted
' each ' Text
'{+' Generic.Inserted
'capturing' Generic.Inserted
'+}' Generic.Inserted
' group ' Text
'[-' Generic.Deleted
'is yielded' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'in the regex' Generic.Inserted
'+}' Generic.Inserted
' with a different\ntoken type. First the `Name.Attribute` token, then a `Text` token for the\noptional whitespace, after that a `Operator` token for the equals sign. Then a\n`Text` token for the whitespace again. The rest of the line is returned as\n`String`.\n\nNote that for this to work, every part of the match must be inside a capturing\ngroup (a ``(...)``), and there must not be any nested capturing groups. If you\nnevertheless need a group, use a non' Text
'-' Text
'capturing group defined using this syntax:\n' Text
'[-' Generic.Deleted
"``r'(?:some|words|here)'``" Generic.Deleted
'-]' Generic.Deleted
'\n' Text
'{+' Generic.Inserted
'``(?:some|words|here)``' Generic.Inserted
'+}' Generic.Inserted
" (note the ``?:`` after the beginning parenthesis).\n\nIf you find yourself needing a capturing group inside the regex which shouldn't\nbe part of the output but is used in the regular expressions for backreferencing\n(eg: ``r'(<(foo|bar)>)(.*?)(</\\2>)'``), you can pass `None` to the bygroups\nfunction and " Text
'[-' Generic.Deleted
'it will skip' Generic.Deleted
'-]' Generic.Deleted
" that group will be skipped in the output.\n\n\nChanging states\n===============\n\nMany lexers need multiple states to work as expected. For example, some\nlanguages allow multiline comments to be nested. Since this is a recursive\npattern it's impossible to lex just using regular expressions.\n\nHere is " Text
'[-' Generic.Deleted
'the solution:\n\n.. sourcecode:: python' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'a lexer that recognizes C' Generic.Inserted
'+' Generic.Inserted
'+' Generic.Inserted
' style comments (multi' Generic.Inserted
'-' Generic.Inserted
'line with ``/* */``\nand single' Generic.Inserted
'-' Generic.Inserted
'line with ``//`` until end of line)::' Generic.Inserted
'+}' Generic.Inserted
'\n\n from pygments.lexer import RegexLexer\n from pygments.token import *\n\n class ' Text
'[-' Generic.Deleted
'ExampleLexer(RegexLexer):' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'CppCommentLexer(RegexLexer):' Generic.Inserted
'+}' Generic.Inserted
"\n name = 'Example Lexer with states'\n\n tokens = " Text
'{' Text
"\n 'root': " Text
'[' Text
"\n (r'" Text
'[' Text
'^/' Text
']' Text
'+' Text
"', Text),\n (r'/\\*', Comment.Multiline, 'comment'),\n (r'//.*?$', Comment.Singleline),\n (r'/', Text)\n " Text
']' Text
",\n 'comment': " Text
'[' Text
"\n (r'" Text
'[' Text
'^*/' Text
']' Text
"', Comment.Multiline),\n (r'/\\*', Comment.Multiline, '#push'),\n (r'\\*/', Comment.Multiline, '#pop'),\n (r'" Text
'[' Text
'*/' Text
']' Text
"', Comment.Multiline)\n " Text
']' Text
'\n ' Text
'}' Text
"\n\nThis lexer starts lexing in the ``'root'`` state. It tries to match as much as\npossible until it finds a slash (``'/'``). If the next character after the slash\nis " Text
'[-' Generic.Deleted
'a star' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'an asterisk' Generic.Inserted
'+}' Generic.Inserted
" (``'*'``) the `RegexLexer` sends those two characters to the\noutput stream marked as `Comment.Multiline` and continues " Text
'[-' Generic.Deleted
'parsing' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'lexing' Generic.Inserted
'+}' Generic.Inserted
" with the rules\ndefined in the ``'comment'`` state.\n\nIf there wasn't " Text
'[-' Generic.Deleted
'a star' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'an asterisk' Generic.Inserted
'+}' Generic.Inserted
" after the slash, the `RegexLexer` checks if it's a\n" Text
'[-' Generic.Deleted
'singleline' Generic.Deleted
'-]' Generic.Deleted
'\n' Text
'{+' Generic.Inserted
'Singleline' Generic.Inserted
'+}' Generic.Inserted
' comment ' Text
'[-' Generic.Deleted
'(eg:' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'(i.e.' Generic.Inserted
'+}' Generic.Inserted
" followed by a second slash). If this also wasn't the\ncase it must be a single " Text
'[-' Generic.Deleted
'slash' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'slash, which is not a comment starter' Generic.Inserted
'+}' Generic.Inserted
" (the separate\nregex for a single slash must also be given, else the slash would be marked as\nan error token).\n\nInside the ``'comment'`` state, we do the same thing again. Scan until the\nlexer finds a star or slash. If it's the opening of a multiline comment, push\nthe ``'comment'`` state on the stack and continue scanning, again in the\n``'comment'`` state. Else, check if it's the end of the multiline comment. If\nyes, pop one state from the stack.\n\nNote: If you pop from an empty stack you'll get an `IndexError`. (There is an\neasy way to prevent this from happening: don't ``'#pop'`` in the root state).\n\nIf the `RegexLexer` encounters a newline that is flagged as an error token, the\nstack is emptied and the lexer continues scanning in the ``'root'`` state. This\n" Text
'[-' Generic.Deleted
'helps' Generic.Deleted
'-]' Generic.Deleted
'\n' Text
'{+' Generic.Inserted
'can help' Generic.Inserted
'+}' Generic.Inserted
' producing error' Text
'-' Text
'tolerant highlighting for erroneous input, e.g. when a\nsingle' Text
'-' Text
'line string is not closed.\n\n\nAdvanced state tricks\n=====================\n\nThere are a few more things you can do with states:\n\n' Text
'-' Text
' You can push multiple states onto the stack if you give a tuple instead of a\n simple string as the third item in a rule tuple. For example, if you want to\n match a comment containing a directive, something ' Text
'[-' Generic.Deleted
'like::' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'like:\n\n .. code' Generic.Inserted
'-' Generic.Inserted
'block:: text' Generic.Inserted
'+}' Generic.Inserted
'\n\n /* <processing directive> rest of comment */\n\n you can use this ' Text
'[-' Generic.Deleted
'rule:\n\n .. sourcecode:: python' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'rule::' Generic.Inserted
'+}' Generic.Inserted
'\n\n tokens = ' Text
'{' Text
"\n 'root': " Text
'[' Text
"\n (r'/\\* <', Comment, ('comment', 'directive')),\n ...\n " Text
']' Text
",\n 'directive': " Text
'[' Text
"\n (r'" Text
'[' Text
'^>' Text
']' Text
"*', Comment.Directive),\n (r'>', Comment, '#pop'),\n " Text
']' Text
",\n 'comment': " Text
'[' Text
"\n (r'" Text
'[' Text
'^*' Text
']' Text
'+' Text
"', Comment),\n (r'\\*/', Comment, '#pop'),\n (r'\\*', Comment),\n " Text
']' Text
'\n ' Text
'}' Text
"\n\n When this encounters the above sample, first ``'comment'`` and ``'directive'``\n are pushed onto the stack, then the lexer continues in the directive state\n until it finds the closing ``>``, then it continues in the comment state until\n the closing ``*/``. Then, both states are popped from the stack again and\n lexing continues in the root state.\n\n .. versionadded:: 0.9\n The tuple can contain the special ``'#push'`` and ``'#pop'`` (but not\n ``'#pop:n'``) directives.\n\n\n" Text
'-' Text
' You can include the rules of a state in the definition of another. This is\n done by using `include` from ' Text
'[-' Generic.Deleted
'`pygments.lexer`:\n\n .. sourcecode:: python' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'`pygments.lexer`::' Generic.Inserted
'+}' Generic.Inserted
'\n\n from pygments.lexer import RegexLexer, bygroups, include\n from pygments.token import *\n\n class ExampleLexer(RegexLexer):\n tokens = ' Text
'{' Text
"\n 'comments': " Text
'[' Text
"\n (r'/\\*.*?\\*/', Comment),\n (r'//.*?\\n', Comment),\n " Text
']' Text
",\n 'root': " Text
'[' Text
"\n include('comments'),\n (r'(function )(\\w" Text
'+' Text
')( ' Text
'{' Text
")',\n bygroups(Keyword, Name, Keyword), 'function'),\n (r'.', Text),\n " Text
']' Text
",\n 'function': " Text
'[' Text
"\n (r'" Text
'[' Text
'^' Text
'}' Text
'/' Text
']' Text
'+' Text
"', Text),\n include('comments'),\n (r'/', Text),\n " Text
'[-' Generic.Deleted
"(r'" Generic.Deleted
'}' Generic.Deleted
"'," Generic.Deleted
'-]' Generic.Deleted
'\n ' Text
'{+' Generic.Inserted
"(r'\\" Generic.Inserted
'}' Generic.Inserted
"'," Generic.Inserted
'+}' Generic.Inserted
" Keyword, '#pop'),\n " Text
']' Text
'\n ' Text
'}' Text
"\n\n This is a hypothetical lexer for a language that consist of functions and\n comments. Because comments can occur at toplevel and in functions, we need\n rules for comments in both states. As you can see, the `include` helper saves\n repeating rules that occur more than once (in this example, the state\n ``'comment'`` will never be entered by the lexer, as it's only there to be\n included in ``'root'`` and ``'function'``).\n\n" Text
'-' Text
' Sometimes, you may want to "combine" a state from existing ones. This is\n possible with the ' Text
'[-' Generic.Deleted
'`combine`' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'`combined`' Generic.Inserted
'+}' Generic.Inserted
" helper from `pygments.lexer`.\n\n If you, instead of a new state, write ``combined('state1', 'state2')`` as the\n third item of a rule tuple, a new anonymous state will be formed from state1\n and state2 and if the rule matches, the lexer will enter this state.\n\n This is not used very often, but can be helpful in some cases, such as the\n `PythonLexer`'s string literal processing.\n\n" Text
'-' Text
' If you want your lexer to start lexing in a different state you can modify the\n stack by ' Text
'[-' Generic.Deleted
'overloading' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'overriding' Generic.Inserted
'+}' Generic.Inserted
' the `get_tokens_unprocessed()` ' Text
'[-' Generic.Deleted
'method:\n\n .. sourcecode:: python' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'method::' Generic.Inserted
'+}' Generic.Inserted
'\n\n from pygments.lexer import RegexLexer\n\n class ' Text
'[-' Generic.Deleted
'MyLexer(RegexLexer):' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'ExampleLexer(RegexLexer):' Generic.Inserted
'+}' Generic.Inserted
'\n tokens = ' Text
'{' Text
'...' Text
'}' Text
'\n\n def get_tokens_unprocessed(self, ' Text
'[-' Generic.Deleted
'text):\n stack = ' Generic.Deleted
'[' Generic.Deleted
"'root', 'otherstate'" Generic.Deleted
']' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
"text, stack=('root', 'otherstate')):" Generic.Inserted
'+}' Generic.Inserted
"\n for item in RegexLexer.get_tokens_unprocessed(text, stack):\n yield item\n\n Some lexers like the `PhpLexer` use this to make the leading ``<?php``\n preprocessor comments optional. Note that you can crash the lexer easily by\n putting values into the stack that don't exist in the token map. Also\n removing ``'root'`` from the stack can result in strange errors!\n\n" Text
'-' Text
' ' Text
'[-' Generic.Deleted
'An' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
"In some lexers, a state should be popped if anything is encountered that isn't\n matched by a rule in the state. You could use an" Generic.Inserted
'+}' Generic.Inserted
' empty regex at the end of ' Text
'[-' Generic.Deleted
'a' Generic.Deleted
'-]' Generic.Deleted
'\n ' Text
'{+' Generic.Inserted
'the' Generic.Inserted
'+}' Generic.Inserted
' state list, ' Text
'[-' Generic.Deleted
"combined with ``'#pop'``, can\n act as" Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'but Pygments provides' Generic.Inserted
'+}' Generic.Inserted
' a ' Text
'[-' Generic.Deleted
'return point' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
"more obvious way of spelling that:\n ``default('#pop')`` is equivalent to ``('', Text, '#pop')``.\n\n .. versionadded:: 2.0\n\n\nSubclassing lexers derived" Generic.Inserted
'+}' Generic.Inserted
' from ' Text
'{+' Generic.Inserted
'RegexLexer\n==========================================\n\n.. versionadded:: 1.6\n\nSometimes multiple languages are very similar, but should still be lexed by\ndifferent lexer classes.\n\nWhen subclassing' Generic.Inserted
'+}' Generic.Inserted
' a ' Text
'{+' Generic.Inserted
'lexer derived from RegexLexer, the ``tokens`` dictionaries\ndefined in the parent and child class are merged. For example::\n\n from pygments.lexer import RegexLexer, inherit\n from pygments.token import *\n\n class BaseLexer(RegexLexer):\n tokens = ' Generic.Inserted
'{' Generic.Inserted
"\n 'root': " Generic.Inserted
'[' Generic.Inserted
"\n ('" Generic.Inserted
'[' Generic.Inserted
'a' Generic.Inserted
'-' Generic.Inserted
'z' Generic.Inserted
']' Generic.Inserted
'+' Generic.Inserted
'\', Name),\n (r\'/\\*\', Comment, \'comment\'),\n (\'"\', String, \'string\'),\n (\'\\s' Generic.Inserted
'+' Generic.Inserted
"', Text),\n " Generic.Inserted
']' Generic.Inserted
",\n 'string': " Generic.Inserted
'[' Generic.Inserted
"\n ('" Generic.Inserted
'[' Generic.Inserted
'^"' Generic.Inserted
']' Generic.Inserted
'+' Generic.Inserted
'\', String),\n (\'"\', String, \'#pop\'),\n ' Generic.Inserted
']' Generic.Inserted
",\n 'comment': " Generic.Inserted
'[' Generic.Inserted
'\n ...\n ' Generic.Inserted
']' Generic.Inserted
',\n ' Generic.Inserted
'}' Generic.Inserted
'\n\n class DerivedLexer(BaseLexer):\n tokens = ' Generic.Inserted
'{' Generic.Inserted
"\n 'root': " Generic.Inserted
'[' Generic.Inserted
"\n ('" Generic.Inserted
'[' Generic.Inserted
'0' Generic.Inserted
'-' Generic.Inserted
'9' Generic.Inserted
']' Generic.Inserted
'+' Generic.Inserted
"', Number),\n inherit,\n " Generic.Inserted
']' Generic.Inserted
",\n 'string': " Generic.Inserted
'[' Generic.Inserted
"\n (r'" Generic.Inserted
'[' Generic.Inserted
'^"\\\\' Generic.Inserted
']' Generic.Inserted
'+' Generic.Inserted
'\', String),\n (r\'\\\\.\', String.Escape),\n (\'"\', String, \'#pop\'),\n ' Generic.Inserted
']' Generic.Inserted
',\n ' Generic.Inserted
'}' Generic.Inserted
'\n\nThe `BaseLexer` defines two states, lexing names and strings. The\n`DerivedLexer` defines its own tokens dictionary, which extends the definitions\nof the base lexer:\n\n* The "root"' Generic.Inserted
'+}' Generic.Inserted
' state ' Text
'{+' Generic.Inserted
'has an additional rule and then the special object `inherit`,\n which tells Pygments to insert the token definitions of the parent class at' Generic.Inserted
'+}' Generic.Inserted
'\n that ' Text
'[-' Generic.Deleted
"doesn't have a clear end marker." Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'point.\n\n* The "string" state is replaced entirely, since there is not `inherit` rule.\n\n* The "comment" state is inherited entirely.' Generic.Inserted
'+}' Generic.Inserted
'\n\n\nUsing multiple lexers\n=====================\n\nUsing multiple lexers for the same input can be tricky. One of the easiest\ncombination techniques is shown here: You can replace the ' Text
'[-' Generic.Deleted
'token type' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'action' Generic.Inserted
'+}' Generic.Inserted
' entry in a rule\ntuple ' Text
'[-' Generic.Deleted
'(the second item)' Generic.Deleted
'-]' Generic.Deleted
' with a lexer class. The matched text will then be lexed with that lexer,\nand the resulting tokens will be yielded.\n\nFor example, look at this stripped' Text
'-' Text
'down HTML ' Text
'[-' Generic.Deleted
'lexer:\n\n.. sourcecode:: python' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'lexer::' Generic.Inserted
'+}' Generic.Inserted
'\n\n from pygments.lexer import RegexLexer, bygroups, using\n from pygments.token import *\n from ' Text
'[-' Generic.Deleted
'pygments.lexers.web' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'pygments.lexers.javascript' Generic.Inserted
'+}' Generic.Inserted
" import JavascriptLexer\n\n class HtmlLexer(RegexLexer):\n name = 'HTML'\n aliases = " Text
'[' Text
"'html'" Text
']' Text
'\n filenames = ' Text
'[' Text
"'*.html', '*.htm'" Text
']' Text
'\n\n flags = re.IGNORECASE | re.DOTALL\n tokens = ' Text
'{' Text
"\n 'root': " Text
'[' Text
"\n ('" Text
'[' Text
'^<&' Text
']' Text
'+' Text
"', Text),\n ('&.*?;', Name.Entity),\n (r'<\\s*script\\s*', Name.Tag, ('script" Text
'-' Text
"content', 'tag')),\n (r'<\\s*" Text
'[' Text
'a' Text
'-' Text
'zA' Text
'-' Text
'Z0' Text
'-' Text
'9:' Text
']' Text
'+' Text
"', Name.Tag, 'tag'),\n (r'<\\s*/\\s*" Text
'[' Text
'a' Text
'-' Text
'zA' Text
'-' Text
'Z0' Text
'-' Text
'9:' Text
']' Text
'+' Text
"\\s*>', Name.Tag),\n " Text
']' Text
",\n 'script" Text
'-' Text
"content': " Text
'[' Text
"\n (r'(." Text
'+' Text
"?)(<\\s*/\\s*script\\s*>)',\n bygroups(using(JavascriptLexer), Name.Tag),\n '#pop'),\n " Text
']' Text
'\n ' Text
'}' Text
'\n\nHere the content of a ``<script>`` tag is passed to a newly created instance of\na `JavascriptLexer` and not processed by the `HtmlLexer`. This is done using\nthe `using` helper that takes the other lexer class as its parameter.\n\nNote the combination of `bygroups` and `using`. This makes sure that the\ncontent up to the ``</script>`` end tag is processed by the `JavascriptLexer`,\nwhile the end tag is yielded as a normal token with the `Name.Tag` type.\n\n' Text
'[-' Generic.Deleted
'As an additional goodie, if the lexer class is replaced by `this` (imported from\n`pygments.lexer`), the "other" lexer will be the current one (because you cannot\nrefer to the current class within the code that runs at class definition time).' Generic.Deleted
'-]' Generic.Deleted
"\n\nAlso note the ``(r'<\\s*script\\s*', Name.Tag, ('script" Text
'-' Text
"content', 'tag'))`` rule.\nHere, two states are pushed onto the state stack, ``'script" Text
'-' Text
"content'`` and\n``'tag'``. That means that first ``'tag'`` is processed, which will " Text
'[-' Generic.Deleted
'parse' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'lex' Generic.Inserted
'+}' Generic.Inserted
"\nattributes and the closing ``>``, then the ``'tag'`` state is popped and the\nnext state on top of the stack will be ``'script" Text
'-' Text
"content'``.\n\n" Text
'{+' Generic.Inserted
'Since you cannot refer to the class currently being defined, use `this`\n(imported from `pygments.lexer`) to refer to the current lexer class, i.e.\n``using(this)``. This construct may seem unnecessary, but this is often the\nmost obvious way of lexing arbitrary syntax between fixed delimiters without\nintroducing deeply nested states.' Generic.Inserted
'+}' Generic.Inserted
'\n\nThe `using()` helper has a special keyword argument, `state`, which works as\nfollows: if given, the lexer to use initially is not in the ``"root"`` state,\nbut in the state given by this argument. This ' Text
'[-' Generic.Deleted
'*only* works' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'does not work' Generic.Inserted
'+}' Generic.Inserted
' with ' Text
'[-' Generic.Deleted
'a `RegexLexer`.' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'advanced\n`RegexLexer` subclasses such as `ExtendedRegexLexer` (see below).' Generic.Inserted
'+}' Generic.Inserted
'\n\nAny other keywords arguments passed to `using()` are added to the keyword\narguments used to create the lexer.\n\n\nDelegating Lexer\n================\n\nAnother approach for nested lexers is the `DelegatingLexer` which is for example\nused for the template engine lexers. It takes two lexers as arguments on\ninitialisation: a `root_lexer` and a `language_lexer`.\n\nThe input is processed as follows: First, the whole text is lexed with the\n`language_lexer`. All tokens yielded with ' Text
'[-' Generic.Deleted
'a' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'the special' Generic.Inserted
'+}' Generic.Inserted
" type of ``Other`` are\nthen concatenated and given to the `root_lexer`. The language tokens of the\n`language_lexer` are then inserted into the `root_lexer`'s token stream at the\nappropriate positions.\n\n" Text
'[-' Generic.Deleted
'.. sourcecode:: python' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'::' Generic.Inserted
'+}' Generic.Inserted
'\n\n from pygments.lexer import DelegatingLexer\n from pygments.lexers.web import HtmlLexer, PhpLexer\n\n class HtmlPhpLexer(DelegatingLexer):\n def __init__(self, **options):\n super(HtmlPhpLexer, self).__init__(HtmlLexer, PhpLexer, **options)\n\nThis procedure ensures that e.g. HTML with template tags in it is highlighted\ncorrectly even if the template tags are put into HTML tags or attributes.\n\nIf you want to change the needle token ``Other`` to something else, you can give\nthe lexer another token type as the third ' Text
'[-' Generic.Deleted
'parameter:\n\n.. sourcecode:: python' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'parameter::' Generic.Inserted
'+}' Generic.Inserted
'\n\n DelegatingLexer.__init__(MyLexer, OtherLexer, Text, **options)\n\n\nCallbacks\n=========\n\nSometimes the grammar of a language is so complex that a lexer would be unable\nto ' Text
'[-' Generic.Deleted
'parse' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'process' Generic.Inserted
'+}' Generic.Inserted
' it just by using regular expressions and stacks.\n\nFor this, the `RegexLexer` allows callbacks to be given in rule tuples, instead\nof token types (`bygroups` and `using` are nothing else but preimplemented\ncallbacks). The callback must be a function taking two arguments:\n\n* the lexer itself\n* the match object for the last matched rule\n\nThe callback must then return an iterable of (or simply yield) ``(index,\ntokentype, value)`` tuples, which are then just passed through by\n`get_tokens_unprocessed()`. The ``index`` here is the position of the token in\nthe input string, ``tokentype`` is the normal token type (like `Name.Builtin`),\nand ``value`` the associated part of the input string.\n\nYou can see an example ' Text
'[-' Generic.Deleted
'here:\n\n.. sourcecode:: python' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'here::' Generic.Inserted
'+}' Generic.Inserted
'\n\n from pygments.lexer import RegexLexer\n from pygments.token import Generic\n\n class HypotheticLexer(RegexLexer):\n\n def headline_callback(lexer, match):\n equal_signs = match.group(1)\n text = match.group(2)\n yield match.start(), Generic.Headline, equal_signs ' Text
'+' Text
' text ' Text
'+' Text
' equal_signs\n\n tokens = ' Text
'{' Text
"\n 'root': " Text
'[' Text
"\n (r'(=" Text
'+' Text
")(.*?)(\\1)', headline_callback)\n " Text
']' Text
'\n ' Text
'}' Text
'\n\nIf the regex for the `headline_callback` matches, the function is called with\nthe match object. Note that after the callback is done, processing continues\nnormally, that is, after the end of the previous match. The callback has no\npossibility to influence the position.\n\nThere are not really any simple examples for lexer callbacks, but you can see\nthem in action e.g. in the ' Text
'[-' Generic.Deleted
'`compiled.py`_ source code' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'`SMLLexer` class' Generic.Inserted
'+}' Generic.Inserted
' in ' Text
'[-' Generic.Deleted
'the `CLexer` and\n`JavaLexer` classes.' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'`ml.py`_.' Generic.Inserted
'+}' Generic.Inserted
'\n\n.. ' Text
'[-' Generic.Deleted
'_compiled.py: http://bitbucket.org/birkenfeld/pygments' Generic.Deleted
'-' Generic.Deleted
'main/src/tip/pygments/lexers/compiled.py' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'_ml.py: http://bitbucket.org/birkenfeld/pygments' Generic.Inserted
'-' Generic.Inserted
'main/src/tip/pygments/lexers/ml.py' Generic.Inserted
'+}' Generic.Inserted
"\n\n\nThe ExtendedRegexLexer class\n============================\n\nThe `RegexLexer`, even with callbacks, unfortunately isn't powerful enough for\nthe funky syntax rules of " Text
'[-' Generic.Deleted
'some' Generic.Deleted
'-]' Generic.Deleted
' languages ' Text
'[-' Generic.Deleted
'that will go unnamed,' Generic.Deleted
'-]' Generic.Deleted
" such as Ruby.\n\nBut fear not; even then you don't have to abandon the regular expression\n" Text
'[-' Generic.Deleted
'approach. For' Generic.Deleted
'-]' Generic.Deleted
'\n' Text
'{+' Generic.Inserted
'approach:' Generic.Inserted
'+}' Generic.Inserted
' Pygments has a subclass of `RegexLexer`, the `ExtendedRegexLexer`.\nAll features known from RegexLexers are available here too, and the tokens are\nspecified in exactly the same way, *except* for one detail:\n\nThe `get_tokens_unprocessed()` method holds its internal state data not as local\nvariables, but in an instance of the `pygments.lexer.LexerContext` class, and\nthat instance is passed to callbacks as a third argument. This means that you\ncan modify the lexer state in callbacks.\n\nThe `LexerContext` class has the following members:\n\n* `text` ' Text
'-' Text
'-' Text
' the input text\n* `pos` ' Text
'-' Text
'-' Text
' the current starting position that is used for matching regexes\n* `stack` ' Text
'-' Text
'-' Text
' a list containing the state stack\n* `end` ' Text
'-' Text
'-' Text
" the maximum position to which regexes are matched, this defaults to\n the length of `text`\n\nAdditionally, the `get_tokens_unprocessed()` method can be given a\n`LexerContext` instead of a string and will then process this context instead of\ncreating a new one for the string argument.\n\nNote that because you can set the current position to anything in the callback,\nit won't be automatically be set by the caller after the callback is finished.\nFor example, this is how the hypothetical lexer above would be written with the\n" Text
'[-' Generic.Deleted
'`ExtendedRegexLexer`:\n\n.. sourcecode:: python' Generic.Deleted
'-]' Generic.Deleted
'\n' Text
'{+' Generic.Inserted
'`ExtendedRegexLexer`::' Generic.Inserted
'+}' Generic.Inserted
'\n\n from pygments.lexer import ExtendedRegexLexer\n from pygments.token import Generic\n\n class ExHypotheticLexer(ExtendedRegexLexer):\n\n def headline_callback(lexer, match, ctx):\n equal_signs = match.group(1)\n text = match.group(2)\n yield match.start(), Generic.Headline, equal_signs ' Text
'+' Text
' text ' Text
'+' Text
' equal_signs\n ctx.pos = match.end()\n\n tokens = ' Text
'{' Text
"\n 'root': " Text
'[' Text
"\n (r'(=" Text
'+' Text
")(.*?)(\\1)', headline_callback)\n " Text
']' Text
'\n ' Text
'}' Text
'\n\nThis might sound confusing (and it can really be). But it is needed, and for an\nexample look at the Ruby lexer in ' Text
'[-' Generic.Deleted
'`agile.py`_.' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'`ruby.py`_.' Generic.Inserted
'+}' Generic.Inserted
'\n\n.. ' Text
'[-' Generic.Deleted
'_agile.py: https://bitbucket.org/birkenfeld/pygments' Generic.Deleted
'-' Generic.Deleted
'main/src/tip/pygments/lexers/agile.py\n\n\nFiltering' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'_ruby.py: https://bitbucket.org/birkenfeld/pygments' Generic.Inserted
'-' Generic.Inserted
"main/src/tip/pygments/lexers/ruby.py\n\n\nHandling Lists of Keywords\n==========================\n\nFor a relatively short list (hundreds) you can construct an optimized regular\nexpression directly using ``words()`` (longer lists, see next section). This\nfunction handles a few things for you automatically, including escaping\nmetacharacters and Python's first" Generic.Inserted
'-' Generic.Inserted
'match rather than longest' Generic.Inserted
'-' Generic.Inserted
'match in\nalternations. Feel free to put the lists themselves in\n``pygments/lexers/_$lang_builtins.py`` (see examples there), and generated by\ncode if possible.\n\nAn example of using ``words()`` is something like::\n\n from pygments.lexer import RegexLexer, words, Name\n\n class MyLexer(RegexLexer):\n\n tokens = ' Generic.Inserted
'{' Generic.Inserted
"\n 'root': " Generic.Inserted
'[' Generic.Inserted
"\n (words(('else', 'elseif'), suffix=r'\\b'), Name.Builtin),\n (r'\\w" Generic.Inserted
'+' Generic.Inserted
"', Name),\n " Generic.Inserted
']' Generic.Inserted
',\n ' Generic.Inserted
'}' Generic.Inserted
'\n\nAs you can see, you can add ``prefix`` and ``suffix`` parts to the constructed\nregex.\n\n\nModifying' Generic.Inserted
'+}' Generic.Inserted
" Token Streams\n=======================\n\nSome languages ship a lot of builtin functions (for example PHP). The total\namount of those functions differs from system to system because not everybody\nhas every extension installed. In the case of PHP there are over 3000 builtin\nfunctions. That's an " Text
'[-' Generic.Deleted
'incredible' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'incredibly' Generic.Inserted
'+}' Generic.Inserted
' huge amount of functions, much more than you\n' Text
'[-' Generic.Deleted
'can' Generic.Deleted
'-]' Generic.Deleted
'\n' Text
'{+' Generic.Inserted
'want to' Generic.Inserted
'+}' Generic.Inserted
' put into a regular expression.\n\nBut because only `Name` tokens can be function names ' Text
'[-' Generic.Deleted
"it's" Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'this is' Generic.Inserted
'+}' Generic.Inserted
' solvable by\noverriding the ``get_tokens_unprocessed()`` method. The following lexer\nsubclasses the `PythonLexer` so that it highlights some additional names as\npseudo ' Text
'[-' Generic.Deleted
'keywords:\n\n.. sourcecode:: python' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'keywords::' Generic.Inserted
'+}' Generic.Inserted
'\n\n from ' Text
'[-' Generic.Deleted
'pygments.lexers.agile' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
'pygments.lexers.python' Generic.Inserted
'+}' Generic.Inserted
' import PythonLexer\n from pygments.token import Name, Keyword\n\n class MyPythonLexer(PythonLexer):\n EXTRA_KEYWORDS = ' Text
'[-' Generic.Deleted
'[' Generic.Deleted
"'foo'," Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
"set(('foo'," Generic.Inserted
'+}' Generic.Inserted
" 'bar', 'foobar', 'barfoo', 'spam', " Text
'[-' Generic.Deleted
"'eggs'" Generic.Deleted
']' Generic.Deleted
'-]' Generic.Deleted
' ' Text
'{+' Generic.Inserted
"'eggs'))" Generic.Inserted
'+}' Generic.Inserted
'\n\n def get_tokens_unprocessed(self, text):\n for index, token, value in PythonLexer.get_tokens_unprocessed(self, text):\n if token is Name and value in self.EXTRA_KEYWORDS:\n yield index, Keyword.Pseudo, value\n else:\n yield index, token, value\n\nThe `PhpLexer` and `LuaLexer` use this method to resolve builtin functions.\n\n' Text
'[-' Generic.Deleted
'.. note:: Do not confuse this with the :doc:`filter <filters>` system.' Generic.Deleted
'-]' Generic.Deleted
'\n' Text
|