python3-docutils: unbroken: import from upstream

All of those patches are picked from upstream.

    xbps-src check python3-docutils

works fine now!
This commit is contained in:
Doan Tran Cong Danh 2019-11-20 11:26:42 +07:00 committed by Juan RP
parent 657a5cd335
commit 6b24f153d7
27 changed files with 9276 additions and 5 deletions

View file

@ -0,0 +1,394 @@
From 41f436c476b1cb6736050a12de0c9732c800019a Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Tue, 19 Nov 2019 23:40:58 +0700
Subject: [PATCH 01/26] py3: Use new style classes
Signed-off-by: Stephen Finucane <stephen@that.guru>
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8345 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/__init__.py | 2 +-
docutils/core.py | 2 +-
docutils/nodes.py | 54 +++++++++++++++++++++--------
docutils/parsers/rst/roles.py | 4 +--
docutils/parsers/rst/states.py | 4 +--
docutils/parsers/rst/tableparser.py | 2 +-
docutils/statemachine.py | 8 ++---
docutils/transforms/__init__.py | 2 +-
docutils/utils/__init__.py | 2 +-
docutils/utils/math/latex2mathml.py | 2 +-
test/DocutilsTestSupport.py | 2 +-
test/alltests.py | 2 +-
test/test_statemachine.py | 2 +-
tools/buildhtml.py | 4 +--
tools/dev/create_unimap.py | 4 +--
tools/dev/unicode2rstsubs.py | 2 +-
16 files changed, 61 insertions(+), 37 deletions(-)
diff --git a/docutils/__init__.py b/docutils/__init__.py
index f06e810..7d6a679 100644
--- a/docutils/__init__.py
+++ b/docutils/__init__.py
@@ -92,7 +92,7 @@ class ApplicationError(StandardError): pass
class DataError(ApplicationError): pass
-class SettingsSpec:
+class SettingsSpec(object):
"""
Runtime setting specification base class.
diff --git a/docutils/core.py b/docutils/core.py
index 3dc12e8..2eebbf2 100644
--- a/docutils/core.py
+++ b/docutils/core.py
@@ -23,7 +23,7 @@ from docutils.transforms import Transformer
from docutils.utils.error_reporting import ErrorOutput, ErrorString
import docutils.readers.doctree
-class Publisher:
+class Publisher(object):
"""
A facade encapsulating the high-level logic of a Docutils system.
diff --git a/docutils/nodes.py b/docutils/nodes.py
index d830616..9573208 100644
--- a/docutils/nodes.py
+++ b/docutils/nodes.py
@@ -1112,12 +1112,12 @@ class FixedTextElement(TextElement):
# Mixins
# ========
-class Resolvable:
+class Resolvable(object):
resolved = 0
-class BackLinkable:
+class BackLinkable(object):
def add_backref(self, refid):
self['backrefs'].append(refid)
@@ -1127,39 +1127,63 @@ class BackLinkable:
# Element Categories
# ====================
-class Root: pass
+class Root(object):
+ pass
+
+
+class Titular(object):
+ pass
-class Titular: pass
-class PreBibliographic:
+class PreBibliographic(object):
"""Category of Node which may occur before Bibliographic Nodes."""
-class Bibliographic: pass
-class Decorative(PreBibliographic): pass
+class Bibliographic(object):
+ pass
+
+
+class Decorative(PreBibliographic):
+ pass
+
+
+class Structural(object):
+ pass
+
+
+class Body(object):
+ pass
-class Structural: pass
-class Body: pass
+class General(Body):
+ pass
-class General(Body): pass
class Sequential(Body):
"""List-like elements."""
+
class Admonition(Body): pass
+
class Special(Body):
"""Special internal body elements."""
+
class Invisible(PreBibliographic):
"""Internal elements that don't appear in output."""
-class Part: pass
-class Inline: pass
+class Part(object):
+ pass
+
+
+class Inline(object):
+ pass
+
-class Referential(Resolvable): pass
+class Referential(Resolvable):
+ pass
class Targetable(Resolvable):
@@ -1171,7 +1195,7 @@ class Targetable(Resolvable):
Required for MoinMoin/reST compatibility."""
-class Labeled:
+class Labeled(object):
"""Contains a `label` as its first element."""
@@ -1856,7 +1880,7 @@ node_class_names = """
"""A list of names of all concrete Node subclasses."""
-class NodeVisitor:
+class NodeVisitor(object):
"""
"Visitor" pattern [GoF95]_ abstract superclass implementation for
diff --git a/docutils/parsers/rst/roles.py b/docutils/parsers/rst/roles.py
index 918e564..aa42c80 100644
--- a/docutils/parsers/rst/roles.py
+++ b/docutils/parsers/rst/roles.py
@@ -181,7 +181,7 @@ def register_generic_role(canonical_name, node_class):
register_canonical_role(canonical_name, role)
-class GenericRole:
+class GenericRole(object):
"""
Generic interpreted text role, where the interpreted text is simply
@@ -198,7 +198,7 @@ class GenericRole:
return [self.node_class(rawtext, utils.unescape(text), **options)], []
-class CustomRole:
+class CustomRole(object):
"""
Wrapper for custom interpreted text roles.
diff --git a/docutils/parsers/rst/states.py b/docutils/parsers/rst/states.py
index d8ca9f0..2ece3b3 100644
--- a/docutils/parsers/rst/states.py
+++ b/docutils/parsers/rst/states.py
@@ -126,7 +126,7 @@ class ParserError(ApplicationError): pass
class MarkupMismatch(Exception): pass
-class Struct:
+class Struct(object):
"""Stores data attributes for dotted-attribute access."""
@@ -459,7 +459,7 @@ def build_regexp(definition, compile=True):
return regexp
-class Inliner:
+class Inliner(object):
"""
Parse inline markup; call the `parse()` method.
diff --git a/docutils/parsers/rst/tableparser.py b/docutils/parsers/rst/tableparser.py
index e19388b..45af72f 100644
--- a/docutils/parsers/rst/tableparser.py
+++ b/docutils/parsers/rst/tableparser.py
@@ -40,7 +40,7 @@ class TableMarkupError(DataError):
DataError.__init__(self, *args)
-class TableParser:
+class TableParser(object):
"""
Abstract superclass for the common parts of the syntax-specific parsers.
diff --git a/docutils/statemachine.py b/docutils/statemachine.py
index 6bb3c6b..2188982 100644
--- a/docutils/statemachine.py
+++ b/docutils/statemachine.py
@@ -114,7 +114,7 @@ from docutils import utils
from docutils.utils.error_reporting import ErrorOutput
-class StateMachine:
+class StateMachine(object):
"""
A finite state machine for text filters using regular expressions.
@@ -518,7 +518,7 @@ class StateMachine:
observer(*info)
-class State:
+class State(object):
"""
State superclass. Contains a list of transitions, and transition methods.
@@ -1034,7 +1034,7 @@ class StateWS(State):
return context, next_state, results
-class _SearchOverride:
+class _SearchOverride(object):
"""
Mix-in class to override `StateMachine` regular expression behavior.
@@ -1067,7 +1067,7 @@ class SearchStateMachineWS(_SearchOverride, StateMachineWS):
pass
-class ViewList:
+class ViewList(object):
"""
List with extended functionality: slices of ViewList objects are child
diff --git a/docutils/transforms/__init__.py b/docutils/transforms/__init__.py
index b009c5f..9271133 100644
--- a/docutils/transforms/__init__.py
+++ b/docutils/transforms/__init__.py
@@ -30,7 +30,7 @@ from docutils import languages, ApplicationError, TransformSpec
class TransformError(ApplicationError): pass
-class Transform:
+class Transform(object):
"""
Docutils transform component abstract base class.
diff --git a/docutils/utils/__init__.py b/docutils/utils/__init__.py
index be1c37e..7760f38 100644
--- a/docutils/utils/__init__.py
+++ b/docutils/utils/__init__.py
@@ -33,7 +33,7 @@ class SystemMessage(ApplicationError):
class SystemMessagePropagation(ApplicationError): pass
-class Reporter:
+class Reporter(object):
"""
Info/warning/error reporter and ``system_message`` element generator.
diff --git a/docutils/utils/math/latex2mathml.py b/docutils/utils/math/latex2mathml.py
index bcb4877..1a01bc8 100644
--- a/docutils/utils/math/latex2mathml.py
+++ b/docutils/utils/math/latex2mathml.py
@@ -155,7 +155,7 @@ negatables = {'=': u'\u2260',
r'\equiv': u'\u2262'}
# LaTeX to MathML translation stuff:
-class math:
+class math(object):
"""Base class for MathML elements."""
nchildren = 1000000
diff --git a/test/DocutilsTestSupport.py b/test/DocutilsTestSupport.py
index 54ba1c4..f7986f5 100644
--- a/test/DocutilsTestSupport.py
+++ b/test/DocutilsTestSupport.py
@@ -92,7 +92,7 @@ except:
StringList.__repr__ = StringList.__str__
-class DevNull:
+class DevNull(object):
"""Output sink."""
diff --git a/test/alltests.py b/test/alltests.py
index 4a9b50f..9373124 100755
--- a/test/alltests.py
+++ b/test/alltests.py
@@ -24,7 +24,7 @@ import DocutilsTestSupport # must be imported before docutils
import docutils
-class Tee:
+class Tee(object):
"""Write to a file and a stream (default: stdout) simultaneously."""
diff --git a/test/test_statemachine.py b/test/test_statemachine.py
index 0e41337..07c561e 100755
--- a/test/test_statemachine.py
+++ b/test/test_statemachine.py
@@ -203,7 +203,7 @@ class SMWSTests(unittest.TestCase):
self.assertEqual(self.sm.run(testtext), expected)
-class EmptyClass:
+class EmptyClass(object):
pass
diff --git a/tools/buildhtml.py b/tools/buildhtml.py
index 3333eab..aa4c759 100755
--- a/tools/buildhtml.py
+++ b/tools/buildhtml.py
@@ -107,7 +107,7 @@ class OptionParser(frontend.OptionParser):
return source, destination
-class Struct:
+class Struct(object):
"""Stores data attributes for dotted-attribute access."""
@@ -115,7 +115,7 @@ class Struct:
self.__dict__.update(keywordargs)
-class Builder:
+class Builder(object):
def __init__(self):
self.publishers = {
diff --git a/tools/dev/create_unimap.py b/tools/dev/create_unimap.py
index 0e45458..a1d92ac 100755
--- a/tools/dev/create_unimap.py
+++ b/tools/dev/create_unimap.py
@@ -28,8 +28,8 @@ def w(s):
text_map = {}
math_map = {}
-class Visitor:
-
+
+class Visitor(object):
"""Node visitor for contents of unicode.xml."""
def visit_character(self, node):
diff --git a/tools/dev/unicode2rstsubs.py b/tools/dev/unicode2rstsubs.py
index b741894..d719005 100755
--- a/tools/dev/unicode2rstsubs.py
+++ b/tools/dev/unicode2rstsubs.py
@@ -59,7 +59,7 @@ def process(infile):
grouper.write_sets()
-class CharacterEntitySetExtractor:
+class CharacterEntitySetExtractor(object):
"""
Extracts character entity information from unicode.xml file, groups it by
--
2.24.0.375.geb5ae68d41

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,719 @@
From c361270fb4ee9172a337f5e9c0b014b362fb0b71 Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Tue, 19 Nov 2019 23:49:35 +0700
Subject: [PATCH 03/26] py3: Switch to 'except foo as bar' syntax
This is the only form supported in Python 3.x.
Signed-off-by: Stephen Finucane <stephen@that.guru>
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8347 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/core.py | 4 ++--
docutils/frontend.py | 8 ++++----
docutils/io.py | 12 ++++++------
docutils/parsers/rst/directives/__init__.py | 6 +++---
docutils/parsers/rst/directives/body.py | 2 +-
docutils/parsers/rst/directives/html.py | 2 +-
docutils/parsers/rst/directives/misc.py | 20 ++++++++++----------
docutils/parsers/rst/directives/tables.py | 10 +++++-----
docutils/parsers/rst/roles.py | 4 ++--
docutils/parsers/rst/states.py | 20 ++++++++++----------
docutils/statemachine.py | 6 +++---
docutils/utils/__init__.py | 2 +-
docutils/utils/error_reporting.py | 4 ++--
docutils/writers/_html_base.py | 4 ++--
docutils/writers/docutils_xml.py | 2 +-
docutils/writers/latex2e/__init__.py | 2 +-
test/DocutilsTestSupport.py | 8 ++++----
test/package_unittest.py | 2 +-
test/test_error_reporting.py | 14 +++++++-------
test/test_language.py | 4 ++--
test/test_publisher.py | 4 ++--
test/test_utils.py | 2 +-
22 files changed, 71 insertions(+), 71 deletions(-)
diff --git a/docutils/core.py b/docutils/core.py
index 6a99020..12a0c93 100644
--- a/docutils/core.py
+++ b/docutils/core.py
@@ -219,10 +219,10 @@ class Publisher(object):
self.apply_transforms()
output = self.writer.write(self.document, self.destination)
self.writer.assemble_parts()
- except SystemExit, error:
+ except SystemExit as error:
exit = 1
exit_status = error.code
- except Exception, error:
+ except Exception as error:
if not self.settings: # exception too early to report nicely
raise
if self.settings.traceback: # Propagate exceptions?
diff --git a/docutils/frontend.py b/docutils/frontend.py
index 1aeae5c..689d904 100644
--- a/docutils/frontend.py
+++ b/docutils/frontend.py
@@ -62,7 +62,7 @@ def read_config_file(option, opt, value, parser):
"""
try:
new_settings = parser.get_config_file_settings(value)
- except ValueError, error:
+ except ValueError as error:
parser.error(error)
parser.values.update(new_settings, parser)
@@ -346,7 +346,7 @@ class Option(optparse.Option):
value = getattr(values, setting)
try:
new_value = self.validator(setting, value, parser)
- except Exception, error:
+ except Exception as error:
raise (optparse.OptionValueError(
'Error in option "%s":\n %s'
% (opt, ErrorString(error))),
@@ -605,7 +605,7 @@ class OptionParser(optparse.OptionParser, docutils.SettingsSpec):
if read_config_files and not self.defaults['_disable_config']:
try:
config_settings = self.get_standard_config_settings()
- except ValueError, error:
+ except ValueError as error:
self.error(SafeString(error))
self.set_defaults_from_dict(config_settings.__dict__)
@@ -826,7 +826,7 @@ Skipping "%s" configuration file.
new_value = option.validator(
setting, value, option_parser,
config_parser=self, config_section=section)
- except Exception, error:
+ except Exception as error:
raise (ValueError(
'Error in config file "%s", section "[%s]":\n'
' %s\n'
diff --git a/docutils/io.py b/docutils/io.py
index 3b0f93e..4466fdb 100644
--- a/docutils/io.py
+++ b/docutils/io.py
@@ -114,7 +114,7 @@ class Input(TransformSpec):
self.successful_encoding = enc
# Return decoded, removing BOMs.
return decoded.replace(u'\ufeff', u'')
- except (UnicodeError, LookupError), err:
+ except (UnicodeError, LookupError) as err:
error = err # in Python 3, the <exception instance> is
# local to the except clause
raise UnicodeError(
@@ -244,7 +244,7 @@ class FileInput(Input):
try:
self.source = open(source_path, mode, **kwargs)
- except IOError, error:
+ except IOError as error:
raise InputError(error.errno, error.strerror, source_path)
else:
self.source = sys.stdin
@@ -272,7 +272,7 @@ class FileInput(Input):
data = b'\n'.join(data.splitlines()) + b'\n'
else:
data = self.source.read()
- except (UnicodeError, LookupError), err: # (in Py3k read() decodes)
+ except (UnicodeError, LookupError) as err: # (in Py3k read() decodes)
if not self.encoding and self.source_path:
# re-read in binary mode and decode with heuristics
b_source = open(self.source_path, 'rb')
@@ -362,7 +362,7 @@ class FileOutput(Output):
kwargs = {}
try:
self.destination = open(self.destination_path, self.mode, **kwargs)
- except IOError, error:
+ except IOError as error:
raise OutputError(error.errno, error.strerror,
self.destination_path)
self.opened = True
@@ -384,7 +384,7 @@ class FileOutput(Output):
try:
self.destination.write(data)
- except TypeError, e:
+ except TypeError as e:
if sys.version_info >= (3,0) and isinstance(data, bytes):
try:
self.destination.buffer.write(data)
@@ -397,7 +397,7 @@ class FileOutput(Output):
self.destination.encoding, self.encoding))
else:
raise e
- except (UnicodeError, LookupError), err:
+ except (UnicodeError, LookupError) as err:
raise UnicodeError(
'Unable to encode output data. output-encoding is: '
'%s.\n(%s)' % (self.encoding, ErrorString(err)))
diff --git a/docutils/parsers/rst/directives/__init__.py b/docutils/parsers/rst/directives/__init__.py
index e0d09fc..8789346 100644
--- a/docutils/parsers/rst/directives/__init__.py
+++ b/docutils/parsers/rst/directives/__init__.py
@@ -86,7 +86,7 @@ def directive(directive_name, language_module, document):
canonicalname = None
try:
canonicalname = language_module.directives[normname]
- except AttributeError, error:
+ except AttributeError as error:
msg_text.append('Problem retrieving directive entry from language '
'module %r: %s.' % (language_module, error))
except KeyError:
@@ -113,7 +113,7 @@ def directive(directive_name, language_module, document):
return None, messages
try:
module = __import__(modulename, globals(), locals(), level=1)
- except ImportError, detail:
+ except ImportError as detail:
messages.append(document.reporter.error(
'Error importing directive module "%s" (directive "%s"):\n%s'
% (modulename, directive_name, detail),
@@ -309,7 +309,7 @@ def unicode_code(code):
return unichr(int(value, 16))
else: # other text
return code
- except OverflowError, detail:
+ except OverflowError as detail:
raise ValueError('code too large (%s)' % detail)
def single_char_or_unicode(argument):
diff --git a/docutils/parsers/rst/directives/body.py b/docutils/parsers/rst/directives/body.py
index b60c3ad..eef1df5 100644
--- a/docutils/parsers/rst/directives/body.py
+++ b/docutils/parsers/rst/directives/body.py
@@ -147,7 +147,7 @@ class CodeBlock(Directive):
try:
tokens = Lexer(u'\n'.join(self.content), language,
self.state.document.settings.syntax_highlight)
- except LexerError, error:
+ except LexerError as error:
raise self.warning(error)
if 'number-lines' in self.options:
diff --git a/docutils/parsers/rst/directives/html.py b/docutils/parsers/rst/directives/html.py
index 78671e8..ea36936 100644
--- a/docutils/parsers/rst/directives/html.py
+++ b/docutils/parsers/rst/directives/html.py
@@ -55,7 +55,7 @@ class MetaBody(states.SpecializedBody):
try:
attname, val = utils.extract_name_value(token)[0]
node[attname.lower()] = val
- except utils.NameValueError, detail:
+ except utils.NameValueError as detail:
line = self.state_machine.line
msg = self.reporter.error(
'Error parsing meta tag attribute "%s": %s.'
diff --git a/docutils/parsers/rst/directives/misc.py b/docutils/parsers/rst/directives/misc.py
index 7672de6..0fc3610 100644
--- a/docutils/parsers/rst/directives/misc.py
+++ b/docutils/parsers/rst/directives/misc.py
@@ -73,12 +73,12 @@ class Include(Directive):
include_file = io.FileInput(source_path=path,
encoding=encoding,
error_handler=e_handler)
- except UnicodeEncodeError, error:
+ except UnicodeEncodeError as error:
raise self.severe(u'Problems with "%s" directive path:\n'
'Cannot encode input file path "%s" '
'(wrong locale?).' %
(self.name, SafeString(path)))
- except IOError, error:
+ except IOError as error:
raise self.severe(u'Problems with "%s" directive path:\n%s.' %
(self.name, ErrorString(error)))
startline = self.options.get('start-line', None)
@@ -89,7 +89,7 @@ class Include(Directive):
rawtext = ''.join(lines[startline:endline])
else:
rawtext = include_file.read()
- except UnicodeError, error:
+ except UnicodeError as error:
raise self.severe(u'Problem with "%s" directive:\n%s' %
(self.name, ErrorString(error)))
# start-after/end-before: no restrictions on newlines in match-text,
@@ -213,12 +213,12 @@ class Raw(Directive):
# TODO: currently, raw input files are recorded as
# dependencies even if not used for the chosen output format.
self.state.document.settings.record_dependencies.add(path)
- except IOError, error:
+ except IOError as error:
raise self.severe(u'Problems with "%s" directive path:\n%s.'
% (self.name, ErrorString(error)))
try:
text = raw_file.read()
- except UnicodeError, error:
+ except UnicodeError as error:
raise self.severe(u'Problem with "%s" directive:\n%s'
% (self.name, ErrorString(error)))
attributes['source'] = path
@@ -230,7 +230,7 @@ class Raw(Directive):
import urllib2
try:
raw_text = urllib2.urlopen(source).read()
- except (urllib2.URLError, IOError, OSError), error:
+ except (urllib2.URLError, IOError, OSError) as error:
raise self.severe(u'Problems with "%s" directive URL "%s":\n%s.'
% (self.name, self.options['url'], ErrorString(error)))
raw_file = io.StringInput(source=raw_text, source_path=source,
@@ -238,7 +238,7 @@ class Raw(Directive):
error_handler=e_handler)
try:
text = raw_file.read()
- except UnicodeError, error:
+ except UnicodeError as error:
raise self.severe(u'Problem with "%s" directive:\n%s'
% (self.name, ErrorString(error)))
attributes['source'] = source
@@ -320,7 +320,7 @@ class Unicode(Directive):
for code in codes:
try:
decoded = directives.unicode_code(code)
- except ValueError, error:
+ except ValueError as error:
raise self.error(u'Invalid character code: %s\n%s'
% (code, ErrorString(error)))
element += nodes.Text(utils.unescape(decoded), decoded)
@@ -406,7 +406,7 @@ class Role(Directive):
self.state.parse_directive_block(
self.content[1:], self.content_offset, converted_role,
option_presets={}))
- except states.MarkupError, detail:
+ except states.MarkupError as detail:
error = self.state_machine.reporter.error(
'Error in "%s" directive:\n%s.' % (self.name, detail),
nodes.literal_block(self.block_text, self.block_text),
@@ -415,7 +415,7 @@ class Role(Directive):
if 'class' not in options:
try:
options['class'] = directives.class_option(new_role_name)
- except ValueError, detail:
+ except ValueError as detail:
error = self.state_machine.reporter.error(
u'Invalid argument for "%s" directive:\n%s.'
% (self.name, SafeString(detail)), nodes.literal_block(
diff --git a/docutils/parsers/rst/directives/tables.py b/docutils/parsers/rst/directives/tables.py
index 83b7b53..b0a4eac 100644
--- a/docutils/parsers/rst/directives/tables.py
+++ b/docutils/parsers/rst/directives/tables.py
@@ -259,9 +259,9 @@ class CSVTable(Table):
col_widths = self.get_column_widths(max_cols)
self.extend_short_rows_with_empty_cells(max_cols,
(table_head, table_body))
- except SystemMessagePropagation, detail:
+ except SystemMessagePropagation as detail:
return [detail.args[0]]
- except csv.Error, detail:
+ except csv.Error as detail:
message = str(detail)
if sys.version_info < (3,) and '1-character string' in message:
message += '\nwith Python 2.x this must be an ASCII character.'
@@ -320,7 +320,7 @@ class CSVTable(Table):
encoding=encoding,
error_handler=error_handler)
csv_data = csv_file.read().splitlines()
- except IOError, error:
+ except IOError as error:
severe = self.state_machine.reporter.severe(
u'Problems with "%s" directive path:\n%s.'
% (self.name, SafeString(error)),
@@ -336,7 +336,7 @@ class CSVTable(Table):
source = self.options['url']
try:
csv_text = urllib2.urlopen(source).read()
- except (urllib2.URLError, IOError, OSError, ValueError), error:
+ except (urllib2.URLError, IOError, OSError, ValueError) as error:
severe = self.state_machine.reporter.severe(
'Problems with "%s" directive URL "%s":\n%s.'
% (self.name, self.options['url'], SafeString(error)),
@@ -424,7 +424,7 @@ class ListTable(Table):
header_rows = self.options.get('header-rows', 0)
stub_columns = self.options.get('stub-columns', 0)
self.check_table_dimensions(table_data, header_rows, stub_columns)
- except SystemMessagePropagation, detail:
+ except SystemMessagePropagation as detail:
return [detail.args[0]]
table_node = self.build_table_from_list(table_data, col_widths,
header_rows, stub_columns)
diff --git a/docutils/parsers/rst/roles.py b/docutils/parsers/rst/roles.py
index bf786b7..49b61dc 100644
--- a/docutils/parsers/rst/roles.py
+++ b/docutils/parsers/rst/roles.py
@@ -109,7 +109,7 @@ def role(role_name, language_module, lineno, reporter):
canonicalname = None
try:
canonicalname = language_module.roles[normname]
- except AttributeError, error:
+ except AttributeError as error:
msg_text.append('Problem retrieving role entry from language '
'module %r: %s.' % (language_module, error))
except KeyError:
@@ -333,7 +333,7 @@ def code_role(role, rawtext, text, lineno, inliner, options={}, content=[]):
try:
tokens = Lexer(utils.unescape(text, True), language,
inliner.document.settings.syntax_highlight)
- except LexerError, error:
+ except LexerError as error:
msg = inliner.reporter.warning(error)
prb = inliner.problematic(rawtext, rawtext, msg)
return [prb], [msg]
diff --git a/docutils/parsers/rst/states.py b/docutils/parsers/rst/states.py
index a2970c8..c9b4fa3 100644
--- a/docutils/parsers/rst/states.py
+++ b/docutils/parsers/rst/states.py
@@ -1497,7 +1497,7 @@ class Body(RSTState):
(optionlist.source, optionlist.line) = self.state_machine.get_source_and_line()
try:
listitem, blank_finish = self.option_list_item(match)
- except MarkupError, error:
+ except MarkupError as error:
# This shouldn't happen; pattern won't match.
msg = self.reporter.error(u'Invalid option list marker: %s' %
error)
@@ -1686,7 +1686,7 @@ class Body(RSTState):
+ 1)
table = self.build_table(tabledata, tableline)
nodelist = [table] + messages
- except tableparser.TableMarkupError, err:
+ except tableparser.TableMarkupError as err:
nodelist = self.malformed_table(block, ' '.join(err.args),
offset=err.offset) + messages
else:
@@ -1698,7 +1698,7 @@ class Body(RSTState):
blank_finish = 1
try:
block = self.state_machine.get_text_block(flush_left=True)
- except statemachine.UnexpectedIndentationError, err:
+ except statemachine.UnexpectedIndentationError as err:
block, src, srcline = err.args
messages.append(self.reporter.error('Unexpected indentation.',
source=src, line=srcline))
@@ -2135,7 +2135,7 @@ class Body(RSTState):
arguments, options, content, content_offset = (
self.parse_directive_block(indented, line_offset,
directive, option_presets))
- except MarkupError, detail:
+ except MarkupError as detail:
error = self.reporter.error(
'Error in "%s" directive:\n%s.' % (type_name,
' '.join(detail.args)),
@@ -2146,7 +2146,7 @@ class Body(RSTState):
content_offset, block_text, self, self.state_machine)
try:
result = directive_instance.run()
- except docutils.parsers.rst.DirectiveError, error:
+ except docutils.parsers.rst.DirectiveError as error:
msg_node = self.reporter.system_message(error.level, error.msg,
line=lineno)
msg_node += nodes.literal_block(block_text, block_text)
@@ -2263,11 +2263,11 @@ class Body(RSTState):
return 0, 'invalid option block'
try:
options = utils.extract_extension_options(node, option_spec)
- except KeyError, detail:
+ except KeyError as detail:
return 0, ('unknown option: "%s"' % detail.args[0])
- except (ValueError, TypeError), detail:
+ except (ValueError, TypeError) as detail:
return 0, ('invalid option value: %s' % ' '.join(detail.args))
- except utils.ExtensionOptionError, detail:
+ except utils.ExtensionOptionError as detail:
return 0, ('invalid option data: %s' % ' '.join(detail.args))
if blank_finish:
return 1, options
@@ -2354,7 +2354,7 @@ class Body(RSTState):
if expmatch:
try:
return method(self, expmatch)
- except MarkupError, error:
+ except MarkupError as error:
lineno = self.state_machine.abs_line_number()
message = ' '.join(error.args)
errors.append(self.reporter.warning(message, line=lineno))
@@ -2777,7 +2777,7 @@ class Text(RSTState):
msg = None
try:
block = self.state_machine.get_text_block(flush_left=True)
- except statemachine.UnexpectedIndentationError, err:
+ except statemachine.UnexpectedIndentationError as err:
block, src, srcline = err.args
msg = self.reporter.error('Unexpected indentation.',
source=src, line=srcline)
diff --git a/docutils/statemachine.py b/docutils/statemachine.py
index 6714a04..6a2322c 100644
--- a/docutils/statemachine.py
+++ b/docutils/statemachine.py
@@ -248,7 +248,7 @@ class StateMachine(object):
break
else:
results.extend(result)
- except TransitionCorrection, exception:
+ except TransitionCorrection as exception:
self.previous_line() # back up for another try
transitions = (exception.args[0],)
if self.debug:
@@ -257,7 +257,7 @@ class StateMachine(object):
'state "%s", transition %s.'
% (state.__class__.__name__, transitions[0])), file=self._stderr)
continue
- except StateCorrection, exception:
+ except StateCorrection as exception:
self.previous_line() # back up for another try
next_state = exception.args[0]
if len(exception.args) == 1:
@@ -413,7 +413,7 @@ class StateMachine(object):
flush_left)
self.next_line(len(block) - 1)
return block
- except UnexpectedIndentationError, err:
+ except UnexpectedIndentationError as err:
block = err.args[0]
self.next_line(len(block) - 1) # advance to last line of block
raise
diff --git a/docutils/utils/__init__.py b/docutils/utils/__init__.py
index 692335a..c71d508 100644
--- a/docutils/utils/__init__.py
+++ b/docutils/utils/__init__.py
@@ -326,7 +326,7 @@ def assemble_option_dict(option_list, options_spec):
raise DuplicateOptionError('duplicate option "%s"' % name)
try:
options[name] = convertor(value)
- except (ValueError, TypeError), detail:
+ except (ValueError, TypeError) as detail:
raise detail.__class__('(option: "%s"; value: %r)\n%s'
% (name, value, ' '.join(detail.args)))
return options
diff --git a/docutils/utils/error_reporting.py b/docutils/utils/error_reporting.py
index 02e62eb..8ea7108 100644
--- a/docutils/utils/error_reporting.py
+++ b/docutils/utils/error_reporting.py
@@ -49,7 +49,7 @@ else:
# locale.getpreferredencoding([do_setlocale=True|False])
# has side-effects | might return a wrong guess.
# (cf. Update 1 in http://stackoverflow.com/questions/4082645/using-python-2-xs-locale-module-to-format-numbers-and-currency)
- except ValueError, error: # OS X may set UTF-8 without language code
+ except ValueError as error: # OS X may set UTF-8 without language code
# see http://bugs.python.org/issue18378
# and https://sourceforge.net/p/docutils/bugs/298/
if "unknown locale: UTF-8" in error.args:
@@ -113,7 +113,7 @@ class SafeString(object):
if isinstance(self.data, EnvironmentError):
u = u.replace(": u'", ": '") # normalize filename quoting
return u
- except UnicodeError, error: # catch ..Encode.. and ..Decode.. errors
+ except UnicodeError as error: # catch ..Encode.. and ..Decode.. errors
if isinstance(self.data, EnvironmentError):
return u"[Errno %s] %s: '%s'" % (self.data.errno,
SafeString(self.data.strerror, self.encoding,
diff --git a/docutils/writers/_html_base.py b/docutils/writers/_html_base.py
index fa27911..23efeea 100644
--- a/docutils/writers/_html_base.py
+++ b/docutils/writers/_html_base.py
@@ -302,7 +302,7 @@ class HTMLTranslator(nodes.NodeVisitor):
content = io.FileInput(source_path=path,
encoding='utf-8').read()
self.settings.record_dependencies.add(path)
- except IOError, err:
+ except IOError as err:
msg = u"Cannot embed stylesheet '%s': %s." % (
path, SafeString(err.strerror))
self.document.reporter.error(msg)
@@ -1159,7 +1159,7 @@ class HTMLTranslator(nodes.NodeVisitor):
'with math-output "MathML"')
except OSError:
raise OSError('is "latexmlmath" in your PATH?')
- except SyntaxError, err:
+ except SyntaxError as err:
err_node = self.document.reporter.error(err, base_node=node)
self.visit_system_message(err_node)
self.body.append(self.starttag(node, 'p'))
diff --git a/docutils/writers/docutils_xml.py b/docutils/writers/docutils_xml.py
index 148041a..e870ee1 100644
--- a/docutils/writers/docutils_xml.py
+++ b/docutils/writers/docutils_xml.py
@@ -186,7 +186,7 @@ class XMLTranslator(nodes.GenericNodeVisitor):
xml_string = xml_string.encode('utf8')
try:
self.xmlparser.parse(StringIO(xml_string))
- except xml.sax._exceptions.SAXParseException, error:
+ except xml.sax._exceptions.SAXParseException as error:
col_num = self.the_handle.locator.getColumnNumber()
line_num = self.the_handle.locator.getLineNumber()
srcline = node.line
diff --git a/docutils/writers/latex2e/__init__.py b/docutils/writers/latex2e/__init__.py
index 5c33d0a..5eaa7f0 100644
--- a/docutils/writers/latex2e/__init__.py
+++ b/docutils/writers/latex2e/__init__.py
@@ -1416,7 +1416,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
content = io.FileInput(source_path=path,
encoding='utf-8').read()
self.settings.record_dependencies.add(path)
- except IOError, err:
+ except IOError as err:
msg = u"Cannot embed stylesheet '%s':\n %s." % (
path, SafeString(err.strerror))
self.document.reporter.error(msg)
diff --git a/test/DocutilsTestSupport.py b/test/DocutilsTestSupport.py
index 25196ec..e77447a 100644
--- a/test/DocutilsTestSupport.py
+++ b/test/DocutilsTestSupport.py
@@ -230,7 +230,7 @@ class CustomTestCase(StandardTestCase):
output = '\n'.join(output.splitlines())
try:
self.assertEqual(output, expected)
- except AssertionError, error:
+ except AssertionError as error:
print('\n%s\ninput:' % (self,), file=sys.stderr)
print(input, file=sys.stderr)
try:
@@ -543,7 +543,7 @@ class GridTableParserTestCase(CustomTestCase):
self.parser.find_head_body_sep()
self.parser.parse_table()
output = self.parser.cells
- except Exception, details:
+ except Exception as details:
output = '%s: %s' % (details.__class__.__name__, details)
self.compare_output(self.input, pformat(output) + '\n',
pformat(self.expected) + '\n')
@@ -552,7 +552,7 @@ class GridTableParserTestCase(CustomTestCase):
try:
output = self.parser.parse(StringList(string2lines(self.input),
'test data'))
- except Exception, details:
+ except Exception as details:
output = '%s: %s' % (details.__class__.__name__, details)
self.compare_output(self.input, pformat(output) + '\n',
pformat(self.expected) + '\n')
@@ -865,7 +865,7 @@ def exception_data(func, *args, **kwds):
"""
try:
func(*args, **kwds)
- except Exception, detail:
+ except Exception as detail:
return (detail, detail.args,
'%s: %s' % (detail.__class__.__name__, detail))
diff --git a/test/package_unittest.py b/test/package_unittest.py
index daf11f4..16b00dc 100644
--- a/test/package_unittest.py
+++ b/test/package_unittest.py
@@ -64,7 +64,7 @@ def parseArgs(argv=sys.argv):
debug =1
if len(args) != 0:
usageExit("No command-line arguments supported yet.")
- except getopt.error, msg:
+ except getopt.error as msg:
usageExit(msg)
def loadTestModules(path, name='', packages=None):
diff --git a/test/test_error_reporting.py b/test/test_error_reporting.py
index c4eae40..bae9db5 100644
--- a/test/test_error_reporting.py
+++ b/test/test_error_reporting.py
@@ -19,7 +19,7 @@ instances like, e.g., ::
try:
something
- except IOError, error:
+ except IOError as error:
print('Found %s' % error)
unless the minimal required Python version has this problem fixed.
@@ -223,29 +223,29 @@ class SafeStringTests_locale(unittest.TestCase):
us = u'\xfc'
try:
open(b'\xfc')
- except IOError, e: # in Python 3 the name for the exception instance
+ except IOError as e: # in Python 3 the name for the exception instance
bioe = e # is local to the except clause
try:
open(u'\xfc')
- except IOError, e:
+ except IOError as e:
uioe = e
except UnicodeEncodeError:
try:
open(u'\xfc'.encode(sys.getfilesystemencoding(), 'replace'))
- except IOError, e:
+ except IOError as e:
uioe = e
try:
os.chdir(b'\xfc')
- except OSError, e:
+ except OSError as e:
bose = e
try:
os.chdir(u'\xfc')
- except OSError, e:
+ except OSError as e:
uose = e
except UnicodeEncodeError:
try:
os.chdir(u'\xfc'.encode(sys.getfilesystemencoding(), 'replace'))
- except OSError, e:
+ except OSError as e:
uose = e
# wrapped test data:
wbioe = SafeString(bioe)
diff --git a/test/test_language.py b/test/test_language.py
index 70a497e..0e05d44 100755
--- a/test/test_language.py
+++ b/test/test_language.py
@@ -144,7 +144,7 @@ class LanguageTestCase(DocutilsTestSupport.CustomTestCase):
func, msg = directives.directive(d, module, None)
if not func:
failures.append('"%s": unknown directive' % d)
- except Exception, error:
+ except Exception as error:
failures.append('"%s": %s' % (d, error))
inverted = self._invert(module.directives)
canonical = directives._directive_registry.keys()
@@ -179,7 +179,7 @@ class LanguageTestCase(DocutilsTestSupport.CustomTestCase):
method = roles._role_registry[d]
#if not method:
# failures.append('"%s": unknown role' % d)
- except KeyError, error:
+ except KeyError as error:
failures.append('"%s": %s' % (d, error))
inverted = self._invert(module.roles)
canonical = roles._role_registry.keys()
diff --git a/test/test_publisher.py b/test/test_publisher.py
index f04ebf7..04d9c71 100755
--- a/test/test_publisher.py
+++ b/test/test_publisher.py
@@ -65,7 +65,7 @@ class PublisherTests(DocutilsTestSupport.StandardTestCase):
try:
core.publish_cmdline(argv=['nonexisting/path'],
settings_overrides={'traceback': True})
- except IOError, e:
+ except IOError as e:
self.assertTrue(isinstance(e, io.InputError))
@@ -74,7 +74,7 @@ class PublisherTests(DocutilsTestSupport.StandardTestCase):
try:
core.publish_cmdline(argv=['data/include.txt', 'nonexisting/path'],
settings_overrides={'traceback': True})
- except IOError, e:
+ except IOError as e:
self.assertTrue(isinstance(e, io.OutputError))
diff --git a/test/test_utils.py b/test/test_utils.py
index e1fcc8f..59e29c8 100755
--- a/test/test_utils.py
+++ b/test/test_utils.py
@@ -88,7 +88,7 @@ class ReporterTests(unittest.TestCase):
and hence fails with unicode message"""
try:
raise Exception(u'mesidʒ')
- except Exception, err:
+ except Exception as err:
sw = self.reporter.system_message(0, err)
self.assertEqual(sw.pformat(), u"""\
<system_message level="0" source="test data" type="DEBUG">
--
2.24.0.375.geb5ae68d41

View file

@ -0,0 +1,599 @@
From 447e4896c9b2487fb28c25f7564ebcb6733d2363 Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Tue, 19 Nov 2019 23:50:50 +0700
Subject: [PATCH 04/26] py3: Add aliases for removed symbols
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Add aliases for symbols that have been removed in Python 3.x, namely
basestring, unicode, unichr and StandardError.
Signed-off-by: Stephen Finucane <stephen@that.guru>
small fixes by Günter Milde.
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8348 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/__init__.py | 3 +-
docutils/frontend.py | 3 +
docutils/io.py | 3 +
docutils/nodes.py | 8 ++-
docutils/parsers/rst/directives/__init__.py | 3 +
docutils/statemachine.py | 10 +++-
docutils/transforms/frontmatter.py | 6 ++
docutils/transforms/universal.py | 5 ++
docutils/utils/__init__.py | 3 +
docutils/utils/error_reporting.py | 10 +++-
docutils/utils/math/math2html.py | 59 ++++---------------
docutils/writers/_html_base.py | 4 ++
docutils/writers/docutils_xml.py | 3 +
docutils/writers/latex2e/__init__.py | 4 ++
docutils/writers/manpage.py | 6 +-
test/DocutilsTestSupport.py | 4 ++
test/test__init__.py | 4 ++
test/test_error_reporting.py | 3 +
test/test_language.py | 7 ++-
test/test_nodes.py | 3 +
.../test_rst/test_directives/test_include.py | 5 ++
.../test_rst/test_directives/test_tables.py | 5 ++
.../test_rst/test_directives/test_unicode.py | 6 ++
tools/dev/create_unimap.py | 10 ++--
24 files changed, 115 insertions(+), 62 deletions(-)
diff --git a/docutils/__init__.py b/docutils/__init__.py
index 7d6a679..8178816 100644
--- a/docutils/__init__.py
+++ b/docutils/__init__.py
@@ -88,7 +88,8 @@ __version_details__ = 'release'
"""
-class ApplicationError(StandardError): pass
+class ApplicationError(Exception): pass
+
class DataError(ApplicationError): pass
diff --git a/docutils/frontend.py b/docutils/frontend.py
index 689d904..ebdbd6a 100644
--- a/docutils/frontend.py
+++ b/docutils/frontend.py
@@ -43,6 +43,9 @@ import docutils.nodes
from docutils.utils.error_reporting import (locale_encoding, SafeString,
ErrorOutput, ErrorString)
+if sys.version_info >= (3, 0):
+ unicode = str # noqa
+
def store_multiple(option, opt, value, parser, *args, **kwargs):
"""
diff --git a/docutils/io.py b/docutils/io.py
index 4466fdb..3cdf00e 100644
--- a/docutils/io.py
+++ b/docutils/io.py
@@ -17,6 +17,9 @@ import codecs
from docutils import TransformSpec
from docutils.utils.error_reporting import locale_encoding, ErrorString, ErrorOutput
+if sys.version_info >= (3, 0):
+ unicode = str # noqa
+
class InputError(IOError): pass
class OutputError(IOError): pass
diff --git a/docutils/nodes.py b/docutils/nodes.py
index 8a5b7bb..fa02c6e 100644
--- a/docutils/nodes.py
+++ b/docutils/nodes.py
@@ -30,6 +30,10 @@ import warnings
import types
import unicodedata
+if sys.version_info >= (3, 0):
+ unicode = str # noqa
+ basestring = str # noqa
+
# ==============================
# Functional Node Base Classes
# ==============================
@@ -61,7 +65,7 @@ class Node(object):
"""
return True
- if sys.version_info < (3,):
+ if sys.version_info < (3, 0):
# on 2.x, str(node) will be a byte string with Unicode
# characters > 255 escaped; on 3.x this is no longer necessary
def __str__(self):
@@ -301,7 +305,7 @@ class Node(object):
except IndexError:
return None
-if sys.version_info < (3,):
+if sys.version_info < (3, 0):
class reprunicode(unicode):
"""
A unicode sub-class that removes the initial u from unicode's repr.
diff --git a/docutils/parsers/rst/directives/__init__.py b/docutils/parsers/rst/directives/__init__.py
index 8789346..7bccb5b 100644
--- a/docutils/parsers/rst/directives/__init__.py
+++ b/docutils/parsers/rst/directives/__init__.py
@@ -16,6 +16,9 @@ from docutils import nodes
from docutils.utils import split_escaped_whitespace, escape2null, unescape
from docutils.parsers.rst.languages import en as _fallback_language_module
+if sys.version_info >= (3, 0):
+ unichr = chr # noqa
+
_directive_registry = {
'attention': ('admonitions', 'Attention'),
diff --git a/docutils/statemachine.py b/docutils/statemachine.py
index 6a2322c..b56f3c5 100644
--- a/docutils/statemachine.py
+++ b/docutils/statemachine.py
@@ -114,6 +114,9 @@ import unicodedata
from docutils import utils
from docutils.utils.error_reporting import ErrorOutput
+if sys.version_info >= (3, 0):
+ unicode = str # noqa
+
class StateMachine(object):
@@ -1124,7 +1127,12 @@ class ViewList(object):
def __ne__(self, other): return self.data != self.__cast(other)
def __gt__(self, other): return self.data > self.__cast(other)
def __ge__(self, other): return self.data >= self.__cast(other)
- def __cmp__(self, other): return cmp(self.data, self.__cast(other))
+
+ def __cmp__(self, other):
+ # from https://docs.python.org/3.0/whatsnew/3.0.html
+ mine = self.data
+ yours = self.__cast(other)
+ return (mine > yours) - (yours < mine)
def __cast(self, other):
if isinstance(other, ViewList):
diff --git a/docutils/transforms/frontmatter.py b/docutils/transforms/frontmatter.py
index f94c9da..1279f50 100644
--- a/docutils/transforms/frontmatter.py
+++ b/docutils/transforms/frontmatter.py
@@ -22,10 +22,16 @@ Transforms related to the front matter of a document or a section
__docformat__ = 'reStructuredText'
import re
+import sys
+
from docutils import nodes, utils
from docutils.transforms import TransformError, Transform
+if sys.version_info >= (3, 0):
+ unicode = str # noqa
+
+
class TitlePromoter(Transform):
"""
diff --git a/docutils/transforms/universal.py b/docutils/transforms/universal.py
index 47e1276..49fb2c8 100644
--- a/docutils/transforms/universal.py
+++ b/docutils/transforms/universal.py
@@ -17,12 +17,17 @@ Transforms needed by most or all documents:
__docformat__ = 'reStructuredText'
import re
+import sys
import time
from docutils import nodes, utils
from docutils.transforms import TransformError, Transform
from docutils.utils import smartquotes
+if sys.version_info >= (3, 0):
+ unicode = str # noqa
+
+
class Decorations(Transform):
"""
diff --git a/docutils/utils/__init__.py b/docutils/utils/__init__.py
index c71d508..77c70f8 100644
--- a/docutils/utils/__init__.py
+++ b/docutils/utils/__init__.py
@@ -22,6 +22,9 @@ from docutils.nodes import unescape
import docutils.io
from docutils.utils.error_reporting import ErrorOutput, SafeString
+if sys.version_info >= (3, 0):
+ unicode = str
+
class SystemMessage(ApplicationError):
diff --git a/docutils/utils/error_reporting.py b/docutils/utils/error_reporting.py
index 8ea7108..8fcc816 100644
--- a/docutils/utils/error_reporting.py
+++ b/docutils/utils/error_reporting.py
@@ -35,7 +35,8 @@ The `SafeString`, `ErrorString` and `ErrorOutput` classes handle
common exceptions.
"""
-import sys, codecs
+import codecs
+import sys
# Guess the locale's encoding.
# If no valid guess can be made, locale_encoding is set to `None`:
@@ -64,6 +65,9 @@ else:
locale_encoding = None
+if sys.version_info >= (3, 0):
+ unicode = str # noqa
+
class SafeString(object):
"""
@@ -199,9 +203,9 @@ class ErrorOutput(object):
self.stream.write(data)
except UnicodeEncodeError:
self.stream.write(data.encode(self.encoding, self.encoding_errors))
- except TypeError:
+ except TypeError:
if isinstance(data, unicode): # passed stream may expect bytes
- self.stream.write(data.encode(self.encoding,
+ self.stream.write(data.encode(self.encoding,
self.encoding_errors))
return
if self.stream in (sys.stderr, sys.stdout):
diff --git a/docutils/utils/math/math2html.py b/docutils/utils/math/math2html.py
index 1f61e23..4967165 100644
--- a/docutils/utils/math/math2html.py
+++ b/docutils/utils/math/math2html.py
@@ -20,10 +20,21 @@
# Alex 20101110
# eLyXer standalone formula conversion to HTML.
+import codecs
+import datetime
+import gettext
+import io
+import os.path
+import sys
+import unicodedata
+import urllib
+if sys.version_info >= (3,0):
+ unicode = str #noqa
+ basestring = str # noqa
+ file = io.IOBase # noqa
-import sys
class Trace(object):
"A tracing class"
@@ -73,12 +84,6 @@ class Trace(object):
show = classmethod(show)
-
-
-import os.path
-import sys
-
-
class BibStylesConfig(object):
"Configuration class from elyxer.config file"
@@ -1305,17 +1310,6 @@ class BranchOptions(object):
return 'options for ' + self.name + ': ' + unicode(self.options)
-
-
-import urllib
-
-
-
-
-
-
-
-
class Cloner(object):
"An object used to clone other objects."
@@ -1699,15 +1693,6 @@ class StringOutput(ContainerOutput):
return [container.string]
-
-
-
-
-
-import sys
-import codecs
-
-
class LineReader(object):
"Reads a file line by line"
@@ -3094,24 +3079,6 @@ class FormulaFactory(object):
return whole
-
-
-import unicodedata
-
-
-
-
-
-
-
-
-
-
-
-
-import gettext
-
-
class Translator(object):
"Reads the configuration file and tries to find a translation."
"Otherwise falls back to the messages in the config file."
@@ -4589,8 +4556,6 @@ class BeginCommand(CommandBit):
FormulaCommand.types += [BeginCommand]
-import datetime
-
class CombiningFunction(OneParamFunction):
diff --git a/docutils/writers/_html_base.py b/docutils/writers/_html_base.py
index 23efeea..a7f3b53 100644
--- a/docutils/writers/_html_base.py
+++ b/docutils/writers/_html_base.py
@@ -40,6 +40,10 @@ from docutils.utils.math import (unichar2tex, pick_math_environment,
math2html, latex2mathml, tex2mathml_extern)
+if sys.version_info >= (3, 0):
+ unicode = str # noqa
+
+
class Writer(writers.Writer):
supported = ('html', 'xhtml') # update in subclass
diff --git a/docutils/writers/docutils_xml.py b/docutils/writers/docutils_xml.py
index e870ee1..34e810d 100644
--- a/docutils/writers/docutils_xml.py
+++ b/docutils/writers/docutils_xml.py
@@ -30,6 +30,9 @@ from StringIO import StringIO
import docutils
from docutils import frontend, writers, nodes
+if sys.version_info >= (3, 0):
+ unicode = str # noqa
+
class RawXmlError(docutils.ApplicationError): pass
diff --git a/docutils/writers/latex2e/__init__.py b/docutils/writers/latex2e/__init__.py
index 5eaa7f0..e21c74b 100644
--- a/docutils/writers/latex2e/__init__.py
+++ b/docutils/writers/latex2e/__init__.py
@@ -28,6 +28,10 @@ from docutils.transforms import writer_aux
from docutils.utils.math import pick_math_environment, unichar2tex
+if sys.version_info >= (3, 0):
+ unicode = str # noqa
+
+
class Writer(writers.Writer):
supported = ('latex','latex2e')
diff --git a/docutils/writers/manpage.py b/docutils/writers/manpage.py
index 287c6f2..9c887c7 100644
--- a/docutils/writers/manpage.py
+++ b/docutils/writers/manpage.py
@@ -45,6 +45,10 @@ by the command whatis or apropos.
__docformat__ = 'reStructuredText'
import re
+import sys
+
+if sys.version_info < (3, 0):
+ range = xrange
import docutils
from docutils import nodes, writers, languages
@@ -255,7 +259,7 @@ class Translator(nodes.NodeVisitor):
# ensure we get a ".TH" as viewers require it.
self.append_header()
# filter body
- for i in xrange(len(self.body)-1, 0, -1):
+ for i in range(len(self.body)-1, 0, -1):
# remove superfluous vertical gaps.
if self.body[i] == '.sp\n':
if self.body[i - 1][:4] in ('.BI ','.IP '):
diff --git a/test/DocutilsTestSupport.py b/test/DocutilsTestSupport.py
index e77447a..c6f5b9f 100644
--- a/test/DocutilsTestSupport.py
+++ b/test/DocutilsTestSupport.py
@@ -89,6 +89,10 @@ except:
import pdb
+if sys.version_info >= (3, 0):
+ unicode = str # noqa
+
+
# Hack to make repr(StringList) look like repr(list):
StringList.__repr__ = StringList.__str__
diff --git a/test/test__init__.py b/test/test__init__.py
index 01a1c59..8f1d749 100644
--- a/test/test__init__.py
+++ b/test/test__init__.py
@@ -16,6 +16,10 @@ import docutils
import docutils.utils
+if sys.version_info >= (3, 0):
+ unicode = str # noqa
+
+
class ApplicationErrorTests(unittest.TestCase):
def test_message(self):
diff --git a/test/test_error_reporting.py b/test/test_error_reporting.py
index bae9db5..893082c 100644
--- a/test/test_error_reporting.py
+++ b/test/test_error_reporting.py
@@ -46,6 +46,9 @@ if sys.version_info < (3,0): # problems solved in py3k
print('cannot test error reporting with problematic locales,\n'
'`import locale` failed.')
+if sys.version_info >= (3, 0):
+ unicode = str # noqa
+
# locales confirmed to use non-ASCII chars in the IOError message
# for a missing file (https://bugs.gentoo.org/show_bug.cgi?id=349101)
diff --git a/test/test_language.py b/test/test_language.py
index 0e05d44..30af81a 100755
--- a/test/test_language.py
+++ b/test/test_language.py
@@ -26,6 +26,9 @@ _reporter = docutils.utils.new_reporter('', _settings)
reference_language = 'en'
+if sys.version_info >= (3, 0):
+ unicode = str # noqa
+
class LanguageTestSuite(DocutilsTestSupport.CustomTestSuite):
@@ -156,7 +159,7 @@ class LanguageTestCase(DocutilsTestSupport.CustomTestCase):
if failures:
text = ('Module docutils.parsers.rst.languages.%s:\n %s'
% (self.language, '\n '.join(failures)))
- if type(text) is unicode:
+ if isinstance(text, unicode):
text = text.encode('raw_unicode_escape')
self.fail(text)
@@ -191,7 +194,7 @@ class LanguageTestCase(DocutilsTestSupport.CustomTestCase):
if failures:
text = ('Module docutils.parsers.rst.languages.%s:\n %s'
% (self.language, '\n '.join(failures)))
- if type(text) is unicode:
+ if isinstance(text, unicode):
text = text.encode('raw_unicode_escape')
self.fail(text)
diff --git a/test/test_nodes.py b/test/test_nodes.py
index f6bc6b2..924569f 100755
--- a/test/test_nodes.py
+++ b/test/test_nodes.py
@@ -17,6 +17,9 @@ from DocutilsTestSupport import nodes, utils
debug = False
+if sys.version_info >= (3, 0):
+ unicode = str # noqa
+
class TextTests(unittest.TestCase):
diff --git a/test/test_parsers/test_rst/test_directives/test_include.py b/test/test_parsers/test_rst/test_directives/test_include.py
index 2a6e5be..6e9dc84 100755
--- a/test/test_parsers/test_rst/test_directives/test_include.py
+++ b/test/test_parsers/test_rst/test_directives/test_include.py
@@ -14,6 +14,11 @@ from __init__ import DocutilsTestSupport
from docutils.parsers.rst import states
from docutils.utils.code_analyzer import with_pygments
+
+if sys.version_info >= (3, 0):
+ unichr = chr # noqa
+
+
def suite():
s = DocutilsTestSupport.ParserTestSuite()
if not with_pygments:
diff --git a/test/test_parsers/test_rst/test_directives/test_tables.py b/test/test_parsers/test_rst/test_directives/test_tables.py
index f7496ad..2c5f832 100755
--- a/test/test_parsers/test_rst/test_directives/test_tables.py
+++ b/test/test_parsers/test_rst/test_directives/test_tables.py
@@ -16,6 +16,11 @@ import platform
from docutils.parsers.rst.directives import tables
+if sys.version_info >= (3, 0):
+ unicode = str # noqa
+ unichr = chr # noqa
+
+
def suite():
s = DocutilsTestSupport.ParserTestSuite()
s.generateTests(totest)
diff --git a/test/test_parsers/test_rst/test_directives/test_unicode.py b/test/test_parsers/test_rst/test_directives/test_unicode.py
index b140050..5cdfd5a 100755
--- a/test/test_parsers/test_rst/test_directives/test_unicode.py
+++ b/test/test_parsers/test_rst/test_directives/test_unicode.py
@@ -8,9 +8,15 @@
Tests for misc.py "unicode" directive.
"""
+import sys
+
from __init__ import DocutilsTestSupport
+if sys.version_info >= (3, 0):
+ unichr = chr # noqa
+
+
def suite():
s = DocutilsTestSupport.ParserTestSuite()
s.generateTests(totest)
diff --git a/tools/dev/create_unimap.py b/tools/dev/create_unimap.py
index 85ac264..74e8bc7 100755
--- a/tools/dev/create_unimap.py
+++ b/tools/dev/create_unimap.py
@@ -14,15 +14,15 @@ from xml.dom import minidom
import sys
import pprint
-if sys.version_info >= (3,0):
- unicode = str
+if sys.version_info >= (3, 0):
+ unicode = str #noqa
else:
- bytes = str
- chr = unichr
+ bytes = str # noqa
+ chr = unichr # noqa
def w(s):
- if sys.version_info >= (3,0) and isinstance(s, unicode):
+ if sys.version_info >= (3, 0) and isinstance(s, unicode):
s = s.encode('utf8')
sys.stdout.write(s)
--
2.24.0.375.geb5ae68d41

View file

@ -0,0 +1,80 @@
From 6bd112802f857b32764afe87ce7828db50077086 Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Tue, 19 Nov 2019 23:52:14 +0700
Subject: [PATCH 05/26] py3: Resolve some additional undefined symbols
Found with flake8
Signed-off-by: Stephen Finucane <stephen@that.guru>
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8352 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/utils/math/math2html.py | 8 ++++----
tools/dev/generate_punctuation_chars.py | 11 -----------
2 files changed, 4 insertions(+), 15 deletions(-)
diff --git a/docutils/utils/math/math2html.py b/docutils/utils/math/math2html.py
index 4967165..4a7209d 100644
--- a/docutils/utils/math/math2html.py
+++ b/docutils/utils/math/math2html.py
@@ -1624,7 +1624,7 @@ class TaggedOutput(ContentsOutput):
def open(self, container):
"Get opening line."
- if not self.checktag():
+ if not self.checktag(container):
return ''
open = '<' + self.tag + '>'
if self.breaklines:
@@ -1633,7 +1633,7 @@ class TaggedOutput(ContentsOutput):
def close(self, container):
"Get closing line."
- if not self.checktag():
+ if not self.checktag(container):
return ''
close = '</' + self.tag.split()[0] + '>'
if self.breaklines:
@@ -1642,14 +1642,14 @@ class TaggedOutput(ContentsOutput):
def selfclosing(self, container):
"Get self-closing line."
- if not self.checktag():
+ if not self.checktag(container):
return ''
selfclosing = '<' + self.tag + '/>'
if self.breaklines:
return selfclosing + '\n'
return selfclosing
- def checktag(self):
+ def checktag(self, container):
"Check that the tag is valid."
if not self.tag:
Trace.error('No tag in ' + unicode(container))
diff --git a/tools/dev/generate_punctuation_chars.py b/tools/dev/generate_punctuation_chars.py
index 5947fe5..a30c5ca 100644
--- a/tools/dev/generate_punctuation_chars.py
+++ b/tools/dev/generate_punctuation_chars.py
@@ -319,17 +319,6 @@ def print_differences(old, new, name):
else:
print('%s unchanged' % name)
-def print_quote_pairs():
- pairs = [(o,c) for o,c in quote_pairs.items()]
- for o,c in sorted(pairs):
- print((u'%s %s' % (o,c)).encode('utf8'))
-
- # # Test open/close matching:
- # for i in range(min(len(openers),len(closers))):
- # print('%4d %s %s' % (i, openers[i].encode('utf8'),
- # closers[i].encode('utf8'))
-
-
# Output
# ------
#
--
2.24.0.375.geb5ae68d41

View file

@ -0,0 +1,263 @@
From efe0c9a75c5b2a8d094840927e93e0e873e77ece Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Tue, 19 Nov 2019 23:52:58 +0700
Subject: [PATCH 06/26] py3: Replace deprecated form of raising exception
Signed-off-by: Stephen Finucane <stephen@that.guru>
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8353 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/frontend.py | 25 ++++++++++---------------
docutils/nodes.py | 12 ++++++------
docutils/transforms/frontmatter.py | 4 ++--
docutils/utils/roman.py | 9 +++++----
docutils/writers/manpage.py | 4 ++--
test/DocutilsTestSupport.py | 21 ++++-----------------
test/package_unittest.py | 2 +-
7 files changed, 30 insertions(+), 47 deletions(-)
diff --git a/docutils/frontend.py b/docutils/frontend.py
index ebdbd6a..4b389b0 100644
--- a/docutils/frontend.py
+++ b/docutils/frontend.py
@@ -74,9 +74,8 @@ def validate_encoding(setting, value, option_parser,
try:
codecs.lookup(value)
except LookupError:
- raise (LookupError('setting "%s": unknown encoding: "%s"'
- % (setting, value)),
- None, sys.exc_info()[2])
+ raise LookupError('setting "%s": unknown encoding: "%s"'
+ % (setting, value))
return value
def validate_encoding_error_handler(setting, value, option_parser,
@@ -84,12 +83,11 @@ def validate_encoding_error_handler(setting, value, option_parser,
try:
codecs.lookup_error(value)
except LookupError:
- raise (LookupError(
+ raise LookupError(
'unknown encoding error handler: "%s" (choices: '
'"strict", "ignore", "replace", "backslashreplace", '
'"xmlcharrefreplace", and possibly others; see documentation for '
- 'the Python ``codecs`` module)' % value),
- None, sys.exc_info()[2])
+ 'the Python ``codecs`` module)' % value)
return value
def validate_encoding_and_error_handler(
@@ -125,8 +123,7 @@ def validate_boolean(setting, value, option_parser,
try:
return option_parser.booleans[value.strip().lower()]
except KeyError:
- raise (LookupError('unknown boolean value: "%s"' % value),
- None, sys.exc_info()[2])
+ raise LookupError('unknown boolean value: "%s"' % value)
def validate_ternary(setting, value, option_parser,
config_parser=None, config_section=None):
@@ -157,8 +154,7 @@ def validate_threshold(setting, value, option_parser,
try:
return option_parser.thresholds[value.lower()]
except (KeyError, AttributeError):
- raise (LookupError('unknown threshold: %r.' % value),
- None, sys.exc_info[2])
+ raise LookupError('unknown threshold: %r.' % value)
def validate_colon_separated_string_list(
setting, value, option_parser, config_parser=None, config_section=None):
@@ -350,10 +346,9 @@ class Option(optparse.Option):
try:
new_value = self.validator(setting, value, parser)
except Exception as error:
- raise (optparse.OptionValueError(
+ raise optparse.OptionValueError(
'Error in option "%s":\n %s'
- % (opt, ErrorString(error))),
- None, sys.exc_info()[2])
+ % (opt, ErrorString(error)))
setattr(values, setting, new_value)
if self.overrides:
setattr(values, self.overrides, None)
@@ -830,12 +825,12 @@ Skipping "%s" configuration file.
setting, value, option_parser,
config_parser=self, config_section=section)
except Exception as error:
- raise (ValueError(
+ raise ValueError(
'Error in config file "%s", section "[%s]":\n'
' %s\n'
' %s = %s'
% (filename, section, ErrorString(error),
- setting, value)), None, sys.exc_info()[2])
+ setting, value))
self.set(section, setting, new_value)
if option.overrides:
self.set(section, option.overrides, None)
diff --git a/docutils/nodes.py b/docutils/nodes.py
index fa02c6e..71189ab 100644
--- a/docutils/nodes.py
+++ b/docutils/nodes.py
@@ -594,8 +594,8 @@ class Element(Node):
assert key.step in (None, 1), 'cannot handle slice with stride'
return self.children[key.start:key.stop]
else:
- raise TypeError, ('element index must be an integer, a slice, or '
- 'an attribute name string')
+ raise TypeError('element index must be an integer, a slice, or '
+ 'an attribute name string')
def __setitem__(self, key, item):
if isinstance(key, basestring):
@@ -609,8 +609,8 @@ class Element(Node):
self.setup_child(node)
self.children[key.start:key.stop] = item
else:
- raise TypeError, ('element index must be an integer, a slice, or '
- 'an attribute name string')
+ raise TypeError('element index must be an integer, a slice, or '
+ 'an attribute name string')
def __delitem__(self, key):
if isinstance(key, basestring):
@@ -621,8 +621,8 @@ class Element(Node):
assert key.step in (None, 1), 'cannot handle slice with stride'
del self.children[key.start:key.stop]
else:
- raise TypeError, ('element index must be an integer, a simple '
- 'slice, or an attribute name string')
+ raise TypeError('element index must be an integer, a simple '
+ 'slice, or an attribute name string')
def __add__(self, other):
return self.children + other
diff --git a/docutils/transforms/frontmatter.py b/docutils/transforms/frontmatter.py
index 1279f50..23b9c95 100644
--- a/docutils/transforms/frontmatter.py
+++ b/docutils/transforms/frontmatter.py
@@ -57,7 +57,7 @@ class TitlePromoter(Transform):
"""
# Type check
if not isinstance(node, nodes.Element):
- raise TypeError, 'node must be of Element-derived type.'
+ raise TypeError('node must be of Element-derived type.')
# `node` must not have a title yet.
assert not (len(node) and isinstance(node[0], nodes.title))
@@ -100,7 +100,7 @@ class TitlePromoter(Transform):
"""
# Type check
if not isinstance(node, nodes.Element):
- raise TypeError, 'node must be of Element-derived type.'
+ raise TypeError('node must be of Element-derived type.')
subsection, index = self.candidate_index(node)
if index is None:
diff --git a/docutils/utils/roman.py b/docutils/utils/roman.py
index 0335f29..fc4680d 100644
--- a/docutils/utils/roman.py
+++ b/docutils/utils/roman.py
@@ -40,9 +40,9 @@ romanNumeralMap = (('M', 1000),
def toRoman(n):
"""convert integer to Roman numeral"""
if not (0 < n < 5000):
- raise OutOfRangeError, "number out of range (must be 1..4999)"
+ raise OutOfRangeError("number out of range (must be 1..4999)")
if int(n) != n:
- raise NotIntegerError, "decimals can not be converted"
+ raise NotIntegerError("decimals can not be converted")
result = ""
for numeral, integer in romanNumeralMap:
@@ -67,9 +67,10 @@ romanNumeralPattern = re.compile("""
def fromRoman(s):
"""convert Roman numeral to integer"""
if not s:
- raise InvalidRomanNumeralError, 'Input can not be blank'
+ raise InvalidRomanNumeralError('Input can not be blank')
+
if not romanNumeralPattern.search(s):
- raise InvalidRomanNumeralError, 'Invalid Roman numeral: %s' % s
+ raise InvalidRomanNumeralError('Invalid Roman numeral: %s' % s)
result = 0
index = 0
diff --git a/docutils/writers/manpage.py b/docutils/writers/manpage.py
index 9c887c7..cbb8648 100644
--- a/docutils/writers/manpage.py
+++ b/docutils/writers/manpage.py
@@ -715,7 +715,7 @@ class Translator(nodes.NodeVisitor):
pass
def visit_header(self, node):
- raise NotImplementedError, node.astext()
+ raise NotImplementedError(node.astext())
def depart_header(self, node):
pass
@@ -855,7 +855,7 @@ class Translator(nodes.NodeVisitor):
self.depart_literal_block(node)
def visit_meta(self, node):
- raise NotImplementedError, node.astext()
+ raise NotImplementedError(node.astext())
def depart_meta(self, node):
pass
diff --git a/test/DocutilsTestSupport.py b/test/DocutilsTestSupport.py
index c6f5b9f..a1fec25 100644
--- a/test/DocutilsTestSupport.py
+++ b/test/DocutilsTestSupport.py
@@ -123,30 +123,17 @@ class StandardTestCase(unittest.TestCase):
operator.
"""
if not first == second:
- raise self.failureException, (
- msg or '%s != %s' % _format_str(first, second))
+ raise self.failureException(
+ msg or '%s != %s' % _format_str(first, second))
def assertNotEqual(self, first, second, msg=None):
"""Fail if the two objects are equal as determined by the '=='
operator.
"""
if first == second:
- raise self.failureException, (
- msg or '%s == %s' % _format_str(first, second))
+ raise self.failureException(
+ msg or '%s == %s' % _format_str(first, second))
- # assertIn and assertNotIn: new in Python 2.7:
- if sys.version_info < (2,7):
-
- def assertIn(self, a, b, msg=None):
- if a not in b:
- raise self.failureException, (
- msg or '%s not in %s' % _format_str(a, b))
-
- def assertNotIn(self, a, b, msg=None):
- if a in b:
- raise self.failureException, (
- msg or '%s in %s' % _format_str(a, b))
-
# aliases for assertion methods, deprecated since Python 2.7
failUnlessEqual = assertEquals = assertEqual
diff --git a/test/package_unittest.py b/test/package_unittest.py
index 16b00dc..4db826b 100644
--- a/test/package_unittest.py
+++ b/test/package_unittest.py
@@ -120,7 +120,7 @@ def loadTestModules(path, name='', packages=None):
elif isinstance(suite, unittest.TestSuite):
testSuite.addTest(suite)
else:
- raise AssertionError, "don't understand suite (%s)" % mod
+ raise AssertionError("don't understand suite (%s)" % mod)
sys.path.pop(0)
return testSuite
--
2.24.0.375.geb5ae68d41

View file

@ -0,0 +1,103 @@
From d6f8634004aa679d2d71037bd63af82052f08fee Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Tue, 19 Nov 2019 23:53:54 +0700
Subject: [PATCH 07/26] py3: Replace 'sys.maxint' with 'sys.maxsize'
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
From the Python 3 release docs [1]:
The sys.maxint constant was removed, since there is no longer a limit
to the value of integers. However, sys.maxsize can be used as an
integer larger than any practical list or string index. It conforms to
the implementations “natural” integer size and is typically the
same as sys.maxint in previous releases on the same platform (assuming
the same build options).
[1] https://docs.python.org/3.1/whatsnew/3.0.html#integers
Signed-off-by: Stephen Finucane <stephen@that.guru>
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8354 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/nodes.py | 4 ++--
docutils/parsers/rst/tableparser.py | 2 +-
docutils/statemachine.py | 2 +-
docutils/transforms/parts.py | 4 ++--
4 files changed, 6 insertions(+), 6 deletions(-)
diff --git a/docutils/nodes.py b/docutils/nodes.py
index 71189ab..c524373 100644
--- a/docutils/nodes.py
+++ b/docutils/nodes.py
@@ -977,7 +977,7 @@ class Element(Node):
'Losing "%s" attribute: %s' % (att, self[att])
self.parent.replace(self, new)
- def first_child_matching_class(self, childclass, start=0, end=sys.maxint):
+ def first_child_matching_class(self, childclass, start=0, end=sys.maxsize):
"""
Return the index of the first child whose class exactly matches.
@@ -997,7 +997,7 @@ class Element(Node):
return None
def first_child_not_matching_class(self, childclass, start=0,
- end=sys.maxint):
+ end=sys.maxsize):
"""
Return the index of the first child whose class does *not* match.
diff --git a/docutils/parsers/rst/tableparser.py b/docutils/parsers/rst/tableparser.py
index 45af72f..2760ea0 100644
--- a/docutils/parsers/rst/tableparser.py
+++ b/docutils/parsers/rst/tableparser.py
@@ -498,7 +498,7 @@ class SimpleTableParser(TableParser):
"""
# "Infinite" value for a dummy last column's beginning, used to
# check for text overflow:
- columns.append((sys.maxint, None))
+ columns.append((sys.maxsize, None))
lastcol = len(columns) - 2
# combining characters do not contribute to the column width
lines = [strip_combining_chars(line) for line in lines]
diff --git a/docutils/statemachine.py b/docutils/statemachine.py
index b56f3c5..5d7fe77 100644
--- a/docutils/statemachine.py
+++ b/docutils/statemachine.py
@@ -1341,7 +1341,7 @@ class StringList(ViewList):
"""A `ViewList` with string-specific methods."""
- def trim_left(self, length, start=0, end=sys.maxint):
+ def trim_left(self, length, start=0, end=sys.maxsize):
"""
Trim `length` characters off the beginning of each item, in-place,
from index `start` to `end`. No whitespace-checking is done on the
diff --git a/docutils/transforms/parts.py b/docutils/transforms/parts.py
index 11b1b23..7a2fa0f 100644
--- a/docutils/transforms/parts.py
+++ b/docutils/transforms/parts.py
@@ -37,7 +37,7 @@ class SectNum(Transform):
self.startnode.parent.remove(self.startnode)
if self.document.settings.sectnum_xform:
if self.maxdepth is None:
- self.maxdepth = sys.maxint
+ self.maxdepth = sys.maxsize
self.update_section_numbers(self.document)
else: # store details for eventual section numbering by the writer
self.document.settings.sectnum_depth = self.maxdepth
@@ -120,7 +120,7 @@ class Contents(Transform):
sections = [sect for sect in node if isinstance(sect, nodes.section)]
entries = []
autonum = 0
- depth = self.startnode.details.get('depth', sys.maxint)
+ depth = self.startnode.details.get('depth', sys.maxsize)
for section in sections:
title = section[0]
auto = title.get('auto') # May be set by SectNum.
--
2.24.0.375.geb5ae68d41

View file

@ -0,0 +1,128 @@
From a46f2bdec20068cf79ff182ae024fc1989d45c74 Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Mon, 26 Aug 2019 16:42:50 +0000
Subject: [PATCH 08/26] py3: Replace 'types.SliceType' with slice, remove
'types.ClassType'.
These types have been removed in Python 3,
`SliceType` is an alias for `slice` already in Python 2.7,
`ClassType` is for user-defined old-style classes (we now use only new style classes).
Signed-off-by: Stephen Finucane <stephen@that.guru>
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8355 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/nodes.py | 11 +++++------
docutils/statemachine.py | 5 ++---
test/test_nodes.py | 4 ++--
3 files changed, 9 insertions(+), 11 deletions(-)
diff --git a/docutils/nodes.py b/docutils/nodes.py
index c524373..a8c0478 100644
--- a/docutils/nodes.py
+++ b/docutils/nodes.py
@@ -27,7 +27,6 @@ import sys
import os
import re
import warnings
-import types
import unicodedata
if sys.version_info >= (3, 0):
@@ -257,11 +256,11 @@ class Node(object):
if include_self and descend and not siblings:
if condition is None:
return self._all_traverse()
- elif isinstance(condition, (types.ClassType, type)):
+ elif isinstance(condition, type):
return self._fast_traverse(condition)
# Check if `condition` is a class (check for TypeType for Python
# implementations that use only new-style classes, like PyPy).
- if isinstance(condition, (types.ClassType, type)):
+ if isinstance(condition, type):
node_class = condition
def condition(node, node_class=node_class):
return isinstance(node, node_class)
@@ -590,7 +589,7 @@ class Element(Node):
return self.attributes[key]
elif isinstance(key, int):
return self.children[key]
- elif isinstance(key, types.SliceType):
+ elif isinstance(key, slice):
assert key.step in (None, 1), 'cannot handle slice with stride'
return self.children[key.start:key.stop]
else:
@@ -603,7 +602,7 @@ class Element(Node):
elif isinstance(key, int):
self.setup_child(item)
self.children[key] = item
- elif isinstance(key, types.SliceType):
+ elif isinstance(key, slice):
assert key.step in (None, 1), 'cannot handle slice with stride'
for node in item:
self.setup_child(node)
@@ -617,7 +616,7 @@ class Element(Node):
del self.attributes[key]
elif isinstance(key, int):
del self.children[key]
- elif isinstance(key, types.SliceType):
+ elif isinstance(key, slice):
assert key.step in (None, 1), 'cannot handle slice with stride'
del self.children[key.start:key.stop]
else:
diff --git a/docutils/statemachine.py b/docutils/statemachine.py
index 5d7fe77..068083a 100644
--- a/docutils/statemachine.py
+++ b/docutils/statemachine.py
@@ -109,7 +109,6 @@ __docformat__ = 'restructuredtext'
import sys
import re
-import types
import unicodedata
from docutils import utils
from docutils.utils.error_reporting import ErrorOutput
@@ -1148,7 +1147,7 @@ class ViewList(object):
# just works.
def __getitem__(self, i):
- if isinstance(i, types.SliceType):
+ if isinstance(i, slice):
assert i.step in (None, 1), 'cannot handle slice with stride'
return self.__class__(self.data[i.start:i.stop],
items=self.items[i.start:i.stop],
@@ -1157,7 +1156,7 @@ class ViewList(object):
return self.data[i]
def __setitem__(self, i, item):
- if isinstance(i, types.SliceType):
+ if isinstance(i, slice):
assert i.step in (None, 1), 'cannot handle slice with stride'
if not isinstance(item, ViewList):
raise TypeError('assigning non-ViewList to ViewList slice')
diff --git a/test/test_nodes.py b/test/test_nodes.py
index 924569f..679c98e 100755
--- a/test/test_nodes.py
+++ b/test/test_nodes.py
@@ -11,7 +11,7 @@ Test module for nodes.py.
import sys
import unittest
-import types
+
import DocutilsTestSupport # must be imported before docutils
from DocutilsTestSupport import nodes, utils
@@ -359,7 +359,7 @@ class MiscTests(unittest.TestCase):
node_class_names = []
for x in dir(nodes):
c = getattr(nodes, x)
- if isinstance(c, (type, types.ClassType)) and \
+ if isinstance(c, type) and \
issubclass(c, nodes.Node) and len(c.__bases__) > 1:
node_class_names.append(x)
node_class_names.sort()
--
2.24.0.375.geb5ae68d41

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,236 @@
From 46d71ef146d5fe74b0186693f91a5f47585b1d79 Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Mon, 26 Aug 2019 16:44:51 +0000
Subject: [PATCH 10/26] py3: Use 'sorted(foo)' instead of 'foo.sort()'
This works with iterators also (like 'dict.keys()' in Python 3)
Signed-off-by: Stephen Finucane <stephen@that.guru>
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8357 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/nodes.py | 6 ++----
docutils/parsers/rst/tableparser.py | 3 +--
docutils/transforms/__init__.py | 3 +--
docutils/utils/math/math2html.py | 3 +--
docutils/writers/_html_base.py | 3 +--
docutils/writers/latex2e/__init__.py | 3 +--
test/DocutilsTestSupport.py | 3 +--
test/test_dependencies.py | 9 +++------
test/test_language.py | 6 ++----
tools/dev/generate_punctuation_chars.py | 3 +--
tools/dev/unicode2rstsubs.py | 6 ++----
11 files changed, 16 insertions(+), 32 deletions(-)
diff --git a/docutils/nodes.py b/docutils/nodes.py
index a8c0478..e29b887 100644
--- a/docutils/nodes.py
+++ b/docutils/nodes.py
@@ -649,8 +649,7 @@ class Element(Node):
return atts
def attlist(self):
- attlist = self.non_default_attributes().items()
- attlist.sort()
+ attlist = sorted(self.non_default_attributes().items())
return attlist
def get(self, key, failobj=None):
@@ -1782,8 +1781,7 @@ class pending(Special, Invisible, Element):
' .transform: %s.%s' % (self.transform.__module__,
self.transform.__name__),
' .details:']
- details = self.details.items()
- details.sort()
+ details = sorted(self.details.items())
for key, value in details:
if isinstance(value, Node):
internals.append('%7s%s:' % ('', key))
diff --git a/docutils/parsers/rst/tableparser.py b/docutils/parsers/rst/tableparser.py
index 2760ea0..937aec8 100644
--- a/docutils/parsers/rst/tableparser.py
+++ b/docutils/parsers/rst/tableparser.py
@@ -286,8 +286,7 @@ class GridTableParser(TableParser):
From the data collected by `scan_cell()`, convert to the final data
structure.
"""
- rowseps = self.rowseps.keys() # list of row boundaries
- rowseps.sort()
+ rowseps = sorted(self.rowseps.keys()) # list of row boundaries
rowindex = {}
for i in range(len(rowseps)):
rowindex[rowseps[i]] = i # row boundary -> row number mapping
diff --git a/docutils/transforms/__init__.py b/docutils/transforms/__init__.py
index 9271133..d444fce 100644
--- a/docutils/transforms/__init__.py
+++ b/docutils/transforms/__init__.py
@@ -153,8 +153,7 @@ class Transformer(TransformSpec):
unknown_reference_resolvers = []
for i in components:
unknown_reference_resolvers.extend(i.unknown_reference_resolvers)
- decorated_list = [(f.priority, f) for f in unknown_reference_resolvers]
- decorated_list.sort()
+ decorated_list = sorted([(f.priority, f) for f in unknown_reference_resolvers])
self.unknown_reference_resolvers.extend([f[1] for f in decorated_list])
def apply_transforms(self):
diff --git a/docutils/utils/math/math2html.py b/docutils/utils/math/math2html.py
index 4a7209d..adcb1cc 100644
--- a/docutils/utils/math/math2html.py
+++ b/docutils/utils/math/math2html.py
@@ -2193,9 +2193,8 @@ class Container(object):
def escape(self, line, replacements = EscapeConfig.entities):
"Escape a line with replacements from elyxer.a map"
- pieces = replacements.keys()
+ pieces = sorted(replacements.keys())
# do them in order
- pieces.sort()
for piece in pieces:
if piece in line:
line = line.replace(piece, replacements[piece])
diff --git a/docutils/writers/_html_base.py b/docutils/writers/_html_base.py
index a7f3b53..a957311 100644
--- a/docutils/writers/_html_base.py
+++ b/docutils/writers/_html_base.py
@@ -366,8 +366,7 @@ class HTMLTranslator(nodes.NodeVisitor):
# Non-empty tag. Place the auxiliary <span> tag
# *inside* the element, as the first child.
suffix += '<span id="%s"></span>' % id
- attlist = atts.items()
- attlist.sort()
+ attlist = sorted(atts.items())
parts = [tagname]
for name, value in attlist:
# value=None was used for boolean attributes without
diff --git a/docutils/writers/latex2e/__init__.py b/docutils/writers/latex2e/__init__.py
index e21c74b..249ec4a 100644
--- a/docutils/writers/latex2e/__init__.py
+++ b/docutils/writers/latex2e/__init__.py
@@ -457,8 +457,7 @@ class SortableDict(dict):
"""
def sortedkeys(self):
"""Return sorted list of keys"""
- keys = self.keys()
- keys.sort()
+ keys = sorted(self.keys())
return keys
def sortedvalues(self):
diff --git a/test/DocutilsTestSupport.py b/test/DocutilsTestSupport.py
index a1fec25..21ea982 100644
--- a/test/DocutilsTestSupport.py
+++ b/test/DocutilsTestSupport.py
@@ -815,8 +815,7 @@ class HtmlWriterPublishPartsTestCase(WriterPublishTestCase):
if not parts[key]:
del parts[key]
# standard output format:
- keys = parts.keys()
- keys.sort()
+ keys = sorted(parts.keys())
output = []
for key in keys:
output.append("%r: '''%s'''"
diff --git a/test/test_dependencies.py b/test/test_dependencies.py
index 298e8a4..0939b6d 100755
--- a/test/test_dependencies.py
+++ b/test/test_dependencies.py
@@ -54,9 +54,8 @@ class RecordDependenciesTests(unittest.TestCase):
if PIL:
keys += ['figure-image']
expected = [paths[key] for key in keys]
- record = self.get_record(writer_name='xml')
+ record = sorted(self.get_record(writer_name='xml'))
# the order of the files is arbitrary
- record.sort()
expected.sort()
self.assertEqual(record, expected)
@@ -67,9 +66,8 @@ class RecordDependenciesTests(unittest.TestCase):
expected = [paths[key] for key in keys]
# stylesheets are tested separately in test_stylesheet_dependencies():
so = {'stylesheet_path': None, 'stylesheet': None}
- record = self.get_record(writer_name='html', settings_overrides=so)
+ record = sorted(self.get_record(writer_name='html', settings_overrides=so))
# the order of the files is arbitrary
- record.sort()
expected.sort()
self.assertEqual(record, expected)
@@ -82,9 +80,8 @@ class RecordDependenciesTests(unittest.TestCase):
if PIL:
keys += ['figure-image']
expected = [paths[key] for key in keys]
- record = self.get_record(writer_name='latex')
+ record = sorted(self.get_record(writer_name='latex'))
# the order of the files is arbitrary
- record.sort()
expected.sort()
self.assertEqual(record, expected)
diff --git a/test/test_language.py b/test/test_language.py
index 30af81a..31ac613 100755
--- a/test/test_language.py
+++ b/test/test_language.py
@@ -150,8 +150,7 @@ class LanguageTestCase(DocutilsTestSupport.CustomTestCase):
except Exception as error:
failures.append('"%s": %s' % (d, error))
inverted = self._invert(module.directives)
- canonical = directives._directive_registry.keys()
- canonical.sort()
+ canonical = sorted(directives._directive_registry.keys())
canonical.remove('restructuredtext-test-directive')
for name in canonical:
if name not in inverted:
@@ -185,8 +184,7 @@ class LanguageTestCase(DocutilsTestSupport.CustomTestCase):
except KeyError as error:
failures.append('"%s": %s' % (d, error))
inverted = self._invert(module.roles)
- canonical = roles._role_registry.keys()
- canonical.sort()
+ canonical = sorted(roles._role_registry.keys())
canonical.remove('restructuredtext-unimplemented-role')
for name in canonical:
if name not in inverted:
diff --git a/tools/dev/generate_punctuation_chars.py b/tools/dev/generate_punctuation_chars.py
index a30c5ca..b718f78 100644
--- a/tools/dev/generate_punctuation_chars.py
+++ b/tools/dev/generate_punctuation_chars.py
@@ -269,8 +269,7 @@ def mark_intervals(s):
Sort string and replace 'cdef' by 'c-f' and similar.
"""
l =[]
- s = [ord(ch) for ch in s]
- s.sort()
+ s = sorted([ord(ch) for ch in s])
for n in s:
try:
if l[-1][-1]+1 == n:
diff --git a/tools/dev/unicode2rstsubs.py b/tools/dev/unicode2rstsubs.py
index b51eec4..ac38bf4 100755
--- a/tools/dev/unicode2rstsubs.py
+++ b/tools/dev/unicode2rstsubs.py
@@ -163,8 +163,7 @@ class CharacterEntitySetExtractor(object):
return name
def write_sets(self):
- sets = list(self.sets.keys())
- sets.sort()
+ sets = sorted(self.sets.keys())
for set_name in sets:
self.write_set(set_name)
@@ -177,8 +176,7 @@ class CharacterEntitySetExtractor(object):
print('writing file "%s"' % outname)
outfile.write(self.header + '\n')
set = self.sets[set_name]
- entities = [(e.lower(), e) for e in set.keys()]
- entities.sort()
+ entities = sorted([(e.lower(), e) for e in set.keys()])
longest = 0
for _, entity_name in entities:
longest = max(longest, len(entity_name))
--
2.24.0.375.geb5ae68d41

View file

@ -0,0 +1,49 @@
From 792080ad1d8ac28483c9c147b0cb79f108b40571 Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Mon, 26 Aug 2019 16:45:09 +0000
Subject: [PATCH 11/26] Cleanup/simplify code following recent changes.
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8358 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/transforms/__init__.py | 4 ++--
docutils/writers/odf_odt/__init__.py | 8 ++------
2 files changed, 4 insertions(+), 8 deletions(-)
diff --git a/docutils/transforms/__init__.py b/docutils/transforms/__init__.py
index d444fce..12bf6f9 100644
--- a/docutils/transforms/__init__.py
+++ b/docutils/transforms/__init__.py
@@ -153,8 +153,8 @@ class Transformer(TransformSpec):
unknown_reference_resolvers = []
for i in components:
unknown_reference_resolvers.extend(i.unknown_reference_resolvers)
- decorated_list = sorted([(f.priority, f) for f in unknown_reference_resolvers])
- self.unknown_reference_resolvers.extend([f[1] for f in decorated_list])
+ decorated_list = sorted((f.priority, f) for f in unknown_reference_resolvers)
+ self.unknown_reference_resolvers.extend(f[1] for f in decorated_list)
def apply_transforms(self):
"""Apply all of the stored transforms, in priority order."""
diff --git a/docutils/writers/odf_odt/__init__.py b/docutils/writers/odf_odt/__init__.py
index c0f43a5..417dc34 100644
--- a/docutils/writers/odf_odt/__init__.py
+++ b/docutils/writers/odf_odt/__init__.py
@@ -68,12 +68,8 @@ except ImportError:
try:
import pygments
import pygments.lexers
- if sys.version_info.major >= 3:
- from .pygmentsformatter import OdtPygmentsProgFormatter, \
- OdtPygmentsLaTeXFormatter
- else:
- from .pygmentsformatter import OdtPygmentsProgFormatter, \
- OdtPygmentsLaTeXFormatter
+ from .pygmentsformatter import (OdtPygmentsProgFormatter,
+ OdtPygmentsLaTeXFormatter)
except (ImportError, SyntaxError):
pygments = None
--
2.24.0.375.geb5ae68d41

View file

@ -0,0 +1,120 @@
From 88fdde83419b6c532948a64d2824f6a663ad33c3 Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Mon, 26 Aug 2019 16:45:33 +0000
Subject: [PATCH 12/26] Use 'isinstance(foo, bar)' instead of 'type(foo) is
bar'
This one is more stylistic than anything.
Signed-off-by: Stephen Finucane <stephen@that.guru>
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8359 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/parsers/rst/directives/tables.py | 4 ++--
docutils/parsers/rst/states.py | 2 +-
docutils/statemachine.py | 2 +-
docutils/utils/math/latex2mathml.py | 2 +-
test/package_unittest.py | 4 ++--
test/test_nodes.py | 2 +-
6 files changed, 8 insertions(+), 8 deletions(-)
diff --git a/docutils/parsers/rst/directives/tables.py b/docutils/parsers/rst/directives/tables.py
index b0a4eac..bf97e26 100644
--- a/docutils/parsers/rst/directives/tables.py
+++ b/docutils/parsers/rst/directives/tables.py
@@ -104,7 +104,7 @@ class Table(Directive):
return self.options.get('widths', '')
def get_column_widths(self, max_cols):
- if type(self.widths) == list:
+ if isinstance(self.widths, list):
if len(self.widths) != max_cols:
error = self.state_machine.reporter.error(
'"%s" widths do not match the number of columns in table '
@@ -152,7 +152,7 @@ class RSTTable(Table):
if 'align' in self.options:
table_node['align'] = self.options.get('align')
tgroup = table_node[0]
- if type(self.widths) == list:
+ if isinstance(self.widths, list):
colspecs = [child for child in tgroup.children
if child.tagname == 'colspec']
for colspec, col_width in zip(colspecs, self.widths):
diff --git a/docutils/parsers/rst/states.py b/docutils/parsers/rst/states.py
index c9b4fa3..2a2e33a 100644
--- a/docutils/parsers/rst/states.py
+++ b/docutils/parsers/rst/states.py
@@ -447,7 +447,7 @@ def build_regexp(definition, compile=True):
name, prefix, suffix, parts = definition
part_strings = []
for part in parts:
- if type(part) is tuple:
+ if isinstance(part, tuple):
part_strings.append(build_regexp(part, None))
else:
part_strings.append(part)
diff --git a/docutils/statemachine.py b/docutils/statemachine.py
index 068083a..6bc03f5 100644
--- a/docutils/statemachine.py
+++ b/docutils/statemachine.py
@@ -737,7 +737,7 @@ class State(object):
names = []
transitions = {}
for namestate in name_list:
- if type(namestate) is stringtype:
+ if isinstance(namestate, stringtype):
transitions[namestate] = self.make_transition(namestate)
names.append(namestate)
else:
diff --git a/docutils/utils/math/latex2mathml.py b/docutils/utils/math/latex2mathml.py
index 255e96f..b7ba048 100644
--- a/docutils/utils/math/latex2mathml.py
+++ b/docutils/utils/math/latex2mathml.py
@@ -168,7 +168,7 @@ class math(object):
self.children = []
if children is not None:
- if type(children) is list:
+ if isinstance(children, list):
for child in children:
self.append(child)
else:
diff --git a/test/package_unittest.py b/test/package_unittest.py
index 4db826b..1c0f077 100644
--- a/test/package_unittest.py
+++ b/test/package_unittest.py
@@ -115,7 +115,7 @@ def loadTestModules(path, name='', packages=None):
# to cheat:
testSuite.addTest(moduleTests)
continue
- if type(suite) == types.FunctionType:
+ if isinstance(suite, types.FunctionType):
testSuite.addTest(suite())
elif isinstance(suite, unittest.TestSuite):
testSuite.addTest(suite)
@@ -152,7 +152,7 @@ def main(suite=None):
print("Debug: Suite=%s" % suite, file=sys.stderr)
testRunner = unittest.TextTestRunner(verbosity=verbosity)
# run suites (if we were called from test_all) or suite...
- if type(suite) == type([]):
+ if isinstance(suite, type([])):
for s in suite:
testRunner.run(s)
else:
diff --git a/test/test_nodes.py b/test/test_nodes.py
index 679c98e..af04e86 100755
--- a/test/test_nodes.py
+++ b/test/test_nodes.py
@@ -121,7 +121,7 @@ class ElementTests(unittest.TestCase):
self.assertEqual(repr(uelement), "<Element: <#text: 'gr\\xfcn'>>")
else:
self.assertEqual(repr(uelement), u"<Element: <#text: 'grün'>>")
- self.assertTrue(isinstance(repr(uelement),str))
+ self.assertTrue(isinstance(repr(uelement), str))
self.assertEqual(str(element), '<Element>text\nmore</Element>')
self.assertEqual(str(uelement), '<Element>gr\xfcn</Element>')
dom = element.asdom()
--
2.24.0.375.geb5ae68d41

View file

@ -0,0 +1,594 @@
From 7e79a539c426bbbb2932286b2efa2cf03a467e46 Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Wed, 20 Nov 2019 00:02:34 +0700
Subject: [PATCH 13/26] Consistent Python 3 checks.
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8360 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/frontend.py | 2 +-
docutils/io.py | 4 ++--
docutils/nodes.py | 12 ++++++------
docutils/parsers/rst/directives/__init__.py | 2 +-
docutils/parsers/rst/directives/misc.py | 4 ++--
docutils/parsers/rst/directives/tables.py | 4 ++--
docutils/statemachine.py | 2 +-
docutils/transforms/frontmatter.py | 2 +-
docutils/transforms/universal.py | 2 +-
docutils/utils/__init__.py | 2 +-
docutils/utils/error_reporting.py | 2 +-
docutils/writers/_html_base.py | 2 +-
docutils/writers/docutils_xml.py | 4 ++--
docutils/writers/latex2e/__init__.py | 2 +-
docutils/writers/manpage.py | 2 +-
docutils/writers/odf_odt/__init__.py | 2 +-
setup.py | 6 +++---
test/DocutilsTestSupport.py | 4 ++--
test/test__init__.py | 2 +-
test/test_error_reporting.py | 2 +-
test/test_language.py | 2 +-
test/test_nodes.py | 16 ++++++++--------
test/test_parsers/test_parser.py | 2 +-
.../test_rst/test_directives/test_include.py | 2 +-
.../test_rst/test_directives/test_tables.py | 2 +-
.../test_rst/test_directives/test_unicode.py | 2 +-
tools/dev/create_unimap.py | 4 ++--
tools/dev/generate_punctuation_chars.py | 4 ++--
28 files changed, 49 insertions(+), 49 deletions(-)
diff --git a/docutils/frontend.py b/docutils/frontend.py
index 4b389b0..627f603 100644
--- a/docutils/frontend.py
+++ b/docutils/frontend.py
@@ -43,7 +43,7 @@ import docutils.nodes
from docutils.utils.error_reporting import (locale_encoding, SafeString,
ErrorOutput, ErrorString)
-if sys.version_info >= (3, 0):
+if sys.version_info >= (3,0):
unicode = str # noqa
diff --git a/docutils/io.py b/docutils/io.py
index 3cdf00e..fb354fd 100644
--- a/docutils/io.py
+++ b/docutils/io.py
@@ -17,7 +17,7 @@ import codecs
from docutils import TransformSpec
from docutils.utils.error_reporting import locale_encoding, ErrorString, ErrorOutput
-if sys.version_info >= (3, 0):
+if sys.version_info >= (3,0):
unicode = str # noqa
@@ -208,7 +208,7 @@ class FileInput(Input):
def __init__(self, source=None, source_path=None,
encoding=None, error_handler='strict',
autoclose=True,
- mode='r' if sys.version_info >= (3, 4) else 'rU', **kwargs):
+ mode='r' if sys.version_info >= (3,0) else 'rU', **kwargs):
"""
:Parameters:
- `source`: either a file-like object (which is read directly), or
diff --git a/docutils/nodes.py b/docutils/nodes.py
index e29b887..3d714a2 100644
--- a/docutils/nodes.py
+++ b/docutils/nodes.py
@@ -29,7 +29,7 @@ import re
import warnings
import unicodedata
-if sys.version_info >= (3, 0):
+if sys.version_info >= (3,0):
unicode = str # noqa
basestring = str # noqa
@@ -64,7 +64,7 @@ class Node(object):
"""
return True
- if sys.version_info < (3, 0):
+ if sys.version_info < (3,0):
# on 2.x, str(node) will be a byte string with Unicode
# characters > 255 escaped; on 3.x this is no longer necessary
def __str__(self):
@@ -304,7 +304,7 @@ class Node(object):
except IndexError:
return None
-if sys.version_info < (3, 0):
+if sys.version_info < (3,0):
class reprunicode(unicode):
"""
A unicode sub-class that removes the initial u from unicode's repr.
@@ -320,7 +320,7 @@ def ensure_str(s):
"""
Failsave conversion of `unicode` to `str`.
"""
- if sys.version_info < (3,) and isinstance(s, unicode):
+ if sys.version_info < (3,0) and isinstance(s, unicode):
return s.encode('ascii', 'backslashreplace')
return s
@@ -352,7 +352,7 @@ class Text(Node, reprunicode):
children = ()
"""Text nodes have no children, and cannot have children."""
- if sys.version_info > (3,):
+ if sys.version_info > (3,0):
def __new__(cls, data, rawsource=None):
"""Prevent the rawsource argument from propagating to str."""
if isinstance(data, bytes):
@@ -544,7 +544,7 @@ class Element(Node):
else:
return self.emptytag()
- if sys.version_info > (3,):
+ if sys.version_info > (3,0):
# 2to3 doesn't convert __unicode__ to __str__
__str__ = __unicode__
diff --git a/docutils/parsers/rst/directives/__init__.py b/docutils/parsers/rst/directives/__init__.py
index 7bccb5b..14fe1ff 100644
--- a/docutils/parsers/rst/directives/__init__.py
+++ b/docutils/parsers/rst/directives/__init__.py
@@ -16,7 +16,7 @@ from docutils import nodes
from docutils.utils import split_escaped_whitespace, escape2null, unescape
from docutils.parsers.rst.languages import en as _fallback_language_module
-if sys.version_info >= (3, 0):
+if sys.version_info >= (3,0):
unichr = chr # noqa
diff --git a/docutils/parsers/rst/directives/misc.py b/docutils/parsers/rst/directives/misc.py
index 0fc3610..3b9b9de 100644
--- a/docutils/parsers/rst/directives/misc.py
+++ b/docutils/parsers/rst/directives/misc.py
@@ -473,7 +473,7 @@ class Date(Directive):
'Invalid context: the "%s" directive can only be used within '
'a substitution definition.' % self.name)
format_str = '\n'.join(self.content) or '%Y-%m-%d'
- if sys.version_info< (3, 0):
+ if sys.version_info< (3,0):
try:
format_str = format_str.encode(locale_encoding or 'utf-8')
except UnicodeEncodeError:
@@ -498,7 +498,7 @@ class Date(Directive):
# time.gmtime(int(source_date_epoch)))
# else:
text = time.strftime(format_str)
- if sys.version_info< (3, 0):
+ if sys.version_info< (3,0):
# `text` is a byte string that may contain non-ASCII characters:
try:
text = text.decode(locale_encoding or 'utf-8')
diff --git a/docutils/parsers/rst/directives/tables.py b/docutils/parsers/rst/directives/tables.py
index bf97e26..36a52e7 100644
--- a/docutils/parsers/rst/directives/tables.py
+++ b/docutils/parsers/rst/directives/tables.py
@@ -263,7 +263,7 @@ class CSVTable(Table):
return [detail.args[0]]
except csv.Error as detail:
message = str(detail)
- if sys.version_info < (3,) and '1-character string' in message:
+ if sys.version_info < (3,0) and '1-character string' in message:
message += '\nwith Python 2.x this must be an ASCII character.'
error = self.state_machine.reporter.error(
'Error with CSV data in "%s" directive:\n%s'
@@ -356,7 +356,7 @@ class CSVTable(Table):
raise SystemMessagePropagation(error)
return csv_data, source
- if sys.version_info < (3,):
+ if sys.version_info < (3,0):
# 2.x csv module doesn't do Unicode
def decode_from_csv(s):
return s.decode('utf-8')
diff --git a/docutils/statemachine.py b/docutils/statemachine.py
index 6bc03f5..16252bb 100644
--- a/docutils/statemachine.py
+++ b/docutils/statemachine.py
@@ -113,7 +113,7 @@ import unicodedata
from docutils import utils
from docutils.utils.error_reporting import ErrorOutput
-if sys.version_info >= (3, 0):
+if sys.version_info >= (3,0):
unicode = str # noqa
diff --git a/docutils/transforms/frontmatter.py b/docutils/transforms/frontmatter.py
index 23b9c95..345e290 100644
--- a/docutils/transforms/frontmatter.py
+++ b/docutils/transforms/frontmatter.py
@@ -28,7 +28,7 @@ from docutils import nodes, utils
from docutils.transforms import TransformError, Transform
-if sys.version_info >= (3, 0):
+if sys.version_info >= (3,0):
unicode = str # noqa
diff --git a/docutils/transforms/universal.py b/docutils/transforms/universal.py
index 49fb2c8..770ec71 100644
--- a/docutils/transforms/universal.py
+++ b/docutils/transforms/universal.py
@@ -24,7 +24,7 @@ from docutils.transforms import TransformError, Transform
from docutils.utils import smartquotes
-if sys.version_info >= (3, 0):
+if sys.version_info >= (3,0):
unicode = str # noqa
diff --git a/docutils/utils/__init__.py b/docutils/utils/__init__.py
index 77c70f8..de39247 100644
--- a/docutils/utils/__init__.py
+++ b/docutils/utils/__init__.py
@@ -22,7 +22,7 @@ from docutils.nodes import unescape
import docutils.io
from docutils.utils.error_reporting import ErrorOutput, SafeString
-if sys.version_info >= (3, 0):
+if sys.version_info >= (3,0):
unicode = str
diff --git a/docutils/utils/error_reporting.py b/docutils/utils/error_reporting.py
index 8fcc816..21bc55b 100644
--- a/docutils/utils/error_reporting.py
+++ b/docutils/utils/error_reporting.py
@@ -65,7 +65,7 @@ else:
locale_encoding = None
-if sys.version_info >= (3, 0):
+if sys.version_info >= (3,0):
unicode = str # noqa
diff --git a/docutils/writers/_html_base.py b/docutils/writers/_html_base.py
index a957311..63d5a5b 100644
--- a/docutils/writers/_html_base.py
+++ b/docutils/writers/_html_base.py
@@ -40,7 +40,7 @@ from docutils.utils.math import (unichar2tex, pick_math_environment,
math2html, latex2mathml, tex2mathml_extern)
-if sys.version_info >= (3, 0):
+if sys.version_info >= (3,0):
unicode = str # noqa
diff --git a/docutils/writers/docutils_xml.py b/docutils/writers/docutils_xml.py
index 34e810d..12306b6 100644
--- a/docutils/writers/docutils_xml.py
+++ b/docutils/writers/docutils_xml.py
@@ -30,7 +30,7 @@ from StringIO import StringIO
import docutils
from docutils import frontend, writers, nodes
-if sys.version_info >= (3, 0):
+if sys.version_info >= (3,0):
unicode = str # noqa
@@ -185,7 +185,7 @@ class XMLTranslator(nodes.GenericNodeVisitor):
self.output.append(xml_string)
self.default_departure(node) # or not?
# Check validity of raw XML:
- if isinstance(xml_string, unicode) and sys.version_info < (3,):
+ if isinstance(xml_string, unicode) and sys.version_info < (3,0):
xml_string = xml_string.encode('utf8')
try:
self.xmlparser.parse(StringIO(xml_string))
diff --git a/docutils/writers/latex2e/__init__.py b/docutils/writers/latex2e/__init__.py
index 249ec4a..2c76b0f 100644
--- a/docutils/writers/latex2e/__init__.py
+++ b/docutils/writers/latex2e/__init__.py
@@ -28,7 +28,7 @@ from docutils.transforms import writer_aux
from docutils.utils.math import pick_math_environment, unichar2tex
-if sys.version_info >= (3, 0):
+if sys.version_info >= (3,0):
unicode = str # noqa
diff --git a/docutils/writers/manpage.py b/docutils/writers/manpage.py
index cbb8648..52cd49c 100644
--- a/docutils/writers/manpage.py
+++ b/docutils/writers/manpage.py
@@ -47,7 +47,7 @@ __docformat__ = 'reStructuredText'
import re
import sys
-if sys.version_info < (3, 0):
+if sys.version_info < (3,0):
range = xrange
import docutils
diff --git a/docutils/writers/odf_odt/__init__.py b/docutils/writers/odf_odt/__init__.py
index 417dc34..75f846c 100644
--- a/docutils/writers/odf_odt/__init__.py
+++ b/docutils/writers/odf_odt/__init__.py
@@ -947,7 +947,7 @@ class ODFTranslator(nodes.GenericNodeVisitor):
self.document.reporter.warning(
'Style "%s" is not a style used by odtwriter.' % (
rststyle, ))
- if sys.version_info.major >= 3:
+ if sys.version_info >= (3,0):
self.format_map[rststyle] = format
else:
self.format_map[rststyle] = format.decode('utf-8')
diff --git a/setup.py b/setup.py
index 4280b98..12c398b 100755
--- a/setup.py
+++ b/setup.py
@@ -13,7 +13,7 @@ try:
from distutils.core import setup, Command
from distutils.command.build import build
from distutils.command.build_py import build_py
- if sys.version_info >= (3,):
+ if sys.version_info >= (3,0):
from distutils.command.build_py import build_py_2to3
from distutils.util import copydir_run_2to3
from distutils.command.install_data import install_data
@@ -27,7 +27,7 @@ except ImportError:
sys.exit(1)
-if sys.version_info >= (3,):
+if sys.version_info >= (3,0):
# copy-convert auxiliary python sources
class copy_build_py_2to3(build_py_2to3):
"""Copy/convert Python source files in given directories recursively.
@@ -97,7 +97,7 @@ def do_setup():
kwargs['cmdclass'] = {'build_data': build_data,
'install_data': smart_install_data}
# Auto-convert source code for Python 3
- if sys.version_info >= (3,):
+ if sys.version_info >= (3,0):
kwargs['cmdclass']['build_py'] = copy_build_py_2to3
else:
kwargs['cmdclass']['build_py'] = build_py
diff --git a/test/DocutilsTestSupport.py b/test/DocutilsTestSupport.py
index 21ea982..390df5b 100644
--- a/test/DocutilsTestSupport.py
+++ b/test/DocutilsTestSupport.py
@@ -89,7 +89,7 @@ except:
import pdb
-if sys.version_info >= (3, 0):
+if sys.version_info >= (3,0):
unicode = str # noqa
@@ -202,7 +202,7 @@ class CustomTestCase(StandardTestCase):
"""`input`, `output`, and `expected` should all be strings."""
if isinstance(input, unicode):
input = input.encode('raw_unicode_escape')
- if sys.version_info > (3,):
+ if sys.version_info > (3,0):
# API difference: Python 3's node.__str__ doesn't escape
#assert expected is None or isinstance(expected, unicode)
if isinstance(expected, bytes):
diff --git a/test/test__init__.py b/test/test__init__.py
index 8f1d749..87ec14f 100644
--- a/test/test__init__.py
+++ b/test/test__init__.py
@@ -16,7 +16,7 @@ import docutils
import docutils.utils
-if sys.version_info >= (3, 0):
+if sys.version_info >= (3,0):
unicode = str # noqa
diff --git a/test/test_error_reporting.py b/test/test_error_reporting.py
index 893082c..4b337e3 100644
--- a/test/test_error_reporting.py
+++ b/test/test_error_reporting.py
@@ -46,7 +46,7 @@ if sys.version_info < (3,0): # problems solved in py3k
print('cannot test error reporting with problematic locales,\n'
'`import locale` failed.')
-if sys.version_info >= (3, 0):
+if sys.version_info >= (3,0):
unicode = str # noqa
diff --git a/test/test_language.py b/test/test_language.py
index 31ac613..455357a 100755
--- a/test/test_language.py
+++ b/test/test_language.py
@@ -26,7 +26,7 @@ _reporter = docutils.utils.new_reporter('', _settings)
reference_language = 'en'
-if sys.version_info >= (3, 0):
+if sys.version_info >= (3,0):
unicode = str # noqa
diff --git a/test/test_nodes.py b/test/test_nodes.py
index af04e86..6805799 100755
--- a/test/test_nodes.py
+++ b/test/test_nodes.py
@@ -17,7 +17,7 @@ from DocutilsTestSupport import nodes, utils
debug = False
-if sys.version_info >= (3, 0):
+if sys.version_info >= (3,0):
unicode = str # noqa
@@ -36,7 +36,7 @@ class TextTests(unittest.TestCase):
self.assertEqual(self.text.shortrepr(),
r"<#text: 'Line 1.\nLine 2.'>")
self.assertEqual(nodes.reprunicode('foo'), u'foo')
- if sys.version_info < (3,):
+ if sys.version_info < (3,0):
self.assertEqual(repr(self.unicode_text), r"<#text: 'M\xf6hren'>")
else:
self.assertEqual(repr(self.unicode_text), u"<#text: 'Möhren'>")
@@ -65,7 +65,7 @@ class TextTests(unittest.TestCase):
self.assertEqual(stripped2, u's noc')
def test_asciirestriction(self):
- if sys.version_info < (3,):
+ if sys.version_info < (3,0):
self.assertRaises(UnicodeDecodeError, nodes.Text,
b'hol%s' % chr(224))
else:
@@ -98,7 +98,7 @@ class ElementTests(unittest.TestCase):
del element['attr']
element['mark'] = u'\u2022'
self.assertEqual(repr(element), '<Element: >')
- if sys.version_info < (3,):
+ if sys.version_info < (3,0):
self.assertEqual(str(element), '<Element mark="\\u2022"/>')
else:
self.assertEqual(str(element), u'<Element mark="\u2022"/>')
@@ -106,7 +106,7 @@ class ElementTests(unittest.TestCase):
self.assertEqual(dom.toxml(), u'<Element mark="\u2022"/>')
dom.unlink()
element['names'] = ['nobody', u'имя', u'näs']
- if sys.version_info < (3,):
+ if sys.version_info < (3,0):
self.assertEqual(repr(element),
'<Element "nobody; \\u0438\\u043c\\u044f; n\\xe4s": >')
else:
@@ -117,7 +117,7 @@ class ElementTests(unittest.TestCase):
element = nodes.Element('text\nmore', nodes.Text('text\nmore'))
uelement = nodes.Element(u'grün', nodes.Text(u'grün'))
self.assertEqual(repr(element), r"<Element: <#text: 'text\nmore'>>")
- if sys.version_info < (3,):
+ if sys.version_info < (3,0):
self.assertEqual(repr(uelement), "<Element: <#text: 'gr\\xfcn'>>")
else:
self.assertEqual(repr(uelement), u"<Element: <#text: 'grün'>>")
@@ -341,7 +341,7 @@ class MiscTests(unittest.TestCase):
self.assertTrue(isinstance(nodes.reprunicode('foo'), unicode))
self.assertEqual(nodes.reprunicode('foo'), u'foo')
self.assertEqual(nodes.reprunicode(u'Möhre'), u'Möhre')
- if sys.version_info < (3,): # strip leading "u" from representation
+ if sys.version_info < (3,0): # strip leading "u" from representation
self.assertEqual(repr(nodes.reprunicode(u'Möhre')),
repr(u'Möhre')[1:])
else: # no change to `unicode` under Python 3k
@@ -350,7 +350,7 @@ class MiscTests(unittest.TestCase):
def test_ensure_str(self):
self.assertTrue(isinstance(nodes.ensure_str(u'über'), str))
self.assertEqual(nodes.ensure_str('over'), 'over')
- if sys.version_info < (3,): # strip leading "u" from representation
+ if sys.version_info < (3,0): # strip leading "u" from representation
self.assertEqual(nodes.ensure_str(u'über'), r'\xfcber')
else:
self.assertEqual(nodes.ensure_str(u'über'), r'über')
diff --git a/test/test_parsers/test_parser.py b/test/test_parsers/test_parser.py
index 6faecc7..6c57963 100644
--- a/test/test_parsers/test_parser.py
+++ b/test/test_parsers/test_parser.py
@@ -23,7 +23,7 @@ class RstParserTests(unittest.TestCase):
document = utils.new_document('test data', frontend.OptionParser(
components=(parser, )).get_default_values())
- if sys.version_info < (3,):
+ if sys.version_info < (3,0):
# supplying string input is supported, but only if ascii-decodable
self.assertRaises(UnicodeDecodeError,
parser.parse, b'hol%s' % chr(224), document)
diff --git a/test/test_parsers/test_rst/test_directives/test_include.py b/test/test_parsers/test_rst/test_directives/test_include.py
index d848262..92d0193 100755
--- a/test/test_parsers/test_rst/test_directives/test_include.py
+++ b/test/test_parsers/test_rst/test_directives/test_include.py
@@ -16,7 +16,7 @@ from docutils.parsers.rst import states
from docutils.utils.code_analyzer import with_pygments
-if sys.version_info >= (3, 0):
+if sys.version_info >= (3,0):
unichr = chr # noqa
diff --git a/test/test_parsers/test_rst/test_directives/test_tables.py b/test/test_parsers/test_rst/test_directives/test_tables.py
index ee930c8..9d417e8 100755
--- a/test/test_parsers/test_rst/test_directives/test_tables.py
+++ b/test/test_parsers/test_rst/test_directives/test_tables.py
@@ -18,7 +18,7 @@ from docutils.parsers.rst.directives import tables
from . import DocutilsTestSupport
-if sys.version_info >= (3, 0):
+if sys.version_info >= (3,0):
unicode = str # noqa
unichr = chr # noqa
diff --git a/test/test_parsers/test_rst/test_directives/test_unicode.py b/test/test_parsers/test_rst/test_directives/test_unicode.py
index b99b5d0..576bc1d 100755
--- a/test/test_parsers/test_rst/test_directives/test_unicode.py
+++ b/test/test_parsers/test_rst/test_directives/test_unicode.py
@@ -14,7 +14,7 @@ import sys
from . import DocutilsTestSupport
-if sys.version_info >= (3, 0):
+if sys.version_info >= (3,0):
unichr = chr # noqa
diff --git a/tools/dev/create_unimap.py b/tools/dev/create_unimap.py
index 74e8bc7..808861d 100755
--- a/tools/dev/create_unimap.py
+++ b/tools/dev/create_unimap.py
@@ -14,7 +14,7 @@ from xml.dom import minidom
import sys
import pprint
-if sys.version_info >= (3, 0):
+if sys.version_info >= (3,0):
unicode = str #noqa
else:
bytes = str # noqa
@@ -22,7 +22,7 @@ else:
def w(s):
- if sys.version_info >= (3, 0) and isinstance(s, unicode):
+ if sys.version_info >= (3,0) and isinstance(s, unicode):
s = s.encode('utf8')
sys.stdout.write(s)
diff --git a/tools/dev/generate_punctuation_chars.py b/tools/dev/generate_punctuation_chars.py
index b718f78..fbb72c0 100644
--- a/tools/dev/generate_punctuation_chars.py
+++ b/tools/dev/generate_punctuation_chars.py
@@ -38,7 +38,7 @@ from __future__ import print_function
import sys
import unicodedata
-if sys.version_info >= (3,):
+if sys.version_info >= (3,0):
unichr = chr # unichr not available in Py3k
else:
import codecs
@@ -361,7 +361,7 @@ if __name__ == '__main__':
# Import the punctuation_chars module from the source
# or Py3k build path for local Python modules::
- if sys.version_info < (3,):
+ if sys.version_info < (3,0):
sys.path.insert(0, '../../docutils')
else:
sys.path.insert(0, '../../build/lib')
--
2.24.0.375.geb5ae68d41

View file

@ -0,0 +1,74 @@
From cfef74f567498f1e097761bc3cae7c0bde2451cc Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Mon, 26 Aug 2019 16:46:50 +0000
Subject: [PATCH 14/26] py3: Replace 'foo.next()' with 'next(foo)'
The former only works in Python 2, while the latter works in Python 2.7
and 3.x.
Signed-off-by: Stephen Finucane <stephen@that.guru>
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8361 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/utils/code_analyzer.py | 2 +-
docutils/utils/math/math2html.py | 2 +-
docutils/writers/manpage.py | 2 +-
test/test_parsers/test_rst/test_directives/test_tables.py | 2 +-
4 files changed, 4 insertions(+), 4 deletions(-)
diff --git a/docutils/utils/code_analyzer.py b/docutils/utils/code_analyzer.py
index 6dc2e15..87a4584 100644
--- a/docutils/utils/code_analyzer.py
+++ b/docutils/utils/code_analyzer.py
@@ -83,7 +83,7 @@ class Lexer(object):
Also strip the final newline (added by pygments).
"""
tokens = iter(tokens)
- (lasttype, lastval) = tokens.next()
+ (lasttype, lastval) = next(tokens)
for ttype, value in tokens:
if ttype is lasttype:
lastval += value
diff --git a/docutils/utils/math/math2html.py b/docutils/utils/math/math2html.py
index adcb1cc..ddaca48 100644
--- a/docutils/utils/math/math2html.py
+++ b/docutils/utils/math/math2html.py
@@ -2208,7 +2208,7 @@ class Container(object):
if ord(pos.current()) > 128:
codepoint = hex(ord(pos.current()))
if codepoint == '0xd835':
- codepoint = hex(ord(pos.next()) + 0xf800)
+ codepoint = hex(ord(next(pos)) + 0xf800)
result += '&#' + codepoint[1:] + ';'
else:
result += pos.current()
diff --git a/docutils/writers/manpage.py b/docutils/writers/manpage.py
index 52cd49c..b39cf25 100644
--- a/docutils/writers/manpage.py
+++ b/docutils/writers/manpage.py
@@ -812,7 +812,7 @@ class Translator(nodes.NodeVisitor):
def visit_list_item(self, node):
# man 7 man argues to use ".IP" instead of ".TP"
self.body.append('.IP %s %d\n' % (
- self._list_char[-1].next(),
+ next(self._list_char[-1]),
self._list_char[-1].get_width(),))
def depart_list_item(self, node):
diff --git a/test/test_parsers/test_rst/test_directives/test_tables.py b/test/test_parsers/test_rst/test_directives/test_tables.py
index 9d417e8..cc450f3 100755
--- a/test/test_parsers/test_rst/test_directives/test_tables.py
+++ b/test/test_parsers/test_rst/test_directives/test_tables.py
@@ -59,7 +59,7 @@ def null_bytes():
csv_data = unicode(csv_data, 'latin1').splitlines()
reader = csv.reader([tables.CSVTable.encode_for_csv(line + '\n')
for line in csv_data])
- reader.next()
+ next(reader)
null_bytes_exception = DocutilsTestSupport.exception_data(null_bytes)[0]
--
2.24.0.375.geb5ae68d41

View file

@ -0,0 +1,38 @@
From 006366f7baaf84baf0158ccd9036c9a53d27c965 Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Mon, 26 Aug 2019 23:12:56 +0000
Subject: [PATCH 15/26] py3: Replace 'foo.has_key(bar)' with 'bar in foo'
Signed-off-by: Stephen Finucane <stephen@that.guru>
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8362 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/writers/manpage.py | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/docutils/writers/manpage.py b/docutils/writers/manpage.py
index b39cf25..8bb025c 100644
--- a/docutils/writers/manpage.py
+++ b/docutils/writers/manpage.py
@@ -312,7 +312,7 @@ class Translator(nodes.NodeVisitor):
def __init__(self, style):
self._style = style
- if node.has_key('start'):
+ if 'start' in node:
self._cnt = node['start'] - 1
else:
self._cnt = 0
@@ -354,7 +354,7 @@ class Translator(nodes.NodeVisitor):
def __repr__(self):
return 'enum_style-%s' % list(self._style)
- if node.has_key('enumtype'):
+ if 'enumtype' in node:
self._list_char.append(enum_char(node['enumtype']))
else:
self._list_char.append(enum_char('bullet'))
--
2.24.0.375.geb5ae68d41

View file

@ -0,0 +1,47 @@
From bf370651321ed721777fe0bb1c4bd4652eea354c Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Mon, 26 Aug 2019 23:13:04 +0000
Subject: [PATCH 16/26] Remove duplicate definition of
`nodes.Element.__contains__`.
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8363 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/nodes.py | 14 ++++++--------
1 file changed, 6 insertions(+), 8 deletions(-)
diff --git a/docutils/nodes.py b/docutils/nodes.py
index 3d714a2..f8da02b 100644
--- a/docutils/nodes.py
+++ b/docutils/nodes.py
@@ -577,13 +577,6 @@ class Element(Node):
def __len__(self):
return len(self.children)
- def __contains__(self, key):
- # support both membership test for children and attributes
- # (has_key is translated to "in" by 2to3)
- if isinstance(key, basestring):
- return key in self.attributes
- return key in self.children
-
def __getitem__(self, key):
if isinstance(key, basestring):
return self.attributes[key]
@@ -668,7 +661,12 @@ class Element(Node):
has_key = hasattr
# support operator ``in``
- __contains__ = hasattr
+ def __contains__(self, key):
+ # support both membership test for children and attributes
+ # (has_key is translated to "in" by 2to3)
+ if isinstance(key, basestring):
+ return key in self.attributes
+ return key in self.children
def get_language_code(self, fallback=''):
"""Return node's language tag.
--
2.24.0.375.geb5ae68d41

View file

@ -0,0 +1,93 @@
From bcc08592dd85f2e7805ab3528659a4396f109b30 Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Wed, 20 Nov 2019 00:05:43 +0700
Subject: [PATCH 17/26] Handle 'ConfigParser' to 'configparser' rename.
Based on a patch by Stephen Finucane.
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8364 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/frontend.py | 14 +++++++++-----
docutils/writers/odf_odt/__init__.py | 4 ++--
2 files changed, 11 insertions(+), 7 deletions(-)
diff --git a/docutils/frontend.py b/docutils/frontend.py
index 627f603..815343d 100644
--- a/docutils/frontend.py
+++ b/docutils/frontend.py
@@ -33,10 +33,14 @@ import os
import os.path
import sys
import warnings
-import ConfigParser as CP
import codecs
import optparse
from optparse import SUPPRESS_HELP
+if sys.version_info >= (3,0):
+ from configparser import RawConfigParser
+else:
+ from ConfigParser import RawConfigParser
+
import docutils
import docutils.utils
import docutils.nodes
@@ -735,7 +739,7 @@ class OptionParser(optparse.OptionParser, docutils.SettingsSpec):
raise KeyError('No option with dest == %r.' % dest)
-class ConfigParser(CP.RawConfigParser):
+class ConfigParser(RawConfigParser):
old_settings = {
'pep_stylesheet': ('pep_html writer', 'stylesheet'),
@@ -757,7 +761,7 @@ Skipping "%s" configuration file.
"""
def __init__(self, *args, **kwargs):
- CP.RawConfigParser.__init__(self, *args, **kwargs)
+ RawConfigParser.__init__(self, *args, **kwargs)
self._files = []
"""List of paths of configuration files read."""
@@ -776,9 +780,9 @@ Skipping "%s" configuration file.
continue
try:
if sys.version_info < (3,2):
- CP.RawConfigParser.readfp(self, fp, filename)
+ RawConfigParser.readfp(self, fp, filename)
else:
- CP.RawConfigParser.read_file(self, fp, filename)
+ RawConfigParser.read_file(self, fp, filename)
except UnicodeDecodeError:
self._stderr.write(self.not_utf8_error % (filename, filename))
fp.close()
diff --git a/docutils/writers/odf_odt/__init__.py b/docutils/writers/odf_odt/__init__.py
index 75f846c..f36980f 100644
--- a/docutils/writers/odf_odt/__init__.py
+++ b/docutils/writers/odf_odt/__init__.py
@@ -30,10 +30,12 @@ from docutils import frontend, nodes, utils, writers, languages
from docutils.readers import standalone
from docutils.transforms import references
if type(sys.version_info)!=type((0,)) and sys.version_info.major >= 3:
+ from configparser import ConfigParser
from io import StringIO
from urllib.request import urlopen
from urllib.error import HTTPError
else:
+ from ConfigParser import ConfigParser
from StringIO import StringIO
from urllib2 import urlopen, HTTPError
@@ -938,8 +940,6 @@ class ODFTranslator(nodes.GenericNodeVisitor):
document.reporter)
self.format_map = {}
if self.settings.odf_config_file:
- from configparser import ConfigParser
-
parser = ConfigParser()
parser.read(self.settings.odf_config_file)
for rststyle, format in parser.items("Formats"):
--
2.24.0.375.geb5ae68d41

View file

@ -0,0 +1,599 @@
From ac408c7ed04500c83a47861c5ac88aee246d178c Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Tue, 27 Aug 2019 12:09:19 +0000
Subject: [PATCH 18/26] py3: Replace 'ur' prefix
While the 'u' prefix was backported to Python 3.3 or thereabouts, 'ur'
remains invalid in Python 3. Just escape all backslashes and use plain
old 'u'.
Based on patch by Stephen Finucane <stephen@that.guru>
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8366 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/utils/math/latex2mathml.py | 28 +-
docutils/utils/math/tex2mathml_extern.py | 3 +-
docutils/utils/smartquotes.py | 24 +-
docutils/writers/latex2e/__init__.py | 280 +++++++++---------
docutils/writers/manpage.py | 8 +-
.../test_rst/test_east_asian_text.py | 4 +-
tools/dev/generate_punctuation_chars.py | 10 +-
7 files changed, 182 insertions(+), 175 deletions(-)
diff --git a/docutils/utils/math/latex2mathml.py b/docutils/utils/math/latex2mathml.py
index b7ba048..1f3bc18 100644
--- a/docutils/utils/math/latex2mathml.py
+++ b/docutils/utils/math/latex2mathml.py
@@ -6,12 +6,12 @@
# Based on rst2mathml.py from the latex_math sandbox project
# © 2005 Jens Jørgen Mortensen
# :License: Released under the terms of the `2-Clause BSD license`_, in short:
-#
+#
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved.
# This file is offered as-is, without any warranty.
-#
+#
# .. _2-Clause BSD license: http://www.spdx.org/licenses/BSD-2-Clause
@@ -412,7 +412,7 @@ def parse_latex_math(string, inline=True):
node = entry
skip = 2
else:
- raise SyntaxError(ur'Syntax error: "%s%s"' % (c, c2))
+ raise SyntaxError(u'Syntax error: "%s%s"' % (c, c2))
elif c.isalpha():
node = node.append(mi(c))
elif c.isdigit():
@@ -453,7 +453,7 @@ def parse_latex_math(string, inline=True):
node.close().append(entry)
node = entry
else:
- raise SyntaxError(ur'Illegal character: "%s"' % c)
+ raise SyntaxError(u'Illegal character: "%s"' % c)
string = string[skip:]
return tree
@@ -474,15 +474,15 @@ def handle_keyword(name, node, string):
node = entry
elif name == 'end':
if not string.startswith('{matrix}'):
- raise SyntaxError(ur'Expected "\end{matrix}"!')
+ raise SyntaxError(u'Expected "\\end{matrix}"!')
skip += 8
node = node.close().close().close()
elif name in ('text', 'mathrm'):
if string[0] != '{':
- raise SyntaxError(ur'Expected "\text{...}"!')
+ raise SyntaxError(u'Expected "\\text{...}"!')
i = string.find('}')
if i == -1:
- raise SyntaxError(ur'Expected "\text{...}"!')
+ raise SyntaxError(u'Expected "\\text{...}"!')
node = node.append(mtext(string[1:i]))
skip += i + 1
elif name == 'sqrt':
@@ -520,7 +520,7 @@ def handle_keyword(name, node, string):
if string.startswith(operator):
break
else:
- raise SyntaxError(ur'Expected something to negate: "\not ..."!')
+ raise SyntaxError(u'Expected something to negate: "\\not ..."!')
node = node.append(mo(negatables[operator]))
skip += len(operator)
elif name == 'mathbf':
@@ -529,12 +529,12 @@ def handle_keyword(name, node, string):
node = style
elif name == 'mathbb':
if string[0] != '{' or not string[1].isupper() or string[2] != '}':
- raise SyntaxError(ur'Expected something like "\mathbb{A}"!')
+ raise SyntaxError(u'Expected something like "\\mathbb{A}"!')
node = node.append(mi(mathbb[string[1]]))
skip += 3
elif name in ('mathscr', 'mathcal'):
if string[0] != '{' or string[2] != '}':
- raise SyntaxError(ur'Expected something like "\mathscr{A}"!')
+ raise SyntaxError(u'Expected something like "\\mathscr{A}"!')
node = node.append(mi(mathscr[string[1]]))
skip += 3
elif name == 'colon': # "normal" colon, not binary operator
@@ -559,12 +559,10 @@ def handle_keyword(name, node, string):
return node, skip
def tex2mathml(tex_math, inline=True):
- """Return string with MathML code corresponding to `tex_math`.
-
+ """Return string with MathML code corresponding to `tex_math`.
+
`inline`=True is for inline math and `inline`=False for displayed math.
"""
-
+
mathml_tree = parse_latex_math(tex_math, inline=inline)
return ''.join(mathml_tree.xml())
-
-
diff --git a/docutils/utils/math/tex2mathml_extern.py b/docutils/utils/math/tex2mathml_extern.py
index 3e7f158..ab82a78 100644
--- a/docutils/utils/math/tex2mathml_extern.py
+++ b/docutils/utils/math/tex2mathml_extern.py
@@ -141,7 +141,8 @@ def blahtexml(math_code, inline=True, reporter=None):
# self-test
if __name__ == "__main__":
- example = ur'\frac{\partial \sin^2(\alpha)}{\partial \vec r} \varpi \, \text{Grüße}'
+ example = (u'\\frac{\\partial \\sin^2(\\alpha)}{\\partial \\vec r}'
+ u'\\varpi \\, \\text{Grüße}')
# print(latexml(example).encode('utf8'))
# print(ttm(example))
print(blahtexml(example).encode('utf8'))
diff --git a/docutils/utils/smartquotes.py b/docutils/utils/smartquotes.py
index 148a4c9..b38fa47 100644
--- a/docutils/utils/smartquotes.py
+++ b/docutils/utils/smartquotes.py
@@ -658,20 +658,21 @@ def educateQuotes(text, language='en'):
text = re.sub(r"'(?=\d{2}s)", smart.apostrophe, text)
# Get most opening single quotes:
- opening_single_quotes_regex = re.compile(ur"""
+ opening_single_quotes_regex = re.compile(u"""
(# ?<= # look behind fails: requires fixed-width pattern
- \s | # a whitespace char, or
+ \\s | # a whitespace char, or
%s | # another separating char, or
&nbsp; | # a non-breaking space entity, or
- [–—] | # literal dashes, or
+ [\u2013 \u2014 ] | # literal dashes, or
-- | # dumb dashes, or
&[mn]dash; | # dash entities (named or
%s | # decimal or
- &\#x201[34]; # hex)
+ &\\#x201[34]; # hex)
)
' # the quote
- (?=\w) # followed by a word character
- """ % (open_class,dec_dashes), re.VERBOSE | re.UNICODE)
+ (?=\\w) # followed by a word character
+ """ % (open_class, dec_dashes), re.VERBOSE | re.UNICODE)
+
text = opening_single_quotes_regex.sub(r'\1'+smart.osquote, text)
# In many locales, single closing quotes are different from apostrophe:
@@ -691,20 +692,21 @@ def educateQuotes(text, language='en'):
text = re.sub(r"""'""", smart.osquote, text)
# Get most opening double quotes:
- opening_double_quotes_regex = re.compile(ur"""
+ opening_double_quotes_regex = re.compile(u"""
(
- \s | # a whitespace char, or
+ \\s | # a whitespace char, or
%s | # another separating char, or
&nbsp; | # a non-breaking space entity, or
- [–—] | # literal dashes, or
+ [\u2013 \u2014 ] | # literal dashes, or
-- | # dumb dashes, or
&[mn]dash; | # dash entities (named or
%s | # decimal or
- &\#x201[34]; # hex)
+ &\\#x201[34]; # hex)
)
" # the quote
- (?=\w) # followed by a word character
+ (?=\\w) # followed by a word character
""" % (open_class,dec_dashes), re.VERBOSE | re.UNICODE)
+
text = opening_double_quotes_regex.sub(r'\1'+smart.opquote, text)
# Double closing quotes:
diff --git a/docutils/writers/latex2e/__init__.py b/docutils/writers/latex2e/__init__.py
index 2c76b0f..636d477 100644
--- a/docutils/writers/latex2e/__init__.py
+++ b/docutils/writers/latex2e/__init__.py
@@ -704,165 +704,165 @@ class CharMaps(object):
# characters that need escaping even in `alltt` environments:
alltt = {
- ord('\\'): ur'\textbackslash{}',
- ord('{'): ur'\{',
- ord('}'): ur'\}',
+ ord('\\'): u'\\textbackslash{}',
+ ord('{'): u'\\{',
+ ord('}'): u'\\}',
}
# characters that normally need escaping:
special = {
- ord('#'): ur'\#',
- ord('$'): ur'\$',
- ord('%'): ur'\%',
- ord('&'): ur'\&',
- ord('~'): ur'\textasciitilde{}',
- ord('_'): ur'\_',
- ord('^'): ur'\textasciicircum{}',
+ ord('#'): u'\\#',
+ ord('$'): u'\\$',
+ ord('%'): u'\\%',
+ ord('&'): u'\\&',
+ ord('~'): u'\\textasciitilde{}',
+ ord('_'): u'\\_',
+ ord('^'): u'\\textasciicircum{}',
# straight double quotes are 'active' in many languages
- ord('"'): ur'\textquotedbl{}',
+ ord('"'): u'\\textquotedbl{}',
# Square brackets are ordinary chars and cannot be escaped with '\',
# so we put them in a group '{[}'. (Alternative: ensure that all
# macros with optional arguments are terminated with {} and text
# inside any optional argument is put in a group ``[{text}]``).
# Commands with optional args inside an optional arg must be put in a
# group, e.g. ``\item[{\hyperref[label]{text}}]``.
- ord('['): ur'{[}',
- ord(']'): ur'{]}',
+ ord('['): u'{[}',
+ ord(']'): u'{]}',
# the soft hyphen is unknown in 8-bit text
# and not properly handled by XeTeX
- 0x00AD: ur'\-', # SOFT HYPHEN
+ 0x00AD: u'\\-', # SOFT HYPHEN
}
# Unicode chars that are not recognized by LaTeX's utf8 encoding
unsupported_unicode = {
# TODO: ensure white space also at the beginning of a line?
- # 0x00A0: ur'\leavevmode\nobreak\vadjust{}~'
- 0x2000: ur'\enskip', # EN QUAD
- 0x2001: ur'\quad', # EM QUAD
- 0x2002: ur'\enskip', # EN SPACE
- 0x2003: ur'\quad', # EM SPACE
- 0x2008: ur'\,', # PUNCTUATION SPACE
- 0x200b: ur'\hspace{0pt}', # ZERO WIDTH SPACE
- 0x202F: ur'\,', # NARROW NO-BREAK SPACE
- # 0x02d8: ur'\\u{ }', # BREVE
- 0x2011: ur'\hbox{-}', # NON-BREAKING HYPHEN
- 0x212b: ur'\AA', # ANGSTROM SIGN
- 0x21d4: ur'\ensuremath{\Leftrightarrow}',
+ # 0x00A0: u'\\leavevmode\\nobreak\\vadjust{}~'
+ 0x2000: u'\\enskip', # EN QUAD
+ 0x2001: u'\\quad', # EM QUAD
+ 0x2002: u'\\enskip', # EN SPACE
+ 0x2003: u'\\quad', # EM SPACE
+ 0x2008: u'\\,', # PUNCTUATION SPACE
+ 0x200b: u'\\hspace{0pt}', # ZERO WIDTH SPACE
+ 0x202F: u'\\,', # NARROW NO-BREAK SPACE
+ # 0x02d8: u'\\\u{ }', # BREVE
+ 0x2011: u'\\hbox{-}', # NON-BREAKING HYPHEN
+ 0x212b: u'\\AA', # ANGSTROM SIGN
+ 0x21d4: u'\\ensuremath{\\Leftrightarrow}',
# Docutils footnote symbols:
- 0x2660: ur'\ensuremath{\spadesuit}',
- 0x2663: ur'\ensuremath{\clubsuit}',
- 0xfb00: ur'ff', # LATIN SMALL LIGATURE FF
- 0xfb01: ur'fi', # LATIN SMALL LIGATURE FI
- 0xfb02: ur'fl', # LATIN SMALL LIGATURE FL
- 0xfb03: ur'ffi', # LATIN SMALL LIGATURE FFI
- 0xfb04: ur'ffl', # LATIN SMALL LIGATURE FFL
+ 0x2660: u'\\ensuremath{\\spadesuit}',
+ 0x2663: u'\\ensuremath{\\clubsuit}',
+ 0xfb00: u'ff', # LATIN SMALL LIGATURE FF
+ 0xfb01: u'fi', # LATIN SMALL LIGATURE FI
+ 0xfb02: u'fl', # LATIN SMALL LIGATURE FL
+ 0xfb03: u'ffi', # LATIN SMALL LIGATURE FFI
+ 0xfb04: u'ffl', # LATIN SMALL LIGATURE FFL
}
# Unicode chars that are recognized by LaTeX's utf8 encoding
utf8_supported_unicode = {
- 0x00A0: ur'~', # NO-BREAK SPACE
- 0x00AB: ur'\guillemotleft{}', # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
- 0x00bb: ur'\guillemotright{}', # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
- 0x200C: ur'\textcompwordmark{}', # ZERO WIDTH NON-JOINER
- 0x2013: ur'\textendash{}',
- 0x2014: ur'\textemdash{}',
- 0x2018: ur'\textquoteleft{}',
- 0x2019: ur'\textquoteright{}',
- 0x201A: ur'\quotesinglbase{}', # SINGLE LOW-9 QUOTATION MARK
- 0x201C: ur'\textquotedblleft{}',
- 0x201D: ur'\textquotedblright{}',
- 0x201E: ur'\quotedblbase{}', # DOUBLE LOW-9 QUOTATION MARK
- 0x2030: ur'\textperthousand{}', # PER MILLE SIGN
- 0x2031: ur'\textpertenthousand{}', # PER TEN THOUSAND SIGN
- 0x2039: ur'\guilsinglleft{}',
- 0x203A: ur'\guilsinglright{}',
- 0x2423: ur'\textvisiblespace{}', # OPEN BOX
- 0x2020: ur'\dag{}',
- 0x2021: ur'\ddag{}',
- 0x2026: ur'\dots{}',
- 0x2122: ur'\texttrademark{}',
+ 0x00A0: u'~', # NO-BREAK SPACE
+ 0x00AB: u'\\guillemotleft{}', # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
+ 0x00bb: u'\\guillemotright{}', # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
+ 0x200C: u'\\textcompwordmark{}', # ZERO WIDTH NON-JOINER
+ 0x2013: u'\\textendash{}',
+ 0x2014: u'\\textemdash{}',
+ 0x2018: u'\\textquoteleft{}',
+ 0x2019: u'\\textquoteright{}',
+ 0x201A: u'\\quotesinglbase{}', # SINGLE LOW-9 QUOTATION MARK
+ 0x201C: u'\\textquotedblleft{}',
+ 0x201D: u'\\textquotedblright{}',
+ 0x201E: u'\\quotedblbase{}', # DOUBLE LOW-9 QUOTATION MARK
+ 0x2030: u'\\textperthousand{}', # PER MILLE SIGN
+ 0x2031: u'\\textpertenthousand{}', # PER TEN THOUSAND SIGN
+ 0x2039: u'\\guilsinglleft{}',
+ 0x203A: u'\\guilsinglright{}',
+ 0x2423: u'\\textvisiblespace{}', # OPEN BOX
+ 0x2020: u'\\dag{}',
+ 0x2021: u'\\ddag{}',
+ 0x2026: u'\\dots{}',
+ 0x2122: u'\\texttrademark{}',
}
# recognized with 'utf8', if textcomp is loaded
textcomp = {
# Latin-1 Supplement
- 0x00a2: ur'\textcent{}', # ¢ CENT SIGN
- 0x00a4: ur'\textcurrency{}', # ¤ CURRENCY SYMBOL
- 0x00a5: ur'\textyen{}', # ¥ YEN SIGN
- 0x00a6: ur'\textbrokenbar{}', # ¦ BROKEN BAR
- 0x00a7: ur'\textsection{}', # § SECTION SIGN
- 0x00a8: ur'\textasciidieresis{}', # ¨ DIAERESIS
- 0x00a9: ur'\textcopyright{}', # © COPYRIGHT SIGN
- 0x00aa: ur'\textordfeminine{}', # ª FEMININE ORDINAL INDICATOR
- 0x00ac: ur'\textlnot{}', # ¬ NOT SIGN
- 0x00ae: ur'\textregistered{}', # ® REGISTERED SIGN
- 0x00af: ur'\textasciimacron{}', # ¯ MACRON
- 0x00b0: ur'\textdegree{}', # ° DEGREE SIGN
- 0x00b1: ur'\textpm{}', # ± PLUS-MINUS SIGN
- 0x00b2: ur'\texttwosuperior{}', # ² SUPERSCRIPT TWO
- 0x00b3: ur'\textthreesuperior{}', # ³ SUPERSCRIPT THREE
- 0x00b4: ur'\textasciiacute{}', # ´ ACUTE ACCENT
- 0x00b5: ur'\textmu{}', # µ MICRO SIGN
- 0x00b6: ur'\textparagraph{}', # ¶ PILCROW SIGN # != \textpilcrow
- 0x00b9: ur'\textonesuperior{}', # ¹ SUPERSCRIPT ONE
- 0x00ba: ur'\textordmasculine{}', # º MASCULINE ORDINAL INDICATOR
- 0x00bc: ur'\textonequarter{}', # 1/4 FRACTION
- 0x00bd: ur'\textonehalf{}', # 1/2 FRACTION
- 0x00be: ur'\textthreequarters{}', # 3/4 FRACTION
- 0x00d7: ur'\texttimes{}', # × MULTIPLICATION SIGN
- 0x00f7: ur'\textdiv{}', # ÷ DIVISION SIGN
+ 0x00a2: u'\\textcent{}', # ¢ CENT SIGN
+ 0x00a4: u'\\textcurrency{}', # ¤ CURRENCY SYMBOL
+ 0x00a5: u'\\textyen{}', # ¥ YEN SIGN
+ 0x00a6: u'\\textbrokenbar{}', # ¦ BROKEN BAR
+ 0x00a7: u'\\textsection{}', # § SECTION SIGN
+ 0x00a8: u'\\textasciidieresis{}', # ¨ DIAERESIS
+ 0x00a9: u'\\textcopyright{}', # © COPYRIGHT SIGN
+ 0x00aa: u'\\textordfeminine{}', # ª FEMININE ORDINAL INDICATOR
+ 0x00ac: u'\\textlnot{}', # ¬ NOT SIGN
+ 0x00ae: u'\\textregistered{}', # ® REGISTERED SIGN
+ 0x00af: u'\\textasciimacron{}', # ¯ MACRON
+ 0x00b0: u'\\textdegree{}', # ° DEGREE SIGN
+ 0x00b1: u'\\textpm{}', # ± PLUS-MINUS SIGN
+ 0x00b2: u'\\texttwosuperior{}', # ² SUPERSCRIPT TWO
+ 0x00b3: u'\\textthreesuperior{}', # ³ SUPERSCRIPT THREE
+ 0x00b4: u'\\textasciiacute{}', # ´ ACUTE ACCENT
+ 0x00b5: u'\\textmu{}', # µ MICRO SIGN
+ 0x00b6: u'\\textparagraph{}', # ¶ PILCROW SIGN # != \textpilcrow
+ 0x00b9: u'\\textonesuperior{}', # ¹ SUPERSCRIPT ONE
+ 0x00ba: u'\\textordmasculine{}', # º MASCULINE ORDINAL INDICATOR
+ 0x00bc: u'\\textonequarter{}', # 1/4 FRACTION
+ 0x00bd: u'\\textonehalf{}', # 1/2 FRACTION
+ 0x00be: u'\\textthreequarters{}', # 3/4 FRACTION
+ 0x00d7: u'\\texttimes{}', # × MULTIPLICATION SIGN
+ 0x00f7: u'\\textdiv{}', # ÷ DIVISION SIGN
# others
- 0x0192: ur'\textflorin{}', # LATIN SMALL LETTER F WITH HOOK
- 0x02b9: ur'\textasciiacute{}', # MODIFIER LETTER PRIME
- 0x02ba: ur'\textacutedbl{}', # MODIFIER LETTER DOUBLE PRIME
- 0x2016: ur'\textbardbl{}', # DOUBLE VERTICAL LINE
- 0x2022: ur'\textbullet{}', # BULLET
- 0x2032: ur'\textasciiacute{}', # PRIME
- 0x2033: ur'\textacutedbl{}', # DOUBLE PRIME
- 0x2035: ur'\textasciigrave{}', # REVERSED PRIME
- 0x2036: ur'\textgravedbl{}', # REVERSED DOUBLE PRIME
- 0x203b: ur'\textreferencemark{}', # REFERENCE MARK
- 0x203d: ur'\textinterrobang{}', # INTERROBANG
- 0x2044: ur'\textfractionsolidus{}', # FRACTION SLASH
- 0x2045: ur'\textlquill{}', # LEFT SQUARE BRACKET WITH QUILL
- 0x2046: ur'\textrquill{}', # RIGHT SQUARE BRACKET WITH QUILL
- 0x2052: ur'\textdiscount{}', # COMMERCIAL MINUS SIGN
- 0x20a1: ur'\textcolonmonetary{}', # COLON SIGN
- 0x20a3: ur'\textfrenchfranc{}', # FRENCH FRANC SIGN
- 0x20a4: ur'\textlira{}', # LIRA SIGN
- 0x20a6: ur'\textnaira{}', # NAIRA SIGN
- 0x20a9: ur'\textwon{}', # WON SIGN
- 0x20ab: ur'\textdong{}', # DONG SIGN
- 0x20ac: ur'\texteuro{}', # EURO SIGN
- 0x20b1: ur'\textpeso{}', # PESO SIGN
- 0x20b2: ur'\textguarani{}', # GUARANI SIGN
- 0x2103: ur'\textcelsius{}', # DEGREE CELSIUS
- 0x2116: ur'\textnumero{}', # NUMERO SIGN
- 0x2117: ur'\textcircledP{}', # SOUND RECORDING COYRIGHT
- 0x211e: ur'\textrecipe{}', # PRESCRIPTION TAKE
- 0x2120: ur'\textservicemark{}', # SERVICE MARK
- 0x2122: ur'\texttrademark{}', # TRADE MARK SIGN
- 0x2126: ur'\textohm{}', # OHM SIGN
- 0x2127: ur'\textmho{}', # INVERTED OHM SIGN
- 0x212e: ur'\textestimated{}', # ESTIMATED SYMBOL
- 0x2190: ur'\textleftarrow{}', # LEFTWARDS ARROW
- 0x2191: ur'\textuparrow{}', # UPWARDS ARROW
- 0x2192: ur'\textrightarrow{}', # RIGHTWARDS ARROW
- 0x2193: ur'\textdownarrow{}', # DOWNWARDS ARROW
- 0x2212: ur'\textminus{}', # MINUS SIGN
- 0x2217: ur'\textasteriskcentered{}', # ASTERISK OPERATOR
- 0x221a: ur'\textsurd{}', # SQUARE ROOT
- 0x2422: ur'\textblank{}', # BLANK SYMBOL
- 0x25e6: ur'\textopenbullet{}', # WHITE BULLET
- 0x25ef: ur'\textbigcircle{}', # LARGE CIRCLE
- 0x266a: ur'\textmusicalnote{}', # EIGHTH NOTE
- 0x26ad: ur'\textmarried{}', # MARRIAGE SYMBOL
- 0x26ae: ur'\textdivorced{}', # DIVORCE SYMBOL
- 0x27e8: ur'\textlangle{}', # MATHEMATICAL LEFT ANGLE BRACKET
- 0x27e9: ur'\textrangle{}', # MATHEMATICAL RIGHT ANGLE BRACKET
+ 0x0192: u'\\textflorin{}', # LATIN SMALL LETTER F WITH HOOK
+ 0x02b9: u'\\textasciiacute{}', # MODIFIER LETTER PRIME
+ 0x02ba: u'\\textacutedbl{}', # MODIFIER LETTER DOUBLE PRIME
+ 0x2016: u'\\textbardbl{}', # DOUBLE VERTICAL LINE
+ 0x2022: u'\\textbullet{}', # BULLET
+ 0x2032: u'\\textasciiacute{}', # PRIME
+ 0x2033: u'\\textacutedbl{}', # DOUBLE PRIME
+ 0x2035: u'\\textasciigrave{}', # REVERSED PRIME
+ 0x2036: u'\\textgravedbl{}', # REVERSED DOUBLE PRIME
+ 0x203b: u'\\textreferencemark{}', # REFERENCE MARK
+ 0x203d: u'\\textinterrobang{}', # INTERROBANG
+ 0x2044: u'\\textfractionsolidus{}', # FRACTION SLASH
+ 0x2045: u'\\textlquill{}', # LEFT SQUARE BRACKET WITH QUILL
+ 0x2046: u'\\textrquill{}', # RIGHT SQUARE BRACKET WITH QUILL
+ 0x2052: u'\\textdiscount{}', # COMMERCIAL MINUS SIGN
+ 0x20a1: u'\\textcolonmonetary{}', # COLON SIGN
+ 0x20a3: u'\\textfrenchfranc{}', # FRENCH FRANC SIGN
+ 0x20a4: u'\\textlira{}', # LIRA SIGN
+ 0x20a6: u'\\textnaira{}', # NAIRA SIGN
+ 0x20a9: u'\\textwon{}', # WON SIGN
+ 0x20ab: u'\\textdong{}', # DONG SIGN
+ 0x20ac: u'\\texteuro{}', # EURO SIGN
+ 0x20b1: u'\\textpeso{}', # PESO SIGN
+ 0x20b2: u'\\textguarani{}', # GUARANI SIGN
+ 0x2103: u'\\textcelsius{}', # DEGREE CELSIUS
+ 0x2116: u'\\textnumero{}', # NUMERO SIGN
+ 0x2117: u'\\textcircledP{}', # SOUND RECORDING COYRIGHT
+ 0x211e: u'\\textrecipe{}', # PRESCRIPTION TAKE
+ 0x2120: u'\\textservicemark{}', # SERVICE MARK
+ 0x2122: u'\\texttrademark{}', # TRADE MARK SIGN
+ 0x2126: u'\\textohm{}', # OHM SIGN
+ 0x2127: u'\\textmho{}', # INVERTED OHM SIGN
+ 0x212e: u'\\textestimated{}', # ESTIMATED SYMBOL
+ 0x2190: u'\\textleftarrow{}', # LEFTWARDS ARROW
+ 0x2191: u'\\textuparrow{}', # UPWARDS ARROW
+ 0x2192: u'\\textrightarrow{}', # RIGHTWARDS ARROW
+ 0x2193: u'\\textdownarrow{}', # DOWNWARDS ARROW
+ 0x2212: u'\\textminus{}', # MINUS SIGN
+ 0x2217: u'\\textasteriskcentered{}', # ASTERISK OPERATOR
+ 0x221a: u'\\textsurd{}', # SQUARE ROOT
+ 0x2422: u'\\textblank{}', # BLANK SYMBOL
+ 0x25e6: u'\\textopenbullet{}', # WHITE BULLET
+ 0x25ef: u'\\textbigcircle{}', # LARGE CIRCLE
+ 0x266a: u'\\textmusicalnote{}', # EIGHTH NOTE
+ 0x26ad: u'\\textmarried{}', # MARRIAGE SYMBOL
+ 0x26ae: u'\\textdivorced{}', # DIVORCE SYMBOL
+ 0x27e8: u'\\textlangle{}', # MATHEMATICAL LEFT ANGLE BRACKET
+ 0x27e9: u'\\textrangle{}', # MATHEMATICAL RIGHT ANGLE BRACKET
}
# Unicode chars that require a feature/package to render
pifont = {
- 0x2665: ur'\ding{170}', # black heartsuit
- 0x2666: ur'\ding{169}', # black diamondsuit
- 0x2713: ur'\ding{51}', # check mark
- 0x2717: ur'\ding{55}', # check mark
+ 0x2665: u'\\ding{170}', # black heartsuit
+ 0x2666: u'\\ding{169}', # black diamondsuit
+ 0x2713: u'\\ding{51}', # check mark
+ 0x2717: u'\\ding{55}', # check mark
}
# TODO: greek alphabet ... ?
# see also LaTeX codec
@@ -1511,14 +1511,14 @@ class LaTeXTranslator(nodes.NodeVisitor):
# the backslash doesn't work, so we use a mirrored slash.
# \reflectbox is provided by graphicx:
self.requirements['graphicx'] = self.graphicx_package
- table[ord('\\')] = ur'\reflectbox{/}'
+ table[ord('\\')] = u'\\reflectbox{/}'
# * ``< | >`` come out as different chars (except for cmtt):
else:
- table[ord('|')] = ur'\textbar{}'
- table[ord('<')] = ur'\textless{}'
- table[ord('>')] = ur'\textgreater{}'
+ table[ord('|')] = u'\\textbar{}'
+ table[ord('<')] = u'\\textless{}'
+ table[ord('>')] = u'\\textgreater{}'
if self.insert_non_breaking_blanks:
- table[ord(' ')] = ur'~'
+ table[ord(' ')] = u'~'
# tab chars may occur in included files (literal or code)
# quick-and-dirty replacement with spaces
# (for better results use `--literal-block-env=lstlisting`)
@@ -2618,7 +2618,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
math_code = '\n'.join([math_code] + self.ids_to_labels(node))
if math_env == '$':
if self.alltt:
- wrapper = ur'\(%s\)'
+ wrapper = u'\\(%s\\)'
else:
wrapper = u'$%s$'
else:
@@ -2769,9 +2769,9 @@ class LaTeXTranslator(nodes.NodeVisitor):
def visit_reference(self, node):
# We need to escape #, \, and % if we use the URL in a command.
- special_chars = {ord('#'): ur'\#',
- ord('%'): ur'\%',
- ord('\\'): ur'\\',
+ special_chars = {ord('#'): u'\\#',
+ ord('%'): u'\\%',
+ ord('\\'): u'\\\\',
}
# external reference (URL)
if 'refuri' in node:
diff --git a/docutils/writers/manpage.py b/docutils/writers/manpage.py
index 8bb025c..ed163de 100644
--- a/docutils/writers/manpage.py
+++ b/docutils/writers/manpage.py
@@ -284,10 +284,10 @@ class Translator(nodes.NodeVisitor):
text = node.astext()
text = text.replace('\\','\\e')
replace_pairs = [
- (u'-', ur'\-'),
- (u'\'', ur'\(aq'),
- (u'´', ur'\''),
- (u'`', ur'\(ga'),
+ (u'-', u'\\-'),
+ (u'\'', u'\\(aq'),
+ (u'´', u"\\'"),
+ (u'`', u'\\(ga'),
]
for (in_char, out_markup) in replace_pairs:
text = text.replace(in_char, out_markup)
diff --git a/test/test_parsers/test_rst/test_east_asian_text.py b/test/test_parsers/test_rst/test_east_asian_text.py
index d819ef8..a13c969 100755
--- a/test/test_parsers/test_rst/test_east_asian_text.py
+++ b/test/test_parsers/test_rst/test_east_asian_text.py
@@ -50,12 +50,12 @@ u"""\
タイトル2
========
"""],
-[ur"""
+[u"""
+-----------------------+
| * ヒョウ:ダイ1ギョウ |
| * ダイ2ギョウ |
+-----------------------+
-| \* ダイ1ギョウ |
+| \\* ダイ1ギョウ |
| * ダイ2ギョウ |
+-----------------------+
""",
diff --git a/tools/dev/generate_punctuation_chars.py b/tools/dev/generate_punctuation_chars.py
index fbb72c0..cfe97df 100644
--- a/tools/dev/generate_punctuation_chars.py
+++ b/tools/dev/generate_punctuation_chars.py
@@ -375,10 +375,16 @@ if __name__ == '__main__':
print_differences(openers, o, 'openers')
if o_wide:
- print('+ openers-wide = ur"""%s"""' % o_wide.encode('utf8'))
+ if sys.version_info < (3, 0):
+ print('+ openers-wide = ur"""%s"""' % o_wide.encode('utf8'))
+ else:
+ print('+ openers-wide = r"""%s"""' % o_wide.encode('utf8'))
print_differences(closers, c, 'closers')
if c_wide:
- print('+ closers-wide = ur"""%s"""' % c_wide.encode('utf8'))
+ if sys.version_info < (3, 0):
+ print('+ closers-wide = ur"""%s"""' % c_wide.encode('utf8'))
+ else:
+ print('+ closers-wide = r"""%s"""' % c_wide.encode('utf8'))
print_differences(delimiters, d + d_wide, 'delimiters')
print_differences(closing_delimiters, cd, 'closing_delimiters')
--
2.24.0.375.geb5ae68d41

View file

@ -0,0 +1,920 @@
From 2e6a65d93d4616f702bbc1f0f5b18c562e403956 Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Wed, 20 Nov 2019 00:08:33 +0700
Subject: [PATCH 19/26] Formatting changes to facilitate integration of "py3"
patchset.
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8367 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/_compat.py | 2 +-
docutils/core.py | 2 +-
docutils/frontend.py | 4 ++--
docutils/io.py | 18 +++++++++---------
docutils/nodes.py | 12 ++++++------
docutils/parsers/rst/directives/__init__.py | 2 +-
docutils/parsers/rst/directives/misc.py | 4 ++--
docutils/parsers/rst/directives/tables.py | 4 ++--
docutils/statemachine.py | 2 +-
docutils/transforms/frontmatter.py | 2 +-
docutils/transforms/universal.py | 2 +-
docutils/utils/__init__.py | 8 ++++----
docutils/utils/error_reporting.py | 4 ++--
docutils/utils/math/math2html.py | 6 +++---
docutils/writers/_html_base.py | 2 +-
docutils/writers/docutils_xml.py | 4 ++--
docutils/writers/latex2e/__init__.py | 2 +-
docutils/writers/manpage.py | 2 +-
docutils/writers/odf_odt/__init__.py | 5 +++--
setup.py | 6 +++---
test/DocutilsTestSupport.py | 6 +++---
test/test__init__.py | 2 +-
test/test_command_line.py | 2 +-
test/test_error_reporting.py | 4 ++--
test/test_functional.py | 8 ++++----
test/test_io.py | 8 ++++----
test/test_language.py | 2 +-
test/test_nodes.py | 16 ++++++++--------
test/test_parsers/test_parser.py | 2 +-
.../test_rst/test_directives/test_include.py | 4 ++--
.../test_rst/test_directives/test_raw.py | 2 +-
.../test_rst/test_directives/test_tables.py | 2 +-
.../test_rst/test_directives/test_unicode.py | 2 +-
tools/dev/create_unimap.py | 4 ++--
tools/dev/generate_punctuation_chars.py | 4 ++--
tools/dev/unicode2rstsubs.py | 2 +-
36 files changed, 82 insertions(+), 81 deletions(-)
diff --git a/docutils/_compat.py b/docutils/_compat.py
index c9de633..1ff959c 100644
--- a/docutils/_compat.py
+++ b/docutils/_compat.py
@@ -14,7 +14,7 @@ This module currently provides the following helper symbols:
import sys
-if sys.version_info < (3,0):
+if sys.version_info < (3, 0):
u_prefix = 'u'
from StringIO import StringIO as BytesIO
else:
diff --git a/docutils/core.py b/docutils/core.py
index 12a0c93..d0db093 100644
--- a/docutils/core.py
+++ b/docutils/core.py
@@ -155,7 +155,7 @@ class Publisher(object):
if argv is None:
argv = sys.argv[1:]
# converting to Unicode (Python 3 does this automatically):
- if sys.version_info < (3,0):
+ if sys.version_info < (3, 0):
# TODO: make this failsafe and reversible?
argv_encoding = (frontend.locale_encoding or 'ascii')
argv = [a.decode(argv_encoding) for a in argv]
diff --git a/docutils/frontend.py b/docutils/frontend.py
index 815343d..7bfff6a 100644
--- a/docutils/frontend.py
+++ b/docutils/frontend.py
@@ -36,7 +36,7 @@ import warnings
import codecs
import optparse
from optparse import SUPPRESS_HELP
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
from configparser import RawConfigParser
else:
from ConfigParser import RawConfigParser
@@ -47,7 +47,7 @@ import docutils.nodes
from docutils.utils.error_reporting import (locale_encoding, SafeString,
ErrorOutput, ErrorString)
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
unicode = str # noqa
diff --git a/docutils/io.py b/docutils/io.py
index fb354fd..9c70f10 100644
--- a/docutils/io.py
+++ b/docutils/io.py
@@ -17,7 +17,7 @@ import codecs
from docutils import TransformSpec
from docutils.utils.error_reporting import locale_encoding, ErrorString, ErrorOutput
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
unicode = str # noqa
@@ -208,7 +208,7 @@ class FileInput(Input):
def __init__(self, source=None, source_path=None,
encoding=None, error_handler='strict',
autoclose=True,
- mode='r' if sys.version_info >= (3,0) else 'rU', **kwargs):
+ mode='r' if sys.version_info >= (3, 0) else 'rU', **kwargs):
"""
:Parameters:
- `source`: either a file-like object (which is read directly), or
@@ -239,7 +239,7 @@ class FileInput(Input):
if source is None:
if source_path:
# Specify encoding in Python 3
- if sys.version_info >= (3,0):
+ if sys.version_info >= (3, 0):
kwargs = {'encoding': self.encoding,
'errors': self.error_handler}
else:
@@ -251,7 +251,7 @@ class FileInput(Input):
raise InputError(error.errno, error.strerror, source_path)
else:
self.source = sys.stdin
- elif (sys.version_info >= (3,0) and
+ elif (sys.version_info >= (3, 0) and
check_encoding(self.source, self.encoding) is False):
# TODO: re-open, warn or raise error?
raise UnicodeError('Encoding clash: encoding given is "%s" '
@@ -268,7 +268,7 @@ class FileInput(Input):
Read and decode a single file and return the data (Unicode string).
"""
try:
- if self.source is sys.stdin and sys.version_info >= (3,0):
+ if self.source is sys.stdin and sys.version_info >= (3, 0):
# read as binary data to circumvent auto-decoding
data = self.source.buffer.read()
# normalize newlines
@@ -358,7 +358,7 @@ class FileOutput(Output):
def open(self):
# Specify encoding in Python 3.
- if sys.version_info >= (3,0) and 'b' not in self.mode:
+ if sys.version_info >= (3, 0) and 'b' not in self.mode:
kwargs = {'encoding': self.encoding,
'errors': self.error_handler}
else:
@@ -378,17 +378,17 @@ class FileOutput(Output):
"""
if not self.opened:
self.open()
- if ('b' not in self.mode and sys.version_info < (3,0)
+ if ('b' not in self.mode and sys.version_info < (3, 0)
or check_encoding(self.destination, self.encoding) is False
):
data = self.encode(data)
- if sys.version_info >= (3,0) and os.linesep != '\n':
+ if sys.version_info >= (3, 0) and os.linesep != '\n':
data = data.replace(b'\n', bytes(os.linesep, 'ascii')) # fix endings
try:
self.destination.write(data)
except TypeError as e:
- if sys.version_info >= (3,0) and isinstance(data, bytes):
+ if sys.version_info >= (3, 0) and isinstance(data, bytes):
try:
self.destination.buffer.write(data)
except AttributeError:
diff --git a/docutils/nodes.py b/docutils/nodes.py
index f8da02b..dd9c4b6 100644
--- a/docutils/nodes.py
+++ b/docutils/nodes.py
@@ -29,7 +29,7 @@ import re
import warnings
import unicodedata
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
unicode = str # noqa
basestring = str # noqa
@@ -64,7 +64,7 @@ class Node(object):
"""
return True
- if sys.version_info < (3,0):
+ if sys.version_info < (3, 0):
# on 2.x, str(node) will be a byte string with Unicode
# characters > 255 escaped; on 3.x this is no longer necessary
def __str__(self):
@@ -304,7 +304,7 @@ class Node(object):
except IndexError:
return None
-if sys.version_info < (3,0):
+if sys.version_info < (3, 0):
class reprunicode(unicode):
"""
A unicode sub-class that removes the initial u from unicode's repr.
@@ -320,7 +320,7 @@ def ensure_str(s):
"""
Failsave conversion of `unicode` to `str`.
"""
- if sys.version_info < (3,0) and isinstance(s, unicode):
+ if sys.version_info < (3, 0) and isinstance(s, unicode):
return s.encode('ascii', 'backslashreplace')
return s
@@ -352,7 +352,7 @@ class Text(Node, reprunicode):
children = ()
"""Text nodes have no children, and cannot have children."""
- if sys.version_info > (3,0):
+ if sys.version_info > (3, 0):
def __new__(cls, data, rawsource=None):
"""Prevent the rawsource argument from propagating to str."""
if isinstance(data, bytes):
@@ -544,7 +544,7 @@ class Element(Node):
else:
return self.emptytag()
- if sys.version_info > (3,0):
+ if sys.version_info > (3, 0):
# 2to3 doesn't convert __unicode__ to __str__
__str__ = __unicode__
diff --git a/docutils/parsers/rst/directives/__init__.py b/docutils/parsers/rst/directives/__init__.py
index 14fe1ff..7bccb5b 100644
--- a/docutils/parsers/rst/directives/__init__.py
+++ b/docutils/parsers/rst/directives/__init__.py
@@ -16,7 +16,7 @@ from docutils import nodes
from docutils.utils import split_escaped_whitespace, escape2null, unescape
from docutils.parsers.rst.languages import en as _fallback_language_module
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
unichr = chr # noqa
diff --git a/docutils/parsers/rst/directives/misc.py b/docutils/parsers/rst/directives/misc.py
index 3b9b9de..0fc3610 100644
--- a/docutils/parsers/rst/directives/misc.py
+++ b/docutils/parsers/rst/directives/misc.py
@@ -473,7 +473,7 @@ class Date(Directive):
'Invalid context: the "%s" directive can only be used within '
'a substitution definition.' % self.name)
format_str = '\n'.join(self.content) or '%Y-%m-%d'
- if sys.version_info< (3,0):
+ if sys.version_info< (3, 0):
try:
format_str = format_str.encode(locale_encoding or 'utf-8')
except UnicodeEncodeError:
@@ -498,7 +498,7 @@ class Date(Directive):
# time.gmtime(int(source_date_epoch)))
# else:
text = time.strftime(format_str)
- if sys.version_info< (3,0):
+ if sys.version_info< (3, 0):
# `text` is a byte string that may contain non-ASCII characters:
try:
text = text.decode(locale_encoding or 'utf-8')
diff --git a/docutils/parsers/rst/directives/tables.py b/docutils/parsers/rst/directives/tables.py
index 36a52e7..b698e08 100644
--- a/docutils/parsers/rst/directives/tables.py
+++ b/docutils/parsers/rst/directives/tables.py
@@ -263,7 +263,7 @@ class CSVTable(Table):
return [detail.args[0]]
except csv.Error as detail:
message = str(detail)
- if sys.version_info < (3,0) and '1-character string' in message:
+ if sys.version_info < (3, 0) and '1-character string' in message:
message += '\nwith Python 2.x this must be an ASCII character.'
error = self.state_machine.reporter.error(
'Error with CSV data in "%s" directive:\n%s'
@@ -356,7 +356,7 @@ class CSVTable(Table):
raise SystemMessagePropagation(error)
return csv_data, source
- if sys.version_info < (3,0):
+ if sys.version_info < (3, 0):
# 2.x csv module doesn't do Unicode
def decode_from_csv(s):
return s.decode('utf-8')
diff --git a/docutils/statemachine.py b/docutils/statemachine.py
index 16252bb..6bc03f5 100644
--- a/docutils/statemachine.py
+++ b/docutils/statemachine.py
@@ -113,7 +113,7 @@ import unicodedata
from docutils import utils
from docutils.utils.error_reporting import ErrorOutput
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
unicode = str # noqa
diff --git a/docutils/transforms/frontmatter.py b/docutils/transforms/frontmatter.py
index 345e290..23b9c95 100644
--- a/docutils/transforms/frontmatter.py
+++ b/docutils/transforms/frontmatter.py
@@ -28,7 +28,7 @@ from docutils import nodes, utils
from docutils.transforms import TransformError, Transform
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
unicode = str # noqa
diff --git a/docutils/transforms/universal.py b/docutils/transforms/universal.py
index 770ec71..49fb2c8 100644
--- a/docutils/transforms/universal.py
+++ b/docutils/transforms/universal.py
@@ -24,7 +24,7 @@ from docutils.transforms import TransformError, Transform
from docutils.utils import smartquotes
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
unicode = str # noqa
diff --git a/docutils/utils/__init__.py b/docutils/utils/__init__.py
index de39247..cc1fd1a 100644
--- a/docutils/utils/__init__.py
+++ b/docutils/utils/__init__.py
@@ -22,7 +22,7 @@ from docutils.nodes import unescape
import docutils.io
from docutils.utils.error_reporting import ErrorOutput, SafeString
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
unicode = str
@@ -592,7 +592,7 @@ def split_escaped_whitespace(text):
return list(itertools.chain(*strings))
def strip_combining_chars(text):
- if isinstance(text, str) and sys.version_info < (3,0):
+ if isinstance(text, str) and sys.version_info < (3, 0):
return text
return u''.join([c for c in text if not unicodedata.combining(c)])
@@ -604,7 +604,7 @@ def find_combining_chars(text):
[3, 6, 9]
"""
- if isinstance(text, str) and sys.version_info < (3,0):
+ if isinstance(text, str) and sys.version_info < (3, 0):
return []
return [i for i,c in enumerate(text) if unicodedata.combining(c)]
@@ -638,7 +638,7 @@ def column_width(text):
Correct ``len(text)`` for wide East Asian and combining Unicode chars.
"""
- if isinstance(text, str) and sys.version_info < (3,0):
+ if isinstance(text, str) and sys.version_info < (3, 0):
return len(text)
width = sum([east_asian_widths[unicodedata.east_asian_width(c)]
for c in text])
diff --git a/docutils/utils/error_reporting.py b/docutils/utils/error_reporting.py
index 21bc55b..02a1dab 100644
--- a/docutils/utils/error_reporting.py
+++ b/docutils/utils/error_reporting.py
@@ -65,7 +65,7 @@ else:
locale_encoding = None
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
unicode = str # noqa
@@ -93,7 +93,7 @@ class SafeString(object):
for arg in self.data.args]
return ', '.join(args)
if isinstance(self.data, unicode):
- if sys.version_info > (3,0):
+ if sys.version_info > (3, 0):
return self.data
else:
return self.data.encode(self.encoding,
diff --git a/docutils/utils/math/math2html.py b/docutils/utils/math/math2html.py
index ddaca48..475519f 100644
--- a/docutils/utils/math/math2html.py
+++ b/docutils/utils/math/math2html.py
@@ -30,7 +30,7 @@ import unicodedata
import urllib
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
unicode = str #noqa
basestring = str # noqa
file = io.IOBase # noqa
@@ -73,7 +73,7 @@ class Trace(object):
def show(cls, message, channel):
"Show a message out of a channel"
- if sys.version_info < (3,0):
+ if sys.version_info < (3, 0):
message = message.encode('utf-8')
channel.write(message + '\n')
@@ -1785,7 +1785,7 @@ class LineWriter(object):
"Write a string"
if not self.file:
self.file = codecs.open(self.filename, 'w', "utf-8")
- if self.file == sys.stdout and sys.version_info < (3,0):
+ if self.file == sys.stdout and sys.version_info < (3, 0):
string = string.encode('utf-8')
self.file.write(string)
diff --git a/docutils/writers/_html_base.py b/docutils/writers/_html_base.py
index 63d5a5b..a957311 100644
--- a/docutils/writers/_html_base.py
+++ b/docutils/writers/_html_base.py
@@ -40,7 +40,7 @@ from docutils.utils.math import (unichar2tex, pick_math_environment,
math2html, latex2mathml, tex2mathml_extern)
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
unicode = str # noqa
diff --git a/docutils/writers/docutils_xml.py b/docutils/writers/docutils_xml.py
index 12306b6..60ee07b 100644
--- a/docutils/writers/docutils_xml.py
+++ b/docutils/writers/docutils_xml.py
@@ -30,7 +30,7 @@ from StringIO import StringIO
import docutils
from docutils import frontend, writers, nodes
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
unicode = str # noqa
@@ -185,7 +185,7 @@ class XMLTranslator(nodes.GenericNodeVisitor):
self.output.append(xml_string)
self.default_departure(node) # or not?
# Check validity of raw XML:
- if isinstance(xml_string, unicode) and sys.version_info < (3,0):
+ if isinstance(xml_string, unicode) and sys.version_info < (3, 0):
xml_string = xml_string.encode('utf8')
try:
self.xmlparser.parse(StringIO(xml_string))
diff --git a/docutils/writers/latex2e/__init__.py b/docutils/writers/latex2e/__init__.py
index 636d477..05b55eb 100644
--- a/docutils/writers/latex2e/__init__.py
+++ b/docutils/writers/latex2e/__init__.py
@@ -28,7 +28,7 @@ from docutils.transforms import writer_aux
from docutils.utils.math import pick_math_environment, unichar2tex
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
unicode = str # noqa
diff --git a/docutils/writers/manpage.py b/docutils/writers/manpage.py
index ed163de..df4f1a3 100644
--- a/docutils/writers/manpage.py
+++ b/docutils/writers/manpage.py
@@ -47,7 +47,7 @@ __docformat__ = 'reStructuredText'
import re
import sys
-if sys.version_info < (3,0):
+if sys.version_info < (3, 0):
range = xrange
import docutils
diff --git a/docutils/writers/odf_odt/__init__.py b/docutils/writers/odf_odt/__init__.py
index f36980f..c79d4c1 100644
--- a/docutils/writers/odf_odt/__init__.py
+++ b/docutils/writers/odf_odt/__init__.py
@@ -37,7 +37,8 @@ if type(sys.version_info)!=type((0,)) and sys.version_info.major >= 3:
else:
from ConfigParser import ConfigParser
from StringIO import StringIO
- from urllib2 import urlopen, HTTPError
+ from urllib2 import HTTPError
+ from urllib2 import urlopen
VERSION = '1.0a'
@@ -947,7 +948,7 @@ class ODFTranslator(nodes.GenericNodeVisitor):
self.document.reporter.warning(
'Style "%s" is not a style used by odtwriter.' % (
rststyle, ))
- if sys.version_info >= (3,0):
+ if sys.version_info >= (3, 0):
self.format_map[rststyle] = format
else:
self.format_map[rststyle] = format.decode('utf-8')
diff --git a/setup.py b/setup.py
index 12c398b..d636f46 100755
--- a/setup.py
+++ b/setup.py
@@ -13,7 +13,7 @@ try:
from distutils.core import setup, Command
from distutils.command.build import build
from distutils.command.build_py import build_py
- if sys.version_info >= (3,0):
+ if sys.version_info >= (3, 0):
from distutils.command.build_py import build_py_2to3
from distutils.util import copydir_run_2to3
from distutils.command.install_data import install_data
@@ -27,7 +27,7 @@ except ImportError:
sys.exit(1)
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
# copy-convert auxiliary python sources
class copy_build_py_2to3(build_py_2to3):
"""Copy/convert Python source files in given directories recursively.
@@ -97,7 +97,7 @@ def do_setup():
kwargs['cmdclass'] = {'build_data': build_data,
'install_data': smart_install_data}
# Auto-convert source code for Python 3
- if sys.version_info >= (3,0):
+ if sys.version_info >= (3, 0):
kwargs['cmdclass']['build_py'] = copy_build_py_2to3
else:
kwargs['cmdclass']['build_py'] = build_py
diff --git a/test/DocutilsTestSupport.py b/test/DocutilsTestSupport.py
index 390df5b..47ba83c 100644
--- a/test/DocutilsTestSupport.py
+++ b/test/DocutilsTestSupport.py
@@ -51,7 +51,7 @@ from pprint import pformat
testroot = os.path.abspath(os.path.dirname(__file__) or os.curdir)
os.chdir(testroot)
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
sys.path.insert(0, os.path.normpath(os.path.join(testroot,
'..', 'build', 'lib')))
sys.path.append(os.path.normpath(os.path.join(testroot, '..',
@@ -89,7 +89,7 @@ except:
import pdb
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
unicode = str # noqa
@@ -202,7 +202,7 @@ class CustomTestCase(StandardTestCase):
"""`input`, `output`, and `expected` should all be strings."""
if isinstance(input, unicode):
input = input.encode('raw_unicode_escape')
- if sys.version_info > (3,0):
+ if sys.version_info > (3, 0):
# API difference: Python 3's node.__str__ doesn't escape
#assert expected is None or isinstance(expected, unicode)
if isinstance(expected, bytes):
diff --git a/test/test__init__.py b/test/test__init__.py
index 87ec14f..8f1d749 100644
--- a/test/test__init__.py
+++ b/test/test__init__.py
@@ -16,7 +16,7 @@ import docutils
import docutils.utils
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
unicode = str # noqa
diff --git a/test/test_command_line.py b/test/test_command_line.py
index eb6ca8a..d9e0850 100644
--- a/test/test_command_line.py
+++ b/test/test_command_line.py
@@ -33,7 +33,7 @@ class CommandLineEncodingTests(unittest.TestCase):
if argv_encoding == 'ascii': # cannot test
return
sys.argv.append('--source-url=test.txt') # pure ASCII argument
- if sys.version_info < (3,0):
+ if sys.version_info < (3, 0):
sys.argv.append(u'--title=Dornröschen'.encode(argv_encoding))
else:
sys.argv.append(u'--title=Dornröschen')
diff --git a/test/test_error_reporting.py b/test/test_error_reporting.py
index 4b337e3..d1509c6 100644
--- a/test/test_error_reporting.py
+++ b/test/test_error_reporting.py
@@ -25,10 +25,10 @@ instances like, e.g., ::
unless the minimal required Python version has this problem fixed.
"""
-import unittest
import sys
import os
import codecs
+import unittest
from io import StringIO, BytesIO
import DocutilsTestSupport # must be imported before docutils
@@ -46,7 +46,7 @@ if sys.version_info < (3,0): # problems solved in py3k
print('cannot test error reporting with problematic locales,\n'
'`import locale` failed.')
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
unicode = str # noqa
diff --git a/test/test_functional.py b/test/test_functional.py
index 5d3beb9..cdc75a0 100755
--- a/test/test_functional.py
+++ b/test/test_functional.py
@@ -160,7 +160,7 @@ expected output and check it in:
output = docutils.core.publish_file(**params)
# ensure output is unicode
output_encoding = params.get('output_encoding', 'utf-8')
- if sys.version_info < (3,0):
+ if sys.version_info < (3, 0):
try:
output = output.decode(output_encoding)
except UnicodeDecodeError:
@@ -172,14 +172,14 @@ expected output and check it in:
no_expected = self.no_expected_template % {
'exp': expected_path, 'out': params['destination_path']}
self.assertTrue(os.access(expected_path, os.R_OK), no_expected)
- if sys.version_info < (3,0):
+ if sys.version_info < (3, 0):
f = open(expected_path, 'r')
else: # samples are UTF8 encoded. 'rb' leads to errors with Python 3!
f = open(expected_path, 'r', encoding='utf-8')
# Normalize line endings:
expected = '\n'.join(f.read().splitlines())
f.close()
- if sys.version_info < (3,0):
+ if sys.version_info < (3, 0):
try:
expected = expected.decode(output_encoding)
except UnicodeDecodeError:
@@ -193,7 +193,7 @@ expected output and check it in:
diff = ''.join(difflib.unified_diff(
expected.splitlines(True), output.splitlines(True),
expected_path, params['destination_path']))
- if sys.version_info < (3,0):
+ if sys.version_info < (3, 0):
diff = diff.encode(sys.stderr.encoding or 'ascii', 'replace')
print('\n%s:' % (self,), file=sys.stderr)
print(diff, file=sys.stderr)
diff --git a/test/test_io.py b/test/test_io.py
index 737a19d..6294613 100755
--- a/test/test_io.py
+++ b/test/test_io.py
@@ -103,7 +103,7 @@ print("hello world")
# if no encoding is given, try decoding with utf8:
input = io.FileInput(source_path='functional/input/cyrillic.txt')
data = input.read()
- if sys.version_info < (3,0):
+ if sys.version_info < (3, 0):
# in Py3k, the locale encoding is used without --input-encoding
# skipping the heuristic
self.assertEqual(input.successful_encoding, 'utf-8')
@@ -111,7 +111,7 @@ print("hello world")
def test_heuristics_no_utf8(self):
# if no encoding is given and decoding with utf8 fails,
# use either the locale encoding (if specified) or latin-1:
- if sys.version_info >= (3,0) and locale_encoding != "utf8":
+ if sys.version_info >= (3, 0) and locale_encoding != "utf8":
# in Py3k, the locale encoding is used without --input-encoding
# skipping the heuristic unless decoding fails.
return
@@ -169,7 +169,7 @@ class OutputTests(unittest.TestCase):
self.assertEqual(self.udrain.getvalue(), self.udata)
def test_write_utf8(self):
- if sys.version_info >= (3,0):
+ if sys.version_info >= (3, 0):
fo = io.FileOutput(destination=self.udrain, encoding='utf8',
autoclose=False)
fo.write(self.udata)
@@ -189,7 +189,7 @@ class OutputTests(unittest.TestCase):
self.assertEqual(self.bdrain.getvalue(), self.bdata)
# Test for Python 3 features:
- if sys.version_info >= (3,0):
+ if sys.version_info >= (3, 0):
def test_write_bytes_to_stdout(self):
# try writing data to `destination.buffer`, if data is
# instance of `bytes` and writing to `destination` fails:
diff --git a/test/test_language.py b/test/test_language.py
index 455357a..31ac613 100755
--- a/test/test_language.py
+++ b/test/test_language.py
@@ -26,7 +26,7 @@ _reporter = docutils.utils.new_reporter('', _settings)
reference_language = 'en'
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
unicode = str # noqa
diff --git a/test/test_nodes.py b/test/test_nodes.py
index 6805799..ec8824e 100755
--- a/test/test_nodes.py
+++ b/test/test_nodes.py
@@ -17,7 +17,7 @@ from DocutilsTestSupport import nodes, utils
debug = False
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
unicode = str # noqa
@@ -36,7 +36,7 @@ class TextTests(unittest.TestCase):
self.assertEqual(self.text.shortrepr(),
r"<#text: 'Line 1.\nLine 2.'>")
self.assertEqual(nodes.reprunicode('foo'), u'foo')
- if sys.version_info < (3,0):
+ if sys.version_info < (3, 0):
self.assertEqual(repr(self.unicode_text), r"<#text: 'M\xf6hren'>")
else:
self.assertEqual(repr(self.unicode_text), u"<#text: 'Möhren'>")
@@ -65,7 +65,7 @@ class TextTests(unittest.TestCase):
self.assertEqual(stripped2, u's noc')
def test_asciirestriction(self):
- if sys.version_info < (3,0):
+ if sys.version_info < (3, 0):
self.assertRaises(UnicodeDecodeError, nodes.Text,
b'hol%s' % chr(224))
else:
@@ -98,7 +98,7 @@ class ElementTests(unittest.TestCase):
del element['attr']
element['mark'] = u'\u2022'
self.assertEqual(repr(element), '<Element: >')
- if sys.version_info < (3,0):
+ if sys.version_info < (3, 0):
self.assertEqual(str(element), '<Element mark="\\u2022"/>')
else:
self.assertEqual(str(element), u'<Element mark="\u2022"/>')
@@ -106,7 +106,7 @@ class ElementTests(unittest.TestCase):
self.assertEqual(dom.toxml(), u'<Element mark="\u2022"/>')
dom.unlink()
element['names'] = ['nobody', u'имя', u'näs']
- if sys.version_info < (3,0):
+ if sys.version_info < (3, 0):
self.assertEqual(repr(element),
'<Element "nobody; \\u0438\\u043c\\u044f; n\\xe4s": >')
else:
@@ -117,7 +117,7 @@ class ElementTests(unittest.TestCase):
element = nodes.Element('text\nmore', nodes.Text('text\nmore'))
uelement = nodes.Element(u'grün', nodes.Text(u'grün'))
self.assertEqual(repr(element), r"<Element: <#text: 'text\nmore'>>")
- if sys.version_info < (3,0):
+ if sys.version_info < (3, 0):
self.assertEqual(repr(uelement), "<Element: <#text: 'gr\\xfcn'>>")
else:
self.assertEqual(repr(uelement), u"<Element: <#text: 'grün'>>")
@@ -341,7 +341,7 @@ class MiscTests(unittest.TestCase):
self.assertTrue(isinstance(nodes.reprunicode('foo'), unicode))
self.assertEqual(nodes.reprunicode('foo'), u'foo')
self.assertEqual(nodes.reprunicode(u'Möhre'), u'Möhre')
- if sys.version_info < (3,0): # strip leading "u" from representation
+ if sys.version_info < (3, 0): # strip leading "u" from representation
self.assertEqual(repr(nodes.reprunicode(u'Möhre')),
repr(u'Möhre')[1:])
else: # no change to `unicode` under Python 3k
@@ -350,7 +350,7 @@ class MiscTests(unittest.TestCase):
def test_ensure_str(self):
self.assertTrue(isinstance(nodes.ensure_str(u'über'), str))
self.assertEqual(nodes.ensure_str('over'), 'over')
- if sys.version_info < (3,0): # strip leading "u" from representation
+ if sys.version_info < (3, 0): # strip leading "u" from representation
self.assertEqual(nodes.ensure_str(u'über'), r'\xfcber')
else:
self.assertEqual(nodes.ensure_str(u'über'), r'über')
diff --git a/test/test_parsers/test_parser.py b/test/test_parsers/test_parser.py
index 6c57963..d2142b4 100644
--- a/test/test_parsers/test_parser.py
+++ b/test/test_parsers/test_parser.py
@@ -23,7 +23,7 @@ class RstParserTests(unittest.TestCase):
document = utils.new_document('test data', frontend.OptionParser(
components=(parser, )).get_default_values())
- if sys.version_info < (3,0):
+ if sys.version_info < (3, 0):
# supplying string input is supported, but only if ascii-decodable
self.assertRaises(UnicodeDecodeError,
parser.parse, b'hol%s' % chr(224), document)
diff --git a/test/test_parsers/test_rst/test_directives/test_include.py b/test/test_parsers/test_rst/test_directives/test_include.py
index 92d0193..31a5c02 100755
--- a/test/test_parsers/test_rst/test_directives/test_include.py
+++ b/test/test_parsers/test_rst/test_directives/test_include.py
@@ -16,7 +16,7 @@ from docutils.parsers.rst import states
from docutils.utils.code_analyzer import with_pygments
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
unichr = chr # noqa
@@ -48,7 +48,7 @@ include_literal = mydir('include_literal.txt')
utf_16_file = mydir('utf-16.csv')
utf_16_error_str = ("UnicodeDecodeError: 'ascii' codec can't decode byte 0xfe "
"in position 0: ordinal not in range(128)")
-if sys.version_info < (3,0):
+if sys.version_info < (3, 0):
utf_16_error_str = ("UnicodeError: Unable to decode input data. "
"Tried the following encodings: 'ascii'.\n"
" (%s)" % utf_16_error_str)
diff --git a/test/test_parsers/test_rst/test_directives/test_raw.py b/test/test_parsers/test_rst/test_directives/test_raw.py
index 2da962a..b86b23f 100755
--- a/test/test_parsers/test_rst/test_directives/test_raw.py
+++ b/test/test_parsers/test_rst/test_directives/test_raw.py
@@ -26,7 +26,7 @@ utf_16_file = os.path.join(mydir, 'utf-16.csv')
utf_16_file_rel = DocutilsTestSupport.utils.relative_path(None, utf_16_file)
utf_16_error_str = ("UnicodeDecodeError: 'ascii' codec can't decode byte 0xfe "
"in position 0: ordinal not in range(128)")
-if sys.version_info < (3,0):
+if sys.version_info < (3, 0):
utf_16_error_str = ("UnicodeError: Unable to decode input data. "
"Tried the following encodings: 'ascii'.\n"
" (%s)" % utf_16_error_str)
diff --git a/test/test_parsers/test_rst/test_directives/test_tables.py b/test/test_parsers/test_rst/test_directives/test_tables.py
index cc450f3..ca27f9a 100755
--- a/test/test_parsers/test_rst/test_directives/test_tables.py
+++ b/test/test_parsers/test_rst/test_directives/test_tables.py
@@ -18,7 +18,7 @@ from docutils.parsers.rst.directives import tables
from . import DocutilsTestSupport
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
unicode = str # noqa
unichr = chr # noqa
diff --git a/test/test_parsers/test_rst/test_directives/test_unicode.py b/test/test_parsers/test_rst/test_directives/test_unicode.py
index 576bc1d..b99b5d0 100755
--- a/test/test_parsers/test_rst/test_directives/test_unicode.py
+++ b/test/test_parsers/test_rst/test_directives/test_unicode.py
@@ -14,7 +14,7 @@ import sys
from . import DocutilsTestSupport
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
unichr = chr # noqa
diff --git a/tools/dev/create_unimap.py b/tools/dev/create_unimap.py
index 808861d..74e8bc7 100755
--- a/tools/dev/create_unimap.py
+++ b/tools/dev/create_unimap.py
@@ -14,7 +14,7 @@ from xml.dom import minidom
import sys
import pprint
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
unicode = str #noqa
else:
bytes = str # noqa
@@ -22,7 +22,7 @@ else:
def w(s):
- if sys.version_info >= (3,0) and isinstance(s, unicode):
+ if sys.version_info >= (3, 0) and isinstance(s, unicode):
s = s.encode('utf8')
sys.stdout.write(s)
diff --git a/tools/dev/generate_punctuation_chars.py b/tools/dev/generate_punctuation_chars.py
index cfe97df..9f211b9 100644
--- a/tools/dev/generate_punctuation_chars.py
+++ b/tools/dev/generate_punctuation_chars.py
@@ -38,7 +38,7 @@ from __future__ import print_function
import sys
import unicodedata
-if sys.version_info >= (3,0):
+if sys.version_info >= (3, 0):
unichr = chr # unichr not available in Py3k
else:
import codecs
@@ -361,7 +361,7 @@ if __name__ == '__main__':
# Import the punctuation_chars module from the source
# or Py3k build path for local Python modules::
- if sys.version_info < (3,0):
+ if sys.version_info < (3, 0):
sys.path.insert(0, '../../docutils')
else:
sys.path.insert(0, '../../build/lib')
diff --git a/tools/dev/unicode2rstsubs.py b/tools/dev/unicode2rstsubs.py
index ac38bf4..028af78 100755
--- a/tools/dev/unicode2rstsubs.py
+++ b/tools/dev/unicode2rstsubs.py
@@ -48,7 +48,7 @@ def main(argv=None):
inpath = 'unicode.xml'
if not os.path.isfile(inpath):
usage(argv[0], 1, 'No such file: "%s".' % inpath)
- if sys.version_info >= (3,0):
+ if sys.version_info >= (3, 0):
infile = open(inpath, mode='rb')
else:
infile = open(inpath)
--
2.24.0.375.geb5ae68d41

View file

@ -0,0 +1,78 @@
From 035c67105f3cbd12ccf6a708f38f1f7f5a17c699 Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Wed, 20 Nov 2019 00:11:04 +0700
Subject: [PATCH 20/26] py3: Handle 'StringIO' to 'io' transition.
This isn't so much a rename as a migration, since things don't do the
same thing.
Based on patch by: Stephen Finucane <stephen@that.guru>
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8368 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/writers/docutils_xml.py | 7 ++++++-
test/test_utils.py | 1 +
test/test_writers/test_docutils_xml.py | 7 ++++++-
3 files changed, 13 insertions(+), 2 deletions(-)
diff --git a/docutils/writers/docutils_xml.py b/docutils/writers/docutils_xml.py
index 60ee07b..51ad6bd 100644
--- a/docutils/writers/docutils_xml.py
+++ b/docutils/writers/docutils_xml.py
@@ -25,11 +25,16 @@ if "_xmlplus" in xml.__path__[0]: # PyXML sub-module
xml.__path__.reverse() # If both are available, prefer stdlib over PyXML
import xml.sax.saxutils
-from StringIO import StringIO
import docutils
from docutils import frontend, writers, nodes
+if sys.version_info >= (3, 0):
+ from io import StringIO # noqa
+else:
+ from StringIO import StringIO # noqa
+
+
if sys.version_info >= (3, 0):
unicode = str # noqa
diff --git a/test/test_utils.py b/test/test_utils.py
index 59e29c8..cb1ec9e 100755
--- a/test/test_utils.py
+++ b/test/test_utils.py
@@ -13,6 +13,7 @@ import unittest
import sys
import os
from DocutilsTestSupport import docutils, utils, nodes
+
try:
from io import StringIO
except ImportError: # io is new in Python 2.6
diff --git a/test/test_writers/test_docutils_xml.py b/test/test_writers/test_docutils_xml.py
index 5a6cda3..ced3473 100755
--- a/test/test_writers/test_docutils_xml.py
+++ b/test/test_writers/test_docutils_xml.py
@@ -15,12 +15,17 @@ Test for docutils XML writer.
"""
from __future__ import absolute_import
-from StringIO import StringIO
+import sys
from . import DocutilsTestSupport # must be imported before docutils
import docutils
import docutils.core
+if sys.version_info >= (3, 0):
+ from io import StringIO
+else:
+ from StringIO import StringIO
+
# sample strings
# --------------
--
2.24.0.375.geb5ae68d41

View file

@ -0,0 +1,91 @@
From 3a610d205259bcf7f22fd8c33c78ffb70829989d Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Wed, 20 Nov 2019 00:14:11 +0700
Subject: [PATCH 21/26] Remove auxiliary Python 2/3 compatibility definition
module.
No longer required since setting minimal supported version to 2.7.
The remaining issues are now handled directly in the affected modules.
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8369 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/_compat.py | 24 ------------------------
test/test_publisher.py | 8 +++++++-
test/test_writers/test_odt.py | 3 +--
3 files changed, 8 insertions(+), 27 deletions(-)
delete mode 100644 docutils/_compat.py
diff --git a/docutils/_compat.py b/docutils/_compat.py
deleted file mode 100644
index 1ff959c..0000000
--- a/docutils/_compat.py
+++ /dev/null
@@ -1,24 +0,0 @@
-# $Id: _compat.py 8164 2017-08-14 11:28:48Z milde $
-# Author: Georg Brandl <georg@python.org>
-# Copyright: This module has been placed in the public domain.
-
-"""
-Python 2/3 compatibility definitions.
-
-This module currently provides the following helper symbols:
-
-* u_prefix (unicode repr prefix: 'u' in 2.x, '' in 3.x)
- (Required in docutils/test/test_publisher.py)
-* BytesIO (a StringIO class that works with bytestrings)
-"""
-
-import sys
-
-if sys.version_info < (3, 0):
- u_prefix = 'u'
- from StringIO import StringIO as BytesIO
-else:
- u_prefix = b''
- # using this hack since 2to3 "fixes" the relative import
- # when using ``from io import BytesIO``
- BytesIO = __import__('io').BytesIO
diff --git a/test/test_publisher.py b/test/test_publisher.py
index 04d9c71..2c3845c 100755
--- a/test/test_publisher.py
+++ b/test/test_publisher.py
@@ -9,10 +9,16 @@ Test the `Publisher` facade and the ``publish_*`` convenience functions.
"""
import pickle
+import sys
+
import DocutilsTestSupport # must be imported before docutils
import docutils
from docutils import core, nodes, io
-from docutils._compat import u_prefix
+
+if sys.version_info < (3, 0):
+ u_prefix = 'u'
+else:
+ u_prefix = b''
test_document = """\
diff --git a/test/test_writers/test_odt.py b/test/test_writers/test_odt.py
index a47b7fb..6ec3ef2 100755
--- a/test/test_writers/test_odt.py
+++ b/test/test_writers/test_odt.py
@@ -36,12 +36,11 @@ import os
import zipfile
from xml.dom import minidom
import tempfile
+from io import BytesIO
from . import DocutilsTestSupport
-
import docutils
import docutils.core
-from docutils._compat import BytesIO
#
# Globals
--
2.24.0.375.geb5ae68d41

View file

@ -0,0 +1,202 @@
From 5ee24817411d9057c738dc1cd7cda8fc5fe03dd6 Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Tue, 27 Aug 2019 12:10:39 +0000
Subject: [PATCH 22/26] py3: Handle 'urllib', 'urllib2' to 'urlib.*' rename
Signed-off-by: Stephen Finucane <stephen@that.guru>
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8370 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/parsers/rst/directives/images.py | 11 +++++++++--
docutils/parsers/rst/directives/misc.py | 10 +++++++---
docutils/parsers/rst/directives/tables.py | 11 ++++++++---
docutils/utils/math/math2html.py | 8 ++++++--
docutils/writers/_html_base.py | 7 +++++--
docutils/writers/latex2e/__init__.py | 9 +++++++--
6 files changed, 42 insertions(+), 14 deletions(-)
diff --git a/docutils/parsers/rst/directives/images.py b/docutils/parsers/rst/directives/images.py
index c813fa3..383075b 100644
--- a/docutils/parsers/rst/directives/images.py
+++ b/docutils/parsers/rst/directives/images.py
@@ -10,12 +10,13 @@ __docformat__ = 'reStructuredText'
import sys
-import urllib
+
from docutils import nodes, utils
from docutils.parsers.rst import Directive
from docutils.parsers.rst import directives, states
from docutils.nodes import fully_normalize_name, whitespace_normalize_name
from docutils.parsers.rst.roles import set_classes
+
try: # check for the Python Imaging Library
import PIL.Image
except ImportError:
@@ -26,6 +27,12 @@ except ImportError:
except ImportError:
PIL = None
+if sys.version_info >= (3, 0):
+ from urllib.request import url2pathname
+else:
+ from urllib import url2pathname
+
+
class Image(Directive):
align_h_values = ('left', 'center', 'right')
@@ -125,7 +132,7 @@ class Figure(Image):
figure_node = nodes.figure('', image_node)
if figwidth == 'image':
if PIL and self.state.document.settings.file_insertion_enabled:
- imagepath = urllib.url2pathname(image_node['uri'])
+ imagepath = url2pathname(image_node['uri'])
try:
img = PIL.Image.open(
imagepath.encode(sys.getfilesystemencoding()))
diff --git a/docutils/parsers/rst/directives/misc.py b/docutils/parsers/rst/directives/misc.py
index 0fc3610..f22dae2 100644
--- a/docutils/parsers/rst/directives/misc.py
+++ b/docutils/parsers/rst/directives/misc.py
@@ -227,10 +227,14 @@ class Raw(Directive):
# Do not import urllib2 at the top of the module because
# it may fail due to broken SSL dependencies, and it takes
# about 0.15 seconds to load.
- import urllib2
+ if sys.version_info >= (3, 0):
+ from urllib.request import urlopen
+ from urllib.error import URLError
+ else:
+ from urllib2 import urlopen, URLError
try:
- raw_text = urllib2.urlopen(source).read()
- except (urllib2.URLError, IOError, OSError) as error:
+ raw_text = urlopen(source).read()
+ except (URLError, IOError, OSError) as error:
raise self.severe(u'Problems with "%s" directive URL "%s":\n%s.'
% (self.name, self.options['url'], ErrorString(error)))
raw_file = io.StringInput(source=raw_text, source_path=source,
diff --git a/docutils/parsers/rst/directives/tables.py b/docutils/parsers/rst/directives/tables.py
index b698e08..6284ab7 100644
--- a/docutils/parsers/rst/directives/tables.py
+++ b/docutils/parsers/rst/directives/tables.py
@@ -332,11 +332,16 @@ class CSVTable(Table):
# Do not import urllib2 at the top of the module because
# it may fail due to broken SSL dependencies, and it takes
# about 0.15 seconds to load.
- import urllib2
+ if sys.version_info >= (3, 0):
+ from urllib.request import urlopen
+ from urllib.error import URLError
+ else:
+ from urllib2 import urlopen, URLError
+
source = self.options['url']
try:
- csv_text = urllib2.urlopen(source).read()
- except (urllib2.URLError, IOError, OSError, ValueError) as error:
+ csv_text = urlopen(source).read()
+ except (URLError, IOError, OSError, ValueError) as error:
severe = self.state_machine.reporter.severe(
'Problems with "%s" directive URL "%s":\n%s.'
% (self.name, self.options['url'], SafeString(error)),
diff --git a/docutils/utils/math/math2html.py b/docutils/utils/math/math2html.py
index 475519f..757dec0 100644
--- a/docutils/utils/math/math2html.py
+++ b/docutils/utils/math/math2html.py
@@ -27,7 +27,11 @@ import io
import os.path
import sys
import unicodedata
-import urllib
+
+if sys.version_info >= (3, 0):
+ from urllib.parse import quote_plus
+else:
+ from urllib import quote_plus
if sys.version_info >= (3, 0):
@@ -2927,7 +2931,7 @@ class Formula(Container):
def googlecharts(self):
"Make the contents using Google Charts http://code.google.com/apis/chart/."
- url = FormulaConfig.urls['googlecharts'] + urllib.quote_plus(self.parsed)
+ url = FormulaConfig.urls['googlecharts'] + quote_plus(self.parsed)
img = '<img class="chart" src="' + url + '" alt="' + self.parsed + '"/>'
self.contents = [Constant(img)]
diff --git a/docutils/writers/_html_base.py b/docutils/writers/_html_base.py
index a957311..f91b06c 100644
--- a/docutils/writers/_html_base.py
+++ b/docutils/writers/_html_base.py
@@ -20,7 +20,6 @@
import sys
import os.path
import re
-import urllib
try: # check for the Python Imaging Library
import PIL.Image
@@ -39,6 +38,10 @@ from docutils.transforms import writer_aux
from docutils.utils.math import (unichar2tex, pick_math_environment,
math2html, latex2mathml, tex2mathml_extern)
+if sys.version_info >= (3, 0):
+ from urllib.request import url2pathname
+else:
+ from urllib import url2pathname
if sys.version_info >= (3, 0):
unicode = str # noqa
@@ -923,7 +926,7 @@ class HTMLTranslator(nodes.NodeVisitor):
if 'scale' in node:
if (PIL and not ('width' in node and 'height' in node)
and self.settings.file_insertion_enabled):
- imagepath = urllib.url2pathname(uri)
+ imagepath = url2pathname(uri)
try:
img = PIL.Image.open(
imagepath.encode(sys.getfilesystemencoding()))
diff --git a/docutils/writers/latex2e/__init__.py b/docutils/writers/latex2e/__init__.py
index 05b55eb..a60de48 100644
--- a/docutils/writers/latex2e/__init__.py
+++ b/docutils/writers/latex2e/__init__.py
@@ -17,16 +17,21 @@ import sys
import os
import re
import string
-import urllib
+
try:
import roman
except ImportError:
import docutils.utils.roman as roman
+
from docutils import frontend, nodes, languages, writers, utils, io
from docutils.utils.error_reporting import SafeString
from docutils.transforms import writer_aux
from docutils.utils.math import pick_math_environment, unichar2tex
+if sys.version_info >= (3, 0):
+ from urllib.request import url2pathname
+else:
+ from urllib import url2pathname
if sys.version_info >= (3, 0):
unicode = str # noqa
@@ -2369,7 +2374,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
self.requirements['graphicx'] = self.graphicx_package
attrs = node.attributes
# Convert image URI to a local file path
- imagepath = urllib.url2pathname(attrs['uri']).replace('\\', '/')
+ imagepath = url2pathname(attrs['uri']).replace('\\', '/')
# alignment defaults:
if not 'align' in attrs:
# Set default align of image in a figure to 'center'
--
2.24.0.375.geb5ae68d41

View file

@ -0,0 +1,352 @@
From 0a68965b7f5880aeb8642a081ff5ebd86a0d1c4e Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Tue, 27 Aug 2019 12:10:52 +0000
Subject: [PATCH 23/26] py3: Fix magic methods
Python 3 uses '__bool__' and '__next__', where Python 2 used
'__nonzero__' and 'next'. Use the new names but add aliases.
Based on patch by Stephen Finucane <stephen@that.guru>
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8371 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/nodes.py | 8 +--
docutils/utils/math/math2html.py | 93 +++++++++++++++++++++++++++-----
docutils/writers/manpage.py | 6 ++-
3 files changed, 89 insertions(+), 18 deletions(-)
diff --git a/docutils/nodes.py b/docutils/nodes.py
index dd9c4b6..6fffa56 100644
--- a/docutils/nodes.py
+++ b/docutils/nodes.py
@@ -53,7 +53,7 @@ class Node(object):
line = None
"""The line number (1-based) of the beginning of this Node in `source`."""
- def __nonzero__(self):
+ def __bool__(self):
"""
Node instances are always true, even if they're empty. A node is more
than a simple container. Its boolean "truth" does not depend on
@@ -64,6 +64,9 @@ class Node(object):
"""
return True
+ if sys.version_info < (3, 0):
+ __nonzero__ = __bool__
+
if sys.version_info < (3, 0):
# on 2.x, str(node) will be a byte string with Unicode
# characters > 255 escaped; on 3.x this is no longer necessary
@@ -544,8 +547,7 @@ class Element(Node):
else:
return self.emptytag()
- if sys.version_info > (3, 0):
- # 2to3 doesn't convert __unicode__ to __str__
+ if sys.version_info >= (3, 0):
__str__ = __unicode__
def starttag(self, quoteattr=None):
diff --git a/docutils/utils/math/math2html.py b/docutils/utils/math/math2html.py
index 757dec0..a7e2aed 100644
--- a/docutils/utils/math/math2html.py
+++ b/docutils/utils/math/math2html.py
@@ -1313,6 +1313,9 @@ class BranchOptions(object):
"String representation"
return 'options for ' + self.name + ': ' + unicode(self.options)
+ if sys.version_info >= (3, 0):
+ __str__ = __unicode__
+
class Cloner(object):
"An object used to clone other objects."
@@ -1453,6 +1456,10 @@ class Parser(object):
"Return a description"
return self.__class__.__name__ + ' (' + unicode(self.begin) + ')'
+ if sys.version_info >= (3, 0):
+ __str__ = __unicode__
+
+
class LoneCommand(Parser):
"A parser for just one command line"
@@ -1986,6 +1993,10 @@ class EndingList(object):
string = string[:-1]
return string + ']'
+ if sys.version_info >= (3, 0):
+ __str__ = __unicode__
+
+
class PositionEnding(object):
"An ending for a parsing position"
@@ -2004,6 +2015,8 @@ class PositionEnding(object):
string += ' (optional)'
return string
+ if sys.version_info >= (3, 0):
+ __str__ = __unicode__
class Position(Globable):
@@ -2046,11 +2059,14 @@ class Position(Globable):
self.skip(current)
return current
- def next(self):
+ def __next__(self):
"Advance the position and return the next character."
self.skipcurrent()
return self.current()
+ if sys.version_info < (3, 0):
+ next = __next__
+
def checkskip(self, string):
"Check for a string at the given position; if there, skip it"
if not self.checkfor(string):
@@ -2312,6 +2328,10 @@ class Container(object):
return self.__class__.__name__
return self.__class__.__name__ + '@' + unicode(self.begin)
+ if sys.version_info >= (3, 0):
+ __str__ = __unicode__
+
+
class BlackBox(Container):
"A container that does not output anything"
@@ -2370,7 +2390,7 @@ class StringContainer(Container):
def extracttext(self):
"Return all text."
return self.string
-
+
def __unicode__(self):
"Return a printable representation."
result = 'StringContainer'
@@ -2381,6 +2401,10 @@ class StringContainer(Container):
ellipsis = ''
return result + ' (' + self.string.strip()[:15] + ellipsis + ')'
+ if sys.version_info >= (3, 0):
+ __str__ = __unicode__
+
+
class Constant(StringContainer):
"A constant string"
@@ -2392,6 +2416,10 @@ class Constant(StringContainer):
def __unicode__(self):
return 'Constant: ' + self.string
+ if sys.version_info >= (3, 0):
+ __str__ = __unicode__
+
+
class TaggedText(Container):
"Text inside a tag"
@@ -2421,9 +2449,8 @@ class TaggedText(Container):
return 'Tagged <unknown tag>'
return 'Tagged <' + self.output.tag + '>'
-
-
-
+ if sys.version_info >= (3, 0):
+ __str__ = __unicode__
class DocumentParameters(object):
@@ -2555,19 +2582,12 @@ class MacroParser(FormulaParser):
"See if the formula is inlined"
self.begin = reader.linenumber + 1
return ['inline']
-
+
def parse(self, reader):
"Parse the formula until the end"
formula = self.parsemultiliner(reader, self.parent.start, self.ending)
reader.nextline()
return formula
-
-
-
-
-
-
-
class FormulaBit(Container):
@@ -2614,6 +2634,10 @@ class FormulaBit(Container):
"Get a string representation"
return self.__class__.__name__ + ' read in ' + self.original
+ if sys.version_info >= (3, 0):
+ __str__ = __unicode__
+
+
class TaggedBit(FormulaBit):
"A tagged string in a formula"
@@ -2656,6 +2680,10 @@ class FormulaConstant(Constant):
"Return a printable representation."
return 'Formula constant: ' + self.string
+ if sys.version_info >= (3, 0):
+ __str__ = __unicode__
+
+
class RawText(FormulaBit):
"A bit of text inside a formula"
@@ -2739,6 +2767,10 @@ class WhiteSpace(FormulaBit):
"Return a printable representation."
return 'Whitespace: *' + self.original + '*'
+ if sys.version_info >= (3, 0):
+ __str__ = __unicode__
+
+
class Bracket(FormulaBit):
"A {} bracket inside a formula"
@@ -2822,7 +2854,6 @@ class SquareBracket(Bracket):
return bracket
-
class MathsProcessor(object):
"A processor for a maths construction inside the FormulaProcessor."
@@ -2834,6 +2865,10 @@ class MathsProcessor(object):
"Return a printable description."
return 'Maths processor ' + self.__class__.__name__
+ if sys.version_info >= (3, 0):
+ __str__ = __unicode__
+
+
class FormulaProcessor(object):
"A processor specifically for formulas."
@@ -2997,6 +3032,10 @@ class Formula(Container):
return 'Formula (' + self.partkey.number + ')'
return 'Unnumbered formula'
+ if sys.version_info >= (3, 0):
+ __str__ = __unicode__
+
+
class WholeFormula(FormulaBit):
"Parse a whole formula"
@@ -3229,6 +3268,10 @@ class NumberCounter(object):
result += ' in mode ' + self.mode
return result
+ if sys.version_info >= (3, 0):
+ __str__ = __unicode__
+
+
class DependentCounter(NumberCounter):
"A counter which depends on another one (the master)."
@@ -3780,6 +3823,10 @@ class Link(Container):
result += ' to ' + self.url
return result
+ if sys.version_info >= (3, 0):
+ __str__ = __unicode__
+
+
class URL(Link):
"A clickable URL"
@@ -3948,6 +3995,10 @@ class Label(Link):
return 'Unnamed label'
return 'Label ' + self.key
+ if sys.version_info >= (3, 0):
+ __str__ = __unicode__
+
+
class Reference(Link):
"A reference to a label."
@@ -4008,6 +4059,8 @@ class Reference(Link):
"Return a printable representation."
return 'Reference ' + self.key
+ if sys.version_info >= (3, 0):
+ __str__ = __unicode__
class FormulaCommand(FormulaBit):
@@ -4630,6 +4683,10 @@ class LimitPreviousCommand(LimitCommand):
"Return a printable representation."
return 'Limit previous command'
+ if sys.version_info >= (3, 0):
+ __str__ = __unicode__
+
+
class LimitsProcessor(MathsProcessor):
"A processor for limits inside an element."
@@ -4854,6 +4911,10 @@ class ParameterDefinition(object):
result += ' (empty)'
return result
+ if sys.version_info >= (3, 0):
+ __str__ = __unicode__
+
+
class ParameterFunction(CommandBit):
"A function with a variable number of parameters defined in a template."
"The parameters are defined as a parameter definition."
@@ -5306,6 +5367,10 @@ class FormulaMacro(Formula):
"Return a printable representation."
return 'Math macro'
+ if sys.version_info >= (3, 0):
+ __str__ = __unicode__
+
+
FormulaFactory.types += [ MacroParameter ]
FormulaCommand.types += [
diff --git a/docutils/writers/manpage.py b/docutils/writers/manpage.py
index df4f1a3..9809dd4 100644
--- a/docutils/writers/manpage.py
+++ b/docutils/writers/manpage.py
@@ -331,7 +331,7 @@ class Translator(nodes.NodeVisitor):
elif style.endswith('roman'):
self._indent = 5
- def next(self):
+ def __next__(self):
if self._style == 'bullet':
return self.enum_style[self._style]
elif self._style == 'emdash':
@@ -349,6 +349,10 @@ class Translator(nodes.NodeVisitor):
return res.lower()
else:
return "%d." % self._cnt
+
+ if sys.version_info < (3, 0):
+ next = __next__
+
def get_width(self):
return self._indent
def __repr__(self):
--
2.24.0.375.geb5ae68d41

View file

@ -0,0 +1,147 @@
From 7e601f5444051a78c0dc3fd6e3676193e7a30076 Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Tue, 27 Aug 2019 12:11:15 +0000
Subject: [PATCH 24/26] py3: Wrap 'foo.keys()', 'zip(foo, bar') in 'list'
In Python 3, 'dict.keys()', 'zip' and 'map' no longer return a list but
rather types 'dict_keys', 'zip' and 'map', respectively. You can't
append to these types nor can you delete from them while in a loop. The
simple solution to both issues is to wrap things in 'list'.
Signed-off-by: Stephen Finucane <stephen@that.guru>
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8372 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/parsers/rst/tableparser.py | 2 +-
docutils/statemachine.py | 2 +-
docutils/utils/__init__.py | 2 +-
docutils/utils/math/math2html.py | 2 +-
docutils/writers/odf_odt/__init__.py | 3 +--
test/DocutilsTestSupport.py | 2 +-
test/test_functional.py | 2 +-
test/test_language.py | 2 +-
test/test_statemachine.py | 2 +-
9 files changed, 9 insertions(+), 10 deletions(-)
diff --git a/docutils/parsers/rst/tableparser.py b/docutils/parsers/rst/tableparser.py
index 937aec8..408d6d8 100644
--- a/docutils/parsers/rst/tableparser.py
+++ b/docutils/parsers/rst/tableparser.py
@@ -290,7 +290,7 @@ class GridTableParser(TableParser):
rowindex = {}
for i in range(len(rowseps)):
rowindex[rowseps[i]] = i # row boundary -> row number mapping
- colseps = self.colseps.keys() # list of column boundaries
+ colseps = list(self.colseps.keys()) # list of column boundaries
colseps.sort()
colindex = {}
for i in range(len(colseps)):
diff --git a/docutils/statemachine.py b/docutils/statemachine.py
index 6bc03f5..0cbf9d3 100644
--- a/docutils/statemachine.py
+++ b/docutils/statemachine.py
@@ -1297,7 +1297,7 @@ class ViewList(object):
self.parent = None
def sort(self, *args):
- tmp = zip(self.data, self.items)
+ tmp = list(zip(self.data, self.items))
tmp.sort(*args)
self.data = [entry[0] for entry in tmp]
self.items = [entry[1] for entry in tmp]
diff --git a/docutils/utils/__init__.py b/docutils/utils/__init__.py
index cc1fd1a..437456b 100644
--- a/docutils/utils/__init__.py
+++ b/docutils/utils/__init__.py
@@ -618,7 +618,7 @@ def column_indices(text):
"""
# TODO: account for asian wide chars here instead of using dummy
# replacements in the tableparser?
- string_indices = range(len(text))
+ string_indices = list(range(len(text)))
for index in find_combining_chars(text):
string_indices[index] = None
return [i for i in string_indices if i is not None]
diff --git a/docutils/utils/math/math2html.py b/docutils/utils/math/math2html.py
index a7e2aed..53dd836 100644
--- a/docutils/utils/math/math2html.py
+++ b/docutils/utils/math/math2html.py
@@ -2819,7 +2819,7 @@ class Bracket(FormulaBit):
def innertext(self, pos):
"Parse some text inside the bracket, following textual rules."
- specialchars = FormulaConfig.symbolfunctions.keys()
+ specialchars = list(FormulaConfig.symbolfunctions.keys())
specialchars.append(FormulaConfig.starts['command'])
specialchars.append(FormulaConfig.starts['bracket'])
specialchars.append(Comment.start)
diff --git a/docutils/writers/odf_odt/__init__.py b/docutils/writers/odf_odt/__init__.py
index c79d4c1..ad32613 100644
--- a/docutils/writers/odf_odt/__init__.py
+++ b/docutils/writers/odf_odt/__init__.py
@@ -1169,8 +1169,7 @@ class ODFTranslator(nodes.GenericNodeVisitor):
fin = os.popen("paperconf -s 2> /dev/null")
content = fin.read()
content = content.split()
- content = map(float, content)
- content = list(content)
+ content = list(map(float, content))
w, h = content
except (IOError, ValueError):
w, h = 612, 792 # default to Letter
diff --git a/test/DocutilsTestSupport.py b/test/DocutilsTestSupport.py
index 47ba83c..222c202 100644
--- a/test/DocutilsTestSupport.py
+++ b/test/DocutilsTestSupport.py
@@ -811,7 +811,7 @@ class HtmlWriterPublishPartsTestCase(WriterPublishTestCase):
parts['html_prolog'] = parts['html_prolog'].replace(
self.standard_html_prolog, '')
# remove empty values:
- for key in parts.keys():
+ for key in list(parts.keys()):
if not parts[key]:
del parts[key]
# standard output format:
diff --git a/test/test_functional.py b/test/test_functional.py
index cdc75a0..b02c250 100755
--- a/test/test_functional.py
+++ b/test/test_functional.py
@@ -152,7 +152,7 @@ expected output and check it in:
del params['test_source']
del params['test_destination']
# Delete private stuff like params['__builtins__']:
- for key in params.keys():
+ for key in list(params.keys()):
if key.startswith('_'):
del params[key]
# Get output (automatically written to the output/ directory
diff --git a/test/test_language.py b/test/test_language.py
index 31ac613..48cd06b 100755
--- a/test/test_language.py
+++ b/test/test_language.py
@@ -52,7 +52,7 @@ class LanguageTestSuite(DocutilsTestSupport.CustomTestSuite):
match = self.language_module_pattern.match(mod)
if match:
languages[match.group(1)] = 1
- self.languages = languages.keys()
+ self.languages = list(languages.keys())
# test language tag normalization:
self.languages += ['en_gb', 'en_US', 'en-CA', 'de-DE', 'de-AT-1901',
'pt-BR', 'pt-foo-BR']
diff --git a/test/test_statemachine.py b/test/test_statemachine.py
index 6352ca4..87f5710 100755
--- a/test/test_statemachine.py
+++ b/test/test_statemachine.py
@@ -152,7 +152,7 @@ class SMWSTests(unittest.TestCase):
self.sm.unlink()
def test___init__(self):
- self.assertEqual(self.sm.states.keys(), ['MockState'])
+ self.assertEqual(list(self.sm.states.keys()), ['MockState'])
self.assertEqual(len(self.sm.states['MockState'].transitions), 4)
def test_get_indented(self):
--
2.24.0.375.geb5ae68d41

View file

@ -0,0 +1,84 @@
From 1d4c3d48fd9a5606925562c1c97e67332578cc65 Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Tue, 27 Aug 2019 12:11:30 +0000
Subject: [PATCH 25/26] Simplify code.
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8373 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/parsers/rst/tableparser.py | 3 +--
docutils/statemachine.py | 3 +--
docutils/writers/odf_odt/__init__.py | 6 ++----
test/DocutilsTestSupport.py | 10 +++-------
4 files changed, 7 insertions(+), 15 deletions(-)
diff --git a/docutils/parsers/rst/tableparser.py b/docutils/parsers/rst/tableparser.py
index 408d6d8..64a192f 100644
--- a/docutils/parsers/rst/tableparser.py
+++ b/docutils/parsers/rst/tableparser.py
@@ -290,8 +290,7 @@ class GridTableParser(TableParser):
rowindex = {}
for i in range(len(rowseps)):
rowindex[rowseps[i]] = i # row boundary -> row number mapping
- colseps = list(self.colseps.keys()) # list of column boundaries
- colseps.sort()
+ colseps = sorted(self.colseps.keys()) # list of column boundaries
colindex = {}
for i in range(len(colseps)):
colindex[colseps[i]] = i # column boundary -> col number map
diff --git a/docutils/statemachine.py b/docutils/statemachine.py
index 0cbf9d3..ebb52ad 100644
--- a/docutils/statemachine.py
+++ b/docutils/statemachine.py
@@ -1297,8 +1297,7 @@ class ViewList(object):
self.parent = None
def sort(self, *args):
- tmp = list(zip(self.data, self.items))
- tmp.sort(*args)
+ tmp = sorted(zip(self.data, self.items), *args)
self.data = [entry[0] for entry in tmp]
self.items = [entry[1] for entry in tmp]
self.parent = None
diff --git a/docutils/writers/odf_odt/__init__.py b/docutils/writers/odf_odt/__init__.py
index ad32613..d03f8e0 100644
--- a/docutils/writers/odf_odt/__init__.py
+++ b/docutils/writers/odf_odt/__init__.py
@@ -1167,10 +1167,8 @@ class ODFTranslator(nodes.GenericNodeVisitor):
def setup_paper(self, root_el):
try:
fin = os.popen("paperconf -s 2> /dev/null")
- content = fin.read()
- content = content.split()
- content = list(map(float, content))
- w, h = content
+ dimensions = fin.read().split()
+ w, h = (float(s) for s in dimensions)
except (IOError, ValueError):
w, h = 612, 792 # default to Letter
finally:
diff --git a/test/DocutilsTestSupport.py b/test/DocutilsTestSupport.py
index 222c202..5e9fed9 100644
--- a/test/DocutilsTestSupport.py
+++ b/test/DocutilsTestSupport.py
@@ -810,14 +810,10 @@ class HtmlWriterPublishPartsTestCase(WriterPublishTestCase):
self.standard_html_meta_value, '...')
parts['html_prolog'] = parts['html_prolog'].replace(
self.standard_html_prolog, '')
- # remove empty values:
- for key in list(parts.keys()):
- if not parts[key]:
- del parts[key]
- # standard output format:
- keys = sorted(parts.keys())
output = []
- for key in keys:
+ for key in sorted(parts.keys()):
+ if not parts[key]:
+ continue
output.append("%r: '''%s'''"
% (key, parts[key]))
if output[-1].endswith("\n'''"):
--
2.24.0.375.geb5ae68d41

View file

@ -0,0 +1,42 @@
From e90cfe945193ac99cc9ac7a439d1ccc2ad857a6c Mon Sep 17 00:00:00 2001
From: Stephen Finucane <stephen@that.guru>
Date: Tue, 27 Aug 2019 12:11:40 +0000
Subject: [PATCH 26/26] py3: Handle 'os.getcwdu' to 'os.getcwd' rename
We don't need to do the reverse since none of the callers seems to care.
Based on patch by: Stephen Finucane <stephen@that.guru>
git-svn-id: http://svn.code.sf.net/p/docutils/code/trunk@8374 929543f6-e4f2-0310-98a6-ba3bd3dd1d04
Signed-off-by: Doan Tran Cong Danh <congdanhqx@gmail.com>
---
docutils/frontend.py | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/docutils/frontend.py b/docutils/frontend.py
index 7bfff6a..372ca44 100644
--- a/docutils/frontend.py
+++ b/docutils/frontend.py
@@ -38,8 +38,10 @@ import optparse
from optparse import SUPPRESS_HELP
if sys.version_info >= (3, 0):
from configparser import RawConfigParser
+ from os import getcwd
else:
from ConfigParser import RawConfigParser
+ from os import getcwdu as getcwd
import docutils
import docutils.utils
@@ -256,7 +258,7 @@ def make_paths_absolute(pathdict, keys, base_path=None):
`OptionParser.relative_path_settings`.
"""
if base_path is None:
- base_path = os.getcwdu() # type(base_path) == unicode
+ base_path = os.getcwd() # type(base_path) == unicode
# to allow combining non-ASCII cwd with unicode values in `pathdict`
for key in keys:
if key in pathdict:
--
2.24.0.375.geb5ae68d41

View file

@ -1,19 +1,22 @@
# Template file for 'python-docutils'
pkgname=python-docutils
version=0.15.2
revision=1
revision=2
archs=noarch
wrksrc="docutils-${version}"
build_style=python-module
pycompile_module="docutils"
hostmakedepends="python-setuptools python3-setuptools"
depends="python"
# docutils/writers/odf_odt/pygmentsformatter.py
depends="python python-Pygments"
short_desc="Python2 documentation utilities"
maintainer="Alessio Sergi <al3hex@gmail.com>"
license="custom:Public Domain, BSD-2-Clause, GPL-3.0-or-later, Python-2.0"
homepage="http://docutils.sourceforge.net"
distfiles="${PYPI_SITE}/d/docutils/docutils-${version}.tar.gz"
checksum=a2aeea129088da402665e92e0b25b04b073c04b2dce4ab65caaa38b7ce2e1a99
checkdepends+="$depends python3-Pygments"
patch_args="-Np1"
alternatives="
docutils:rst2html:/usr/bin/rst2html.py2
@ -48,12 +51,12 @@ python3-docutils_package() {
docutils:rst2xml:/usr/bin/rst2xml.py3
docutils:rstpep2html:/usr/bin/rstpep2html.py3"
archs=noarch
depends="python3"
depends="python3 python3-Pygments"
pycompile_module="docutils"
short_desc="${short_desc/Python2/Python3}"
pkg_install() {
vmove usr/bin/*3
vmove usr/lib/python3*
vmove "usr/bin/*3"
vmove "usr/lib/python3*"
vlicense COPYING.txt COPYING
}
}