aboutsummaryrefslogtreecommitdiffstats
path: root/markdown/__init__.py
diff options
context:
space:
mode:
authorWaylan Limberg <waylan.limberg@icloud.com>2014-11-20 16:07:03 -0500
committerWaylan Limberg <waylan.limberg@icloud.com>2014-11-20 16:07:03 -0500
commit8f66a94eab1389d97041944ed24afd2bf7c4389c (patch)
tree10b53664076650be951468cbbb163f3d637e5891 /markdown/__init__.py
parent0c2143819ef7de53be52f7a4d47e027ff194a9b4 (diff)
downloadmarkdown-8f66a94eab1389d97041944ed24afd2bf7c4389c.tar.gz
markdown-8f66a94eab1389d97041944ed24afd2bf7c4389c.tar.bz2
markdown-8f66a94eab1389d97041944ed24afd2bf7c4389c.zip
Flake8 cleanup (mostly whitespace).
Got all but a couple files in the tests (ran out of time today). Apparently I have been using some bad form for years (although a few things seemed to look better before the update). Anyway, conformant now.
Diffstat (limited to 'markdown/__init__.py')
-rw-r--r--markdown/__init__.py187
1 files changed, 111 insertions, 76 deletions
diff --git a/markdown/__init__.py b/markdown/__init__.py
index 3ea8e05..0c4f271 100644
--- a/markdown/__init__.py
+++ b/markdown/__init__.py
@@ -32,7 +32,7 @@ License: BSD (see LICENSE for details).
from __future__ import absolute_import
from __future__ import unicode_literals
-from .__version__ import version, version_info
+from .__version__ import version, version_info # flake8: noqa
import codecs
import sys
import logging
@@ -59,24 +59,24 @@ class Markdown(object):
doc_tag = "div" # Element used to wrap document - later removed
option_defaults = {
- 'html_replacement_text' : '[HTML_REMOVED]',
- 'tab_length' : 4,
- 'enable_attributes' : True,
- 'smart_emphasis' : True,
- 'lazy_ol' : True,
+ 'html_replacement_text': '[HTML_REMOVED]',
+ 'tab_length': 4,
+ 'enable_attributes': True,
+ 'smart_emphasis': True,
+ 'lazy_ol': True,
}
output_formats = {
- 'html' : to_html_string,
- 'html4' : to_html_string,
- 'html5' : to_html_string,
- 'xhtml' : to_xhtml_string,
+ 'html': to_html_string,
+ 'html4': to_html_string,
+ 'html5': to_html_string,
+ 'xhtml': to_xhtml_string,
'xhtml1': to_xhtml_string,
'xhtml5': to_xhtml_string,
}
ESCAPED_CHARS = ['\\', '`', '*', '_', '{', '}', '[', ']',
- '(', ')', '>', '#', '+', '-', '.', '!']
+ '(', ')', '>', '#', '+', '-', '.', '!']
def __init__(self, *args, **kwargs):
"""
@@ -92,15 +92,19 @@ class Markdown(object):
* 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).
+ * "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).
+ * "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: Deprecated! Disallow raw html. One of "remove", "replace" or "escape".
- * html_replacement_text: Deprecated! Text used when safe_mode is set to "replace".
+ * safe_mode: Deprecated! Disallow raw html. One of "remove", "replace"
+ or "escape".
+ * html_replacement_text: Deprecated! 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
@@ -113,13 +117,14 @@ class Markdown(object):
for c, arg in enumerate(args):
if pos[c] not in kwargs:
kwargs[pos[c]] = arg
- if c+1 == len(pos): #pragma: no cover
+ if c+1 == len(pos): # pragma: no cover
# ignore any additional args
break
if len(args):
- warnings.warn('Positional arguments are pending depreacted in Markdown '
- 'and will be deprecated in version 2.6. Use keyword '
- 'arguments only.', PendingDeprecationWarning)
+ warnings.warn('Positional arguments are pending depreacted in '
+ 'Markdown and will be deprecated in version 2.6. '
+ 'Use keyword arguments only.',
+ PendingDeprecationWarning)
# Loop through kwargs and assign defaults
for option, default in self.option_defaults.items():
@@ -131,16 +136,19 @@ class Markdown(object):
self.enable_attributes = False
if 'safe_mode' in kwargs:
- warnings.warn('"safe_mode" is pending deprecation in Python-Markdown '
- 'and will be deprecated in version 2.6. Use an HTML '
- 'sanitizer (like Bleach http://bleach.readthedocs.org/) '
- 'if you are parsing untrusted markdown text. See the '
- '2.5 release notes for more info', PendingDeprecationWarning)
+ warnings.warn('"safe_mode" is pending deprecation in '
+ 'Python-Markdown and will be deprecated in '
+ 'version 2.6. Use an HTML sanitizer (like '
+ 'Bleach http://bleach.readthedocs.org/) '
+ 'if you are parsing untrusted markdown text. '
+ 'See the 2.5 release notes for more info',
+ PendingDeprecationWarning)
if 'html_replacement_text' in kwargs:
- warnings.warn('The "html_replacement_text" keyword is pending deprecation '
- 'in Python-Markdown and will be deprecated in version 2.6 '
- 'along with "safe_mode".', PendingDeprecationWarning)
+ warnings.warn('The "html_replacement_text" keyword is pending '
+ 'deprecation in Python-Markdown and will be '
+ 'deprecated in version 2.6 along with "safe_mode".',
+ PendingDeprecationWarning)
self.registeredExtensions = []
self.docType = ""
@@ -180,8 +188,10 @@ class Markdown(object):
ext = self.build_extension(ext, configs.get(ext, {}))
if isinstance(ext, Extension):
ext.extendMarkdown(self, globals())
- logger.debug('Successfully loaded extension "%s.%s".'
- % (ext.__class__.__module__, ext.__class__.__name__))
+ logger.debug(
+ 'Successfully loaded extension "%s.%s".'
+ % (ext.__class__.__module__, ext.__class__.__name__)
+ )
elif ext is not None:
raise TypeError(
'Extension "%s.%s" must be of type: "markdown.Extension"'
@@ -196,63 +206,85 @@ class Markdown(object):
following format: "extname(key1=value1,key2=value2)"
"""
-
+
configs = dict(configs)
-
+
# Parse extensions config params (ignore the order)
- pos = ext_name.find("(") # find the first "("
+ pos = ext_name.find("(") # find the first "("
if pos > 0:
ext_args = ext_name[pos+1:-1]
ext_name = ext_name[:pos]
pairs = [x.split("=") for x in ext_args.split(",")]
configs.update([(x.strip(), y.strip()) for (x, y) in pairs])
- warnings.warn('Setting configs in the Named Extension string is pending deprecation. '
- 'It is recommended that you pass an instance of the extension class to '
- 'Markdown or use the "extension_configs" keyword. The current behavior '
- 'will be deprecated in version 2.6 and raise an error in version 2.7. '
- 'See the Release Notes for Python-Markdown version 2.5 for more info.',
- PendingDeprecationWarning)
+ warnings.warn('Setting configs in the Named Extension string is '
+ 'pending deprecation. It is recommended that you '
+ 'pass an instance of the extension class to '
+ 'Markdown or use the "extension_configs" keyword. '
+ 'The current behavior will be deprecated in '
+ 'version 2.6 and raise an error in version 2.7. '
+ 'See the Release Notes for Python-Markdown version '
+ '2.5 for more info.', PendingDeprecationWarning)
# Get class name (if provided): `path.to.module:ClassName`
- ext_name, class_name = ext_name.split(':', 1) if ':' in ext_name else (ext_name, '')
+ ext_name, class_name = ext_name.split(':', 1) \
+ if ':' in ext_name else (ext_name, '')
# Try loading the extension first from one place, then another
- try:
+ try:
# Assume string uses dot syntax (`path.to.some.module`)
module = importlib.import_module(ext_name)
- logger.debug('Successfuly imported extension module "%s".' % ext_name)
- # For backward compat (until deprecation) check that this is an extension
- if '.' not in ext_name and not (hasattr(module, 'extendMarkdown') or (class_name and hasattr(module, class_name))):
- # We have a name conflict (eg: extensions=['tables'] and PyTables is installed)
+ logger.debug(
+ 'Successfuly imported extension module "%s".' % ext_name
+ )
+ # For backward compat (until deprecation)
+ # check that this is an extension.
+ if ('.' not in ext_name and not (hasattr(module, 'extendMarkdown')
+ or (class_name and hasattr(module, class_name)))):
+ # We have a name conflict
+ # eg: extensions=['tables'] and PyTables is installed
raise ImportError
except ImportError:
# Preppend `markdown.extensions.` to name
module_name = '.'.join(['markdown.extensions', ext_name])
- try:
+ try:
module = importlib.import_module(module_name)
- logger.debug('Successfuly imported extension module "%s".' % module_name)
- warnings.warn('Using short names for Markdown\'s builtin extensions is pending deprecation. '
- 'Use the full path to the extension with Python\'s dot notation '
- '(eg: "%s" instead of "%s"). The current behavior will be deprecated in '
- 'version 2.6 and raise an error in version 2.7. See the Release Notes for '
- 'Python-Markdown version 2.5 for more info.' % (module_name, ext_name),
- PendingDeprecationWarning)
+ logger.debug(
+ 'Successfuly imported extension module "%s".' %
+ module_name
+ )
+ warnings.warn('Using short names for Markdown\'s builtin '
+ 'extensions is pending deprecation. Use the '
+ 'full path to the extension with Python\'s dot '
+ 'notation (eg: "%s" instead of "%s"). The '
+ 'current behavior will be deprecated in '
+ 'version 2.6 and raise an error in version '
+ '2.7. See the Release Notes for '
+ 'Python-Markdown version 2.5 for more info.' %
+ (module_name, ext_name),
+ PendingDeprecationWarning)
except ImportError:
# Preppend `mdx_` to name
module_name_old_style = '_'.join(['mdx', ext_name])
- try:
+ try:
module = importlib.import_module(module_name_old_style)
- logger.debug('Successfuly imported extension module "%s".' % module_name_old_style)
- warnings.warn('Markdown\'s behavuor of appending "mdx_" to an extension name '
- 'is pending deprecation. Use the full path to the extension with '
- 'Python\'s dot notation (eg: "%s" instead of "%s"). The '
- 'current behavior will be deprecated in version 2.6 and raise an '
- 'error in version 2.7. See the Release Notes for Python-Markdown '
- 'version 2.5 for more info.' % (module_name_old_style, ext_name),
- PendingDeprecationWarning)
+ logger.debug(
+ 'Successfuly imported extension module "%s".' %
+ module_name_old_style)
+ warnings.warn('Markdown\'s behavuor of appending "mdx_" '
+ 'to an extension name is pending '
+ 'deprecation. Use the full path to the '
+ 'extension with Python\'s dot notation '
+ '(eg: "%s" instead of "%s"). The current '
+ 'behavior will be deprecated in version '
+ '2.6 and raise an error in version 2.7. '
+ 'See the Release Notes for Python-Markdown '
+ 'version 2.5 for more info.' %
+ (module_name_old_style, ext_name),
+ PendingDeprecationWarning)
except ImportError as e:
- message = "Failed loading extension '%s' from '%s', '%s' or '%s'" \
- % (ext_name, ext_name, module_name, module_name_old_style)
+ message = "Failed loading extension '%s' from '%s', '%s' " \
+ "or '%s'" % (ext_name, ext_name, module_name,
+ module_name_old_style)
e.args = (message,) + e.args[1:]
raise
@@ -297,8 +329,8 @@ class Markdown(object):
valid_formats = list(self.output_formats.keys())
valid_formats.sort()
message = 'Invalid Output Format: "%s". Use one of %s.' \
- % (self.output_format,
- '"' + '", "'.join(valid_formats) + '"')
+ % (self.output_format,
+ '"' + '", "'.join(valid_formats) + '"')
e.args = (message,) + e.args[1:]
raise
return self
@@ -354,16 +386,18 @@ class Markdown(object):
output = self.serializer(root)
if self.stripTopLevelTags:
try:
- start = output.index('<%s>'%self.doc_tag)+len(self.doc_tag)+2
- end = output.rindex('</%s>'%self.doc_tag)
+ start = output.index(
+ '<%s>' % self.doc_tag) + len(self.doc_tag) + 2
+ end = output.rindex('</%s>' % self.doc_tag)
output = output[start:end].strip()
- except ValueError: #pragma: no cover
- if output.strip().endswith('<%s />'%self.doc_tag):
+ except ValueError: # pragma: no cover
+ if output.strip().endswith('<%s />' % self.doc_tag):
# We have an empty document
output = ''
else:
# We have a serious problem
- raise ValueError('Markdown failed to strip top-level tags. Document=%r' % output.strip())
+ raise ValueError('Markdown failed to strip top-level '
+ 'tags. Document=%r' % output.strip())
# Run the text post-processors
for pp in self.postprocessors.values():
@@ -407,7 +441,7 @@ class Markdown(object):
if not isinstance(text, util.text_type):
text = text.decode(encoding)
- text = text.lstrip('\ufeff') # remove the byte-order mark
+ text = text.lstrip('\ufeff') # remove the byte-order mark
# Convert
html = self.convert(text)
@@ -426,7 +460,7 @@ class Markdown(object):
output_file.write(html)
# Don't close here. User may want to write more.
else:
- # Encode manually and write bytes to stdout.
+ # Encode manually and write bytes to stdout.
html = html.encode(encoding, "xmlcharrefreplace")
try:
# Write bytes directly to buffer (Python 3).
@@ -446,6 +480,7 @@ Those are the two functions we really mean to export: markdown() and
markdownFromFile().
"""
+
def markdown(text, *args, **kwargs):
"""Convert a markdown string to HTML and return HTML as a unicode string.
@@ -489,12 +524,12 @@ def markdownFromFile(*args, **kwargs):
if c == len(pos):
break
if len(args):
- warnings.warn('Positional arguments are pending depreacted in Markdown '
- 'and will be deprecated in version 2.6. Use keyword '
- 'arguments only.', PendingDeprecationWarning)
+ warnings.warn('Positional arguments are pending depreacted in '
+ 'Markdown and will be deprecated in version 2.6. '
+ 'Use keyword arguments only.',
+ PendingDeprecationWarning)
md = Markdown(**kwargs)
md.convertFile(kwargs.get('input', None),
kwargs.get('output', None),
kwargs.get('encoding', None))
-