util.py 9.8 KB

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