<s> """<STR_LIT>""" <EOL> from markdown import Extension <EOL> from markdown . treeprocessors import Treeprocessor <EOL> from markdown . util import etree <EOL> import unicodedata as UD <EOL> class AutoTextDirectionTreeprocessor ( Treeprocessor ) : <EOL> """<STR_LIT>""" <EOL> BLOCK_LVL_ELS = { '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT:p>' , '<STR_LIT>' , '<STR_LIT>' } <EOL> def run ( self , doc ) : <EOL> for elem in doc . getiterator ( ) : <EOL> if elem . tag in AutoTextDirectionTreeprocessor . BLOCK_LVL_ELS : <EOL> if elem . text is not None : <EOL> elem . set ( '<STR_LIT>' , self . _check_true_dir ( elem . text ) ) <EOL> else : <EOL> elem . set ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> def _check_true_dir ( self , text ) : <EOL> is_rtl = False <EOL> is_ltr = False <EOL> quoted_text = False <EOL> last_inline_html_char_pos = text . rfind ( "<STR_LIT:>>" ) <EOL> if last_inline_html_char_pos > - <NUM_LIT:1> : <EOL> it_here = text [ last_inline_html_char_pos + <NUM_LIT:1> : ] <EOL> else : <EOL> it_here = text <EOL> for ch in it_here : <EOL> res = UD . bidirectional ( ch ) <EOL> if ch == '<STR_LIT:">' : <EOL> quoted_text = not quoted_text <EOL> elif not quoted_text and res in { '<STR_LIT:R>' , '<STR_LIT>' } : <EOL> is_rtl = True <EOL> elif not quoted_text and res == '<STR_LIT:L>' : <EOL> is_ltr = True <EOL> if is_rtl : <EOL> return '<STR_LIT>' <EOL> elif is_ltr : <EOL> return '<STR_LIT>' <EOL> else : <EOL> return '<STR_LIT>' <EOL> class AutoTextDirectionExtension ( Extension ) : <EOL> def extendMarkdown ( self , md , md_globals ) : <EOL> md . registerExtension ( self ) <EOL> self . processor = AutoTextDirectionTreeprocessor ( ) <EOL> self . processor . md = md <EOL> md . treeprocessors . add ( '<STR_LIT>' , self . processor , '<STR_LIT>' ) <EOL> def makeExtension ( configs = { } ) : <EOL> return AutoTextDirectionExtension ( configs = configs ) </s>
