mime.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. """
  2. pygments.lexers.mime
  3. ~~~~~~~~~~~~~~~~~~~~
  4. Lexer for Multipurpose Internet Mail Extensions (MIME) data.
  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 RegexLexer, include
  10. from pygments.lexers import get_lexer_for_mimetype
  11. from pygments.token import Text, Name, String, Operator, Comment, Other
  12. from pygments.util import get_int_opt, ClassNotFound
  13. __all__ = ["MIMELexer"]
  14. class MIMELexer(RegexLexer):
  15. """
  16. Lexer for Multipurpose Internet Mail Extensions (MIME) data. This lexer is
  17. designed to process nested multipart data.
  18. It assumes that the given data contains both header and body (and is
  19. split at an empty line). If no valid header is found, then the entire data
  20. will be treated as body.
  21. Additional options accepted:
  22. `MIME-max-level`
  23. Max recursion level for nested MIME structure. Any negative number
  24. would treated as unlimited. (default: -1)
  25. `Content-Type`
  26. Treat the data as a specific content type. Useful when header is
  27. missing, or this lexer would try to parse from header. (default:
  28. `text/plain`)
  29. `Multipart-Boundary`
  30. Set the default multipart boundary delimiter. This option is only used
  31. when `Content-Type` is `multipart` and header is missing. This lexer
  32. would try to parse from header by default. (default: None)
  33. `Content-Transfer-Encoding`
  34. Treat the data as a specific encoding. Or this lexer would try to parse
  35. from header by default. (default: None)
  36. """
  37. name = "MIME"
  38. aliases = ["mime"]
  39. mimetypes = ["multipart/mixed",
  40. "multipart/related",
  41. "multipart/alternative"]
  42. url = 'https://en.wikipedia.org/wiki/MIME'
  43. version_added = '2.5'
  44. def __init__(self, **options):
  45. super().__init__(**options)
  46. self.boundary = options.get("Multipart-Boundary")
  47. self.content_transfer_encoding = options.get("Content_Transfer_Encoding")
  48. self.content_type = options.get("Content_Type", "text/plain")
  49. self.max_nested_level = get_int_opt(options, "MIME-max-level", -1)
  50. def get_header_tokens(self, match):
  51. field = match.group(1)
  52. if field.lower() in self.attention_headers:
  53. yield match.start(1), Name.Tag, field + ":"
  54. yield match.start(2), Text.Whitespace, match.group(2)
  55. pos = match.end(2)
  56. body = match.group(3)
  57. for i, t, v in self.get_tokens_unprocessed(body, ("root", field.lower())):
  58. yield pos + i, t, v
  59. else:
  60. yield match.start(), Comment, match.group()
  61. def get_body_tokens(self, match):
  62. pos_body_start = match.start()
  63. entire_body = match.group()
  64. # skip first newline
  65. if entire_body[0] == '\n':
  66. yield pos_body_start, Text.Whitespace, '\n'
  67. pos_body_start = pos_body_start + 1
  68. entire_body = entire_body[1:]
  69. # if it is not a multipart
  70. if not self.content_type.startswith("multipart") or not self.boundary:
  71. for i, t, v in self.get_bodypart_tokens(entire_body):
  72. yield pos_body_start + i, t, v
  73. return
  74. # find boundary
  75. bdry_pattern = rf"^--{re.escape(self.boundary)}(--)?\n"
  76. bdry_matcher = re.compile(bdry_pattern, re.MULTILINE)
  77. # some data has prefix text before first boundary
  78. m = bdry_matcher.search(entire_body)
  79. if m:
  80. pos_part_start = pos_body_start + m.end()
  81. pos_iter_start = lpos_end = m.end()
  82. yield pos_body_start, Text, entire_body[:m.start()]
  83. yield pos_body_start + lpos_end, String.Delimiter, m.group()
  84. else:
  85. pos_part_start = pos_body_start
  86. pos_iter_start = 0
  87. # process tokens of each body part
  88. for m in bdry_matcher.finditer(entire_body, pos_iter_start):
  89. # bodypart
  90. lpos_start = pos_part_start - pos_body_start
  91. lpos_end = m.start()
  92. part = entire_body[lpos_start:lpos_end]
  93. for i, t, v in self.get_bodypart_tokens(part):
  94. yield pos_part_start + i, t, v
  95. # boundary
  96. yield pos_body_start + lpos_end, String.Delimiter, m.group()
  97. pos_part_start = pos_body_start + m.end()
  98. # some data has suffix text after last boundary
  99. lpos_start = pos_part_start - pos_body_start
  100. if lpos_start != len(entire_body):
  101. yield pos_part_start, Text, entire_body[lpos_start:]
  102. def get_bodypart_tokens(self, text):
  103. # return if:
  104. # * no content
  105. # * no content type specific
  106. # * content encoding is not readable
  107. # * max recurrsion exceed
  108. if not text.strip() or not self.content_type:
  109. return [(0, Other, text)]
  110. cte = self.content_transfer_encoding
  111. if cte and cte not in {"8bit", "7bit", "quoted-printable"}:
  112. return [(0, Other, text)]
  113. if self.max_nested_level == 0:
  114. return [(0, Other, text)]
  115. # get lexer
  116. try:
  117. lexer = get_lexer_for_mimetype(self.content_type)
  118. except ClassNotFound:
  119. return [(0, Other, text)]
  120. if isinstance(lexer, type(self)):
  121. lexer.max_nested_level = self.max_nested_level - 1
  122. return lexer.get_tokens_unprocessed(text)
  123. def store_content_type(self, match):
  124. self.content_type = match.group(1)
  125. prefix_len = match.start(1) - match.start(0)
  126. yield match.start(0), Text.Whitespace, match.group(0)[:prefix_len]
  127. yield match.start(1), Name.Label, match.group(2)
  128. yield match.end(2), String.Delimiter, '/'
  129. yield match.start(3), Name.Label, match.group(3)
  130. def get_content_type_subtokens(self, match):
  131. yield match.start(1), Text, match.group(1)
  132. yield match.start(2), Text.Whitespace, match.group(2)
  133. yield match.start(3), Name.Attribute, match.group(3)
  134. yield match.start(4), Operator, match.group(4)
  135. yield match.start(5), String, match.group(5)
  136. if match.group(3).lower() == "boundary":
  137. boundary = match.group(5).strip()
  138. if boundary[0] == '"' and boundary[-1] == '"':
  139. boundary = boundary[1:-1]
  140. self.boundary = boundary
  141. def store_content_transfer_encoding(self, match):
  142. self.content_transfer_encoding = match.group(0).lower()
  143. yield match.start(0), Name.Constant, match.group(0)
  144. attention_headers = {"content-type", "content-transfer-encoding"}
  145. tokens = {
  146. "root": [
  147. (r"^([\w-]+):( *)([\s\S]*?\n)(?![ \t])", get_header_tokens),
  148. (r"^$[\s\S]+", get_body_tokens),
  149. ],
  150. "header": [
  151. # folding
  152. (r"\n[ \t]", Text.Whitespace),
  153. (r"\n(?![ \t])", Text.Whitespace, "#pop"),
  154. ],
  155. "content-type": [
  156. include("header"),
  157. (
  158. r"^\s*((multipart|application|audio|font|image|model|text|video"
  159. r"|message)/([\w-]+))",
  160. store_content_type,
  161. ),
  162. (r'(;)((?:[ \t]|\n[ \t])*)([\w:-]+)(=)([\s\S]*?)(?=;|\n(?![ \t]))',
  163. get_content_type_subtokens),
  164. (r';[ \t]*\n(?![ \t])', Text, '#pop'),
  165. ],
  166. "content-transfer-encoding": [
  167. include("header"),
  168. (r"([\w-]+)", store_content_transfer_encoding),
  169. ],
  170. }