o !5p`p@sdZdZddlZddlZddlZddlZddlZddlZddlZddl m Z m Z m Z ddl m Z ddlmZddlZ ddlmZmZejdkrIeZGd d d e ZGd d d e ZGd ddeZGddde ZGdddeZGdddeZGdddeZddZddZ ddZ!Gddde Z"dd Z#d!d"Z$d#d$Z%dSd%d&Z&d'd(Z'd)d*Z(dSd+d,Z)d-d.Z*d/d0Z+d1d2Z,d3d4Z-d5d6Z.d7d8Z/d9d:Z0d;d<Z1d=d>Z2d?d?d@d@d@d@dAZ3 dBdCZ4dDdEZ5dFdGZ6dHdIZ7GdJdKdKeZ8dLdMdNdOdPZ9dSdQdRZ:dS)Tz: Miscellaneous utilities for the documentation utilities. reStructuredTextN)ApplicationError DataError__version_info__)nodes)unescape) ErrorOutput SafeStringrc@seZdZddZdS) SystemMessagecCst||||_dSN) Exception__init__astextlevel)selfsystem_messagerr9/usr/lib/python3/dist-packages/docutils/utils/__init__.pyrs zSystemMessage.__init__N)__name__ __module__ __qualname__rrrrrr s r c@ eZdZdS)SystemMessagePropagationNrrrrrrrr$ rc@seZdZdZdZ ed\ZZZ Z Z  dddZ dd d Z d d Zd dZddZddZddZddZddZddZddZdS)Reporteraq Info/warning/error reporter and ``system_message`` element generator. Five levels of system messages are defined, along with corresponding methods: `debug()`, `info()`, `warning()`, `error()`, and `severe()`. There is typically one Reporter object per process. A Reporter object is instantiated with thresholds for reporting (generating warnings) and halting processing (raising exceptions), a switch to turn debug output on or off, and an I/O stream for warnings. These are stored as instance attributes. When a system message is generated, its level is compared to the stored thresholds, and a warning or error is generated as appropriate. Debug messages are produced if the stored debug switch is on, independently of other thresholds. Message output is sent to the stored warning stream if not set to ''. The Reporter class also employs a modified form of the "Observer" pattern [GoF95]_ to track system messages generated. The `attach_observer` method should be called before parsing, with a bound method or function which accepts system messages. The observer can be removed with `detach_observer`, and another added in its place. .. [GoF95] Gamma, Helm, Johnson, Vlissides. *Design Patterns: Elements of Reusable Object-Oriented Software*. Addison-Wesley, Reading, MA, USA, 1995. zDEBUG INFO WARNING ERROR SEVERENFbackslashreplacecCsl||_ ||_ ||_ ||_ ||_ t|tst|||}||_ |p*t|dd|_ g|_ d|_ dS)a7 :Parameters: - `source`: The path to or description of the source data. - `report_level`: The level at or above which warning output will be sent to `stream`. - `halt_level`: The level at or above which `SystemMessage` exceptions will be raised, halting execution. - `debug`: Show debug (level=0) system messages? - `stream`: Where warning output is sent. Can be file-like (has a ``.write`` method), a string (file name, opened for writing), '' (empty string) or `False` (for discarding all stream messages) or `None` (implies `sys.stderr`; default). - `encoding`: The output encoding. - `error_handler`: The error handler for stderr output encoding. encodingasciiN) source error_handler debug_flag report_level halt_level isinstancerstreamgetattrr observers max_level)rr#r&r'r)debugr r$rrrrPs(  zReporter.__init__cCsFtjdtdd||_||_t|tst||j|j}||_ ||_ dS)Nzhdocutils.utils.Reporter.set_conditions deprecated; set attributes via configuration settings or directly stacklevel) warningswarnDeprecationWarningr&r'r(rr r$r)r%)rcategoryr&r'r)r-rrrset_conditionss  zReporter.set_conditionscCs|j|dS)z The `observer` parameter is a function or bound method which takes one argument, a `nodes.system_message` instance. N)r+appendrobserverrrrattach_observerszReporter.attach_observercCs|j|dSr )r+remover7rrrdetach_observerszReporter.detach_observercCs|jD]}||qdSr )r+)rmessager8rrrnotify_observerss  zReporter.notify_observersc Oslt|tr t|}|}d|vr0t|d\}}|d=|dur&|d||dur0|d|d|vr^z ||d\}}Wn tyMd\}}Ynw|durV||d<|dur^||d<|d|j t j |g|R||j |d|}|j r||jks|jr||jks||jkr|j |d||jkrt||||jks|jr||t||j|_|S)zs Return a system_message object. Raise an exception or generate a warning if appropriate. base_nodeNr#lineNN)rtype )r(rr copyget_source_line setdefaultget_source_and_linegetAttributeErrorr#rrlevelsr)r&r% DEBUG_LEVELr'writerr r=maxr,) rrr<childrenkwargs attributesr#r?msgrrrrsP          zReporter.system_messagecOs$|jr|j|jg|Ri|SdS)z Level-0, "DEBUG": an internal reporting issue. Typically, there is no effect on the processing. Level-0 system messages are handled separately from the others. N)r%rrJrargsrNrrrr-szReporter.debugcO|j|jg|Ri|S)z Level-1, "INFO": a minor issue that can be ignored. Typically there is no effect on processing, and level-1 system messages are not reported. )r INFO_LEVELrQrrrinfoz Reporter.infocOrS)z Level-2, "WARNING": an issue that should be addressed. If ignored, there may be unpredictable problems with the output. )r WARNING_LEVELrQrrrwarningrVzReporter.warningcOrS)zz Level-3, "ERROR": an error that should be addressed. If ignored, the output will contain errors. )r ERROR_LEVELrQrrrerrorrVzReporter.errorcOrS)z Level-4, "SEVERE": a severe error that must be addressed. If ignored, the output will contain severe errors. Typically level-4 system messages are turned into exceptions which halt processing. )r SEVERE_LEVELrQrrrsevereszReporter.severe)NFNr)NF)rrr__doc__splitrIrangerJrTrWrYr[rr5r9r;r=rr-rUrXrZr\rrrrr's0 4  .  rc@r)ExtensionOptionErrorNrrrrrr`rr`c@r)BadOptionErrorNrrrrrrarrac@r)BadOptionDataErrorNrrrrrrbrrbc@r)DuplicateOptionErrorNrrrrrrcrrccCst|}t||}|S)aC Return a dictionary mapping extension option names to converted values. :Parameters: - `field_list`: A flat field list without field arguments, where each field body consists of a single paragraph only. - `options_spec`: Dictionary mapping known option names to a conversion function such as `int` or `float`. :Exceptions: - `KeyError` for unknown option names. - `ValueError` for invalid option values (raised by the conversion function). - `TypeError` for invalid option value types (raised by conversion function). - `DuplicateOptionError` for duplicate options. - `BadOptionError` for invalid fields. - `BadOptionDataError` for invalid option data (missing name, missing data, bad quotes, etc.). )extract_optionsassemble_option_dict) field_list options_spec option_list option_dictrrrextract_extension_optionss rjcCsg}|D]^}t|ddkrtdt|d}|d}t|dkr-d}n.t|dksMt|dtjrMt|ddksMt|ddtj sSt d||dd}| ||fq|S)a Return a list of option (name, value) pairs from field names & bodies. :Parameter: `field_list`: A flat field list, where each field name is a single word and each field body consists of a single paragraph only. :Exceptions: - `BadOptionError` for invalid fields. - `BadOptionDataError` for invalid option data (missing name, missing data, bad quotes, etc.). rz:extension option field name may not contain multiple wordsNzMextension option field body may contain a single paragraph only (option "%s")) lenrr^rastrlowerr(r paragraphTextrbr6)rfrhfieldnamebodydatarrrrds(  $rdc Csi}|D]>\}}||}|durt|||vrtd|z||||<WqttfyB}z|d||d|jfd}~ww|S)aa Return a mapping of option names to values. :Parameters: - `option_list`: A list of (name, value) pairs (the output of `extract_options()`). - `options_spec`: Dictionary mapping known option names to a conversion function such as `int` or `float`. :Exceptions: - `KeyError` for unknown option names. - `DuplicateOptionError` for duplicate options. - `ValueError` for invalid option values (raised by conversion function). - `TypeError` for invalid option value types (raised by conversion function). Nzduplicate option "%s"z(option: "%s"; value: %r) %s )KeyErrorrc ValueError TypeError __class__joinrR)rhrgoptionsrrvalue convertordetailrrrre1s   rec@r)NameValueErrorNrrrrrrRrrc Cst|tr|Sz |td}Wn6ty'|s!tdYStd|t yGz|dd}Wnt yD|dd}YnwYnwt|S)z Ensure `path` is Unicode. Return `nodes.reprunicode` object. Decode file/path string in a failsave manner if not already done. strictz1`path` value must be a String or ``None``, not %rzutf-8r!replace) r(unicodedecodesysgetfilesystemencodingrHr reprunicoderwUnicodeDecodeError)pathrrr decode_pathUs&     rcCsNg}|r|d}|dkrtd|d|}|dks|s#td||dd}|s5td||dd vr|||dd}|dkrQtd ||dft||dkrk||drktd ||df|d|}||dd}n|d }|dkr|}d }n|d|}||dd}|||f|s|S)z Return a list of (name, value) from a line of the form "name=value ...". :Exception: `NameValueError` for invalid input (missing name, missing data, bad quotes, etc.). =r"z missing "="Nrz!missing attribute name before "="rkzmissing value after "%s="z'"z%attribute "%s" missing end quote (%s)z8attribute "%s" end quote (%s) not followed by whitespacerur)findrstriplstriprlr6rn)r?attlistequalsattnameendquotertspacerrrextract_name_valuemsP         !rc Cs&t||j|j|j|j|j|jd}|S)z Return a new Reporter object. :Parameters: `source` : string The path to or description of the source text of the document. `settings` : optparse.Values object Runtime settings. )r)r-r r$)rr&r'warning_streamr-error_encodingerror_encoding_error_handler) source_pathsettingsreporterrrr new_reporters rcCsRddlm}|dur|}t|}t||}tj|||d}||d|S)a Return a new empty document object. :Parameters: `source_path` : string The path to or description of the source text of the document. `settings` : optparse.Values object Runtime settings. If none are provided, a default core set will be used. If you will use the document object with any Docutils components, you must provide their default settings as well. For example, if parsing rST, at least provide the rst-parser settings, obtainable as follows:: settings = docutils.frontend.OptionParser( components=(docutils.parsers.rst.Parser,) ).get_default_values() r)frontendN)r#r") docutilsr OptionParserget_default_valuesrrrdocument note_source)rrrrrrrr new_documents    rcCsht|dkr.t|dtjr0|d}|D]\}}||}|r-t||||d<dSqdSdSdS)Nrkr)rlr(rrpsearchsub)rokeyword_substitutionstextnodepattern substitutionmatchrrrclean_rcs_keywordss  rcCstj|p t|dtj}tj|tj}|dd|ddkr+d|S|||rS|rS|d|dkrS|||rS|rS|d|dks?|dgt |d|}d|S)z Build and return a path to `target`, relative to `source` (both files). If there is no common prefix, return the absolute path to `target`. dummy_fileNr./r"z..rk) osrabspathrAr^seprzreversepoprl)r#target source_parts target_partspartsrrr relative_paths"  rcCs4|jr|jr Jd|dkr|j}t||jS|jS)z Retrieve a stylesheet reference from the settings object. Deprecated. Use get_stylesheet_list() instead to enable specification of multiple stylesheets as a comma-separated list. 6stylesheet and stylesheet_path are mutually exclusive.N)stylesheet_path stylesheet _destinationr)r relative_torrrget_stylesheet_references rcsTjr jr Jdjpjpg}t|ts!dd|dD}fdd|DS)zJ Retrieve list of stylesheet references from the settings object. rcSsg|]}|qSr)r.0rrrr sz'get_stylesheet_list..,csg|]}t|jqSr)find_file_in_dirsstylesheet_dirsrrrrr s)rrr(listr^)r stylesheetsrrrget_stylesheet_lists  rcCsZtj|r|S|D] }|dkr|}n tj|}tj||}tj|r*|Sq |S)z} Search for `path` in the list of directories `dirs`. Return the first expansion that matches an existing file. .)rrisabs expanduserrzexists)rdirsdfrrrrs   rcCs&|dddurt|dddkS|jS)z Return whether or not to trim footnote space. If trim_footnote_reference_space is not None, return it. If trim_footnote_reference_space is None, return False unless the footnote reference style is 'superscript'. trim_footnote_reference_spaceNfootnote_references superscript)rEr*rrrrrget_trim_footnote_ref_space"s rcCs*|r|js|jr|j|jfS|j}|sdS)zk Return the "source" and "line" attributes from the `node` given or from its closest ancestor. r@)r#r?parent)noderrrrD0s   rDcCstg}d} |d|}|dkr|||dd|S|||||d||d|d |d }q) z;Return a string with escape-backslashes converted to nulls.rT\r"Nrrkr.)rr6rz)textrstartfoundrrr escape2null;s  rcCs&|d}dd|D}ttj|S)zh Split `text` on escaped whitespace (null+space or null+newline). Return a list of strings. z cSsg|]}|dqS)z )r^)rstringrrrrPsz,split_escaped_whitespace..)r^r itertoolschain)rstringsrrrsplit_escaped_whitespaceJs rcCs,t|tr tjdkr |Sddd|DS)Nr rcSsg|] }t|s|qSr unicodedata combiningrcrrrrWsz)strip_combining_chars..)r(rmr version_inforzrrrrstrip_combining_charsTsrcCs*t|tr tjdkr gSddt|DS)uReturn indices of all combining chars in Unicode string `text`. >>> from docutils.utils import find_combining_chars >>> find_combining_chars(u'A t̆ab̆lĕ') [3, 6, 9] r cSsg|] \}}t|r|qSrr)rirrrrrcsz(find_combining_chars..)r(rmrr enumeraterrrrfind_combining_charsYsrcCs4ttt|}t|D]}d||<q dd|DS)uIndices of Unicode string `text` when skipping combining characters. >>> from docutils.utils import column_indices >>> column_indices(u'A t̆ab̆lĕ') [0, 1, 2, 4, 5, 7, 8] NcSsg|]}|dur|qSr r)rrrrrrrsz"column_indices..)rr_rlr)rstring_indicesindexrrrcolumn_indiceses  rr.rk)WFNaHNAcCsBt|trtjdkrt|Stdd|D}|tt|8}|S)zqReturn the column width of text. Correct ``len(text)`` for wide East Asian and combining Unicode chars. r cSsg|] }tt|qSr)east_asian_widthsreast_asian_widthrrrrrsz column_width..)r(rmrrrlsumr)rwidthrrr column_width~srcCs$g}|D] }||vr||q|Sr )r6)Lritemrrruniqs  rcCstjdtddt||S)z Return `itertools.combinations`.zVdocutils.utils.unique_combinations is deprecated; use itertools.combinations directly.r.r/)r1r2r3r combinations)itemsnrrrunique_combinationss rcCs|dd}tdd|}dd|dD}|df}g}tt|ddD]}t ||D] }| d ||q1q)||7}|S) aWReturn a list of normalized combinations for a `BCP 47` language tag. Example: >>> from docutils.utils import normalize_language_tag >>> normalize_language_tag('de_AT-1901') ['de-at-1901', 'de-at', 'de-1901', 'de'] >>> normalize_language_tag('de-CH-x_altquot') ['de-ch-x-altquot', 'de-ch', 'de-x-altquot', 'de'] -_z_([a-zA-Z0-9])_z_\1-cSsg|]}|qSrr)rsubtagrrrrsz*normalize_language_tag..rr") rnrrerr^rr_rlrrr6rz)tagsubtagsbase_tagtaglistrtagsrrrnormalize_language_tags  r c@s>eZdZdZdgfddZddZddZd d Zd d ZdS) DependencyListz List of dependencies, with file recording support. Note that the output file is not automatically closed. You have to explicitly call the close() method. NcCs"|||D]}||qdS)z Initialize the dependency list, automatically setting the output file to `output_file` (see `set_output()`) and adding all supplied dependencies. N) set_outputadd)r output_file dependenciesrrrrrs  zDependencyList.__init__cCs>g|_|r|dkr d}n|}tjj|ddd|_dSd|_dS)aH Set the output file and clear the list of already added dependencies. `output_file` must be a string. The specified file is immediately overwritten. If output_file is '-', the output will be written to stdout. If it is None, no file output is done when calling add(). rNutf8F)destination_pathr autoclose)rrio FileOutputfile)rr ofrrrr s  zDependencyList.set_outputcGs>|D]}||jvr|j||jdur|j|dqdS)z If the dependency `filename` has not already been added, append it to self.list and print it to self.file if self.file is not None. NrB)rr6rrK)r filenamesfilenamerrrr s   zDependencyList.addcCs|jd|_dS)z( Close the output file. N)rclose)rrrrrs  zDependencyList.closecCs8z|jj}Wn tyd}Ynwd|jj||jfS)Nz %s(%r, %s))rrrrHryrr)rr rrr__repr__s   zDependencyList.__repr__) rrrr]rr r rrrrrrr s  r abrcr)alphabeta candidatefinalcCsj|durt}|jrd|j}nd}t|j}|jr|j}nd}|jr%d}nd}d|j|j||||f}|S)a4 Return a version identifier string built from `version_info`, a `docutils.VersionInfo` namedtuple instance or compatible tuple. If `version_info` is not provided, by default return a version identifier string based on `docutils.__version_info__` (i.e. the current Docutils version). Nz.%srz.devz %s.%s%s%s%s%s)rmicrorelease_level_abbreviations releaselevelserialreleasemajorminor)rr!r#r$devversionrrrversion_identifiers*  r*r );r] __docformat__rros.pathrrr1rrrrrrdocutils.nodesr docutils.iodocutils.utils.error_reportingrr rrmrr robjectrr`rarbrcrjrdrerrrrrrrrrrrrDrrrrrrrrrr r r"r*rrrrs~   L !,      E