__init__.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. # $Id: __init__.py 9068 2022-06-13 12:05:08Z milde $
  2. # Author: David Goodger <goodger@python.org>
  3. # Copyright: This module has been placed in the public domain.
  4. """
  5. Miscellaneous utilities for the documentation utilities.
  6. """
  7. __docformat__ = 'reStructuredText'
  8. import sys
  9. import os
  10. import os.path
  11. import re
  12. import itertools
  13. import warnings
  14. import unicodedata
  15. from docutils import ApplicationError, DataError, __version_info__
  16. from docutils import io, nodes
  17. # for backwards compatibility
  18. from docutils.nodes import unescape # noqa: F401
  19. class SystemMessage(ApplicationError):
  20. def __init__(self, system_message, level):
  21. Exception.__init__(self, system_message.astext())
  22. self.level = level
  23. class SystemMessagePropagation(ApplicationError):
  24. pass
  25. class Reporter:
  26. """
  27. Info/warning/error reporter and ``system_message`` element generator.
  28. Five levels of system messages are defined, along with corresponding
  29. methods: `debug()`, `info()`, `warning()`, `error()`, and `severe()`.
  30. There is typically one Reporter object per process. A Reporter object is
  31. instantiated with thresholds for reporting (generating warnings) and
  32. halting processing (raising exceptions), a switch to turn debug output on
  33. or off, and an I/O stream for warnings. These are stored as instance
  34. attributes.
  35. When a system message is generated, its level is compared to the stored
  36. thresholds, and a warning or error is generated as appropriate. Debug
  37. messages are produced if the stored debug switch is on, independently of
  38. other thresholds. Message output is sent to the stored warning stream if
  39. not set to ''.
  40. The Reporter class also employs a modified form of the "Observer" pattern
  41. [GoF95]_ to track system messages generated. The `attach_observer` method
  42. should be called before parsing, with a bound method or function which
  43. accepts system messages. The observer can be removed with
  44. `detach_observer`, and another added in its place.
  45. .. [GoF95] Gamma, Helm, Johnson, Vlissides. *Design Patterns: Elements of
  46. Reusable Object-Oriented Software*. Addison-Wesley, Reading, MA, USA,
  47. 1995.
  48. """
  49. levels = 'DEBUG INFO WARNING ERROR SEVERE'.split()
  50. """List of names for system message levels, indexed by level."""
  51. # system message level constants:
  52. (DEBUG_LEVEL,
  53. INFO_LEVEL,
  54. WARNING_LEVEL,
  55. ERROR_LEVEL,
  56. SEVERE_LEVEL) = range(5)
  57. def __init__(self, source, report_level, halt_level, stream=None,
  58. debug=False, encoding=None, error_handler='backslashreplace'):
  59. """
  60. :Parameters:
  61. - `source`: The path to or description of the source data.
  62. - `report_level`: The level at or above which warning output will
  63. be sent to `stream`.
  64. - `halt_level`: The level at or above which `SystemMessage`
  65. exceptions will be raised, halting execution.
  66. - `debug`: Show debug (level=0) system messages?
  67. - `stream`: Where warning output is sent. Can be file-like (has a
  68. ``.write`` method), a string (file name, opened for writing),
  69. '' (empty string) or `False` (for discarding all stream messages)
  70. or `None` (implies `sys.stderr`; default).
  71. - `encoding`: The output encoding.
  72. - `error_handler`: The error handler for stderr output encoding.
  73. """
  74. self.source = source
  75. """The path to or description of the source data."""
  76. self.error_handler = error_handler
  77. """The character encoding error handler."""
  78. self.debug_flag = debug
  79. """Show debug (level=0) system messages?"""
  80. self.report_level = report_level
  81. """The level at or above which warning output will be sent
  82. to `self.stream`."""
  83. self.halt_level = halt_level
  84. """The level at or above which `SystemMessage` exceptions
  85. will be raised, halting execution."""
  86. if not isinstance(stream, io.ErrorOutput):
  87. stream = io.ErrorOutput(stream, encoding, error_handler)
  88. self.stream = stream
  89. """Where warning output is sent."""
  90. self.encoding = encoding or getattr(stream, 'encoding', 'ascii')
  91. """The output character encoding."""
  92. self.observers = []
  93. """List of bound methods or functions to call with each system_message
  94. created."""
  95. self.max_level = -1
  96. """The highest level system message generated so far."""
  97. def set_conditions(self, category, report_level, halt_level,
  98. stream=None, debug=False):
  99. warnings.warn('docutils.utils.Reporter.set_conditions() deprecated; '
  100. 'Will be removed in Docutils 0.21 or later. '
  101. 'Set attributes via configuration settings or directly.',
  102. DeprecationWarning, stacklevel=2)
  103. self.report_level = report_level
  104. self.halt_level = halt_level
  105. if not isinstance(stream, io.ErrorOutput):
  106. stream = io.ErrorOutput(stream, self.encoding, self.error_handler)
  107. self.stream = stream
  108. self.debug_flag = debug
  109. def attach_observer(self, observer):
  110. """
  111. The `observer` parameter is a function or bound method which takes one
  112. argument, a `nodes.system_message` instance.
  113. """
  114. self.observers.append(observer)
  115. def detach_observer(self, observer):
  116. self.observers.remove(observer)
  117. def notify_observers(self, message):
  118. for observer in self.observers:
  119. observer(message)
  120. def system_message(self, level, message, *children, **kwargs):
  121. """
  122. Return a system_message object.
  123. Raise an exception or generate a warning if appropriate.
  124. """
  125. # `message` can be a `str` or `Exception` instance.
  126. if isinstance(message, Exception):
  127. message = str(message)
  128. attributes = kwargs.copy()
  129. if 'base_node' in kwargs:
  130. source, line = get_source_line(kwargs['base_node'])
  131. del attributes['base_node']
  132. if source is not None:
  133. attributes.setdefault('source', source)
  134. if line is not None:
  135. attributes.setdefault('line', line)
  136. # assert source is not None, "line- but no source-argument"
  137. if 'source' not in attributes:
  138. # 'line' is absolute line number
  139. try:
  140. source, line = self.get_source_and_line(attributes.get('line'))
  141. except AttributeError:
  142. source, line = None, None
  143. if source is not None:
  144. attributes['source'] = source
  145. if line is not None:
  146. attributes['line'] = line
  147. # assert attributes['line'] is not None, (message, kwargs)
  148. # assert attributes['source'] is not None, (message, kwargs)
  149. attributes.setdefault('source', self.source)
  150. msg = nodes.system_message(message, level=level,
  151. type=self.levels[level],
  152. *children, **attributes)
  153. if self.stream and (level >= self.report_level
  154. or self.debug_flag and level == self.DEBUG_LEVEL
  155. or level >= self.halt_level):
  156. self.stream.write(msg.astext() + '\n')
  157. if level >= self.halt_level:
  158. raise SystemMessage(msg, level)
  159. if level > self.DEBUG_LEVEL or self.debug_flag:
  160. self.notify_observers(msg)
  161. self.max_level = max(level, self.max_level)
  162. return msg
  163. def debug(self, *args, **kwargs):
  164. """
  165. Level-0, "DEBUG": an internal reporting issue. Typically, there is no
  166. effect on the processing. Level-0 system messages are handled
  167. separately from the others.
  168. """
  169. if self.debug_flag:
  170. return self.system_message(self.DEBUG_LEVEL, *args, **kwargs)
  171. def info(self, *args, **kwargs):
  172. """
  173. Level-1, "INFO": a minor issue that can be ignored. Typically there is
  174. no effect on processing, and level-1 system messages are not reported.
  175. """
  176. return self.system_message(self.INFO_LEVEL, *args, **kwargs)
  177. def warning(self, *args, **kwargs):
  178. """
  179. Level-2, "WARNING": an issue that should be addressed. If ignored,
  180. there may be unpredictable problems with the output.
  181. """
  182. return self.system_message(self.WARNING_LEVEL, *args, **kwargs)
  183. def error(self, *args, **kwargs):
  184. """
  185. Level-3, "ERROR": an error that should be addressed. If ignored, the
  186. output will contain errors.
  187. """
  188. return self.system_message(self.ERROR_LEVEL, *args, **kwargs)
  189. def severe(self, *args, **kwargs):
  190. """
  191. Level-4, "SEVERE": a severe error that must be addressed. If ignored,
  192. the output will contain severe errors. Typically level-4 system
  193. messages are turned into exceptions which halt processing.
  194. """
  195. return self.system_message(self.SEVERE_LEVEL, *args, **kwargs)
  196. class ExtensionOptionError(DataError): pass
  197. class BadOptionError(ExtensionOptionError): pass
  198. class BadOptionDataError(ExtensionOptionError): pass
  199. class DuplicateOptionError(ExtensionOptionError): pass
  200. def extract_extension_options(field_list, options_spec):
  201. """
  202. Return a dictionary mapping extension option names to converted values.
  203. :Parameters:
  204. - `field_list`: A flat field list without field arguments, where each
  205. field body consists of a single paragraph only.
  206. - `options_spec`: Dictionary mapping known option names to a
  207. conversion function such as `int` or `float`.
  208. :Exceptions:
  209. - `KeyError` for unknown option names.
  210. - `ValueError` for invalid option values (raised by the conversion
  211. function).
  212. - `TypeError` for invalid option value types (raised by conversion
  213. function).
  214. - `DuplicateOptionError` for duplicate options.
  215. - `BadOptionError` for invalid fields.
  216. - `BadOptionDataError` for invalid option data (missing name,
  217. missing data, bad quotes, etc.).
  218. """
  219. option_list = extract_options(field_list)
  220. return assemble_option_dict(option_list, options_spec)
  221. def extract_options(field_list):
  222. """
  223. Return a list of option (name, value) pairs from field names & bodies.
  224. :Parameter:
  225. `field_list`: A flat field list, where each field name is a single
  226. word and each field body consists of a single paragraph only.
  227. :Exceptions:
  228. - `BadOptionError` for invalid fields.
  229. - `BadOptionDataError` for invalid option data (missing name,
  230. missing data, bad quotes, etc.).
  231. """
  232. option_list = []
  233. for field in field_list:
  234. if len(field[0].astext().split()) != 1:
  235. raise BadOptionError(
  236. 'extension option field name may not contain multiple words')
  237. name = str(field[0].astext().lower())
  238. body = field[1]
  239. if len(body) == 0:
  240. data = None
  241. elif (len(body) > 1
  242. or not isinstance(body[0], nodes.paragraph)
  243. or len(body[0]) != 1
  244. or not isinstance(body[0][0], nodes.Text)):
  245. raise BadOptionDataError(
  246. 'extension option field body may contain\n'
  247. 'a single paragraph only (option "%s")' % name)
  248. else:
  249. data = body[0][0].astext()
  250. option_list.append((name, data))
  251. return option_list
  252. def assemble_option_dict(option_list, options_spec):
  253. """
  254. Return a mapping of option names to values.
  255. :Parameters:
  256. - `option_list`: A list of (name, value) pairs (the output of
  257. `extract_options()`).
  258. - `options_spec`: Dictionary mapping known option names to a
  259. conversion function such as `int` or `float`.
  260. :Exceptions:
  261. - `KeyError` for unknown option names.
  262. - `DuplicateOptionError` for duplicate options.
  263. - `ValueError` for invalid option values (raised by conversion
  264. function).
  265. - `TypeError` for invalid option value types (raised by conversion
  266. function).
  267. """
  268. options = {}
  269. for name, value in option_list:
  270. convertor = options_spec[name] # raises KeyError if unknown
  271. if convertor is None:
  272. raise KeyError(name) # or if explicitly disabled
  273. if name in options:
  274. raise DuplicateOptionError('duplicate option "%s"' % name)
  275. try:
  276. options[name] = convertor(value)
  277. except (ValueError, TypeError) as detail:
  278. raise detail.__class__('(option: "%s"; value: %r)\n%s'
  279. % (name, value, ' '.join(detail.args)))
  280. return options
  281. class NameValueError(DataError): pass
  282. def decode_path(path):
  283. """
  284. Ensure `path` is Unicode. Return `str` instance.
  285. Decode file/path string in a failsafe manner if not already done.
  286. """
  287. # TODO: is this still required with Python 3?
  288. if isinstance(path, str):
  289. return path
  290. try:
  291. path = path.decode(sys.getfilesystemencoding(), 'strict')
  292. except AttributeError: # default value None has no decode method
  293. if not path:
  294. return ''
  295. raise ValueError('`path` value must be a String or ``None``, '
  296. f'not {path!r}')
  297. except UnicodeDecodeError:
  298. try:
  299. path = path.decode('utf-8', 'strict')
  300. except UnicodeDecodeError:
  301. path = path.decode('ascii', 'replace')
  302. return path
  303. def extract_name_value(line):
  304. """
  305. Return a list of (name, value) from a line of the form "name=value ...".
  306. :Exception:
  307. `NameValueError` for invalid input (missing name, missing data, bad
  308. quotes, etc.).
  309. """
  310. attlist = []
  311. while line:
  312. equals = line.find('=')
  313. if equals == -1:
  314. raise NameValueError('missing "="')
  315. attname = line[:equals].strip()
  316. if equals == 0 or not attname:
  317. raise NameValueError(
  318. 'missing attribute name before "="')
  319. line = line[equals+1:].lstrip()
  320. if not line:
  321. raise NameValueError(
  322. 'missing value after "%s="' % attname)
  323. if line[0] in '\'"':
  324. endquote = line.find(line[0], 1)
  325. if endquote == -1:
  326. raise NameValueError(
  327. 'attribute "%s" missing end quote (%s)'
  328. % (attname, line[0]))
  329. if len(line) > endquote + 1 and line[endquote + 1].strip():
  330. raise NameValueError(
  331. 'attribute "%s" end quote (%s) not followed by '
  332. 'whitespace' % (attname, line[0]))
  333. data = line[1:endquote]
  334. line = line[endquote+1:].lstrip()
  335. else:
  336. space = line.find(' ')
  337. if space == -1:
  338. data = line
  339. line = ''
  340. else:
  341. data = line[:space]
  342. line = line[space+1:].lstrip()
  343. attlist.append((attname.lower(), data))
  344. return attlist
  345. def new_reporter(source_path, settings):
  346. """
  347. Return a new Reporter object.
  348. :Parameters:
  349. `source` : string
  350. The path to or description of the source text of the document.
  351. `settings` : optparse.Values object
  352. Runtime settings.
  353. """
  354. reporter = Reporter(
  355. source_path, settings.report_level, settings.halt_level,
  356. stream=settings.warning_stream, debug=settings.debug,
  357. encoding=settings.error_encoding,
  358. error_handler=settings.error_encoding_error_handler)
  359. return reporter
  360. def new_document(source_path, settings=None):
  361. """
  362. Return a new empty document object.
  363. :Parameters:
  364. `source_path` : string
  365. The path to or description of the source text of the document.
  366. `settings` : optparse.Values object
  367. Runtime settings. If none are provided, a default core set will
  368. be used. If you will use the document object with any Docutils
  369. components, you must provide their default settings as well.
  370. For example, if parsing rST, at least provide the rst-parser
  371. settings, obtainable as follows:
  372. Defaults for parser component::
  373. settings = docutils.frontend.get_default_settings(
  374. docutils.parsers.rst.Parser)
  375. Defaults and configuration file customizations::
  376. settings = docutils.core.Publisher(
  377. parser=docutils.parsers.rst.Parser).get_settings()
  378. """
  379. # Import at top of module would lead to circular dependency!
  380. from docutils import frontend
  381. if settings is None:
  382. settings = frontend.get_default_settings()
  383. source_path = decode_path(source_path)
  384. reporter = new_reporter(source_path, settings)
  385. document = nodes.document(settings, reporter, source=source_path)
  386. document.note_source(source_path, -1)
  387. return document
  388. def clean_rcs_keywords(paragraph, keyword_substitutions):
  389. if len(paragraph) == 1 and isinstance(paragraph[0], nodes.Text):
  390. textnode = paragraph[0]
  391. for pattern, substitution in keyword_substitutions:
  392. match = pattern.search(textnode)
  393. if match:
  394. paragraph[0] = nodes.Text(pattern.sub(substitution, textnode))
  395. return
  396. def relative_path(source, target):
  397. """
  398. Build and return a path to `target`, relative to `source` (both files).
  399. If there is no common prefix, return the absolute path to `target`.
  400. """
  401. source_parts = os.path.abspath(source or type(target)('dummy_file')
  402. ).split(os.sep)
  403. target_parts = os.path.abspath(target).split(os.sep)
  404. # Check first 2 parts because '/dir'.split('/') == ['', 'dir']:
  405. if source_parts[:2] != target_parts[:2]:
  406. # Nothing in common between paths.
  407. # Return absolute path, using '/' for URLs:
  408. return '/'.join(target_parts)
  409. source_parts.reverse()
  410. target_parts.reverse()
  411. while (source_parts and target_parts
  412. and source_parts[-1] == target_parts[-1]):
  413. # Remove path components in common:
  414. source_parts.pop()
  415. target_parts.pop()
  416. target_parts.reverse()
  417. parts = ['..'] * (len(source_parts) - 1) + target_parts
  418. return '/'.join(parts)
  419. def get_stylesheet_reference(settings, relative_to=None):
  420. """
  421. Retrieve a stylesheet reference from the settings object.
  422. Deprecated. Use get_stylesheet_list() instead to
  423. enable specification of multiple stylesheets as a comma-separated
  424. list.
  425. """
  426. warnings.warn('utils.get_stylesheet_reference()'
  427. ' is obsoleted by utils.get_stylesheet_list()'
  428. ' and will be removed in Docutils 2.0.',
  429. DeprecationWarning, stacklevel=2)
  430. if settings.stylesheet_path:
  431. assert not settings.stylesheet, (
  432. 'stylesheet and stylesheet_path are mutually exclusive.')
  433. if relative_to is None:
  434. relative_to = settings._destination
  435. return relative_path(relative_to, settings.stylesheet_path)
  436. else:
  437. return settings.stylesheet
  438. # Return 'stylesheet' or 'stylesheet_path' arguments as list.
  439. #
  440. # The original settings arguments are kept unchanged: you can test
  441. # with e.g. ``if settings.stylesheet_path:``
  442. #
  443. # Differences to ``get_stylesheet_reference``:
  444. # * return value is a list
  445. # * no re-writing of the path (and therefore no optional argument)
  446. # (if required, use ``utils.relative_path(source, target)``
  447. # in the calling script)
  448. def get_stylesheet_list(settings):
  449. """
  450. Retrieve list of stylesheet references from the settings object.
  451. """
  452. assert not (settings.stylesheet and settings.stylesheet_path), (
  453. 'stylesheet and stylesheet_path are mutually exclusive.')
  454. stylesheets = settings.stylesheet_path or settings.stylesheet or []
  455. # programmatically set default may be string with comma separated list:
  456. if not isinstance(stylesheets, list):
  457. stylesheets = [path.strip() for path in stylesheets.split(',')]
  458. if settings.stylesheet_path:
  459. # expand relative paths if found in stylesheet-dirs:
  460. stylesheets = [find_file_in_dirs(path, settings.stylesheet_dirs)
  461. for path in stylesheets]
  462. if os.sep != '/': # for URLs, we need POSIX paths
  463. stylesheets = [path.replace(os.sep, '/') for path in stylesheets]
  464. return stylesheets
  465. def find_file_in_dirs(path, dirs):
  466. """
  467. Search for `path` in the list of directories `dirs`.
  468. Return the first expansion that matches an existing file.
  469. """
  470. if os.path.isabs(path):
  471. return path
  472. for d in dirs:
  473. if d == '.':
  474. f = path
  475. else:
  476. d = os.path.expanduser(d)
  477. f = os.path.join(d, path)
  478. if os.path.exists(f):
  479. return f
  480. return path
  481. def get_trim_footnote_ref_space(settings):
  482. """
  483. Return whether or not to trim footnote space.
  484. If trim_footnote_reference_space is not None, return it.
  485. If trim_footnote_reference_space is None, return False unless the
  486. footnote reference style is 'superscript'.
  487. """
  488. if settings.setdefault('trim_footnote_reference_space', None) is None:
  489. return getattr(settings, 'footnote_references', None) == 'superscript'
  490. else:
  491. return settings.trim_footnote_reference_space
  492. def get_source_line(node):
  493. """
  494. Return the "source" and "line" attributes from the `node` given or from
  495. its closest ancestor.
  496. """
  497. while node:
  498. if node.source or node.line:
  499. return node.source, node.line
  500. node = node.parent
  501. return None, None
  502. def escape2null(text):
  503. """Return a string with escape-backslashes converted to nulls."""
  504. parts = []
  505. start = 0
  506. while True:
  507. found = text.find('\\', start)
  508. if found == -1:
  509. parts.append(text[start:])
  510. return ''.join(parts)
  511. parts.append(text[start:found])
  512. parts.append('\x00' + text[found+1:found+2])
  513. start = found + 2 # skip character after escape
  514. def split_escaped_whitespace(text):
  515. """
  516. Split `text` on escaped whitespace (null+space or null+newline).
  517. Return a list of strings.
  518. """
  519. strings = text.split('\x00 ')
  520. strings = [string.split('\x00\n') for string in strings]
  521. # flatten list of lists of strings to list of strings:
  522. return list(itertools.chain(*strings))
  523. def strip_combining_chars(text):
  524. return ''.join(c for c in text if not unicodedata.combining(c))
  525. def find_combining_chars(text):
  526. """Return indices of all combining chars in Unicode string `text`.
  527. >>> from docutils.utils import find_combining_chars
  528. >>> find_combining_chars('A t̆ab̆lĕ')
  529. [3, 6, 9]
  530. """
  531. return [i for i, c in enumerate(text) if unicodedata.combining(c)]
  532. def column_indices(text):
  533. """Indices of Unicode string `text` when skipping combining characters.
  534. >>> from docutils.utils import column_indices
  535. >>> column_indices('A t̆ab̆lĕ')
  536. [0, 1, 2, 4, 5, 7, 8]
  537. """
  538. # TODO: account for asian wide chars here instead of using dummy
  539. # replacements in the tableparser?
  540. string_indices = list(range(len(text)))
  541. for index in find_combining_chars(text):
  542. string_indices[index] = None
  543. return [i for i in string_indices if i is not None]
  544. east_asian_widths = {'W': 2, # Wide
  545. 'F': 2, # Full-width (wide)
  546. 'Na': 1, # Narrow
  547. 'H': 1, # Half-width (narrow)
  548. 'N': 1, # Neutral (not East Asian, treated as narrow)
  549. 'A': 1, # Ambiguous (s/b wide in East Asian context,
  550. } # narrow otherwise, but that doesn't work)
  551. """Mapping of result codes from `unicodedata.east_asian_widt()` to character
  552. column widths."""
  553. def column_width(text):
  554. """Return the column width of text.
  555. Correct ``len(text)`` for wide East Asian and combining Unicode chars.
  556. """
  557. width = sum(east_asian_widths[unicodedata.east_asian_width(c)]
  558. for c in text)
  559. # correction for combining chars:
  560. width -= len(find_combining_chars(text))
  561. return width
  562. def uniq(L):
  563. r = []
  564. for item in L:
  565. if item not in r:
  566. r.append(item)
  567. return r
  568. def normalize_language_tag(tag):
  569. """Return a list of normalized combinations for a `BCP 47` language tag.
  570. Example:
  571. >>> from docutils.utils import normalize_language_tag
  572. >>> normalize_language_tag('de_AT-1901')
  573. ['de-at-1901', 'de-at', 'de-1901', 'de']
  574. >>> normalize_language_tag('de-CH-x_altquot')
  575. ['de-ch-x-altquot', 'de-ch', 'de-x-altquot', 'de']
  576. """
  577. # normalize:
  578. tag = tag.lower().replace('-', '_')
  579. # split (except singletons, which mark the following tag as non-standard):
  580. tag = re.sub(r'_([a-zA-Z0-9])_', r'_\1-', tag)
  581. subtags = [subtag for subtag in tag.split('_')]
  582. base_tag = (subtags.pop(0),)
  583. # find all combinations of subtags
  584. taglist = []
  585. for n in range(len(subtags), 0, -1):
  586. for tags in itertools.combinations(subtags, n):
  587. taglist.append('-'.join(base_tag+tags))
  588. taglist += base_tag
  589. return taglist
  590. class DependencyList:
  591. """
  592. List of dependencies, with file recording support.
  593. Note that the output file is not automatically closed. You have
  594. to explicitly call the close() method.
  595. """
  596. def __init__(self, output_file=None, dependencies=[]):
  597. """
  598. Initialize the dependency list, automatically setting the
  599. output file to `output_file` (see `set_output()`) and adding
  600. all supplied dependencies.
  601. """
  602. self.set_output(output_file)
  603. for i in dependencies:
  604. self.add(i)
  605. def set_output(self, output_file):
  606. """
  607. Set the output file and clear the list of already added
  608. dependencies.
  609. `output_file` must be a string. The specified file is
  610. immediately overwritten.
  611. If output_file is '-', the output will be written to stdout.
  612. If it is None, no file output is done when calling add().
  613. """
  614. self.list = []
  615. if output_file:
  616. if output_file == '-':
  617. of = None
  618. else:
  619. of = output_file
  620. self.file = io.FileOutput(destination_path=of,
  621. encoding='utf-8', autoclose=False)
  622. else:
  623. self.file = None
  624. def add(self, *filenames):
  625. """
  626. If the dependency `filename` has not already been added,
  627. append it to self.list and print it to self.file if self.file
  628. is not None.
  629. """
  630. for filename in filenames:
  631. if filename not in self.list:
  632. self.list.append(filename)
  633. if self.file is not None:
  634. self.file.write(filename+'\n')
  635. def close(self):
  636. """
  637. Close the output file.
  638. """
  639. self.file.close()
  640. self.file = None
  641. def __repr__(self):
  642. try:
  643. output_file = self.file.name
  644. except AttributeError:
  645. output_file = None
  646. return '%s(%r, %s)' % (self.__class__.__name__, output_file, self.list)
  647. release_level_abbreviations = {
  648. 'alpha': 'a',
  649. 'beta': 'b',
  650. 'candidate': 'rc',
  651. 'final': ''}
  652. def version_identifier(version_info=None):
  653. """
  654. Return a version identifier string built from `version_info`, a
  655. `docutils.VersionInfo` namedtuple instance or compatible tuple. If
  656. `version_info` is not provided, by default return a version identifier
  657. string based on `docutils.__version_info__` (i.e. the current Docutils
  658. version).
  659. """
  660. if version_info is None:
  661. version_info = __version_info__
  662. if version_info.micro:
  663. micro = '.%s' % version_info.micro
  664. else:
  665. # 0 is omitted:
  666. micro = ''
  667. releaselevel = release_level_abbreviations[version_info.releaselevel]
  668. if version_info.serial:
  669. serial = version_info.serial
  670. else:
  671. # 0 is omitted:
  672. serial = ''
  673. if version_info.release:
  674. dev = ''
  675. else:
  676. dev = '.dev'
  677. version = '%s.%s%s%s%s%s' % (
  678. version_info.major,
  679. version_info.minor,
  680. micro,
  681. releaselevel,
  682. serial,
  683. dev)
  684. return version