Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Used 2to3 tool for python3 compatibility. Fixes #13 #16

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion main.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def main():
parser = optparse.OptionParser()
(options, args) = parser.parse_args()
if len(args) != 2:
print 'usage: pydown mdfile directory'
print('usage: pydown mdfile directory')
else:
handle(*args)

Expand Down
48 changes: 24 additions & 24 deletions markdown/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,14 @@
import codecs
import sys
import logging
import util
from preprocessors import build_preprocessors
from blockprocessors import build_block_parser
from treeprocessors import build_treeprocessors
from inlinepatterns import build_inlinepatterns
from postprocessors import build_postprocessors
from extensions import Extension
from serializers import to_html_string, to_xhtml_string
from . import util
from .preprocessors import build_preprocessors
from .blockprocessors import build_block_parser
from .treeprocessors import build_treeprocessors
from .inlinepatterns import build_inlinepatterns
from .postprocessors import build_postprocessors
from .extensions import Extension
from .serializers import to_html_string, to_xhtml_string

__all__ = ['Markdown', 'markdown', 'markdownFromFile']

Expand Down Expand Up @@ -110,19 +110,19 @@ def __init__(self, *args, **kwargs):
pos = ['extensions', 'extension_configs', 'safe_mode', 'output_format']
c = 0
for arg in args:
if not kwargs.has_key(pos[c]):
if pos[c] not in kwargs:
kwargs[pos[c]] = arg
c += 1
if c == len(pos):
# ignore any additional args
break

# Loop through kwargs and assign defaults
for option, default in self.option_defaults.items():
for option, default in list(self.option_defaults.items()):
setattr(self, option, kwargs.get(option, default))

self.safeMode = kwargs.get('safe_mode', False)
if self.safeMode and not kwargs.has_key('enable_attributes'):
if self.safeMode and 'enable_attributes' not in kwargs:
# Disable attributes in safeMode when not explicitly set
self.enable_attributes = False

Expand Down Expand Up @@ -160,7 +160,7 @@ def registerExtensions(self, extensions, configs):

"""
for ext in extensions:
if isinstance(ext, basestring):
if isinstance(ext, str):
ext = self.build_extension(ext, configs.get(ext, []))
if isinstance(ext, Extension):
# might raise NotImplementedError, but that's the extension author's problem
Expand Down Expand Up @@ -209,8 +209,8 @@ def build_extension(self, ext_name, configs = []):
# If the module is loaded successfully, we expect it to define a
# function called makeExtension()
try:
return module.makeExtension(configs.items())
except AttributeError, e:
return module.makeExtension(list(configs.items()))
except AttributeError as e:
logger.warn("Failed to initiate extension '%s': %s" % (ext_name, e))
return None

Expand Down Expand Up @@ -238,7 +238,7 @@ def set_output_format(self, format):
self.serializer = self.output_formats[format.lower()]
except KeyError:
raise KeyError('Invalid Output Format: "%s". Use one of %s.' \
% (format, self.output_formats.keys()))
% (format, list(self.output_formats.keys())))
return self

def convert(self, source):
Expand All @@ -265,11 +265,11 @@ def convert(self, source):

# Fixup the source text
if not source.strip():
return u"" # a blank unicode string
return "" # a blank unicode string

try:
source = unicode(source)
except UnicodeDecodeError, e:
source = str(source)
except UnicodeDecodeError as e:
# Customise error message while maintaining original trackback
e.reason += '. -- Note: Markdown only accepts unicode input!'
raise
Expand All @@ -281,14 +281,14 @@ def convert(self, source):

# Split into lines and run the line preprocessors.
self.lines = source.split("\n")
for prep in self.preprocessors.values():
for prep in list(self.preprocessors.values()):
self.lines = prep.run(self.lines)

# Parse the high-level elements.
root = self.parser.parseDocument(self.lines).getroot()

# Run the tree-processors
for treeprocessor in self.treeprocessors.values():
for treeprocessor in list(self.treeprocessors.values()):
newRoot = treeprocessor.run(root)
if newRoot:
root = newRoot
Expand All @@ -309,7 +309,7 @@ def convert(self, source):
raise ValueError('Markdown failed to strip top-level tags. Document=%r' % output.strip())

# Run the text post-processors
for pp in self.postprocessors.values():
for pp in list(self.postprocessors.values()):
output = pp.run(output)

return output.strip()
Expand Down Expand Up @@ -347,10 +347,10 @@ def convertFile(self, input=None, output=None, encoding=None):
input_file.close()
else:
text = sys.stdin.read()
if not isinstance(text, unicode):
if not isinstance(text, str):
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)
Expand Down Expand Up @@ -419,7 +419,7 @@ def markdownFromFile(*args, **kwargs):
pos = ['input', 'output', 'extensions', 'encoding']
c = 0
for arg in args:
if not kwargs.has_key(pos[c]):
if pos[c] not in kwargs:
kwargs[pos[c]] = arg
c += 1
if c == len(pos):
Expand Down
6 changes: 3 additions & 3 deletions markdown/blockparser.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

import util
import odict
from . import util
from . import odict

class State(list):
""" Track the current and nested state of the parser.
Expand Down Expand Up @@ -89,7 +89,7 @@ def parseBlocks(self, parent, blocks):

"""
while blocks:
for processor in self.blockprocessors.values():
for processor in list(self.blockprocessors.values()):
if processor.test(parent, blocks[0]):
if processor.run(parent, blocks) is not False:
# run returns True or None
Expand Down
4 changes: 2 additions & 2 deletions markdown/blockprocessors.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@

import logging
import re
import util
from blockparser import BlockParser
from . import util
from .blockparser import BlockParser

logger = logging.getLogger('MARKDOWN')

Expand Down
8 changes: 4 additions & 4 deletions markdown/extensions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ def getConfig(self, key, default=''):

def getConfigs(self):
""" Return all configs settings as a dict. """
return dict([(key, self.getConfig(key)) for key in self.config.keys()])
return dict([(key, self.getConfig(key)) for key in list(self.config.keys())])

def getConfigInfo(self):
""" Return all config descriptions as a list of tuples. """
return [(key, self.config[key][1]) for key in self.config.keys()]
return [(key, self.config[key][1]) for key in list(self.config.keys())]

def setConfig(self, key, value):
""" Set a config setting for `key` with the given `value`. """
Expand All @@ -46,6 +46,6 @@ def extendMarkdown(self, md, md_globals):
* md_globals: Global variables in the markdown module namespace.

"""
raise NotImplementedError, 'Extension "%s.%s" must define an "extendMarkdown"' \
'method.' % (self.__class__.__module__, self.__class__.__name__)
raise NotImplementedError('Extension "%s.%s" must define an "extendMarkdown"' \
'method.' % (self.__class__.__module__, self.__class__.__name__))

6 changes: 3 additions & 3 deletions markdown/extensions/attr_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@ def _handle_key_value(s, t):

def _handle_word(s, t):
if t.startswith('.'):
return u'.', t[1:]
return '.', t[1:]
if t.startswith('#'):
return u'id', t[1:]
return 'id', t[1:]
return t, t

_scanner = Scanner([
Expand Down Expand Up @@ -120,7 +120,7 @@ def assign_attrs(self, elem, attrs):

class AttrListExtension(markdown.extensions.Extension):
def extendMarkdown(self, md, md_globals):
if 'headerid' in md.treeprocessors.keys():
if 'headerid' in list(md.treeprocessors.keys()):
# insert after 'headerid' treeprocessor
md.treeprocessors.add('attr_list', AttrListTreeprocessor(md), '>headerid')
else:
Expand Down
8 changes: 4 additions & 4 deletions markdown/extensions/footnotes.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,15 +119,15 @@ def makeFootnoteRefId(self, id):
def makeFootnotesDiv(self, root):
""" Return div of footnotes as et Element. """

if not self.footnotes.keys():
if not list(self.footnotes.keys()):
return None

div = etree.Element("div")
div.set('class', 'footnote')
hr = etree.SubElement(div, "hr")
ol = etree.SubElement(div, "ol")

for id in self.footnotes.keys():
for id in list(self.footnotes.keys()):
li = etree.SubElement(ol, "li")
li.set("id", self.makeFootnoteId(id))
self.parser.parseChunk(li, self.footnotes[id])
Expand Down Expand Up @@ -250,13 +250,13 @@ def __init__(self, pattern, footnotes):

def handleMatch(self, m):
id = m.group(2)
if id in self.footnotes.footnotes.keys():
if id in list(self.footnotes.footnotes.keys()):
sup = etree.Element("sup")
a = etree.SubElement(sup, "a")
sup.set('id', self.footnotes.makeFootnoteRefId(id))
a.set('href', '#' + self.footnotes.makeFootnoteId(id))
a.set('rel', 'footnote')
a.text = unicode(self.footnotes.footnotes.index(id) + 1)
a.text = str(self.footnotes.footnotes.index(id) + 1)
return sup
else:
return None
Expand Down
4 changes: 2 additions & 2 deletions markdown/extensions/headerid.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,9 +151,9 @@ def _get_meta(self):
level = int(self.config['level']) - 1
force = self._str2bool(self.config['forceid'])
if hasattr(self.md, 'Meta'):
if self.md.Meta.has_key('header_level'):
if 'header_level' in self.md.Meta:
level = int(self.md.Meta['header_level'][0]) - 1
if self.md.Meta.has_key('header_forceid'):
if 'header_forceid' in self.md.Meta:
force = self._str2bool(self.md.Meta['header_forceid'][0])
return level, force

Expand Down
2 changes: 1 addition & 1 deletion markdown/extensions/html_tidy.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def run(self, text):
# Pass text to Tidy. As Tidy does not accept unicode we need to encode
# it and decode its return value.
enc = self.markdown.tidy_options.get('char_encoding', 'utf8')
return unicode(tidy.parseString(text.encode(enc),
return str(tidy.parseString(text.encode(enc),
**self.markdown.tidy_options),
encoding=enc)

Expand Down
2 changes: 1 addition & 1 deletion markdown/extensions/toc.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def run(self, doc):
prettify = self.markdown.treeprocessors.get('prettify')
if prettify: prettify.run(div)
toc = self.markdown.serializer(div)
for pp in self.markdown.postprocessors.values():
for pp in list(self.markdown.postprocessors.values()):
toc = pp.run(toc)
self.markdown.toc = toc

Expand Down
6 changes: 3 additions & 3 deletions markdown/extensions/wikilinks.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,11 +136,11 @@ def _getMeta(self):
end_url = self.config['end_url']
html_class = self.config['html_class']
if hasattr(self.md, 'Meta'):
if self.md.Meta.has_key('wiki_base_url'):
if 'wiki_base_url' in self.md.Meta:
base_url = self.md.Meta['wiki_base_url'][0]
if self.md.Meta.has_key('wiki_end_url'):
if 'wiki_end_url' in self.md.Meta:
end_url = self.md.Meta['wiki_end_url'][0]
if self.md.Meta.has_key('wiki_html_class'):
if 'wiki_html_class' in self.md.Meta:
html_class = self.md.Meta['wiki_html_class'][0]
return base_url, end_url, html_class

Expand Down
10 changes: 5 additions & 5 deletions markdown/inlinepatterns.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,18 +41,18 @@
* finally we apply strong and emphasis
"""

import util
import odict
from . import util
from . import odict
import re
from urlparse import urlparse, urlunparse
from urllib.parse import urlparse, urlunparse
import sys
# If you see an ImportError for htmlentitydefs after using 2to3 to convert for
# use by Python3, then you are probably using the buggy version from Python 3.0.
# We recomend using the tool from Python 3.1 even if you will be running the
# code on Python 3.0. The following line should be converted by the tool to:
# `from html import entities` and later calls to `htmlentitydefs` should be
# changed to call `entities`. Python 3.1's tool does this but 3.0's does not.
import htmlentitydefs
import html.entities


def build_inlinepatterns(md_instance, **kwargs):
Expand Down Expand Up @@ -441,7 +441,7 @@ def handleMatch(self, m):

def codepoint2name(code):
"""Return entity definition by code, or the code if not defined."""
entity = htmlentitydefs.codepoint2name.get(code)
entity = html.entities.codepoint2name.get(code)
if entity:
return "%s%s;" % (util.AMP_SUBSTITUTE, entity)
else:
Expand Down
10 changes: 5 additions & 5 deletions markdown/odict.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def __init__(self, data=None):
data = {}
super(OrderedDict, self).__init__(data)
if isinstance(data, dict):
self.keyOrder = data.keys()
self.keyOrder = list(data.keys())
else:
self.keyOrder = []
for key, value in data:
Expand All @@ -25,7 +25,7 @@ def __init__(self, data=None):
def __deepcopy__(self, memo):
from copy import deepcopy
return self.__class__([(key, deepcopy(value, memo))
for key, value in self.iteritems()])
for key, value in self.items()])

def __setitem__(self, key, value):
super(OrderedDict, self).__setitem__(key, value)
Expand Down Expand Up @@ -55,7 +55,7 @@ def popitem(self):
return result

def items(self):
return zip(self.keyOrder, self.values())
return list(zip(self.keyOrder, list(self.values())))

def iteritems(self):
for key in self.keyOrder:
Expand All @@ -75,7 +75,7 @@ def itervalues(self):
yield super(OrderedDict, self).__getitem__(key)

def update(self, dict_):
for k, v in dict_.items():
for k, v in list(dict_.items()):
self.__setitem__(k, v)

def setdefault(self, key, default):
Expand Down Expand Up @@ -109,7 +109,7 @@ def __repr__(self):
Replace the normal dict.__repr__ with a version that returns the keys
in their sorted order.
"""
return '{%s}' % ', '.join(['%r: %r' % (k, v) for k, v in self.items()])
return '{%s}' % ', '.join(['%r: %r' % (k, v) for k, v in list(self.items())])

def clear(self):
super(OrderedDict, self).clear()
Expand Down
6 changes: 3 additions & 3 deletions markdown/postprocessors.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
"""

import re
import util
import odict
from . import util
from . import odict

def build_postprocessors(md_instance, **kwargs):
""" Build the default postprocessors for Markdown. """
Expand Down Expand Up @@ -95,7 +95,7 @@ class UnescapePostprocessor(Postprocessor):
RE = re.compile('%s(\d+)%s' % (util.STX, util.ETX))

def unescape(self, m):
return unichr(int(m.group(1)))
return chr(int(m.group(1)))

def run(self, text):
return self.RE.sub(self.unescape, text)
Loading