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-2021 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. .. versionadded:: 2.5
  37. """
  38. name = "MIME"
  39. aliases = ["mime"]
  40. mimetypes = ["multipart/mixed",
  41. "multipart/related",
  42. "multipart/alternative"]
  43. def __init__(self, **options):
  44. super().__init__(**options)
  45. self.boundary = options.get("Multipart-Boundary")
  46. self.content_transfer_encoding = options.get("Content_Transfer_Encoding")
  47. self.content_type = options.get("Content_Type", "text/plain")
  48. self.max_nested_level = get_int_opt(options, "MIME-max-level", -1)
  49. def get_header_tokens(self, match):
  50. field = match.group(1)
  51. if field.lower() in self.attention_headers:
  52. yield match.start(1), Name.Tag, field + ":"
  53. yield match.start(2), Text.Whitespace, match.group(2)
  54. pos = match.end(2)
  55. body = match.group(3)
  56. for i, t, v in self.get_tokens_unprocessed(body, ("root", field.lower())):
  57. yield pos + i, t, v
  58. else:
  59. yield match.start(), Comment, match.group()
  60. def get_body_tokens(self, match):
  61. pos_body_start = match.start()
  62. entire_body = match.group()
  63. # skip first newline
  64. if entire_body[0] == '\n':
  65. yield pos_body_start, Text.Whitespace, '\n'
  66. pos_body_start = pos_body_start + 1
  67. entire_body = entire_body[1:]
  68. # if it is not a mulitpart
  69. if not self.content_type.startswith("multipart") or not self.boundary:
  70. for i, t, v in self.get_bodypart_tokens(entire_body):
  71. yield pos_body_start + i, t, v
  72. return
  73. # find boundary
  74. bdry_pattern = r"^--%s(--)?\n" % re.escape(self.boundary)
  75. bdry_matcher = re.compile(bdry_pattern, re.MULTILINE)
  76. # some data has prefix text before first boundary
  77. m = bdry_matcher.search(entire_body)
  78. if m:
  79. pos_part_start = pos_body_start + m.end()
  80. pos_iter_start = lpos_end = m.end()
  81. yield pos_body_start, Text, entire_body[:m.start()]
  82. yield pos_body_start + lpos_end, String.Delimiter, m.group()
  83. else:
  84. pos_part_start = pos_body_start
  85. pos_iter_start = 0
  86. # process tokens of each body part
  87. for m in bdry_matcher.finditer(entire_body, pos_iter_start):
  88. # bodypart
  89. lpos_start = pos_part_start - pos_body_start
  90. lpos_end = m.start()
  91. part = entire_body[lpos_start:lpos_end]
  92. for i, t, v in self.get_bodypart_tokens(part):
  93. yield pos_part_start + i, t, v
  94. # boundary
  95. yield pos_body_start + lpos_end, String.Delimiter, m.group()
  96. pos_part_start = pos_body_start + m.end()
  97. # some data has suffix text after last boundary
  98. lpos_start = pos_part_start - pos_body_start
  99. if lpos_start != len(entire_body):
  100. yield pos_part_start, Text, entire_body[lpos_start:]
  101. def get_bodypart_tokens(self, text):
  102. # return if:
  103. # * no content
  104. # * no content type specific
  105. # * content encoding is not readable
  106. # * max recurrsion exceed
  107. if not text.strip() or not self.content_type:
  108. return [(0, Other, text)]
  109. cte = self.content_transfer_encoding
  110. if cte and cte not in {"8bit", "7bit", "quoted-printable"}:
  111. return [(0, Other, text)]
  112. if self.max_nested_level == 0:
  113. return [(0, Other, text)]
  114. # get lexer
  115. try:
  116. lexer = get_lexer_for_mimetype(self.content_type)
  117. except ClassNotFound:
  118. return [(0, Other, text)]
  119. if isinstance(lexer, type(self)):
  120. lexer.max_nested_level = self.max_nested_level - 1
  121. return lexer.get_tokens_unprocessed(text)
  122. def store_content_type(self, match):
  123. self.content_type = match.group(1)
  124. prefix_len = match.start(1) - match.start(0)
  125. yield match.start(0), Text.Whitespace, match.group(0)[:prefix_len]
  126. yield match.start(1), Name.Label, match.group(2)
  127. yield match.end(2), String.Delimiter, '/'
  128. yield match.start(3), Name.Label, match.group(3)
  129. def get_content_type_subtokens(self, match):
  130. yield match.start(1), Text, match.group(1)
  131. yield match.start(2), Text.Whitespace, match.group(2)
  132. yield match.start(3), Name.Attribute, match.group(3)
  133. yield match.start(4), Operator, match.group(4)
  134. yield match.start(5), String, match.group(5)
  135. if match.group(3).lower() == "boundary":
  136. boundary = match.group(5).strip()
  137. if boundary[0] == '"' and boundary[-1] == '"':
  138. boundary = boundary[1:-1]
  139. self.boundary = boundary
  140. def store_content_transfer_encoding(self, match):
  141. self.content_transfer_encoding = match.group(0).lower()
  142. yield match.start(0), Name.Constant, match.group(0)
  143. attention_headers = {"content-type", "content-transfer-encoding"}
  144. tokens = {
  145. "root": [
  146. (r"^([\w-]+):( *)([\s\S]*?\n)(?![ \t])", get_header_tokens),
  147. (r"^$[\s\S]+", get_body_tokens),
  148. ],
  149. "header": [
  150. # folding
  151. (r"\n[ \t]", Text.Whitespace),
  152. (r"\n(?![ \t])", Text.Whitespace, "#pop"),
  153. ],
  154. "content-type": [
  155. include("header"),
  156. (
  157. r"^\s*((multipart|application|audio|font|image|model|text|video"
  158. r"|message)/([\w-]+))",
  159. store_content_type,
  160. ),
  161. (r'(;)((?:[ \t]|\n[ \t])*)([\w:-]+)(=)([\s\S]*?)(?=;|\n(?![ \t]))',
  162. get_content_type_subtokens),
  163. (r';[ \t]*\n(?![ \t])', Text, '#pop'),
  164. ],
  165. "content-transfer-encoding": [
  166. include("header"),
  167. (r"([\w-]+)", store_content_transfer_encoding),
  168. ],
  169. }