jsx.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. """
  2. pygments.lexers.jsx
  3. ~~~~~~~~~~~~~~~~~~~
  4. Lexers for JSX (React).
  5. :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
  6. :license: BSD, see LICENSE for details.
  7. """
  8. import re
  9. from pygments.lexer import bygroups, default, include, inherit
  10. from pygments.lexers.javascript import JavascriptLexer
  11. from pygments.token import Name, Operator, Punctuation, String, Text, \
  12. Whitespace
  13. __all__ = ['JsxLexer']
  14. class JsxLexer(JavascriptLexer):
  15. """For JavaScript Syntax Extension (JSX).
  16. """
  17. name = "JSX"
  18. aliases = ["jsx", "react"]
  19. filenames = ["*.jsx", "*.react"]
  20. mimetypes = ["text/jsx", "text/typescript-jsx"]
  21. url = "https://facebook.github.io/jsx/"
  22. version_added = '2.17'
  23. flags = re.MULTILINE | re.DOTALL
  24. # Use same tokens as `JavascriptLexer`, but with tags and attributes support
  25. tokens = {
  26. "root": [
  27. include("jsx"),
  28. inherit,
  29. ],
  30. "jsx": [
  31. (r"</?>", Punctuation), # JSXFragment <>|</>
  32. (r"(<)(\w+)(\.?)", bygroups(Punctuation, Name.Tag, Punctuation), "tag"),
  33. (
  34. r"(</)(\w+)(>)",
  35. bygroups(Punctuation, Name.Tag, Punctuation),
  36. ),
  37. (
  38. r"(</)(\w+)",
  39. bygroups(Punctuation, Name.Tag),
  40. "fragment",
  41. ), # Same for React.Context
  42. ],
  43. "tag": [
  44. (r"\s+", Whitespace),
  45. (r"([\w-]+)(\s*)(=)(\s*)", bygroups(Name.Attribute, Whitespace, Operator, Whitespace), "attr"),
  46. (r"[{}]+", Punctuation),
  47. (r"[\w\.]+", Name.Attribute),
  48. (r"(/?)(\s*)(>)", bygroups(Punctuation, Text, Punctuation), "#pop"),
  49. ],
  50. "fragment": [
  51. (r"(.)(\w+)", bygroups(Punctuation, Name.Attribute)),
  52. (r"(>)", bygroups(Punctuation), "#pop"),
  53. ],
  54. "attr": [
  55. (r"\{", Punctuation, "expression"),
  56. (r'".*?"', String, "#pop"),
  57. (r"'.*?'", String, "#pop"),
  58. default("#pop"),
  59. ],
  60. "expression": [
  61. (r"\{", Punctuation, "#push"),
  62. (r"\}", Punctuation, "#pop"),
  63. include("root"),
  64. ],
  65. }