3 \2?@sdZddlmZddlmZddlmZmZddlZddlZddl Z ddl m Z ddl m Z dd lmZdd lmZdd lmZdd lmZdd lmZddlmZmZdddgZe jdZGdddeZddZ ddZ!dS)a Python Markdown =============== Python Markdown converts Markdown to HTML and can be used as a library or called from the command line. ## Basic usage as a module: import markdown html = markdown.markdown(your_text_string) See for more information and instructions on how to extend the functionality of Python Markdown. Read that before you try modifying this file. ## Authors and License Started by [Manfred Stienstra](http://www.dwerg.net/). Continued and maintained by [Yuri Takhteyev](http://www.freewisdom.org), [Waylan Limberg](http://achinghead.com/) and [Artem Yunusov](http://blog.splyer.com). Contact: markdown@freewisdom.org Copyright 2007-2013 The Python Markdown Project (v. 1.7 and later) Copyright 200? Django Software Foundation (OrderedDict implementation) Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b) Copyright 2004 Manfred Stienstra (the original version) License: BSD (see LICENSE for details). )absolute_import)unicode_literals)version version_infoN)util)build_preprocessors)build_block_parser)build_treeprocessors)build_inlinepatterns)build_postprocessors) Extension)to_html_stringto_xhtml_stringMarkdownmarkdownmarkdownFromFileZMARKDOWNc@seZdZdZdZddddddZeeeeeedZdd d d d d ddddddddddgZ ddZ ddZ ddZ gfddZ d d!Zd"d#Zd$d%Zd&d'Zd+d)d*Zd(S),rzConvert Markdown to HTML.Zdivz[HTML_REMOVED]T)Zhtml_replacement_textZ tab_lengthenable_attributesZsmart_emphasisZlazy_ol)htmlZhtml4Zhtml5Zxhtmlxhtml1Zxhtml5\`*_{}[]()>#+-.!cOsddddg}d}x:|D]2}|||kr2||||<|d7}|t|krPqWx*|jjD]\}}t|||j||qXW|jdd|_|jrd|krd|_g|_d |_d |_ |j i|_ t j |_|j|jdg|jdid |j|jdd |jd S)a Creates a new Markdown instance. Keyword arguments: * extensions: A list of extensions. If they are of type string, the module mdx_name.py will be loaded. If they are a subclass of markdown.Extension, they will be used as-is. * extension_configs: Configuration settingis for extensions. * output_format: Format of output. Supported formats are: * "xhtml1": Outputs XHTML 1.x. Default. * "xhtml5": Outputs XHTML style tags of HTML 5 * "xhtml": Outputs latest supported version of XHTML (currently XHTML 1.1). * "html4": Outputs HTML 4 * "html5": Outputs HTML style tags of HTML 5 * "html": Outputs latest supported version of HTML (currently HTML 4). Note that it is suggested that the more specific formats ("xhtml1" and "html4") be used as "xhtml" or "html" may change in the future if it makes sense at that time. * safe_mode: Disallow raw html. One of "remove", "replace" or "escape". * html_replacement_text: Text used when safe_mode is set to "replace". * tab_length: Length of tabs in the source. Default: 4 * enable_attributes: Enable the conversion of attributes. Default: True * smart_emphasis: Treat `_connected_words_` intelligently Default: True * lazy_ol: Ignore number of first item of ordered lists. Default: True extensionsZextension_configsZ safe_mode output_formatrrFrT)r'configsrN)lenoption_defaultsitemssetattrgetZsafeModerregisteredExtensionsZdocTypestripTopLevelTags build_parser referencesrZ HtmlStash htmlStashregisterExtensionsset_output_formatreset)selfargskwargsposcargoptiondefaultr@build/lib/markdown/__init__.py__init__Ns.      zMarkdown.__init__cCs6t||_t||_t||_t||_t||_ |S)z* Build the parser from the various parts. ) r preprocessorsr parserr ZinlinePatternsr treeprocessorsr postprocessors)r8r@r@rAr2s      zMarkdown.build_parsercCslxf|D]^}t|tjr*|j||j|g}t|trD|j|tq|dk rtd|j j |j j fqW|S)a* Register extensions with this instance of Markdown. Keyword arguments: * extensions: A list of extensions, which can either be strings or objects. See the docstring on Markdown. * configs: A dictionary mapping module names to config options. Nz7Extension "%s.%s" must be of type: "markdown.Extension") isinstancer string_typebuild_extensionr/r ZextendMarkdownglobals TypeError __class__ __module____name__)r8r'r*extr@r@rAr5s   zMarkdown.registerExtensionsc $Cszt|}|jd}|dkr^||dd}|d|}dd|jdD}|jdd|D|}d |krxd jd |g}yt|ii|jd dg}Wn|tk rd jd |g}y t|}WnJtk r } z,d |||f} | f| jdd| _WYdd} ~ XnXYnXy|j |j St k rt} z4| jd} d|| f} | f| jdd| _WYdd} ~ XnXdS)zBuild extension by name, then return the module. The extension name may contain arguments as part of the string in the following format: "extname(key1=value1,key2=value2)" rrrNcSsg|]}|jdqS)=)split).0xr@r@rA sz,Markdown.build_extension..,cSs g|]\}}|j|jfqSr@)strip)rRrSyr@r@rArTsr%zmarkdown.extensionsrZmdxz/Failed loading extension '%s' from '%s' or '%s'z%Failed to initiate extension '%s': %s) dictfindrQupdatejoin __import__ rpartition ImportErrorr9Z makeExtensionr-AttributeError) r8Zext_namer*r;Zext_argsZpairs module_namemoduleZmodule_name_old_styleemessager@r@rArIs:       zMarkdown.build_extensioncCs|jj||S)z# This gets called by the extension )r0append)r8 extensionr@r@rAregisterExtensions zMarkdown.registerExtensioncCs:|jj|jjx |jD]}t|dr|jqW|S)zR Resets all state variables so that we can start with a new text. r7)r4r7r3clearr0hasattr)r8rfr@r@rAr7s      zMarkdown.resetcCs|j|_y|j|j|_Wnltk r}zPt|jj}|jd|jddj|df}|f|j dd|_ WYdd}~XnX|S)z/ Set the output format for the class instance. z+Invalid Output Format: "%s". Use one of %s."z", "rN) lowerr(output_formats serializerKeyErrorlistkeyssortr\r9)r8formatrcZ valid_formatsrdr@r@rAr6s zMarkdown.set_output_formatc Csx|js dSytj|}Wn2tk rL}z|jd7_WYdd}~XnX|jd|_x |jjD]}|j |j|_qfW|j j |jj }x(|j jD]}|j |}|dk r|}qW|j|}|jrPyB|jd|jt|jd}|jd|j} ||| j}WnBtk rN|jjd|jr:d}ntd |jYnXx|jjD]} | j |}q\W|jS) a Convert markdown to serialized XHTML or HTML. Keyword arguments: * source: Source text as a Unicode string. Markdown processing takes place in five steps: 1. A bunch of "preprocessors" munge the input text. 2. BlockParser() parses the high-level structural elements of the pre-processed text into an ElementTree. 3. A bunch of "treeprocessors" are run against the ElementTree. One such treeprocessor runs InlinePatterns against the ElementTree, detecting inline markup. 4. Some post-processors are run against the text after the ElementTree has been serialized into text. 5. The output is written to a string. r)z/. -- Note: Markdown only accepts unicode input!N z<%s>zz<%s />z4Markdown failed to strip top-level tags. Document=%r)rVr text_typeUnicodeDecodeErrorreasonrQlinesrCvaluesrunrDZ parseDocumentZgetrootrErmr1indexdoc_tagr+rindex ValueErrorendswithrF) r8sourcercZpreprootZ treeprocessorZnewRootoutputstartendppr@r@rAconverts8   zMarkdown.convertNc Cs|pd}|rJt|tjr*tj|d|d}ntj||}|j}|jn tj j}t|tj sj|j |}|j d}|j |}|rt|tjrtj|d|dd}|j||jn tj|}||dd}|j|nB|j|d}ytjjj|Wn"tk rtjj|YnX|S) a?Converts a markdown file and returns the HTML as a unicode string. Decodes the file using the provided encoding (defaults to utf-8), passes the file content to markdown, and outputs the html to either the provided stream or the file with provided name, using the same encoding as the source file. The 'xmlcharrefreplace' error handler is used when encoding the output. **Note:** This is the only place that decoding and encoding of unicode takes place in Python-Markdown. (All other code is unicode-in / unicode-out.) Keyword arguments: * input: File object or path. Reads from stdin if `None`. * output: File object or path. Writes to stdout if `None`. * encoding: Encoding of input and output files. Defaults to utf-8. zutf-8r)modeencodinguwxmlcharrefreplace)rerrors)r)rGrrHcodecsopen getreaderreadclosesysstdinrudecodelstriprwrite getwriterencodestdoutbufferr`) r8inputrrZ input_filetextrZ output_filewriterr@r@rA convertFile@s8              zMarkdown.convertFile)NNN)rNrM __qualname____doc__r|r,rrrlZ ESCAPED_CHARSrBr2r5rIrgr7r6rrr@r@r@rAr5s0?  . DcOst||}|j|S)aConvert a markdown string to HTML and return HTML as a unicode string. This is a shortcut function for `Markdown` class to cover the most basic use case. It initializes an instance of Markdown, loads the necessary extensions and runs the parser on the given text. Keyword arguments: * text: Markdown formatted text as Unicode or ASCII string. * Any arguments accepted by the Markdown class. Returns: An HTML document as a string. )rr)rr9r:mdr@r@rArs cOsddddg}d}x:|D]2}|||kr2||||<|d7}|t|krPqWtf|}|j|jdd|jdd|jdddS)aRead markdown code from a file and write it to a file or a stream. This is a shortcut function which initializes an instance of Markdown, and calls the convertFile method rather than convert. Keyword arguments: * input: a file name or readable object. * output: a file name or writable object. * encoding: Encoding of input and output. * Any arguments accepted by the Markdown class. rrr'rrrN)r+rrr/)r9r:r;r<r=rr@r@rArs       )"r __future__rr __version__rrrrZloggingr)rrCrZblockprocessorsr rEr Zinlinepatternsr rFr r'r Z serializersrr__all__Z getLoggerloggerobjectrrrr@r@r@rAs*           X