util.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. """
  2. pygments.util
  3. ~~~~~~~~~~~~~
  4. Utility functions.
  5. :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
  6. :license: BSD, see LICENSE for details.
  7. """
  8. import re
  9. from io import TextIOWrapper
  10. import html
  11. split_path_re = re.compile(r'[/\\ ]')
  12. doctype_lookup_re = re.compile(r'''
  13. <!DOCTYPE\s+(
  14. [a-zA-Z_][a-zA-Z0-9]*
  15. (?: \s+ # optional in HTML5
  16. [a-zA-Z_][a-zA-Z0-9]*\s+
  17. "[^"]*")?
  18. )
  19. [^>]*>
  20. ''', re.DOTALL | re.MULTILINE | re.VERBOSE)
  21. tag_re = re.compile(r'<([a-zA-Z][a-zA-Z0-9._:-]*)(\s[^>]*)?>.*?</\1\s*>',
  22. re.IGNORECASE | re.DOTALL | re.MULTILINE)
  23. xml_decl_re = re.compile(r'\s*<\?xml[^>]*\?>', re.I)
  24. class ClassNotFound(ValueError):
  25. """Raised if one of the lookup functions didn't find a matching class."""
  26. class OptionError(Exception):
  27. """
  28. This exception will be raised by all option processing functions if
  29. the type or value of the argument is not correct.
  30. """
  31. def get_choice_opt(options, optname, allowed, default=None, normcase=False):
  32. """
  33. If the key `optname` from the dictionary is not in the sequence
  34. `allowed`, raise an error, otherwise return it.
  35. """
  36. string = options.get(optname, default)
  37. if normcase:
  38. string = string.lower()
  39. if string not in allowed:
  40. raise OptionError('Value for option {} must be one of {}'.format(optname, ', '.join(map(str, allowed))))
  41. return string
  42. def get_bool_opt(options, optname, default=None):
  43. """
  44. Intuitively, this is `options.get(optname, default)`, but restricted to
  45. Boolean value. The Booleans can be represented as string, in order to accept
  46. Boolean value from the command line arguments. If the key `optname` is
  47. present in the dictionary `options` and is not associated with a Boolean,
  48. raise an `OptionError`. If it is absent, `default` is returned instead.
  49. The valid string values for ``True`` are ``1``, ``yes``, ``true`` and
  50. ``on``, the ones for ``False`` are ``0``, ``no``, ``false`` and ``off``
  51. (matched case-insensitively).
  52. """
  53. string = options.get(optname, default)
  54. if isinstance(string, bool):
  55. return string
  56. elif isinstance(string, int):
  57. return bool(string)
  58. elif not isinstance(string, str):
  59. raise OptionError(f'Invalid type {string!r} for option {optname}; use '
  60. '1/0, yes/no, true/false, on/off')
  61. elif string.lower() in ('1', 'yes', 'true', 'on'):
  62. return True
  63. elif string.lower() in ('0', 'no', 'false', 'off'):
  64. return False
  65. else:
  66. raise OptionError(f'Invalid value {string!r} for option {optname}; use '
  67. '1/0, yes/no, true/false, on/off')
  68. def get_int_opt(options, optname, default=None):
  69. """As :func:`get_bool_opt`, but interpret the value as an integer."""
  70. string = options.get(optname, default)
  71. try:
  72. return int(string)
  73. except TypeError:
  74. raise OptionError(f'Invalid type {string!r} for option {optname}; you '
  75. 'must give an integer value')
  76. except ValueError:
  77. raise OptionError(f'Invalid value {string!r} for option {optname}; you '
  78. 'must give an integer value')
  79. def get_list_opt(options, optname, default=None):
  80. """
  81. If the key `optname` from the dictionary `options` is a string,
  82. split it at whitespace and return it. If it is already a list
  83. or a tuple, it is returned as a list.
  84. """
  85. val = options.get(optname, default)
  86. if isinstance(val, str):
  87. return val.split()
  88. elif isinstance(val, (list, tuple)):
  89. return list(val)
  90. else:
  91. raise OptionError(f'Invalid type {val!r} for option {optname}; you '
  92. 'must give a list value')
  93. def docstring_headline(obj):
  94. if not obj.__doc__:
  95. return ''
  96. res = []
  97. for line in obj.__doc__.strip().splitlines():
  98. if line.strip():
  99. res.append(" " + line.strip())
  100. else:
  101. break
  102. return ''.join(res).lstrip()
  103. def make_analysator(f):
  104. """Return a static text analyser function that returns float values."""
  105. def text_analyse(text):
  106. try:
  107. rv = f(text)
  108. except Exception:
  109. return 0.0
  110. if not rv:
  111. return 0.0
  112. try:
  113. return min(1.0, max(0.0, float(rv)))
  114. except (ValueError, TypeError):
  115. return 0.0
  116. text_analyse.__doc__ = f.__doc__
  117. return staticmethod(text_analyse)
  118. def shebang_matches(text, regex):
  119. r"""Check if the given regular expression matches the last part of the
  120. shebang if one exists.
  121. >>> from pygments.util import shebang_matches
  122. >>> shebang_matches('#!/usr/bin/env python', r'python(2\.\d)?')
  123. True
  124. >>> shebang_matches('#!/usr/bin/python2.4', r'python(2\.\d)?')
  125. True
  126. >>> shebang_matches('#!/usr/bin/python-ruby', r'python(2\.\d)?')
  127. False
  128. >>> shebang_matches('#!/usr/bin/python/ruby', r'python(2\.\d)?')
  129. False
  130. >>> shebang_matches('#!/usr/bin/startsomethingwith python',
  131. ... r'python(2\.\d)?')
  132. True
  133. It also checks for common windows executable file extensions::
  134. >>> shebang_matches('#!C:\\Python2.4\\Python.exe', r'python(2\.\d)?')
  135. True
  136. Parameters (``'-f'`` or ``'--foo'`` are ignored so ``'perl'`` does
  137. the same as ``'perl -e'``)
  138. Note that this method automatically searches the whole string (eg:
  139. the regular expression is wrapped in ``'^$'``)
  140. """
  141. index = text.find('\n')
  142. if index >= 0:
  143. first_line = text[:index].lower()
  144. else:
  145. first_line = text.lower()
  146. if first_line.startswith('#!'):
  147. try:
  148. found = [x for x in split_path_re.split(first_line[2:].strip())
  149. if x and not x.startswith('-')][-1]
  150. except IndexError:
  151. return False
  152. regex = re.compile(rf'^{regex}(\.(exe|cmd|bat|bin))?$', re.IGNORECASE)
  153. if regex.search(found) is not None:
  154. return True
  155. return False
  156. def doctype_matches(text, regex):
  157. """Check if the doctype matches a regular expression (if present).
  158. Note that this method only checks the first part of a DOCTYPE.
  159. eg: 'html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"'
  160. """
  161. m = doctype_lookup_re.search(text)
  162. if m is None:
  163. return False
  164. doctype = m.group(1)
  165. return re.compile(regex, re.I).match(doctype.strip()) is not None
  166. def html_doctype_matches(text):
  167. """Check if the file looks like it has a html doctype."""
  168. return doctype_matches(text, r'html')
  169. _looks_like_xml_cache = {}
  170. def looks_like_xml(text):
  171. """Check if a doctype exists or if we have some tags."""
  172. if xml_decl_re.match(text):
  173. return True
  174. key = hash(text)
  175. try:
  176. return _looks_like_xml_cache[key]
  177. except KeyError:
  178. m = doctype_lookup_re.search(text)
  179. if m is not None:
  180. return True
  181. rv = tag_re.search(text[:1000]) is not None
  182. _looks_like_xml_cache[key] = rv
  183. return rv
  184. def surrogatepair(c):
  185. """Given a unicode character code with length greater than 16 bits,
  186. return the two 16 bit surrogate pair.
  187. """
  188. # From example D28 of:
  189. # http://www.unicode.org/book/ch03.pdf
  190. return (0xd7c0 + (c >> 10), (0xdc00 + (c & 0x3ff)))
  191. def format_lines(var_name, seq, raw=False, indent_level=0):
  192. """Formats a sequence of strings for output."""
  193. lines = []
  194. base_indent = ' ' * indent_level * 4
  195. inner_indent = ' ' * (indent_level + 1) * 4
  196. lines.append(base_indent + var_name + ' = (')
  197. if raw:
  198. # These should be preformatted reprs of, say, tuples.
  199. for i in seq:
  200. lines.append(inner_indent + i + ',')
  201. else:
  202. for i in seq:
  203. # Force use of single quotes
  204. r = repr(i + '"')
  205. lines.append(inner_indent + r[:-2] + r[-1] + ',')
  206. lines.append(base_indent + ')')
  207. return '\n'.join(lines)
  208. def duplicates_removed(it, already_seen=()):
  209. """
  210. Returns a list with duplicates removed from the iterable `it`.
  211. Order is preserved.
  212. """
  213. lst = []
  214. seen = set()
  215. for i in it:
  216. if i in seen or i in already_seen:
  217. continue
  218. lst.append(i)
  219. seen.add(i)
  220. return lst
  221. class Future:
  222. """Generic class to defer some work.
  223. Handled specially in RegexLexerMeta, to support regex string construction at
  224. first use.
  225. """
  226. def get(self):
  227. raise NotImplementedError
  228. def guess_decode(text):
  229. """Decode *text* with guessed encoding.
  230. First try UTF-8; this should fail for non-UTF-8 encodings.
  231. Then try the preferred locale encoding.
  232. Fall back to latin-1, which always works.
  233. """
  234. try:
  235. text = text.decode('utf-8')
  236. return text, 'utf-8'
  237. except UnicodeDecodeError:
  238. try:
  239. import locale
  240. prefencoding = locale.getpreferredencoding()
  241. text = text.decode(prefencoding)
  242. return text, prefencoding
  243. except (UnicodeDecodeError, LookupError):
  244. text = text.decode('latin1')
  245. return text, 'latin1'
  246. def guess_decode_from_terminal(text, term):
  247. """Decode *text* coming from terminal *term*.
  248. First try the terminal encoding, if given.
  249. Then try UTF-8. Then try the preferred locale encoding.
  250. Fall back to latin-1, which always works.
  251. """
  252. if getattr(term, 'encoding', None):
  253. try:
  254. text = text.decode(term.encoding)
  255. except UnicodeDecodeError:
  256. pass
  257. else:
  258. return text, term.encoding
  259. return guess_decode(text)
  260. def terminal_encoding(term):
  261. """Return our best guess of encoding for the given *term*."""
  262. if getattr(term, 'encoding', None):
  263. return term.encoding
  264. import locale
  265. return locale.getpreferredencoding()
  266. class UnclosingTextIOWrapper(TextIOWrapper):
  267. # Don't close underlying buffer on destruction.
  268. def close(self):
  269. self.flush()
  270. def html_escape(string, quote=True) -> str:
  271. """Return a safe version of the passed `string`,
  272. and an empty string if `None`.
  273. `NoneType` is not supported by `html.escape`, as `html.escape`
  274. uses the built-in `replace` function on `string`, so we need to
  275. check for it first.
  276. Optional flag quote is true by default, which also escapes
  277. double and single quotes.
  278. See https://docs.python.org/3/library/html.html#html.escape for more details.
  279. """
  280. if string is not None:
  281. # TODO: Eventually, check that string is a str, and if not, print a
  282. # warning or error here.
  283. return html.escape(str(string), quote=quote)
  284. return ''