summaryrefslogtreecommitdiff
path: root/venv/lib/python3.11/site-packages/pygments/lexers/jsx.py
blob: 90cecc02771cff6726c7935ad1fc008cc42f6a54 (plain)
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
"""
    pygments.lexers.jsx
    ~~~~~~~~~~~~~~~~~~~

    Lexers for JSX (React).

    :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

import re

from pygments.lexer import bygroups, default, include, inherit
from pygments.lexers.javascript import JavascriptLexer
from pygments.token import Name, Operator, Punctuation, String, Text, \
    Whitespace

__all__ = ['JsxLexer']


class JsxLexer(JavascriptLexer):
    """For JavaScript Syntax Extension (JSX).

    .. versionadded:: 2.17
    """

    name = "JSX"
    aliases = ["jsx", "react"]
    filenames = ["*.jsx", "*.react"]
    mimetypes = ["text/jsx", "text/typescript-jsx"]
    url = "https://facebook.github.io/jsx/"

    flags = re.MULTILINE | re.DOTALL

    # Use same tokens as `JavascriptLexer`, but with tags and attributes support
    tokens = {
        "root": [
            include("jsx"),
            inherit,
        ],
        "jsx": [
            (r"</?>", Punctuation),  # JSXFragment <>|</>
            (r"(<)(\w+)(\.?)", bygroups(Punctuation, Name.Tag, Punctuation), "tag"),
            (
                r"(</)(\w+)(>)",
                bygroups(Punctuation, Name.Tag, Punctuation),
            ),
            (
                r"(</)(\w+)",
                bygroups(Punctuation, Name.Tag),
                "fragment",
            ),  # Same for React.Context
        ],
        "tag": [
            (r"\s+", Whitespace),
            (r"([\w-]+)(\s*)(=)(\s*)", bygroups(Name.Attribute, Whitespace, Operator, Whitespace), "attr"),
            (r"[{}]+", Punctuation),
            (r"[\w\.]+", Name.Attribute),
            (r"(/?)(\s*)(>)", bygroups(Punctuation, Text, Punctuation), "#pop"),
        ],
        "fragment": [
            (r"(.)(\w+)", bygroups(Punctuation, Name.Attribute)),
            (r"(>)", bygroups(Punctuation), "#pop"),
        ],
        "attr": [
            (r"\{", Punctuation, "expression"),
            (r'".*?"', String, "#pop"),
            (r"'.*?'", String, "#pop"),
            default("#pop"),
        ],
        "expression": [
            (r"\{", Punctuation, "#push"),
            (r"\}", Punctuation, "#pop"),
            include("root"),
        ],
    }