util.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. split_path_re = re.compile(r'[/\\ ]')
  12. doctype_lookup_re = re.compile(r'''
  13. (<\?.*?\?>)?\s*
  14. <!DOCTYPE\s+(
  15. [a-zA-Z_][a-zA-Z0-9]*
  16. (?: \s+ # optional in HTML5
  17. [a-zA-Z_][a-zA-Z0-9]*\s+
  18. "[^"]*")?
  19. )
  20. [^>]*>
  21. ''', re.DOTALL | re.MULTILINE | re.VERBOSE)
  22. tag_re = re.compile(r'<(.+?)(\s.*?)?>.*?</.+?>',
  23. re.UNICODE | re.IGNORECASE | re.DOTALL | re.MULTILINE)
  24. xml_decl_re = re.compile(r'\s*<\?xml[^>]*\?>', re.I)
  25. class ClassNotFound(ValueError):
  26. """Raised if one of the lookup functions didn't find a matching class."""
  27. class OptionError(Exception):
  28. pass
  29. def get_choice_opt(options, optname, allowed, default=None, normcase=False):
  30. string = options.get(optname, default)
  31. if normcase:
  32. string = string.lower()
  33. if string not in allowed:
  34. raise OptionError('Value for option %s must be one of %s' %
  35. (optname, ', '.join(map(str, allowed))))
  36. return string
  37. def get_bool_opt(options, optname, default=None):
  38. string = options.get(optname, default)
  39. if isinstance(string, bool):
  40. return string
  41. elif isinstance(string, int):
  42. return bool(string)
  43. elif not isinstance(string, string_types):
  44. raise OptionError('Invalid type %r for option %s; use '
  45. '1/0, yes/no, true/false, on/off' % (
  46. string, optname))
  47. elif string.lower() in ('1', 'yes', 'true', 'on'):
  48. return True
  49. elif string.lower() in ('0', 'no', 'false', 'off'):
  50. return False
  51. else:
  52. raise OptionError('Invalid value %r for option %s; use '
  53. '1/0, yes/no, true/false, on/off' % (
  54. string, optname))
  55. def get_int_opt(options, optname, default=None):
  56. string = options.get(optname, default)
  57. try:
  58. return int(string)
  59. except TypeError:
  60. raise OptionError('Invalid type %r for option %s; you '
  61. 'must give an integer value' % (
  62. string, optname))
  63. except ValueError:
  64. raise OptionError('Invalid value %r for option %s; you '
  65. 'must give an integer value' % (
  66. string, optname))
  67. def get_list_opt(options, optname, default=None):
  68. val = options.get(optname, default)
  69. if isinstance(val, string_types):
  70. return val.split()
  71. elif isinstance(val, (list, tuple)):
  72. return list(val)
  73. else:
  74. raise OptionError('Invalid type %r for option %s; you '
  75. 'must give a list value' % (
  76. val, optname))
  77. def docstring_headline(obj):
  78. if not obj.__doc__:
  79. return ''
  80. res = []
  81. for line in obj.__doc__.strip().splitlines():
  82. if line.strip():
  83. res.append(" " + line.strip())
  84. else:
  85. break
  86. return ''.join(res).lstrip()
  87. def make_analysator(f):
  88. """Return a static text analyser function that returns float values."""
  89. def text_analyse(text):
  90. try:
  91. rv = f(text)
  92. except Exception:
  93. return 0.0
  94. if not rv:
  95. return 0.0
  96. try:
  97. return min(1.0, max(0.0, float(rv)))
  98. except (ValueError, TypeError):
  99. return 0.0
  100. text_analyse.__doc__ = f.__doc__
  101. return staticmethod(text_analyse)
  102. def shebang_matches(text, regex):
  103. r"""Check if the given regular expression matches the last part of the
  104. shebang if one exists.
  105. >>> from pygments.util import shebang_matches
  106. >>> shebang_matches('#!/usr/bin/env python', r'python(2\.\d)?')
  107. True
  108. >>> shebang_matches('#!/usr/bin/python2.4', r'python(2\.\d)?')
  109. True
  110. >>> shebang_matches('#!/usr/bin/python-ruby', r'python(2\.\d)?')
  111. False
  112. >>> shebang_matches('#!/usr/bin/python/ruby', r'python(2\.\d)?')
  113. False
  114. >>> shebang_matches('#!/usr/bin/startsomethingwith python',
  115. ... r'python(2\.\d)?')
  116. True
  117. It also checks for common windows executable file extensions::
  118. >>> shebang_matches('#!C:\\Python2.4\\Python.exe', r'python(2\.\d)?')
  119. True
  120. Parameters (``'-f'`` or ``'--foo'`` are ignored so ``'perl'`` does
  121. the same as ``'perl -e'``)
  122. Note that this method automatically searches the whole string (eg:
  123. the regular expression is wrapped in ``'^$'``)
  124. """
  125. index = text.find('\n')
  126. if index >= 0:
  127. first_line = text[:index].lower()
  128. else:
  129. first_line = text.lower()
  130. if first_line.startswith('#!'):
  131. try:
  132. found = [x for x in split_path_re.split(first_line[2:].strip())
  133. if x and not x.startswith('-')][-1]
  134. except IndexError:
  135. return False
  136. regex = re.compile(r'^%s(\.(exe|cmd|bat|bin))?$' % regex, re.IGNORECASE)
  137. if regex.search(found) is not None:
  138. return True
  139. return False
  140. def doctype_matches(text, regex):
  141. """Check if the doctype matches a regular expression (if present).
  142. Note that this method only checks the first part of a DOCTYPE.
  143. eg: 'html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"'
  144. """
  145. m = doctype_lookup_re.match(text)
  146. if m is None:
  147. return False
  148. doctype = m.group(2)
  149. return re.compile(regex, re.I).match(doctype.strip()) is not None
  150. def html_doctype_matches(text):
  151. """Check if the file looks like it has a html doctype."""
  152. return doctype_matches(text, r'html')
  153. _looks_like_xml_cache = {}
  154. def looks_like_xml(text):
  155. """Check if a doctype exists or if we have some tags."""
  156. if xml_decl_re.match(text):
  157. return True
  158. key = hash(text)
  159. try:
  160. return _looks_like_xml_cache[key]
  161. except KeyError:
  162. m = doctype_lookup_re.match(text)
  163. if m is not None:
  164. return True
  165. rv = tag_re.search(text[:1000]) is not None
  166. _looks_like_xml_cache[key] = rv
  167. return rv
  168. # Python narrow build compatibility
  169. def _surrogatepair(c):
  170. # Given a unicode character code
  171. # with length greater than 16 bits,
  172. # return the two 16 bit surrogate pair.
  173. # From example D28 of:
  174. # http://www.unicode.org/book/ch03.pdf
  175. return (0xd7c0 + (c >> 10), (0xdc00 + (c & 0x3ff)))
  176. def unirange(a, b):
  177. """Returns a regular expression string to match the given non-BMP range."""
  178. if b < a:
  179. raise ValueError("Bad character range")
  180. if a < 0x10000 or b < 0x10000:
  181. raise ValueError("unirange is only defined for non-BMP ranges")
  182. if sys.maxunicode > 0xffff:
  183. # wide build
  184. return u'[%s-%s]' % (unichr(a), unichr(b))
  185. else:
  186. # narrow build stores surrogates, and the 're' module handles them
  187. # (incorrectly) as characters. Since there is still ordering among
  188. # these characters, expand the range to one that it understands. Some
  189. # background in http://bugs.python.org/issue3665 and
  190. # http://bugs.python.org/issue12749
  191. #
  192. # Additionally, the lower constants are using unichr rather than
  193. # literals because jython [which uses the wide path] can't load this
  194. # file if they are literals.
  195. ah, al = _surrogatepair(a)
  196. bh, bl = _surrogatepair(b)
  197. if ah == bh:
  198. return u'(?:%s[%s-%s])' % (unichr(ah), unichr(al), unichr(bl))
  199. else:
  200. buf = []
  201. buf.append(u'%s[%s-%s]' %
  202. (unichr(ah), unichr(al),
  203. ah == bh and unichr(bl) or unichr(0xdfff)))
  204. if ah - bh > 1:
  205. buf.append(u'[%s-%s][%s-%s]' %
  206. unichr(ah+1), unichr(bh-1), unichr(0xdc00), unichr(0xdfff))
  207. if ah != bh:
  208. buf.append(u'%s[%s-%s]' %
  209. (unichr(bh), unichr(0xdc00), unichr(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(object):
  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. # Python 2/3 compatibility
  287. if sys.version_info < (3, 0):
  288. unichr = unichr
  289. xrange = xrange
  290. string_types = (str, unicode)
  291. text_type = unicode
  292. u_prefix = 'u'
  293. iteritems = dict.iteritems
  294. itervalues = dict.itervalues
  295. import StringIO
  296. import cStringIO
  297. # unfortunately, io.StringIO in Python 2 doesn't accept str at all
  298. StringIO = StringIO.StringIO
  299. BytesIO = cStringIO.StringIO
  300. else:
  301. unichr = chr
  302. xrange = range
  303. string_types = (str,)
  304. text_type = str
  305. u_prefix = ''
  306. iteritems = dict.items
  307. itervalues = dict.values
  308. from io import StringIO, BytesIO, TextIOWrapper
  309. class UnclosingTextIOWrapper(TextIOWrapper):
  310. # Don't close underlying buffer on destruction.
  311. def close(self):
  312. self.flush()
  313. def add_metaclass(metaclass):
  314. """Class decorator for creating a class with a metaclass."""
  315. def wrapper(cls):
  316. orig_vars = cls.__dict__.copy()
  317. orig_vars.pop('__dict__', None)
  318. orig_vars.pop('__weakref__', None)
  319. for slots_var in orig_vars.get('__slots__', ()):
  320. orig_vars.pop(slots_var)
  321. return metaclass(cls.__name__, cls.__bases__, orig_vars)
  322. return wrapper