o n_q@sdZddlmZdZddlZddlZddlZddlmZddl m Z ej dkr)e Z Gdd d eZGd d d eZGd d d eZGdddeZGdddeZGdddeeZGdddeeZGdddeZGdddeZGdddeZGdddeZGdddeZGd d!d!eZGd"d#d#eZGd$d%d%eZGd&d'd'eZGd(d)d)eZ Gd*d+d+eZ!Gd,d-d-eZ"d.d/e#d0fd1d2Z$d3d4Z%dS)5a A finite state machine specialized for regular-expression-based text filters, this module defines the following classes: - `StateMachine`, a state machine - `State`, a state superclass - `StateMachineWS`, a whitespace-sensitive version of `StateMachine` - `StateWS`, a state superclass for use with `StateMachineWS` - `SearchStateMachine`, uses `re.search()` instead of `re.match()` - `SearchStateMachineWS`, uses `re.search()` instead of `re.match()` - `ViewList`, extends standard Python lists. - `StringList`, string-specific ViewList. Exception classes: - `StateMachineError` - `UnknownStateError` - `DuplicateStateError` - `UnknownTransitionError` - `DuplicateTransitionError` - `TransitionPatternNotFound` - `TransitionMethodNotFound` - `UnexpectedIndentationError` - `TransitionCorrection`: Raised to switch to another transition. - `StateCorrection`: Raised to switch to another state & transition. Functions: - `string2lines()`: split a multi-line string into a list of one-line strings How To Use This Module ====================== (See the individual classes, methods, and attributes for details.) 1. Import it: ``import statemachine`` or ``from statemachine import ...``. You will also need to ``import re``. 2. Derive a subclass of `State` (or `StateWS`) for each state in your state machine:: class MyState(statemachine.State): Within the state's class definition: a) Include a pattern for each transition, in `State.patterns`:: patterns = {'atransition': r'pattern', ...} b) Include a list of initial transitions to be set up automatically, in `State.initial_transitions`:: initial_transitions = ['atransition', ...] c) Define a method for each transition, with the same name as the transition pattern:: def atransition(self, match, context, next_state): # do something result = [...] # a list return context, next_state, result # context, next_state may be altered Transition methods may raise an `EOFError` to cut processing short. d) You may wish to override the `State.bof()` and/or `State.eof()` implicit transition methods, which handle the beginning- and end-of-file. e) In order to handle nested processing, you may wish to override the attributes `State.nested_sm` and/or `State.nested_sm_kwargs`. If you are using `StateWS` as a base class, in order to handle nested indented blocks, you may wish to: - override the attributes `StateWS.indent_sm`, `StateWS.indent_sm_kwargs`, `StateWS.known_indent_sm`, and/or `StateWS.known_indent_sm_kwargs`; - override the `StateWS.blank()` method; and/or - override or extend the `StateWS.indent()`, `StateWS.known_indent()`, and/or `StateWS.firstknown_indent()` methods. 3. Create a state machine object:: sm = StateMachine(state_classes=[MyState, ...], initial_state='MyState') 4. Obtain the input text, which needs to be converted into a tab-free list of one-line strings. For example, to read text from a file called 'inputfile':: input_string = open('inputfile').read() input_lines = statemachine.string2lines(input_string) 5. Run the state machine on the input text and collect the results, a list:: results = sm.run(input_lines) 6. Remove any lingering circular references:: sm.unlink() )print_functionrestructuredtextN)utils) ErrorOutput)rc@seZdZdZd6ddZddZ  d7d d Zd8d d Zd9ddZddZ ddZ ddZ d9ddZ ddZ ddZddZddZd8d d!Zd"d#Zd6d$d%Zd8d&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Zd2d3Zd4d5ZdS): StateMachinea A finite state machine for text filters using regular expressions. The input is provided in the form of a list of one-line strings (no newlines). States are subclasses of the `State` class. Transitions consist of regular expression patterns and transition methods, and are defined in each state. The state machine is started with the `run()` method, which returns the results of processing in a list. FcCs^d|_ d|_ d|_ d|_ ||_ ||_ ||_ i|_ ||g|_ t |_ dS)a+ Initialize a `StateMachine` object; add state objects. Parameters: - `state_classes`: a list of `State` (sub)classes. - `initial_state`: a string, the class name of the initial state. - `debug`: a boolean; produce verbose output if true (nonzero). Nr) input_lines input_offsetline line_offsetdebug initial_state current_statestates add_states observersr_stderr)self state_classesrr r7/usr/lib/python3/dist-packages/docutils/statemachine.py__init__s*  zStateMachine.__init__cCs"|jD]}|qd|_dSz9Remove circular references to objects no longer required.N)rvaluesunlinkrstaterrrrs  zStateMachine.unlinkrNc CsX|t|tr ||_nt||d|_||_d|_|p|j|_|jr3t d|jd |jf|j dd}g}| }z|jrFt d|j d| |\}} ||  zSz)||jrr|j|j\} } t d | | |jf|j d||||\}} } Wn"ty|jrt d |jj|j d||} || YWnzw|| Wnjty} z"|| jd f}|jrt d |jj|d f|j dWYd} ~ qRd} ~ wty} z0|| jd } t| jd krd}n| jd f}|jrt d| |d f|j dWYd} ~ nd} ~ wwd}| | }qSWn |jr&|g|_|S)a Run the state machine on `input_lines`. Return results (a list). Reset `self.line_offset` and `self.current_state`. Run the beginning-of-file transition. Input one line at a time and check for a matching transition. If a match is found, call the transition method and possibly change the state. Store the context returned by the transition method to be passed on to the next transition matched. Accumulate the results returned by the transition methods in a list. Run the end-of-file transition. Finally, return the accumulated results. Parameters: - `input_lines`: a list of strings without newlines, or `StringList`. - `input_offset`: the line offset of `input_lines` from the beginning of the file. - `context`: application-specific storage. - `input_source`: name or path of source of `input_lines`. - `initial_state`: name of initial state. sourcerz5 StateMachine.run: input_lines (line_offset=%s): | %sz | fileNz! StateMachine.run: bof transitionTz4 StateMachine.run: line (source=%r, offset=%r): | %sz$ StateMachine.run: %s.eof transitionrzE StateMachine.run: TransitionCorrection to state "%s", transition %s.z@ StateMachine.run: StateCorrection to state "%s", transition %s.) runtime_init isinstance StringListr r r rrr printjoinr get_statebofextend next_lineinfor check_lineEOFError __class____name__eofTransitionCorrection previous_lineargsStateCorrectionlenerrorr)rr r context input_sourcer transitionsresultsrresultroffset next_state exceptionrrrruns             zStateMachine.runcCs`|r|jr||jkrtd|j||f|jd||_z|j|jWSty/t|jw)z Return current state object; set it first if `next_state` given. Parameter `next_state`: a string, the name of the next state. Exception: `UnknownStateError` raised if `next_state` unknown. zJ StateMachine.get_state: Changing state from "%s" to "%s" (input line %s).r )r rr&abs_line_numberrrKeyErrorUnknownStateError)rr>rrrr(s  zStateMachine.get_stater"cCsVz%z|j|7_|j|j|_Wn tyd|_tw|jW|S|w)z9Load `self.line` with the `n`'th next line and return it.N)r r r IndexErrorr.notify_observersrnrrrr++s zStateMachine.next_linecCs.z |j|jd WStyYdSw)z3Return 1 if the next line is blank or non-existant.r")r r striprDrrrris_next_line_blank8s  zStateMachine.is_next_line_blankcCs|jt|jdkS)z0Return 1 if the input is at or past end-of-file.r")r r6r rIrrrat_eof?szStateMachine.at_eofcCs |jdkS)z8Return 1 if the input is at or before beginning-of-file.r)r rIrrrat_bofC zStateMachine.at_bofcCs<|j|8_|jdkrd|_n|j|j|_||jS)z=Load `self.line` with the `n`'th previous line and return it.rN)r r r rErFrrrr3Gs  zStateMachine.previous_linecCsTz$z||j|_|j|j|_Wn tyd|_tw|jW|S|w)z?Jump to absolute line offset `line_offset`, load and return it.N)r r r r rDr.rErr rrr goto_lineQs  zStateMachine.goto_linecCs|j||jS)zrerrrr-s8    zStateMachine.check_linecCs.|j}||jvr t||||j|j|<dS)z Initialize & add a `state_class` (`State` subclass) object. Exception: `DuplicateStateError` raised if `state_class` was already added. N)r0rDuplicateStateErrorr )r state_class statenamerrr add_states zStateMachine.add_statecCs|D]}||qdS)zE Add `state_classes` (a list of `State` subclasses). N)rn)rrrlrrrrs zStateMachine.add_statescCs|jD]}|qdS)z+ Initialize `self.states`. N)rrr#rrrrr#s zStateMachine.runtime_initcCsXt\}}}}}td||f|jdtd||jdtd|||f|jddS)zReport error details.z%s: %sr z input line %szmodule %s, line %s, function %sN)_exception_datar&rrA)rtypevaluemoduler functionrrrr7s zStateMachine.errorcCs|j|dS)z The `observer` parameter is a function or bound method which takes two arguments, the source and offset of the current line. N)rappendrobserverrrrattach_observerszStateMachine.attach_observercCs|j|dSN)rremoverurrrdetach_observerszStateMachine.detach_observerc CsB|jD]}z |j|j}Wn tyd}Ynw||qdS)NrS)rr r,r rD)rrvr,rrrrEs   zStateMachine.notify_observersF)rNNNrxr")r0 __module__ __qualname____doc__rrr@r(r+rJrKrLr3rOrPrRrArUr]r_r-rnrr#r7rwrzrErrrrrxs8 / \       )  rc@seZdZdZdZ dZ dZ dZ dddZddZ dd Z d d Z d d Z ddZ ddZdddZddZddZddZddZddZdS) Stateav State superclass. Contains a list of transitions, and transition methods. Transition methods all have the same signature. They take 3 parameters: - An `re` match object. ``match.string`` contains the matched input line, ``match.start()`` gives the start index of the match, and ``match.end()`` gives the end index. - A context object, whose meaning is application-defined (initial value ``None``). It can be used to store any information required by the state machine, and the retured context is passed on to the next transition method unchanged. - The name of the next state, a string, taken from the transitions list; normally it is returned unchanged, but it may be altered by the transition method if necessary. Transition methods all return a 3-tuple: - A context object, as (potentially) modified by the transition method. - The next state name (a return value of ``None`` means no state change). - The processing result, a list, which is accumulated by the state machine. Transition methods may raise an `EOFError` to cut processing short. There are two implicit transitions, and corresponding transition methods are defined: `bof()` handles the beginning-of-file, and `eof()` handles the end-of-file. These methods have non-standard signatures and return values. `bof()` returns the initial context and results, and may be used to return a header string, or do any other processing needed. `eof()` should handle any remaining context and wrap things up; it returns the final processing result. Typical applications need only subclass `State` (or a subclass), set the `patterns` and `initial_transitions` class attributes, and provide corresponding transition methods. The default object initialization will take care of constructing the list of transitions. NFcCsbg|_ i|_ |||_ ||_ |jdur|jj|_|jdur/|jg|jjd|_dSdS)z Initialize a `State` object; make & add initial transitions. Parameters: - `statemachine`: the controlling `StateMachine` object. - `debug`: a boolean; produce verbose output if true. N)rr) rdr:add_initial_transitions state_machiner nested_smr/nested_sm_kwargsr0rrr rrrrLs      zState.__init__cCsdS)z{ Initialize this `State` before running the state machine; called from `self.state_machine.run()`. NrrIrrrr#pszState.runtime_initcC d|_dSr)rrIrrrrwrMz State.unlinkcCs*|jr||j\}}|||dSdS)z>Make and add transitions listed in `self.initial_transitions`.N)initial_transitionsmake_transitionsadd_transitionsrnamesr:rrrr{s zState.add_initial_transitionscCsJ|D]}||jvr t|||vrt|q||jdd<|j|dS)a" Add a list of transitions to the start of the transition list. Parameters: - `names`: a list of transition names. - `transitions`: a mapping of names to transition tuples. Exceptions: `DuplicateTransitionError`, `UnknownTransitionError`. Nr)r:DuplicateTransitionErrorUnknownTransitionErrorrdupdate)rrr:rhrrrrs zState.add_transitionscCs0||jvr t||g|jdd<||j|<dS)z Add a transition to the start of the transition list. Parameter `transition`: a ready-made transition 3-tuple. Exception: `DuplicateTransitionError`. Nr)r:rrd)rrh transitionrrradd_transitions zState.add_transitioncCs*z |j|=|j|WdSt|)z^ Remove a transition by `name`. Exception: `UnknownTransitionError`. N)r:rdryr)rrhrrrremove_transitions zState.remove_transitioncCs|dur|jj}z|j|}t|dst|}|j|<Wnty/td|jj|fwzt||}Wnt yHt d|jj|fw|||fS)a Make & return a transition tuple based on `name`. This is a convenience function to simplify transition creation. Parameters: - `name`: a string, the name of the transition pattern & method. This `State` object must have a method called '`name`', and a dictionary `self.patterns` containing a key '`name`'. - `next_state`: a string, the name of the next `State` object for this transition. A value of ``None`` (or absent) implies no state change (i.e., continue with the same state). Exceptions: `TransitionPatternNotFound`, `TransitionMethodNotFound`. Nrez%s.patterns[%r]z%s.%s) r/r0patternshasattrrecompilerBTransitionPatternNotFoundgetattrAttributeErrorTransitionMethodNotFound)rrhr>rirjrrrmake_transitions(     zState.make_transitioncCsftd}g}i}|D]$}t||r||||<||q |j|||d<||dq ||fS)z Return a list of transition names and a transition mapping. Parameter `name_list`: a list, where each entry is either a transition name string, or a 1- or 2-tuple (transition name, optional next state name). rZr)rpr$rrt)r name_list stringtyperr: namestaterrrrs  zState.make_transitionscCs |dgfS)a' Called when there is no match from `StateMachine.check_line()`. Return the same values returned by transition methods: - context: unchanged; - next state name: ``None``; - empty result list. Override in subclasses to catch this event. Nr)rr8r:rrrrfs zState.no_matchcCs|gfS)z Handle beginning-of-file. Return unchanged `context`, empty result. Override in subclasses. Parameter `context`: application-defined storage. rrr8rrrr)sz State.bofcCsgS)z Handle end-of-file. Return empty result. Override in subclasses. Parameter `context`: application-defined storage. rrrrrr1sz State.eofcCs ||gfS)z A "do nothing" transition method. Return unchanged `context` & `next_state`, empty result. Useful for simple state changes (actionless transitions). rrrer8r>rrrnops z State.nopr{rx)r0r}r~rrrrrrr#rrrrrrrrfr)r1rrrrrrs.' $ ! rc@s2eZdZdZd ddZd ddZ  d dd Zd S) StateMachineWSaq `StateMachine` subclass specialized for whitespace recognition. There are three methods provided for extracting indented text blocks: - `get_indented()`: use when the indent is unknown. - `get_known_indented()`: use when the indent is known for all lines. - `get_first_known_indented()`: use when only the first line's indent is known. FTcCsr|}|j|j||\}}}|r|t|d|r3|ds3||d7}|r3|dr#||||fS)a Return a block of indented lines of text, and info. Extract an indented block where the indent is unknown for all lines. :Parameters: - `until_blank`: Stop collecting at the first blank line if true. - `strip_indent`: Strip common leading indent if true (default). :Return: - the indented block (a list of lines of text), - its indent, - its first line offset from BOF, and - whether or not it finished with a blank line. r"rrRr get_indentedr r+r6rH trim_start)r until_blank strip_indentr=indentedindent blank_finishrrrrs  zStateMachineWS.get_indentedcCsp|}|jj|j|||d\}}}|t|d|r3|ds3||d7}|r3|dr#|||fS)a Return an indented block and info. Extract an indented block where the indent is known for all lines. Starting with the current line, extract the entire text block with at least `indent` indentation (which must be whitespace, except for the first line). :Parameters: - `indent`: The number of indent columns/characters. - `until_blank`: Stop collecting at the first blank line if true. - `strip_indent`: Strip `indent` characters of indentation if true (default). :Return: - the indented block, - its first line offset from BOF, and - whether or not it finished with a blank line. ) block_indentr"rr)rrrrr=rrrrrget_known_indented6s  z!StateMachineWS.get_known_indentedcCsv|}|jj|j|||d\}}}|t|d|r5|r5|ds5||d7}|r5|dr%||||fS)a Return an indented block and info. Extract an indented block where the indent is known for the first line and unknown for all other lines. :Parameters: - `indent`: The first line's indent (# of columns/characters). - `until_blank`: Stop collecting at the first blank line if true (1). - `strip_indent`: Strip `indent` characters of indentation if true (1, default). - `strip_top`: Strip blank lines from the beginning of the block. :Return: - the indented block, - its indent, - its first line offset from BOF, and - whether or not it finished with a blank line. ) first_indentr"rr)rrrr strip_topr=rrrrrget_first_known_indentedTs  z'StateMachineWS.get_first_known_indentedN)FT)FTT)r0r}r~rrrrrrrrrs rc@sxeZdZdZdZ dZ dZ dZ e de ddZ dZ dddZ d d Z d d Zd dZddZddZdS)StateWSa State superclass specialized for whitespace (blank lines & indents). Use this class with `StateMachineWS`. The transitions 'blank' (for blank lines) and 'indent' (for indented text blocks) are added automatically, before any other transitions. The transition method `blank()` handles blank lines and `indent()` handles nested indented blocks. Indented blocks trigger a new state machine to be created by `indent()` and run. The class of the state machine to be created is in `indent_sm`, and the constructor keyword arguments are in the dictionary `indent_sm_kwargs`. The methods `known_indent()` and `firstknown_indent()` are provided for indented blocks where the indent (all lines' and first line's only, respectively) is known to the transition method, along with the attributes `known_indent_sm` and `known_indent_sm_kwargs`. Neither transition method is triggered automatically. Nz *$z +)blankrFcCs^t||||jdur|j|_|jdur|j|_|jdur"|j|_|jdur-|j|_dSdS)z Initialize a `StateSM` object; extends `State.__init__()`. Check for indent state machine attributes, set defaults if not set. N)rr indent_smrindent_sm_kwargsrknown_indent_smknown_indent_sm_kwargsrrrrrs     zStateWS.__init__cCsHt||jdur i|_|j|j||j\}}|||dS)z Add whitespace-specific transitions before those defined in subclass. Extends `State.add_initial_transitions()`. N)rrrr ws_patternsrws_initial_transitionsrrrrrrs  zStateWS.add_initial_transitionscCs||||S)z9Handle blank lines. Does nothing. Override in subclasses.)rrrrrrz StateWS.blankc CsB|j\}}}}|jdd|ji|j}|j||d} ||| fS)z Handle an indented text block. Extend or override in subclasses. Recursively run the registered state machine for indented blocks (`self.indent_sm`). r r Nr)rrrr rr@) rrer8r>rrr rsmr;rrrrs   zStateWS.indentc CF|j|\}}}|jdd|ji|j}|j||d}|||fS)a Handle a known-indent text block. Extend or override in subclasses. Recursively run the registered state machine for known-indent indented blocks (`self.known_indent_sm`). The indent is the length of the match, ``match.end()``. r rNr)rrendrr rr@ rrer8r>rr rrr;rrr known_indents  zStateWS.known_indentc Cr)a0 Handle an indented text block (first line's indent known). Extend or override in subclasses. Recursively run the registered state machine for known-indent indented blocks (`self.known_indent_sm`). The indent is the length of the match, ``match.end()``. r rNr)rrrrr rr@rrrrfirst_known_indents  zStateWS.first_known_indentr{)r0r}r~rrrrrrrrrrrrrrrrrrrrvs,  rc@seZdZdZddZdS)_SearchOverridea Mix-in class to override `StateMachine` regular expression behavior. Changes regular expression matching, from the default `re.match()` (succeeds only if the pattern matches at the start of `self.line`) to `re.search()` (succeeds if the pattern matches anywhere in `self.line`). When subclassing a `StateMachine`, list this class **first** in the inheritance list of the class definition. cCs ||jS)z Return the result of a regular expression search. Overrides `StateMachine.match()`. Parameter `pattern`: `re` compiled regular expression. )searchr )rrirrrres z_SearchOverride.matchN)r0r}r~rrerrrrrs rc@eZdZdZdS)SearchStateMachinez@`StateMachine` which uses `re.search()` instead of `re.match()`.Nr0r}r~rrrrrrrc@r)SearchStateMachineWSzB`StateMachineWS` which uses `re.search()` instead of `re.match()`.Nrrrrrrrrc@sTeZdZdZ  dRddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ ddZ ddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*ZeZd+d,Zd-d.ZdSd0d1ZdSd2d3ZdTd5d6ZdUd8d9ZdUd:d;Zdd?Z!d@dAZ"dBdCZ#dDdEZ$dFdGZ%dHdIZ&dJdKZ'dLdMZ(dNdOZ)dPdQZ*dS)VViewLista> List with extended functionality: slices of ViewList objects are child lists, linked to their parents. Changes made to a child list also affect the parent list. A child list is effectively a "view" (in the SQL sense) of the parent list. Changes to parent lists, however, do *not* affect active child lists. If a parent list is changed, any active child lists should be recreated. The start and end of the slice can be trimmed using the `trim_start()` and `trim_end()` methods, without affecting the parent list. The link between child and parent lists can be broken by calling `disconnect()` on the child list. Also, ViewList objects keep track of the source & offset of each item. This information is accessible via the `source()`, `offset()`, and `info()` methods. Ncsg|_ g|_ ||_ ||_ t|tr&|jdd|_|jdd|_n|durCt||_|r5||_nfddtt|D|_t|jt|jksQJddS)Ncsg|]}|fqSrr).0irrr Pz%ViewList.__init__.. data mismatch) dataitemsparent parent_offsetr$rlistranger6)rinitlistrrrrrrrr8s"   zViewList.__init__cC t|jSrx)strrrIrrr__str__Ss zViewList.__str__cCsd|jj|j|jfS)Nz%s(%s, items=%s))r/r0rrrIrrr__repr__VszViewList.__repr__cCs|j||kSrxr_ViewList__castrotherrrr__lt__ZzViewList.__lt__cCs|j||kSrxrrrrr__le__[rzViewList.__le__cCs|j||kSrxrrrrr__eq__\rzViewList.__eq__cCs|j||kSrxrrrrr__ne__]rzViewList.__ne__cCs|j||kSrxrrrrr__gt__^rzViewList.__gt__cCs|j||kSrxrrrrr__ge___rzViewList.__ge__cCs |j}||}||k||kSrxr)rrmineyoursrrr__cmp__as zViewList.__cmp__cCst|tr|jS|Srx)r$rrrrrr__castgs zViewList.__castcCs ||jvSrxrritemrrr __contains__m zViewList.__contains__cCrrx)r6rrIrrr__len__nrzViewList.__len__cCsZt|tr(|jdvsJd|j|j|j|j|j|j|j||jp%ddS|j|S)NNr"cannot handle slice with strider)rrr)r$slicestepr/rstartstoprrrrrr __getitem__ts   zViewList.__getitem__cCst|trU|jdvsJdt|tstd|j|j|j|j<|j|j|j|j<t |jt |jks9Jd|j rS||j |jpCd|j |jpLt ||j <dSdS||j|<|j rg||j ||j <dSdS)Nrrz(assigning non-ViewList to ViewList slicerr) r$rrrrTrrrrr6rr)rrrrrr __setitem__}s"   zViewList.__setitem__cCsz|j|=|j|=|jr|j||j=WdSWdStyU|jdus(Jd|j|j|j=|j|j|j=|jrR|j|jpAd|j|jpJt||j=YdSYdSw)Nrr) rrrrrTrrrr6rrrr __delitem__s   zViewList.__delitem__cCs0t|tr|j|j|j|j|jdStd)Nrz!adding non-ViewList to a ViewListr$rr/rrrTrrrr__add__  zViewList.__add__cCs0t|tr|j|j|j|j|jdStd)Nrz!adding ViewList to a non-ViewListrrrrr__radd__rzViewList.__radd__cCs&t|tr|j|j7_|Std)Nz!argument to += must be a ViewList)r$rrrTrrrr__iadd__s zViewList.__iadd__cCs|j|j||j|dS)Nr)r/rrrFrrr__mul__szViewList.__mul__cCs |j|9_|j|9_|Srx)rrrFrrr__imul__szViewList.__imul__cCsRt|ts td|jr|jt|j|j||j|j|j |j dS)Nz(extending a ViewList with a non-ViewList) r$rrTrr\r6rrr*rrrrrr*s zViewList.extendrcCsZ|dur ||dS|jr|jt|j|j||||j||j||fdSrx)r*rr\r6rrrtr)rrrr=rrrrts zViewList.appendcCs|dur:t|ts td|j|j||<|j|j||<|jr8t|j|t|j}|j||j|dSdS|j|||j|||f|jrgt|j|t|j}|j||j|||dSdS)Nz+inserting non-ViewList with no source given) r$rrTrrrr6r\r)rrrrr=indexrrrr\s" zViewList.insertrcCsH|jrt|j|t|j}|j||j|j||j|Srx)rr6rpoprr)rrrrrrrs   z ViewList.popr"cCsh|t|jkrtd|t|jf|dkrtd|jd|=|jd|=|jr2|j|7_dSdS)zW Remove items from the start of the list, without touching the parent. CSize of trim too large; can't trim %s items from a list of size %s.rTrim size must be >= 0.N)r6rrDrrrrFrrrrs   zViewList.trim_startcCsT|t|jkrtd|t|jf|dkrtd|j| d=|j| d=dS)zU Remove items from the end of the list, without touching the parent. rrrN)r6rrDrrFrrrtrim_ends zViewList.trim_endcCs||}||=dSrx)r)rrrrrrrys  zViewList.removecC |j|Srx)rcountrrrrr zViewList.countcCrrx)rrrrrrrrzViewList.indexcCs|j|jd|_dSrx)rreverserrrIrrrrs   zViewList.reversecGsDtt|j|jg|R}dd|D|_dd|D|_d|_dS)NcSg|]}|dqS)rrrentryrrrr rz!ViewList.sort..cSrr|rrrrrr r)sortedziprrr)rr4tmprrrsort s z ViewList.sortcCsFz|j|WSty"|t|jkr!|j|dddfYSw)z%Return source & offset for index `i`.r"rN)rrDr6rrrrrr,s  z ViewList.infocC||dS)zReturn source for index `i`.rr,rrrrrrzViewList.sourcecCr)zReturn offset for index `i`.r"rrrrrr=rzViewList.offsetcCr)z-Break link between this list and parent list.N)rrIrrr disconnect"rMzViewList.disconnectccs.t|j|jD] \}\}}|||fVqdS)z8Return iterator yielding (source, offset, value) tuples.N)r rr)rrqrr=rrrxitems&szViewList.xitemscCs|D]}td|qdS)z=Print the list in `grep` format (`source:offset:value` lines)z%s:%d:%sN)rr&)rr rrrpprint+s zViewList.pprint)NNNNN)Nr)rr|)+r0r}r~rrrrrrrrrrrrrrrrrrrrr__rmul__rr*rtr\rrrryrrrr r,rr=rrrrrrrr$sV         rc@sReZdZdZdejfddZdddZ  dd d Zdd d Z ddZ ddZ d S)r%z*A `ViewList` with string-specific methods.rcs*fdd|j||D|j||<dS)z Trim `length` characters off the beginning of each item, in-place, from index `start` to `end`. No whitespace-checking is done on the trimmed text. Does not affect slice parent. cg|]}|dqSrxrrr lengthrrr;sz(StringList.trim_left..Nr)rrrrrrr trim_left5s  zStringList.trim_leftFcCs||}t|j}||kr8|j|}|sn#|r0|ddkr0||\}}t|||||d|d7}||ks |||S)r^r r")r6rrHr,r`)rrrarlastr rr=rrrr_>s   zStringList.get_text_blockTNcCsB|}|}|dur|dur|}|dur|d7}t|j}||krs|j|} | rG| ddks8|durG| d|rG||koE|j|d } n.| } | sS|rRd} n#n|durkt| t| } |durf| }nt|| }|d7}||ksd} |||} |dur| r| jd|d| jd<|r|r| j||dud| |pd| fS)a Extract and return a StringList of indented lines of text. Collect all lines with indentation, determine the minimum indentation, remove the minimum indentation from all indented lines (unless `strip_indent` is false), and return them. All lines up to but not including the first unindented line will be returned. :Parameters: - `start`: The index of the first line to examine. - `until_blank`: Stop collecting at the first blank line if true. - `strip_indent`: Strip common leading indent if true (default). - `block_indent`: The indent of the entire block, if known. - `first_indent`: The indent of the first line, if known. :Return: - a StringList of indented lines with mininum indent removed; - the amount of the indent; - a boolean: did the indented block finish with a blank line or EOF? Nr"rr)r)r6rrHlstripminr)rrrrrrrrrr rstripped line_indentrbrrrrSsJ     zStringList.get_indentedc s|||}|tt|jD]c}t|j|}z||}Wnty5|t|j|t|7}Ynwz||}WntyR|t|j|t|7}Ynw|j||||j|<} | rrtt| t| q|rdkr|krn|Sfdd|jD|_|S)Nrcrrxrrrrrrsz+StringList.get_2D_block..) rr6rrcolumn_indicesrDrstriprr) rtopleftbottomrightrrbrcir rrr get_2D_blocks,      zStringList.get_2D_blockcCsptj}tt|jD]+}|j|}t|tr5g}|D]}||||dvr,||qd||j|<q dS)z Pad all double-width characters in self by appending `pad_char` to each. For East Asian language support. WFrZN) unicodedataeast_asian_widthrr6rr$unicodertr')rpad_charr*rr newcharrrrpad_double_widths     zStringList.pad_double_widthcCs0tt|jD]}|j||||j|<qdS)z6Replace all occurrences of substring `old` with `new`.N)rr6rreplace)roldr-rrrrr0szStringList.replacer{)rFTNN)T) r0r}r~rsysmaxsizerr_rr'r/r0rrrrr%1s  < r%c@ eZdZdS)StateMachineErrorNr0r}r~rrrrr5rr5c@r4)rCNr6rrrrrCrrCc@r4)rkNr6rrrrrkrrkc@r4)rNr6rrrrrrrc@r4)rNr6rrrrrrrc@r4)rNr6rrrrrrrc@r4)rNr6rrrrrrrc@r4)r`Nr6rrrrr`rr`c@r)r2z Raise from within a transition method to switch to another transition. Raise with one argument, the new transition name. Nrrrrrr2r2c@r)r5z Raise from within a transition method to switch to another state. Raise with one or two arguments: new state name, and an optional new transition name. Nrrrrrr5r7r5Fz[ ]cs*|r|d|}fdd|D}|S)a6 Return a list of one-line strings with tabs expanded, no newlines, and trailing whitespace stripped. Each tab is expanded with between 1 and `tab_width` spaces, so that the next character's index becomes a multiple of `tab_width` (8 by default). Parameters: - `astring`: a multi-line string. - `tab_width`: the number of columns between tab stops. - `convert_whitespace`: convert form feeds and vertical tabs to spaces? - `whitespace`: pattern object with the to-be-converted whitespace characters (default [\v\f]). rcsg|] }|qSr) expandtabsr!)rs tab_widthrrrsz string2lines..)sub splitlines)astringr<convert_whitespace whitespacelinesrr;r string2liness rCcCs>t\}}}|jr|j}|js |jj}|j||j|j|jfS)z Return exception information: - the exception's class name; - the exception object; - the name of the file containing the offending code; - the line number of the offending code; - the function name of the offending code. ) r2exc_infotb_nexttb_framef_coder0 co_filename tb_linenoco_name)rprq tracebackcoderrrros ro)&r __future__r __docformat__r2rr)docutilsrdocutils.utils.error_reportingr version_inforr+objectrrrrrrrrr% Exceptionr5rCrkrrrrr`r2r5rrCrorrrrsT e    g