Package: discount
This Python package is actypesbinding ofDavid Loren’sDiscount, a C implementation ofJohn Gruber’sMarkdown.ContentsIntroductionUsing theMarkdownclassUsinglibmarkdownRunning the test suiteSource code and reporting bugsLicenseCreditsIntroductionMarkdown is a text-to-HTML conversion tool for web writers.  Markdown
allows you to write using an easy-to-read, easy-to-write plain text
format, then convert it to structurally valid XHTML (or HTML).ThediscountPython module contains two things of interest:libmarkdown, a submodule that provides access to the public C
functions defined by Discount.Markdown, a helper class built on top oflibmarkdown,
providing a more familiar Pythonic interfaceUsing theMarkdownclassTheMarkdownclass wraps the C functions exposed in thelibmarkdownsubmodule and handles the ctypes leg work for you.  If
you want to use the Discount functions directly, skip to the next
section aboutlibmarkdown.Let’s take a look at a simple example:import sys
import discount

mkd = discount.Markdown(sys.stdin)
mkd.write_html_content(sys.stdout)Markdowntakes one required argument,input_file_or_string,
which is either a file object or a string-like object.Note:There are limitations to what kind of file-like objects
can be passed toMarkdown.  File-like objects likeStringIOcan’t be handled at the C level in the same way as OS
file objects likesys.stdinandsys.stdout, or file
objects returned by the builtinopen()method.Markdownalso has methods for getting the output as a string,
instead of writing to a file-like object.  Let’s look at a modified
version of the first example, this time using strings:import discount

mkd = discount.Markdown('`test`')
print mkd.get_html_content()Currently,Markdowndoes not manage character encoding, since theMarkdownwraps C functions that support any character encoding
that is a superset of ASCII.  However, when working with unicode
objects in Python, you will need to pass them as bytestrings toMarkdown, and then convert them back to unicode afterwards.  Here
is an example of how you could do this:import discount

txt = u'\xeb' # a unicode character, an e with an umlaut
mkd = discount.Markdown(txt.encode('utf-8'))
out = mkd.get_html_content()
val = out.decode('utf-8')TheMarkdownclass constructor also takes optional boolean keyword
arguments that map to Discount flags compilation flags.tocGenerate table-of-contents headers (each generated <h1>, <h2>,
etc will include a id=”name” argument.)  Useget_html_toc()orwrite_html_toc()to generate the table-of-contents
itself.strictDisable relaxed emphasis and superscripts.autolinkGreedily expand links; if a url is encountered, convert it to a
hyperlink even if it isn’t surrounded with<>s.safelinkBe paranoid about how[][]is expanded into a link - if the
url isn’t a local reference,http://,https://,ftp://, ornews://, it will not be converted into a
hyperlink.ignore_headerDo not process thepandoc document header, but treat it like
regular text.ignore_linksDo not allow<aor expand[][]into a link.ignore_imagesDo not allow<imgor expand![][]into a image.ignore_tablesDon’t processPHP Markdown Extratables.ignore_smartypantsDisableSmartyPantsprocessing.ignore_embedded_htmlDisable all embedded HTML by replacing all<’s with&lt;.ignore_pseudo_protocolsDo not processpseudo-protocols.Pandoc header elements can be retrieved with the methodsget_pandoc_title(),get_pandoc_author()andget_pandoc_date().The converted HTML document parts can be retrieved as a string
with theget_html_css(),get_html_toc()andget_html_content()methods, or written to a file with thewrite_html_css(fp),write_html_toc(fp)andwrite_html_content(fp)methods, wherefpis the output file
descriptor.Discount provides two hooks for manipulating links while processing
markdown.  The first lets you rewrite urls specified by[]()markup or<link/>tags, and the second lets you add additional
HTML attributes on<a/>tags generated by Discount.  You can pass
callback functions toMarkdown’srewrite_links_funcandlink_attrs_funckeyword arguments respectively.Here is an example of a callback function that adds the domain name to
internal pages:def add_basepath(url):
    if url.startswith('/'):
        return 'http://example.com%s' % url

md = Markdown(
    '`[a](/a.html)`',
    rewrite_links_func=add_basepath
)Here is an example that opens external pages in another window/tab:def add_target_blank(url):
    if url.startswith('http://'):
        return 'target="_blank"'

md = Markdown(
    '`[a](http://example.com/a.html)`',
    link_attrs_func=add_target_blank
)Alternatively, you can attach these callbacks using decorators:md = Markdown('`[a](/a.html)`')

@md.rewrite_links
def add_basepath(url):
    # same as above
    ...

md = Markdown('`[a](http://example.com/a.html)`')

@md.link_attrs
def add_target_blank(url):
    # same as above
    ...Under some conditions, the functions inlibmarkdownmay return
integer error codes.  These errors are raised as aMarkdownErrorexceptions when using theMarkdownclass.UsinglibmarkdownIf you are familiar with using the C library and would rather use
Discount library directly,libmarkdownis what you are looking
for; it’s simply a thin wrapper around the original C implementation.libmarkdownexposes the public functions and flags documented on
theDiscount homepage.In Python you’ll need to do some extra work preparing Python objects
you want to pass tolibmarkdown’s functions.Most of these functions acceptFILE*andchar**types as their
arguments, which require some additional ctypes boilerplate.To get aFILE*from a Python file descriptor for use withlibmarkdown, use the following pattern:i = ctypes.pythonapi.PyFile_AsFile(sys.stdin)
o = ctypes.pythonapi.PyFile_AsFile(sys.stdout)
doc = libmarkdown.mkd_in(i, 0)
libmarkdown.markdown(doc, o, 0))Forlibmarkdownfunctions to which you pass achar**, use the
following pattern:cp = ctypes.c_char_p('')
ln = libmarkdown.mkd_document(doc, ctypes.byref(cp))
html_text = cp.value[:ln]It is important to initializec_char_pwith an empty string.Running the test suiteTests are available with the source distibution ofdiscountin thetests.pyfile.  The C shared object should be compiled first:python setup.py build_extThen you can run the tests:python tests.pySource code and reporting bugsYou can obtain the source code and report bugs onGitHub project page.LicenseSee theLICENSEfile in the source distribution for details.Creditsdiscountis maintained byTamas Kemenczy, and is funded byTrapeze.  TheDiscountC library is written and maintained byDavid Lorenand contributors.  See theAUTHORSfile for
details.