U C^up@sdZdZddlZddlZddlZddlZddlZddlZddlZddl m Z m Z m Z ddl m Z ddlmZddlZ ddlmZmZGdd d e ZGd d d e ZGd d d ZGddde ZGdddeZGdddeZGdddeZddZddZddZGddde ZddZd d!Z d"d#Z!dRd$d%Z"d&d'Z#d(d)Z$dSd*d+Z%d,d-Z&d.d/Z'd0d1Z(d2d3Z)d4d5Z*d6d7Z+d8d9Z,d:d;Z-dd>d?d?d?d?d@Z/dAdBZ0dCdDZ1dEdFZ2dGdHZ3GdIdJdJe4Z5dKdLdMdNdOZ6dTdPdQZ7dS)Uz: Miscellaneous utilities for the documentation utilities. ZreStructuredTextN)ApplicationError DataError__version_info__)nodes)unescape) ErrorOutput SafeStringc@seZdZddZdS) SystemMessagecCst||||_dSN) Exception__init__astextlevel)selfsystem_messagerr=/tmp/pip-install-6_kvzl1k/docutils/docutils/utils/__init__.pyr szSystemMessage.__init__N)__name__ __module__ __qualname__r rrrrr sr c@s eZdZdS)SystemMessagePropagationNrrrrrrrr!src@seZdZdZdZeed\ZZ Z Z Z dddZ dd d Zd 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 SEVERENFbackslashreplacecCs\||_||_||_||_||_t|ts4t|||}||_|pHt|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)rrr!r"r$debugrrrrrr Ms  zReporter.__init__cCsFtjdtdd||_||_t|ts6t||j|j}||_ ||_ dS)Nzhdocutils.utils.Reporter.set_conditions deprecated; set attributes via configuration settings or directly stacklevel) warningswarnDeprecationWarningr!r"r#rrrr$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&remover2rrrdetach_observerszReporter.detach_observercCs|jD] }||qdSr )r&)rmessager3rrrnotify_observerss zReporter.notify_observersc Os|t|trt|}|}d|kr`t|d\}}|d=|dk rL|d||dk r`|d|d|krz||d\}}Wntk rd\}}YnX|dk r||d<|dk r||d<|d|j t j |f|||j |d|}|j r6||jks"|jr||jks"||jkr6|j |d||jkrLt||||jks`|jrj||t||j|_|S)zs Return a system_message object. Raise an exception or generate a warning if appropriate. Z base_nodeNrlineNN)rtype )r#r rcopyget_source_line setdefaultZget_source_and_linegetAttributeErrorrrrlevelsr$r!r DEBUG_LEVELr"writer r r8maxr') rrr7childrenkwargs attributesrr9msgrrrrsR      zReporter.system_messagecOs|jr|j|jf||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 rrCrargsrGrrrr(szReporter.debugcOs|j|jf||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_LEVELrJrrrinfosz Reporter.infocOs|j|jf||S)z Level-2, "WARNING": an issue that should be addressed. If ignored, there may be unpredictable problems with the output. )r WARNING_LEVELrJrrrwarningszReporter.warningcOs|j|jf||S)zz Level-3, "ERROR": an error that should be addressed. If ignored, the output will contain errors. )r ERROR_LEVELrJrrrerrorszReporter.errorcOs|j|jf||S)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_LEVELrJrrrsevereszReporter.severe)NFNr)NF)rrr__doc__splitrBlistrangerCrLrNrPrRr r0r4r6r8rr(rMrOrQrSrrrrr$s2  4 / rc@s eZdZdS)ExtensionOptionErrorNrrrrrrXsrXc@s eZdZdS)BadOptionErrorNrrrrrrYsrYc@s eZdZdS)BadOptionDataErrorNrrrrrrZsrZc@s eZdZdS)DuplicateOptionErrorNrrrrrr[sr[cCst|}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 rbcCsg}|D]}t|ddkr,tdt|d}|d}t|dkrZd}n^t|dkst|dtjrt|ddkst|ddtj st d|n|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")) lenr rUrYstrlowerr#r paragraphTextrZr1)r^r`fieldnamebodydatarrrr\s.  r\c Csi}|D]\}}||}|dkr(t|||kr|d }|dkr|}d }n |d|}||dd}|||fq|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.). =rz missing "="Nrz!missing attribute name before "="rczmissing value after "%s="z'"z%attribute "%s" missing end quote (%s)z8attribute "%s" end quote (%s) not followed by whitespacerm)findrustriplstriprdr1rf)r9attlistequalsZattnameZendquoterlspacerrrextract_name_valuehsN          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(rr)rr!r"Zwarning_streamr(Zerror_encodingZerror_encoding_error_handler) source_pathsettingsreporterrrr new_reporters rcCsRddlm}|dkr |}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, at least provide the parser settings, obtainable as follows:: settings = docutils.frontend.OptionParser( components=(docutils.parsers.rst.Parser,) ).get_default_values() r)frontendN)rr) docutilsr OptionParserget_default_valuesr}rrdocumentZ note_source)rrrrrrrr new_documents    rcCs`t|dkr\t|dtjr\|d}|D]2\}}||}|r(t||||d<dSq(dS)Nrcr)rdr#rrhsearchsub)rgZkeyword_substitutionsZtextnodepatternZ substitutionmatchrrrclean_rcs_keywordss  rcCstj|pt|dtj}tj|tj}|dd|ddkrVd|S|||r|r|d|dkr||qf|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`. Z dummy_fileNr)/rz..rc) osr|abspathr;rUseprrreversepoprd)rtargetZ source_partsZ target_partspartsrrr relative_paths   rcCs8|jr.|jrtd|dkr"|j}t||jS|jSdS)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 stylesheetAssertionErrorZ _destinationr)r relative_torrrget_stylesheet_references rcsTjrjrtdjp"jp"g}t|tsBdd|dD}fdd|DS)zJ Retrieve list of stylesheet references from the settings object. rcSsg|] }|qSr)r.0r|rrr sz'get_stylesheet_list..,csg|]}t|jqSr)find_file_in_dirsZstylesheet_dirsrrrrrs)rrrr#rVrU)rZ stylesheetsrrrget_stylesheet_lists  rcCsZtj|r|S|D]@}|dkr&|}ntj|}tj||}tj|r|Sq|S)z} Search for `path` in the list of directories `dirs`. Return the first expansion that matches an existing file. .)rr|isabs expanduserrrexists)r|dirsdfrrrr s    rcCs(|jdkrt|do|jdkS|jSdS)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'. Nfootnote_referencesZ superscript)Ztrim_footnote_reference_spacehasattrrrrrrget_trim_footnote_ref_spaces  rcCs(|r$|js|jr|j|jfS|j}qdS)zk Return the "source" and "line" attributes from the `node` given or from its closest ancestor. r:)rr9parent)noderrrr>,s   r>cCsvg}d}|d|}|dkr8|||dd|S|||||d||d|d|d}qdS) z;Return a string with escape-backslashes converted to nulls.r\rNrrcr))rr1rr)textrstartfoundrrr escape2null7s  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 )rU)rstringrrrrLsz,split_escaped_whitespace..)rUrV itertoolschain)rstringsrrrsplit_escaped_whitespaceFs rcCs,t|trtjdkr|Sddd|DS)NrrcSsg|]}t|s|qSr unicodedata combiningrcrrrrSs z)strip_combining_chars..)r#rery version_inforrrrrrstrip_combining_charsPsrcCs*t|trtjdkrgSddt|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] rcSsg|]\}}t|r|qSrr)rirrrrr_s z(find_combining_chars..)r#reryr enumeraterrrrfind_combining_charsUsrcCs4ttt|}t|D] }d||<qdd|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|]}|dk r|qSr r)rrrrrrnsz"column_indices..)rVrWrdr)rZstring_indicesindexrrrcolumn_indicesas   rr)rc)WFZNaHNAcCsBt|trtjdkrt|Stdd|D}|tt|8}|S)zqReturn the column width of text. Correct ``len(text)`` for wide East Asian and combining Unicode chars. rcSsg|]}tt|qSr)east_asian_widthsreast_asian_widthrrrrrsz column_width..)r#reryrrdsumr)rwidthrrr column_widthzsrcCs$g}|D]}||kr||q|Sr )r1)Lritemrrruniqs  rcCstjdtddt||S)z Return `itertools.combinations`.zVdocutils.utils.unique_combinations is deprecated; use itertools.combinations directly.r)r*)r,r-r.r combinations)itemsnrrrunique_combinationss rcCs|dd}tdd|}dd|dD}|df}g}tt|ddD]*}t ||D]}| d ||qbqR||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)rZsubtagrrrrsz*normalize_language_tag..rr) rfrwrerrUrrWrdrrr1rr)tagZsubtagsZbase_tagZtaglistrtagsrrrnormalize_language_tags  rc@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_fileZ dependenciesrrrrr s zDependencyList.__init__cCs<g|_|r2|dkrd}n|}tjj|ddd|_nd|_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)Zdestination_pathrZ autoclose)rVrioZ FileOutputfile)rrZofrrrrs  zDependencyList.set_outputcGs>|D]4}||jkr|j||jdk r|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. Nr<)rVr1rrD)r filenamesfilenamerrrrs    zDependencyList.addcCs|jd|_dS)z( Close the output file. N)rclose)rrrrrs zDependencyList.closecCs:z |jj}Wntk r$d}YnXd|jj||jfS)Nz %s(%r, %s))rrjrArqrrV)rrrrr__repr__s   zDependencyList.__repr__) rrrrTr rrrrrrrrrs   rabrcr)alphabeta candidatefinalcCsj|dkr t}|jrd|j}nd}t|j}|jr:|j}nd}|jrJd}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)rrrrdevversionrrrversion_identifiers*  r)N)N)N)8rTZ __docformat__ryros.pathrrr,rrrrrrZdocutils.nodesrZ docutils.ioZdocutils.utils.error_reportingrrr rrrXrYrZr[rbr\r]rur}rrrrrrrrrr>rrrrrrrrrrobjectrrrrrrrsv  M !,        E