util.py 10.0 KB

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