First and foremost, Python-Markdown is intended to be a python library moduleused by various projects to convert Markdown syntax into HTML.
The Basics¶
First and foremost, Python-Markdown is intended to be a python library module used by various projects to convert Markdown syntax into HTML. This is equivalent to executing the code of a Python module: typically, this function adds classes and constants to the module.
To use markdown as a module:
The Details¶
Python-Markdown provides two public functions (markdown.markdown
and markdown.markdownFromFile
) both of which wrap thepublic class markdown.Markdown
. If you’re processing onedocument at a time, these functions will serve your needs. However, if you needto process multiple documents, it may be advantageous to create a singleinstance of the markdown.Markdown
class and pass multiple documents throughit. If you do use a single instance though, make sure to call the reset
method appropriately (see below).
markdown.markdown(text [, **kwargs])¶
The following options are available on the markdown.markdown
function:
The source Unicode string. (required)
Important
Python-Markdown expects a Unicode string as input (some simple ASCII binary strings may work only bycoincidence) and returns output as a Unicode string. Do not pass binary strings to it! If your input isencoded, (e.g. as UTF-8), it is your responsibility to decode it. For example:
If you want to write the output to disk, you must encode it yourself:
A list of extensions.
Python-Markdown provides an API for third parties towrite extensions to the parser adding their own additions or changes to thesyntax. A few commonly used extensions are shipped with the markdownlibrary. See the extension documentation for alist of available extensions.
The list of extensions may contain instances of extensions and/or stringsof extension names.
Note
The preferred method is to pass in an instance of an extension. Stringsshould only be used when it is impossible to import the Extension Classdirectly (from the command line or in a template).
When passing in extension instances, each class instance must be a subclassof markdown.extensions.Extension
and any configuration options should bedefined when initiating the class instance rather than using theextension_configs
keyword. For example:
If an extension name is provided as a string, the string must either be theregistered entry point of any installed extension or the importable pathusing Python’s dot notation.
See the documentation specific to an extension for the string name assignedto an extension as an entry point. Simply include the defined name asa string in the list of extensions. For example, if an extension has thename myext
assigned to it and the extension is properly installed, thendo the following:
If an extension does not have a registered entry point, Python’s dotnotation may be used instead. The extension must be installed as aPython module on your PYTHONPATH. Generally, a class should be specified inthe name. The class must be at the end of the name and be separated by acolon from the module.
Therefore, if you were to import the class like this:
Then load the extension as follows:
If only one extension is defined within a module and the module includes amakeExtension
function which returns an instance of the extension, thenthe class name is not necessary. For example, in that case one could doextensions=['path.to.module']
. Check the documentation for a specificextension to determine if it supports this feature.
When loading an extension by name (as a string), you can only pass inconfiguration settings to the extension by using theextension_configs
keyword.
See Also
See the documentation of the Extension API forassistance in creating extensions.
A dictionary of configuration settings for extensions.
Any configuration settings will only be passed to extensions loaded by name(as a string). When loading extensions as class instances, pass theconfiguration settings directly to the class when initializing it.
Note
The preferred method is to pass in an instance of an extension, whichdoes not require use of the extension_configs
keyword at all.See the extensions keyword for details.
The dictionary of configuration settings must be in the following format:
When specifying the extension name, be sure to use the exact samestring as is used in the extensions keyword to load theextension. Otherwise, the configuration settings will not be applied tothe extension. In other words, you cannot use the entry point in onplace and Python dot notation in the other. While both may be valid fora given extension, they will not be recognized as being the sameextension by Markdown.
See the documentation specific to the extension you are using for help inspecifying configuration settings for that extension.
Format of output.
Supported formats are:
'xhtml'
: Outputs XHTML style tags. Default.'html5'
: Outputs HTML style tags.
The values can be in either lowercase or uppercase.
Length of tabs in the source. Default: 4
markdown.markdownFromFile (**kwargs)
¶
With a few exceptions, markdown.markdownFromFile
accepts the same options asmarkdown.markdown
. It does not accept a text
(or Unicode) string.Instead, it accepts the following required options:
The source text file.
input
may be set to one of three options:
- a string which contains a path to a readable file on the file system,
- a readable file-like object,
- or
None
(default) which will read fromstdin
.
The target which output is written to.
output
may be set to one of three options:
- a string which contains a path to a writable file on the file system,
- a writable file-like object,
- or
None
(default) which will write tostdout
.
The encoding of the source text file.
Defaults to 'utf-8'
. The same encoding will always be used for input and output.The xmlcharrefreplace
error handler is used when encoding the output.
Note
This is the only place that decoding and encoding of Unicodetakes place in Python-Markdown. If this rather naive solution does notmeet your specific needs, it is suggested that you write your own codeto handle your encoding/decoding needs.
markdown.Markdown([**kwargs])¶
The same options are available when initializing the markdown.Markdown
classas on the markdown.markdown
function, except that the class doesnot accept a source text string on initialization. Rather, the source textstring must be passed to one of two instance methods.
Warning
Instances of the markdown.Markdown
class are only thread safe withinthe thread they were created in. A single instance should not be accessedfrom multiple threads.
Markdown.convert(source)¶
The source
text must meet the same requirements as the text
argument of the markdown.markdown
function.
Python Markdown Example
You should also use this method if you want to process multiple stringswithout creating a new instance of the class for each string.
Depending on which options and/or extensions are being used, the parser mayneed its state reset between each call to convert
.
To make this easier, you can also chain calls to reset
together:
Markdown.convertFile(**kwargs)¶
The arguments of this method are identical to the arguments of the samename on the markdown.markdownFromFile
function (input
,output
, and encoding
). As with theconvert
method, this method should be used toprocess multiple files without creating a new instance of the class foreach document. State may need to be reset
between each call toconvertFile
as is the case with convert
.
Overview
PyMdown Extensions is a collection of extensions for Python Markdown. They were originally written to make writing documentation more enjoyable. They cover a wide range of solutions, and while not every extension is needed by all people, there is usually at least one useful extension for everybody.
Usage
All extensions are found under the module namespace of pymdownx
. Assuming we wanted to specify the use of the MagicLink extension, we would include it in Python Markdown like so:
Check out documentation on each extension to learn more about how to configure and use each one.
Reminder
Please read the Usage Notes for information on extension compatibility and general notes to be aware of when using these extensions.
Extensions
Arithmatex
Arithmatex is an extension that preserves LaTeX math equations (frac{sqrt x}{y^3}) during the Markdown conversion process so that they can be used with MathJax.
B64
B64 converts all local images in a document to base64 encoding and embeds them in the document.
BetterEm
BetterEm is a different approach to emphasis than Python Markdown's default. It works similar but handles certain corner cases differently.
Caret
Caret is an extension that is syntactically built around the ^
character. It adds support for inserting superscripts and adds an easy way to place in an <ins>
tag.
Critic
Critic adds handling and support of Critic Markup.
Details
Details creates collapsible elements with <details><summary>
tags.
Thanks!
EscapeAll
EscapeAll allows the escaping of any character, some with additional effects. Check it out to learn more.
Extra
Extra is just like Python Markdown's Extra package except it uses PyMdown Extensions to substitute similar extensions.
Highlight
Highlight allows you to configure the syntax highlighting of SuperFences and InlineHilite. Also passes standard Markdown indented code blocks through the syntax highlighter.
InlineHilite
InlineHilite highlights inline code: frommoduleimportfunctionasfunc
.
Python Markdown Module Tutorial
Keys
Python Markdown Tutorial
Keys makes inserting key inputs into documents as easy as pressing Ctrl+Alt+Del.
MagicLink
MagicLink linkafies URL and email links without having to wrap them in Markdown syntax. Also, shortens repository issue, pull request, and commit links automatically for popular code hosting providers. You can even use special shorthand syntax to link to issues, diffs, and even mention people
PathConverter
PathConverter converts paths to absolute or relative to a given base path.
ProgressBar
ProgressBar creates progress bars quick and easy.
SaneHeaders
SaneHeaders modifies hash headers to only be evaluated if the starting hash symbols are followed by at least one space. This is useful if you use other extensions that also use the hash symbol (like our own MagicLink extension).
SmartSymbols
SmartSymbols inserts commonly used Unicode characters via simple ASCII representations: =/=
→ ≠.
Snippets
Snippets include other Markdown or HTML snippets into the current Markdown file being parsed.
StripHTML
StripHTML can strip out HTML comments and specific tag attributes.
SuperFences
SuperFences is like Python Markdown's fences, but better. Nest fences under lists, admonitions, and other syntaxes. You can even create special custom fences for content like UML.
Tabbed
Tabbed allows for tabbed Markdown content:
More Markdown content.
Tasklist
Tasklist allows inserting lists with check boxes.
- eggs
- bread
- milk
Tilde
Tilde is syntactically built around the ~
character. It adds support for inserting subscripts and adds an easy way to place text in a <del>
tag.