| 1 |
""" |
| 2 |
Python Markdown |
| 3 |
=============== |
| 4 |
|
| 5 |
Python Markdown converts Markdown to HTML and can be used as a library or |
| 6 |
called from the command line. |
| 7 |
|
| 8 |
## Basic usage as a module: |
| 9 |
|
| 10 |
import markdown |
| 11 |
html = markdown.markdown(your_text_string) |
| 12 |
|
| 13 |
See <http://www.freewisdom.org/projects/python-markdown/> for more |
| 14 |
information and instructions on how to extend the functionality of |
| 15 |
Python Markdown. Read that before you try modifying this file. |
| 16 |
|
| 17 |
## Authors and License |
| 18 |
|
| 19 |
Started by [Manfred Stienstra](http://www.dwerg.net/). Continued and |
| 20 |
maintained by [Yuri Takhteyev](http://www.freewisdom.org), [Waylan |
| 21 |
Limberg](http://achinghead.com/) and [Artem Yunusov](http://blog.splyer.com). |
| 22 |
|
| 23 |
Contact: markdown@freewisdom.org |
| 24 |
|
| 25 |
Copyright 2007, 2008 The Python Markdown Project (v. 1.7 and later) |
| 26 |
Copyright 200? Django Software Foundation (OrderedDict implementation) |
| 27 |
Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b) |
| 28 |
Copyright 2004 Manfred Stienstra (the original version) |
| 29 |
|
| 30 |
License: BSD (see LICENSE for details). |
| 31 |
""" |
| 32 |
|
| 33 |
version = "2.1.0" |
| 34 |
version_info = (2,1,0, "Dev") |
| 35 |
|
| 36 |
import re |
| 37 |
import codecs |
| 38 |
import logging |
| 39 |
import util |
| 40 |
from preprocessors import build_preprocessors |
| 41 |
from blockprocessors import build_block_parser |
| 42 |
from treeprocessors import build_treeprocessors |
| 43 |
from inlinepatterns import build_inlinepatterns |
| 44 |
from postprocessors import build_postprocessors |
| 45 |
from extensions import Extension |
| 46 |
import html4 |
| 47 |
|
| 48 |
# For backwards compatibility in the 2.0.x series |
| 49 |
# The things defined in these modules started off in __init__.py so third |
| 50 |
# party code might need to access them here. |
| 51 |
from util import * |
| 52 |
|
| 53 |
logger = logging.getLogger('MARKDOWN') |
| 54 |
|
| 55 |
|
| 56 |
class Markdown: |
| 57 |
"""Convert Markdown to HTML.""" |
| 58 |
|
| 59 |
doc_tag = "div" # Element used to wrap document - later removed |
| 60 |
|
| 61 |
option_defaults = { |
| 62 |
'html_replacement_text' : '[HTML_REMOVED]', |
| 63 |
'tab_length' : 4, |
| 64 |
'enable_attributes' : True, |
| 65 |
'smart_emphasis' : True, |
| 66 |
'lazy_ol' : True, |
| 67 |
} |
| 68 |
|
| 69 |
output_formats = { |
| 70 |
'html' : html4.to_html_string, |
| 71 |
'html4' : html4.to_html_string, |
| 72 |
'xhtml' : util.etree.tostring, |
| 73 |
'xhtml1': util.etree.tostring, |
| 74 |
} |
| 75 |
|
| 76 |
def __init__(self, extensions=[], **kwargs): |
| 77 |
""" |
| 78 |
Creates a new Markdown instance. |
| 79 |
|
| 80 |
Keyword arguments: |
| 81 |
|
| 82 |
* extensions: A list of extensions. |
| 83 |
If they are of type string, the module mdx_name.py will be loaded. |
| 84 |
If they are a subclass of markdown.Extension, they will be used |
| 85 |
as-is. |
| 86 |
* extension-configs: Configuration settingis for extensions. |
| 87 |
* output_format: Format of output. Supported formats are: |
| 88 |
* "xhtml1": Outputs XHTML 1.x. Default. |
| 89 |
* "xhtml": Outputs latest supported version of XHTML (currently XHTML 1.1). |
| 90 |
* "html4": Outputs HTML 4 |
| 91 |
* "html": Outputs latest supported version of HTML (currently HTML 4). |
| 92 |
Note that it is suggested that the more specific formats ("xhtml1" |
| 93 |
and "html4") be used as "xhtml" or "html" may change in the future |
| 94 |
if it makes sense at that time. |
| 95 |
* safe_mode: Disallow raw html. One of "remove", "replace" or "escape". |
| 96 |
* html_replacement_text: Text used when safe_mode is set to "replace". |
| 97 |
* tab_length: Length of tabs in the source. Default: 4 |
| 98 |
* enable_attributes: Enable the conversion of attributes. Default: True |
| 99 |
* smart_emphsasis: Treat `_connected_words_` intelegently Default: True |
| 100 |
* lazy_ol: Ignore number of first item of ordered lists. Default: True |
| 101 |
|
| 102 |
""" |
| 103 |
|
| 104 |
for option, default in self.option_defaults.items(): |
| 105 |
setattr(self, option, kwargs.get(option, default)) |
| 106 |
|
| 107 |
self.safeMode = kwargs.get('safe_mode', False) |
| 108 |
self.registeredExtensions = [] |
| 109 |
self.docType = "" |
| 110 |
self.stripTopLevelTags = True |
| 111 |
|
| 112 |
self.build_parser() |
| 113 |
|
| 114 |
self.references = {} |
| 115 |
self.htmlStash = util.HtmlStash() |
| 116 |
self.registerExtensions(extensions = extensions, |
| 117 |
configs = kwargs.get('extension_configs', {})) |
| 118 |
self.set_output_format(kwargs.get('output_format', 'xhtml1')) |
| 119 |
self.reset() |
| 120 |
|
| 121 |
def build_parser(self): |
| 122 |
""" Build the parser from the various parts. """ |
| 123 |
self.preprocessors = build_preprocessors(self) |
| 124 |
self.parser = build_block_parser(self) |
| 125 |
self.inlinePatterns = build_inlinepatterns(self) |
| 126 |
self.treeprocessors = build_treeprocessors(self) |
| 127 |
self.postprocessors = build_postprocessors(self) |
| 128 |
return self |
| 129 |
|
| 130 |
def registerExtensions(self, extensions, configs): |
| 131 |
""" |
| 132 |
Register extensions with this instance of Markdown. |
| 133 |
|
| 134 |
Keyword aurguments: |
| 135 |
|
| 136 |
* extensions: A list of extensions, which can either |
| 137 |
be strings or objects. See the docstring on Markdown. |
| 138 |
* configs: A dictionary mapping module names to config options. |
| 139 |
|
| 140 |
""" |
| 141 |
for ext in extensions: |
| 142 |
if isinstance(ext, basestring): |
| 143 |
ext = self.build_extension(ext, configs.get(ext, [])) |
| 144 |
if isinstance(ext, Extension): |
| 145 |
# might raise NotImplementedError, but that's the extension author's problem |
| 146 |
ext.extendMarkdown(self, globals()) |
| 147 |
else: |
| 148 |
raise ValueError('Extension "%s.%s" must be of type: "markdown.Extension".' \ |
| 149 |
% (ext.__class__.__module__, ext.__class__.__name__)) |
| 150 |
|
| 151 |
return self |
| 152 |
|
| 153 |
def build_extension(self, ext_name, configs = []): |
| 154 |
"""Build extension by name, then return the module. |
| 155 |
|
| 156 |
The extension name may contain arguments as part of the string in the |
| 157 |
following format: "extname(key1=value1,key2=value2)" |
| 158 |
|
| 159 |
""" |
| 160 |
|
| 161 |
# Parse extensions config params (ignore the order) |
| 162 |
configs = dict(configs) |
| 163 |
pos = ext_name.find("(") # find the first "(" |
| 164 |
if pos > 0: |
| 165 |
ext_args = ext_name[pos+1:-1] |
| 166 |
ext_name = ext_name[:pos] |
| 167 |
pairs = [x.split("=") for x in ext_args.split(",")] |
| 168 |
configs.update([(x.strip(), y.strip()) for (x, y) in pairs]) |
| 169 |
|
| 170 |
# Setup the module names |
| 171 |
ext_module = 'markdown.extensions' |
| 172 |
module_name_new_style = '.'.join([ext_module, ext_name]) |
| 173 |
module_name_old_style = '_'.join(['mdx', ext_name]) |
| 174 |
|
| 175 |
# Try loading the extention first from one place, then another |
| 176 |
try: # New style (markdown.extensons.<extension>) |
| 177 |
module = __import__(module_name_new_style, {}, {}, [ext_module]) |
| 178 |
except ImportError: |
| 179 |
try: # Old style (mdx_<extension>) |
| 180 |
module = __import__(module_name_old_style) |
| 181 |
except ImportError: |
| 182 |
logger.warn("Failed loading extension '%s' from '%s' or '%s'" |
| 183 |
% (ext_name, module_name_new_style, module_name_old_style)) |
| 184 |
# Return None so we don't try to initiate none-existant extension |
| 185 |
return None |
| 186 |
|
| 187 |
# If the module is loaded successfully, we expect it to define a |
| 188 |
# function called makeExtension() |
| 189 |
try: |
| 190 |
return module.makeExtension(configs.items()) |
| 191 |
except AttributeError, e: |
| 192 |
logger.warn("Failed to initiate extension '%s': %s" % (ext_name, e)) |
| 193 |
return None |
| 194 |
|
| 195 |
def registerExtension(self, extension): |
| 196 |
""" This gets called by the extension """ |
| 197 |
self.registeredExtensions.append(extension) |
| 198 |
return self |
| 199 |
|
| 200 |
def reset(self): |
| 201 |
""" |
| 202 |
Resets all state variables so that we can start with a new text. |
| 203 |
""" |
| 204 |
self.htmlStash.reset() |
| 205 |
self.references.clear() |
| 206 |
|
| 207 |
for extension in self.registeredExtensions: |
| 208 |
if hasattr(extension, 'reset'): |
| 209 |
extension.reset() |
| 210 |
|
| 211 |
return self |
| 212 |
|
| 213 |
def set_output_format(self, format): |
| 214 |
""" Set the output format for the class instance. """ |
| 215 |
try: |
| 216 |
self.serializer = self.output_formats[format.lower()] |
| 217 |
except KeyError: |
| 218 |
raise KeyError('Invalid Output Format: "%s". Use one of %s.' \ |
| 219 |
% (format, self.output_formats.keys())) |
| 220 |
return self |
| 221 |
|
| 222 |
def convert(self, source): |
| 223 |
""" |
| 224 |
Convert markdown to serialized XHTML or HTML. |
| 225 |
|
| 226 |
Keyword arguments: |
| 227 |
|
| 228 |
* source: Source text as a Unicode string. |
| 229 |
|
| 230 |
Markdown processing takes place in five steps: |
| 231 |
|
| 232 |
1. A bunch of "preprocessors" munge the input text. |
| 233 |
2. BlockParser() parses the high-level structural elements of the |
| 234 |
pre-processed text into an ElementTree. |
| 235 |
3. A bunch of "treeprocessors" are run against the ElementTree. One |
| 236 |
such treeprocessor runs InlinePatterns against the ElementTree, |
| 237 |
detecting inline markup. |
| 238 |
4. Some post-processors are run against the text after the ElementTree |
| 239 |
has been serialized into text. |
| 240 |
5. The output is written to a string. |
| 241 |
|
| 242 |
""" |
| 243 |
|
| 244 |
# Fixup the source text |
| 245 |
if not source.strip(): |
| 246 |
return u"" # a blank unicode string |
| 247 |
|
| 248 |
try: |
| 249 |
source = unicode(source) |
| 250 |
except UnicodeDecodeError, e: |
| 251 |
# Customise error message while maintaining original trackback |
| 252 |
e.reason += '. -- Note: Markdown only accepts unicode input!' |
| 253 |
raise |
| 254 |
|
| 255 |
source = source.replace(util.STX, "").replace(util.ETX, "") |
| 256 |
source = source.replace("\r\n", "\n").replace("\r", "\n") + "\n\n" |
| 257 |
source = re.sub(r'\n\s+\n', '\n\n', source) |
| 258 |
source = source.expandtabs(self.tab_length) |
| 259 |
|
| 260 |
# Split into lines and run the line preprocessors. |
| 261 |
self.lines = source.split("\n") |
| 262 |
for prep in self.preprocessors.values(): |
| 263 |
self.lines = prep.run(self.lines) |
| 264 |
|
| 265 |
# Parse the high-level elements. |
| 266 |
root = self.parser.parseDocument(self.lines).getroot() |
| 267 |
|
| 268 |
# Run the tree-processors |
| 269 |
for treeprocessor in self.treeprocessors.values(): |
| 270 |
newRoot = treeprocessor.run(root) |
| 271 |
if newRoot: |
| 272 |
root = newRoot |
| 273 |
|
| 274 |
# Serialize _properly_. Strip top-level tags. |
| 275 |
output, length = codecs.utf_8_decode(self.serializer(root, encoding="utf-8")) |
| 276 |
if self.stripTopLevelTags: |
| 277 |
try: |
| 278 |
start = output.index('<%s>'%self.doc_tag)+len(self.doc_tag)+2 |
| 279 |
end = output.rindex('</%s>'%self.doc_tag) |
| 280 |
output = output[start:end].strip() |
| 281 |
except ValueError: |
| 282 |
if output.strip().endswith('<%s />'%self.doc_tag): |
| 283 |
# We have an empty document |
| 284 |
output = '' |
| 285 |
else: |
| 286 |
# We have a serious problem |
| 287 |
raise ValueError('Markdown failed to strip top-level tags. Document=%r' % output.strip()) |
| 288 |
|
| 289 |
# Run the text post-processors |
| 290 |
for pp in self.postprocessors.values(): |
| 291 |
output = pp.run(output) |
| 292 |
|
| 293 |
return output.strip() |
| 294 |
|
| 295 |
def convertFile(self, input=None, output=None, encoding=None): |
| 296 |
"""Converts a markdown file and returns the HTML as a unicode string. |
| 297 |
|
| 298 |
Decodes the file using the provided encoding (defaults to utf-8), |
| 299 |
passes the file content to markdown, and outputs the html to either |
| 300 |
the provided stream or the file with provided name, using the same |
| 301 |
encoding as the source file. |
| 302 |
|
| 303 |
**Note:** This is the only place that decoding and encoding of unicode |
| 304 |
takes place in Python-Markdown. (All other code is unicode-in / |
| 305 |
unicode-out.) |
| 306 |
|
| 307 |
Keyword arguments: |
| 308 |
|
| 309 |
* input: File object or path of file as string. |
| 310 |
* output: Name of output file. Writes to stdout if `None`. |
| 311 |
* encoding: Encoding of input and output files. Defaults to utf-8. |
| 312 |
|
| 313 |
""" |
| 314 |
|
| 315 |
encoding = encoding or "utf-8" |
| 316 |
|
| 317 |
# Read the source |
| 318 |
if isinstance(input, basestring): |
| 319 |
input_file = codecs.open(input, mode="r", encoding=encoding) |
| 320 |
else: |
| 321 |
input_file = input |
| 322 |
text = input_file.read() |
| 323 |
input_file.close() |
| 324 |
text = text.lstrip(u'\ufeff') # remove the byte-order mark |
| 325 |
|
| 326 |
# Convert |
| 327 |
html = self.convert(text) |
| 328 |
|
| 329 |
# Write to file or stdout |
| 330 |
if isinstance(output, (str, unicode)): |
| 331 |
output_file = codecs.open(output, "w", encoding=encoding) |
| 332 |
output_file.write(html) |
| 333 |
output_file.close() |
| 334 |
else: |
| 335 |
output.write(html.encode(encoding)) |
| 336 |
|
| 337 |
return self |
| 338 |
|
| 339 |
|
| 340 |
""" |
| 341 |
EXPORTED FUNCTIONS |
| 342 |
============================================================================= |
| 343 |
|
| 344 |
Those are the two functions we really mean to export: markdown() and |
| 345 |
markdownFromFile(). |
| 346 |
""" |
| 347 |
|
| 348 |
def markdown(text, *args, **kwargs): |
| 349 |
"""Convert a markdown string to HTML and return HTML as a unicode string. |
| 350 |
|
| 351 |
This is a shortcut function for `Markdown` class to cover the most |
| 352 |
basic use case. It initializes an instance of Markdown, loads the |
| 353 |
necessary extensions and runs the parser on the given text. |
| 354 |
|
| 355 |
Keyword arguments: |
| 356 |
|
| 357 |
* text: Markdown formatted text as Unicode or ASCII string. |
| 358 |
* Any arguments accepted by the Markdown class. |
| 359 |
|
| 360 |
Returns: An HTML document as a string. |
| 361 |
|
| 362 |
""" |
| 363 |
md = Markdown(*args, **kwargs) |
| 364 |
return md.convert(text) |
| 365 |
|
| 366 |
|
| 367 |
def markdownFromFile(input = None, |
| 368 |
output = None, |
| 369 |
extensions = [], |
| 370 |
encoding = None, |
| 371 |
*args, **kwargs): |
| 372 |
"""Read markdown code from a file and write it to a file or a stream.""" |
| 373 |
md = Markdown(extensions=extensions, *args, **kwargs) |
| 374 |
md.convertFile(input, output, encoding) |