| 159a274 by Yuri Takhteyev at 2008-11-17 |
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 |
| a4229ae by Waylan Limberg at 2010-07-07 |
11 |
html = markdown.markdown(your_text_string) |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
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 |
|
| a4229ae by Waylan Limberg at 2010-07-07 |
30 |
License: BSD (see LICENSE for details). |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
31 |
""" |
|
32 |
|
| a9f85f4 by Waylan Limberg at 2010-07-14 |
33 |
version = "2.1.0" |
| d955e45 by Waylan Limberg at 2010-07-14 |
34 |
version_info = (2,1,0, "Dev") |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
35 |
|
|
36 |
import re |
|
37 |
import codecs |
| 8bc4135 by Craig de Stigter at 2011-04-18 |
38 |
import logging |
| 2eb00c8 by Toshio Kuratomi at 2010-07-06 |
39 |
import util |
| a33a044 by Waylan Limberg at 2010-07-07 |
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 |
| fb262f7 by Waylan Limberg at 2010-08-29 |
45 |
from extensions import Extension |
| 9b1de64 by Waylan Limberg at 2010-07-07 |
46 |
import html4 |
| be6891a by Waylan Limberg at 2009-01-29 |
47 |
|
| ac77988 by Toshio Kuratomi at 2010-07-06 |
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. |
| d2bb675 by Craig de Stigter at 2011-04-18 |
51 |
from util import * |
| 8bc4135 by Craig de Stigter at 2011-04-18 |
52 |
|
|
53 |
logger = logging.getLogger('MARKDOWN') |
| ac77988 by Toshio Kuratomi at 2010-07-06 |
54 |
|
| 159a274 by Yuri Takhteyev at 2008-11-17 |
55 |
|
|
56 |
class Markdown: |
|
57 |
"""Convert Markdown to HTML.""" |
|
58 |
|
| 9b1de64 by Waylan Limberg at 2010-07-07 |
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, |
| ef7b35a by Waylan Limberg at 2011-04-29 |
66 |
'lazy_ol' : True, |
| 9b1de64 by Waylan Limberg at 2010-07-07 |
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): |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
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. |
| 9b1de64 by Waylan Limberg at 2010-07-07 |
86 |
* extension-configs: Configuration settingis for extensions. |
| c89c126 by Eric Abrahamsen at 2009-01-28 |
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). |
| ee6fb73 by Lucas van Dijk at 2010-01-25 |
92 |
Note that it is suggested that the more specific formats ("xhtml1" |
| c89c126 by Eric Abrahamsen at 2009-01-28 |
93 |
and "html4") be used as "xhtml" or "html" may change in the future |
| ee6fb73 by Lucas van Dijk at 2010-01-25 |
94 |
if it makes sense at that time. |
| 9b1de64 by Waylan Limberg at 2010-07-07 |
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 |
| ef7b35a by Waylan Limberg at 2011-04-29 |
100 |
* lazy_ol: Ignore number of first item of ordered lists. Default: True |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
101 |
|
|
102 |
""" |
| ee6fb73 by Lucas van Dijk at 2010-01-25 |
103 |
|
| 9b1de64 by Waylan Limberg at 2010-07-07 |
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) |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
108 |
self.registeredExtensions = [] |
|
109 |
self.docType = "" |
|
110 |
self.stripTopLevelTags = True |
|
111 |
|
| a33a044 by Waylan Limberg at 2010-07-07 |
112 |
self.build_parser() |
| 60ef37b by Yuri Takhteyev at 2008-11-18 |
113 |
|
| 159a274 by Yuri Takhteyev at 2008-11-17 |
114 |
self.references = {} |
| 2b6754a by Waylan Limberg at 2010-07-06 |
115 |
self.htmlStash = util.HtmlStash() |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
116 |
self.registerExtensions(extensions = extensions, |
| 9b1de64 by Waylan Limberg at 2010-07-07 |
117 |
configs = kwargs.get('extension_configs', {})) |
|
118 |
self.set_output_format(kwargs.get('output_format', 'xhtml1')) |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
119 |
self.reset() |
|
120 |
|
| a33a044 by Waylan Limberg at 2010-07-07 |
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) |
| e06b6b2 by David Chambers at 2010-12-04 |
128 |
return self |
| a33a044 by Waylan Limberg at 2010-07-07 |
129 |
|
| 159a274 by Yuri Takhteyev at 2008-11-17 |
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): |
| fb262f7 by Waylan Limberg at 2010-08-29 |
143 |
ext = self.build_extension(ext, configs.get(ext, [])) |
| 5670f4c by Waylan Limberg at 2009-08-27 |
144 |
if isinstance(ext, Extension): |
| 8bc4135 by Craig de Stigter at 2011-04-18 |
145 |
# might raise NotImplementedError, but that's the extension author's problem |
|
146 |
ext.extendMarkdown(self, globals()) |
| 5670f4c by Waylan Limberg at 2009-08-27 |
147 |
else: |
| 8bc4135 by Craig de Stigter at 2011-04-18 |
148 |
raise ValueError('Extension "%s.%s" must be of type: "markdown.Extension".' \ |
| 5670f4c by Waylan Limberg at 2009-08-27 |
149 |
% (ext.__class__.__module__, ext.__class__.__name__)) |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
150 |
|
| e06b6b2 by David Chambers at 2010-12-04 |
151 |
return self |
|
152 |
|
| fb262f7 by Waylan Limberg at 2010-08-29 |
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: |
| 8bc4135 by Craig de Stigter at 2011-04-18 |
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 |
| fb262f7 by Waylan Limberg at 2010-08-29 |
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: |
| 8bc4135 by Craig de Stigter at 2011-04-18 |
192 |
logger.warn("Failed to initiate extension '%s': %s" % (ext_name, e)) |
|
193 |
return None |
| fb262f7 by Waylan Limberg at 2010-08-29 |
194 |
|
| 159a274 by Yuri Takhteyev at 2008-11-17 |
195 |
def registerExtension(self, extension): |
|
196 |
""" This gets called by the extension """ |
|
197 |
self.registeredExtensions.append(extension) |
| e06b6b2 by David Chambers at 2010-12-04 |
198 |
return self |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
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: |
| ee6fb73 by Lucas van Dijk at 2010-01-25 |
208 |
if hasattr(extension, 'reset'): |
|
209 |
extension.reset() |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
210 |
|
| e06b6b2 by David Chambers at 2010-12-04 |
211 |
return self |
|
212 |
|
| 9b1de64 by Waylan Limberg at 2010-07-07 |
213 |
def set_output_format(self, format): |
| c89c126 by Eric Abrahamsen at 2009-01-28 |
214 |
""" Set the output format for the class instance. """ |
| cdcfbac by Waylan Limberg at 2009-03-17 |
215 |
try: |
|
216 |
self.serializer = self.output_formats[format.lower()] |
|
217 |
except KeyError: |
| 8bc4135 by Craig de Stigter at 2011-04-18 |
218 |
raise KeyError('Invalid Output Format: "%s". Use one of %s.' \ |
| cdcfbac by Waylan Limberg at 2009-03-17 |
219 |
% (format, self.output_formats.keys())) |
| e06b6b2 by David Chambers at 2010-12-04 |
220 |
return self |
| c89c126 by Eric Abrahamsen at 2009-01-28 |
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 |
|
| a4229ae by Waylan Limberg at 2010-07-07 |
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 |
|
| c89c126 by Eric Abrahamsen at 2009-01-28 |
242 |
""" |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
243 |
|
|
244 |
# Fixup the source text |
| 38ff334 by Waylan Limberg at 2009-03-21 |
245 |
if not source.strip(): |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
246 |
return u"" # a blank unicode string |
| 8bc4135 by Craig de Stigter at 2011-04-18 |
247 |
|
| 8c46de4 by Waylan Limberg at 2011-04-29 |
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 |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
254 |
|
| 2eb00c8 by Toshio Kuratomi at 2010-07-06 |
255 |
source = source.replace(util.STX, "").replace(util.ETX, "") |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
256 |
source = source.replace("\r\n", "\n").replace("\r", "\n") + "\n\n" |
|
257 |
source = re.sub(r'\n\s+\n', '\n\n', source) |
| 9b1de64 by Waylan Limberg at 2010-07-07 |
258 |
source = source.expandtabs(self.tab_length) |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
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. |
| b688bf5 by Waylan Limberg at 2009-08-23 |
275 |
output, length = codecs.utf_8_decode(self.serializer(root, encoding="utf-8")) |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
276 |
if self.stripTopLevelTags: |
| 7bfdc83 by Waylan Limberg at 2009-06-05 |
277 |
try: |
| 9b1de64 by Waylan Limberg at 2010-07-07 |
278 |
start = output.index('<%s>'%self.doc_tag)+len(self.doc_tag)+2 |
|
279 |
end = output.rindex('</%s>'%self.doc_tag) |
| 7bfdc83 by Waylan Limberg at 2009-06-05 |
280 |
output = output[start:end].strip() |
|
281 |
except ValueError: |
| 9b1de64 by Waylan Limberg at 2010-07-07 |
282 |
if output.strip().endswith('<%s />'%self.doc_tag): |
| 7bfdc83 by Waylan Limberg at 2009-06-05 |
283 |
# We have an empty document |
|
284 |
output = '' |
|
285 |
else: |
|
286 |
# We have a serious problem |
| 8bc4135 by Craig de Stigter at 2011-04-18 |
287 |
raise ValueError('Markdown failed to strip top-level tags. Document=%r' % output.strip()) |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
288 |
|
|
289 |
# Run the text post-processors |
|
290 |
for pp in self.postprocessors.values(): |
| c89c126 by Eric Abrahamsen at 2009-01-28 |
291 |
output = pp.run(output) |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
292 |
|
| c89c126 by Eric Abrahamsen at 2009-01-28 |
293 |
return output.strip() |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
294 |
|
| c89c126 by Eric Abrahamsen at 2009-01-28 |
295 |
def convertFile(self, input=None, output=None, encoding=None): |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
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 |
|
| 215fa18 by Waylan Limberg at 2009-10-21 |
309 |
* input: File object or path of file as string. |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
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 |
| 215fa18 by Waylan Limberg at 2009-10-21 |
318 |
if isinstance(input, basestring): |
|
319 |
input_file = codecs.open(input, mode="r", encoding=encoding) |
|
320 |
else: |
|
321 |
input_file = input |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
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 |
| b50560e by Toshio Kuratomi at 2010-07-05 |
330 |
if isinstance(output, (str, unicode)): |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
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 |
|
| e06b6b2 by David Chambers at 2010-12-04 |
337 |
return self |
|
338 |
|
| 159a274 by Yuri Takhteyev at 2008-11-17 |
339 |
|
|
340 |
""" |
|
341 |
EXPORTED FUNCTIONS |
|
342 |
============================================================================= |
|
343 |
|
|
344 |
Those are the two functions we really mean to export: markdown() and |
|
345 |
markdownFromFile(). |
|
346 |
""" |
|
347 |
|
| 5366b69 by Waylan Limberg at 2010-08-29 |
348 |
def markdown(text, *args, **kwargs): |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
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. |
| ef7b35a by Waylan Limberg at 2011-04-29 |
358 |
* Any arguments accepted by the Markdown class. |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
359 |
|
|
360 |
Returns: An HTML document as a string. |
|
361 |
|
|
362 |
""" |
| 5366b69 by Waylan Limberg at 2010-08-29 |
363 |
md = Markdown(*args, **kwargs) |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
364 |
return md.convert(text) |
|
365 |
|
|
366 |
|
|
367 |
def markdownFromFile(input = None, |
|
368 |
output = None, |
|
369 |
extensions = [], |
|
370 |
encoding = None, |
| 5366b69 by Waylan Limberg at 2010-08-29 |
371 |
*args, **kwargs): |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
372 |
"""Read markdown code from a file and write it to a file or a stream.""" |
| 5366b69 by Waylan Limberg at 2010-08-29 |
373 |
md = Markdown(extensions=extensions, *args, **kwargs) |
| 159a274 by Yuri Takhteyev at 2008-11-17 |
374 |
md.convertFile(input, output, encoding) |
|
375 |
|
|
376 |
|
|
377 |
|