B \Rr@sdZdZddlZddlZddlZddlZddlZddlZddlZddl m Z m Z m Z ddl m Z ddlZ ddlmZmZGddde ZGd d d e ZGd d d ZGd dde ZGdddeZGdddeZGdddeZddZddZddZGddde ZddZdd Zd!d"ZdTd#d$Z d%d&Z!d'd(Z"dUd)d*Z#d+d,Z$d-d.Z%d/d0Z&d1d2Z'd3d4Z(dVd6d7Z)d8d9Z*d:d;Z+dd?Z-d@d@dAdAdAdAdBZ.dCdDZ/dEdFZ0dGdHZ1dIdJZ2GdKdLdLe3Z4dMdNdOdPdQZ5dWdRdSZ6dS)Xz: Miscellaneous utilities for the documentation utilities. ZreStructuredTextN)ApplicationError DataError__version_info__)nodes) ErrorOutput SafeStringc@seZdZddZdS) SystemMessagecCst||||_dS)N) Exception__init__astextlevel)selfsystem_messager r;/tmp/pip-build-uw_ogi45/docutils/docutils/utils/__init__.pyr szSystemMessage.__init__N)__name__ __module__ __qualname__r rrrrrsrc@s eZdZdS)SystemMessagePropagationN)rrrrrrrr 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)r rrrr!debugrrrrrr Ls  zReporter.__init__cCsFtjdtdd||_||_t|ts6t||j|j}||_ ||_ dS)Nzhdocutils.utils.Reporter.set_conditions deprecated; set attributes via configuration settings or directly) stacklevel) warningswarnDeprecationWarningrrr rrrr!r)r categoryrrr!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#append)r observerrrrattach_observerszReporter.attach_observercCs|j|dS)N)r#remove)r r.rrrdetach_observerszReporter.detach_observercCsx|jD] }||qWdS)N)r#)r messager.rrrnotify_observerss zReporter.notify_observersc Os|t|trt|}|}d|kr`t|d\}}|d=|dk rL|d||dk r`|d|d|kry||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_nodeNrline)NN)r type )r r rcopyget_source_line setdefaultZget_source_and_linegetAttributeErrorrrrlevelsr!rr DEBUG_LEVELrwriter rr3maxr$) r r r2childrenkwargs attributesrr4msgrrrrs@       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)rrr=)r argsrArrrr%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_LEVEL)r rDrArrrinfosz 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_LEVEL)r rDrArrrwarningszReporter.warningcOs|j|jf||S)zz Level-3, "ERROR": an error that should be addressed. If ignored, the output will contain errors. )r ERROR_LEVEL)r rDrArrrerrorszReporter.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_LEVEL)r rDrArrrsevereszReporter.severe)NFNr)NF)rrr__doc__splitr<listranger=rErGrIrKr r,r/r1r3rr%rFrHrJrLrrrrr#s 3 / rc@s eZdZdS)ExtensionOptionErrorN)rrrrrrrrQsrQc@s eZdZdS)BadOptionErrorN)rrrrrrrrRsrRc@s eZdZdS)BadOptionDataErrorN)rrrrrrrrSsrSc@s eZdZdS)DuplicateOptionErrorN)rrrrrrrrTsrTcCst|}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 r[cCsg}x|D]}t|ddkr.tdt|d}|d}t|dkr\d}n^t|dkst|dtjrt|ddkst|ddtj st d|n|dd}| ||fq W|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 rNrRstrlowerr r paragraphTextrSr-)rWrYfieldnamebodydatarrrrUs"   $ rUc Csi}x|D]\}}||}|dkr*t|||kr>td|y||||<Wq ttfk r}z |d||d|jfWdd}~XYq Xq W|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 )KeyErrorrT ValueError TypeError __class__joinrD)rYrXoptionsrcvalueZ convertorZdetailrrrrV.s ,rVc@s eZdZdS)NameValueErrorN)rrrrrrrrnOsrnc Cst|tr|Sy|td}Wn^tk r<t|Stk ry|dd}Wn tk rz|dd}YnXYnXt|S)z Ensure `path` is Unicode. Return `nodes.reprunicode` object. Decode file/path string in a failsave manner if not already done. strictzutf-8rreplace) r r^decodesysgetfilesystemencodingr;rZ reprunicodeUnicodeDecodeError)pathrrr decode_pathRs  rvcCsVg}xJ|rP|d}|dkr(td|d|}|dksD|sLtd||dd}|sptd||dd kr||dd}|dkrtd ||dft||dkr||drtd ||df|d|}||dd}n>|d }|dkr|}d }n |d|}||dd}|||fqW|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 "="r\zmissing value after "%s="z'"z%attribute "%s" missing end quote (%s)z8attribute "%s" end quote (%s) not followed by whitespacerf)findrnstriplstripr]r-r_)r4attlistequalsZattnameZendquoterespacerrrextract_name_valuegsB          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)rrrZwarning_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_valuesrvrrdocumentZ note_source)rrrrrrrr new_documents    rcCsbt|dkr^t|dtjr^|d}x8|D]0\}}||}|r*t||||d<dSq*WdS)Nr\r)r]r rrasearchsub)r`Zkeyword_substitutionsZtextnodepatternZ substitutionmatchrrrclean_rcs_keywordss rcCstj|pt|dtj}tj|tj}|dd|ddkrVd|S||x,|r|r|d|dkr||qhW|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..r\) osruabspathr5rNseprkreversepopr])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. z6stylesheet and stylesheet_path are mutually exclusive.N)stylesheet_path stylesheetAssertionErrorZ _destinationr)rZ relative_torrrget_stylesheet_references rcsTjrjrtdjp"jp"g}t|tsBdd|dD}fdd|DS)zJ Retrieve list of stylesheet references from the settings object. z6stylesheet and stylesheet_path are mutually exclusive.cSsg|] }|qSr)rz).0rurrr sz'get_stylesheet_list..,csg|]}t|jqSr)find_file_in_dirsZstylesheet_dirs)rru)rrrrs)rrrr rOrN)rZ stylesheetsr)rrget_stylesheet_lists  rcCsZtj|r|SxD|D]<}|dkr(|}ntj|}tj||}tj|r|SqW|S)z} Search for `path` in the list of directories `dirs`. Return the first expansion that matches an existing file. .)rruisabs expanduserrkexists)rudirsdfrrrr 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_spacehasattrr)rrrrget_trim_footnote_ref_spaces   rcCs,x&|r&|js|jr|j|jfS|j}qWdS)zk Return the "source" and "line" attributes from the `node` given or from its closest ancestor. )NN)rr4parent)noderrrr8+s    r8cCszg}d}xl|d|}|dkr:|||dd|S|||||d||d|d|d}q WdS) z;Return a string with escape-backslashes converted to nulls.r\rNrxr\r&)ryr-rk)textrstartfoundrrr escape2null6s  rFcCs6|r|ddSxdD]}d||}qW|SdS)zw Return a string with nulls removed or restored to backslashes. Backslash-escaped spaces are also removed. rr)z z rrxN)rprkrN)rZrestore_backslashesZrespect_whitespacerrrrunescapeCs   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 )rN)rstringrrrrUsz,split_escaped_whitespace..)rNrO itertoolschain)rstringsrrrsplit_escaped_whitespaceOs rcCs,t|trtjdkr|Sddd|DS)N)rrxcSsg|]}t|s|qSr) unicodedata combining)rcrrrr\sz)strip_combining_chars..)r r^rr version_infork)rrrrstrip_combining_charsYsrcCs*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] )rrcSsg|]\}}t|r|qSr)rr)rirrrrrhsz(find_combining_chars..)r r^rrr enumerate)rrrrfind_combining_chars^srcCs8ttt|}xt|D] }d||<qWdd|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|qS)Nr)rrrrrrwsz"column_indices..)rOrPr]r)rZstring_indicesindexrrrcolumn_indicesjs  rr&r\)WFZNaHNAcCsdt|trtjdkrt|Sytdd|D}Wntk rNt|}YnX|tt|8}|S)zqReturn the column width of text. Correct ``len(text)`` for wide East Asian and combining Unicode chars. )rrcSsg|]}tt|qSr)east_asian_widthsreast_asian_width)rrrrrrsz column_width..)r r^rrrr]sumr;r)rwidthrrr column_widthsrcCs(g}x|D]}||kr ||q W|S)N)r-)Lritemrrruniqs  rccsf|dkrgVnRxPtt||dD]8}x2t||dd|dD]}||g|VqFWq&WdS)z=Return n-length tuples, in sorted order, no repeated elementsrr\N)rPr]unique_combinations)itemsnrccrrrrs  rcCs|dd}tdd|}dd|dD}|dg}g}x@tt|ddD],}x&t||D]}| d ||qdWqTW||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) r_rprerrNrrPr]rr-rk)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&||x|D]}||qWdS)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)rOrioZ FileOutputfile)r rZofrrrrs zDependencyList.set_outputcGsBx<|D]4}||jkr|j||jdk r|j|dqWdS)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. Nr6)rOr-rr>)r filenamesfilenamerrrrs     zDependencyList.addcCs|jd|_dS)z( Close the output file. N)rclose)r rrrrs zDependencyList.closecCs:y |jj}Wntk r$d}YnXd|jj||jfS)Nz %s(%r, %s))rrcr;rjrrO)r rrrr__repr__s   zDependencyList.__repr__) rrrrMr rrrrrrrrrs   rabrcrx)alphabeta candidatefinalcCsz|dkr t}|dr"d|d}nd}t|d}|drD|d}nd}|drVd}nd}d |d |d ||||f}|S) z~ Given a `version_info` tuple (default is docutils.__version_info__), build & return a version identifier string. Nr&z.%srxrrz.devz %s.%s%s%s%s%srr\)rrelease_level_abbreviations)rmicro releaselevelserialdevversionrrrversion_identifier s*  r)N)N)FF)N)7rMZ __docformat__rrros.pathrrr(rrrrrrZ docutils.ioZdocutils.utils.error_reportingrrrrrrQrRrSrTr[rUrVrnrvrrrrrrrrrr8rrrrrrrrrrrobjectrrrrrrrsr M !,        E