You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

351 lines
10 KiB

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