util.py 8.9 KB

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