<s> import re <EOL> from lifeflow . markdown import markdown <EOL> def smart_str ( s , encoding = '<STR_LIT:utf-8>' , errors = '<STR_LIT:strict>' ) : <EOL> """<STR_LIT>""" <EOL> if not isinstance ( s , basestring ) : <EOL> try : <EOL> return str ( s ) <EOL> except UnicodeEncodeError : <EOL> return unicode ( s ) . encode ( encoding , errors ) <EOL> elif isinstance ( s , unicode ) : <EOL> return s . encode ( encoding , errors ) <EOL> elif s and encoding != '<STR_LIT:utf-8>' : <EOL> return s . decode ( '<STR_LIT:utf-8>' , errors ) . encode ( encoding , errors ) <EOL> else : <EOL> return s <EOL> class ForeignFormatsExtension ( markdown . Extension ) : <EOL> def __name__ ( self ) : <EOL> return u"<STR_LIT>" <EOL> def extendMarkdown ( self , md , md_global ) : <EOL> preprocessor = ForeignFormatsBlockPreprocessor ( ) <EOL> preprocessor . md = md <EOL> md . textPreprocessors . insert ( <NUM_LIT:0> , preprocessor ) <EOL> FORMATTERS = { } <EOL> try : <EOL> import textile <EOL> def func ( x ) : <EOL> return textile . textile ( smart_str ( x ) , encoding = '<STR_LIT:utf-8>' , output = '<STR_LIT:utf-8>' ) <EOL> FORMATTERS [ "<STR_LIT>" ] = func <EOL> except ImportError : <EOL> pass <EOL> try : <EOL> from docutils . core import publish_parts <EOL> def func ( x ) : <EOL> return publish_parts ( source = x , writer_name = "<STR_LIT>" ) [ "<STR_LIT>" ] <EOL> FORMATTERS [ "<STR_LIT>" ] = func <EOL> except ImportError : <EOL> pass <EOL> FOREIGN_FORMAT_BLOCK_REGEX = re . compile ( r"<STR_LIT>" , re . DOTALL | re . MULTILINE ) <EOL> class ForeignFormatsBlockPreprocessor : <EOL> def run ( self , text ) : <EOL> while <NUM_LIT:1> : <EOL> m = FOREIGN_FORMAT_BLOCK_REGEX . search ( text ) <EOL> if not m : break ; <EOL> format = m . group ( '<STR_LIT>' ) . lower ( ) <EOL> txt = m . group ( '<STR_LIT>' ) <EOL> if FORMATTERS . has_key ( format ) : <EOL> func = FORMATTERS [ format ] <EOL> txt = func ( txt ) <EOL> placeholder = self . md . htmlStash . store ( txt , safe = True ) <EOL> text = '<STR_LIT>' % ( text [ : m . start ( ) ] , placeholder , text [ m . end ( ) : ] ) <EOL> return text <EOL> def makeExtension ( configs = None ) : <EOL> return ForeignFormatsExtension ( configs = configs ) </s>
