',
'\\emph{\\texttt{mp(1)}}')
+
def test_latex_escaping():
# correct escaping in normal mode
yield (verify, u'Γ\\\\∞$', None,
diff --git a/tests/test_search.py b/tests/test_search.py
index cd2ff76f2..b7c38674f 100644
--- a/tests/test_search.py
+++ b/tests/test_search.py
@@ -20,6 +20,7 @@ from util import with_app
settings = parser = None
+
def setup_module():
global settings, parser
optparser = frontend.OptionParser(components=(rst.Parser,))
@@ -33,6 +34,7 @@ FILE_CONTENTS = '''\
test that non-comments are indexed: fermion
'''
+
def test_wordcollector():
doc = utils.new_document(b'test data', settings)
doc['file'] = 'dummy'
diff --git a/tests/test_util_i18n.py b/tests/test_util_i18n.py
index 6ff988c81..3e0cfd5f3 100644
--- a/tests/test_util_i18n.py
+++ b/tests/test_util_i18n.py
@@ -47,7 +47,7 @@ def test_catalog_outdated(dir):
mo_file.write_text('#')
assert not cat.is_outdated() # if mo is exist and newer than po
- os.utime(mo_file, (os.stat(mo_file).st_mtime - 10,) * 2) # to be outdate
+ os.utime(mo_file, (os.stat(mo_file).st_mtime - 10,) * 2) # to be outdate
assert cat.is_outdated() # if mo is exist and older than po
@@ -213,6 +213,7 @@ def test_format_date():
assert i18n.format_date(format, date=datet) == 'Feb 7, 2016, 5:11:17 AM'
assert i18n.format_date(format, date=date) == 'Feb 7, 2016'
+
def test_get_filename_for_language():
app = TestApp()
diff --git a/tests/test_util_nodes.py b/tests/test_util_nodes.py
index a41af3cc8..e7a4b7e90 100644
--- a/tests/test_util_nodes.py
+++ b/tests/test_util_nodes.py
@@ -87,7 +87,6 @@ def test_extract_messages():
nodes.rubric, 1,
)
-
text = dedent(
"""
| spam
@@ -100,7 +99,6 @@ def test_extract_messages():
nodes.line, 2,
)
-
text = dedent(
"""
section
@@ -118,7 +116,6 @@ def test_extract_messages():
nodes.line, 2,
)
-
text = dedent(
"""
* | **Title 1**
diff --git a/tests/util.py b/tests/util.py
index b3f5e01d9..cb0d3f7a0 100644
--- a/tests/util.py
+++ b/tests/util.py
@@ -26,7 +26,7 @@ from sphinx.theming import Theme
from sphinx.ext.autodoc import AutoDirective
from sphinx.pycode import ModuleAnalyzer
-from path import path, repr_as
+from path import path, repr_as # NOQA
try:
# Python >=3.3
@@ -110,6 +110,7 @@ except ImportError:
def assert_in(x, thing, msg=''):
if x not in thing:
assert False, msg or '%r is not in %r' % (x, thing)
+
def assert_not_in(x, thing, msg=''):
if x in thing:
assert False, msg or '%r is in %r' % (x, thing)
From 3d5319e705561942ef5eeef911206e1aad2b5cfa Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 12 Jun 2016 00:27:59 +0900
Subject: [PATCH 084/217] Use six in util/reindent.py
---
utils/reindent.py | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/utils/reindent.py b/utils/reindent.py
index c8a062417..7679045cb 100755
--- a/utils/reindent.py
+++ b/utils/reindent.py
@@ -44,6 +44,7 @@ import os
import sys
import shutil
import tokenize
+from six.ranges import range
__version__ = "1"
@@ -218,7 +219,7 @@ class Reindenter:
want = have2want.get(have, -1)
if want < 0:
# Then it probably belongs to the next real stmt.
- for j in xrange(i+1, len(stats)-1):
+ for j in range(i+1, len(stats)-1):
jline, jlevel = stats[j]
if jlevel >= 0:
if have == getlspace(lines[jline]):
@@ -228,7 +229,7 @@ class Reindenter:
# comment like this one,
# in which case we should shift it like its base
# line got shifted.
- for j in xrange(i-1, -1, -1):
+ for j in range(i-1, -1, -1):
jline, jlevel = stats[j]
if jlevel >= 0:
want = (have + getlspace(after[jline-1]) -
From 5f7b393d1c45234f1bb18b5d5b53e6e2554b4055 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 12 Jun 2016 00:39:12 +0900
Subject: [PATCH 085/217] Add html5lib to tox.ini
---
tox.ini | 1 +
1 file changed, 1 insertion(+)
diff --git a/tox.ini b/tox.ini
index 8fcb7b177..b646fd285 100644
--- a/tox.ini
+++ b/tox.ini
@@ -6,6 +6,7 @@ deps=
nose
sqlalchemy
whoosh
+ html5lib
setenv =
SPHINX_TEST_TEMPDIR = {envdir}/testbuild
commands=
From e41a6340da2cd301b4a7db58184f2fa0fe1420b9 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 12 Jun 2016 00:39:40 +0900
Subject: [PATCH 086/217] '%' is no needed after \sphinxAtStartFootnote
---
sphinx/writers/latex.py | 4 +--
tests/test_build_latex.py | 62 +++++++++++++++++++--------------------
2 files changed, 33 insertions(+), 33 deletions(-)
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index b436b9cfc..8151ed93c 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -979,9 +979,9 @@ class LaTeXTranslator(nodes.NodeVisitor):
def visit_collected_footnote(self, node):
self.in_footnote += 1
if 'footnotetext' in node:
- self.body.append('\\footnotetext[%s]{\sphinxAtStartFootnote%%\n' % node['number'])
+ self.body.append('\\footnotetext[%s]{\sphinxAtStartFootnote\n' % node['number'])
else:
- self.body.append('\\footnote[%s]{\sphinxAtStartFootnote%%\n' % node['number'])
+ self.body.append('\\footnote[%s]{\sphinxAtStartFootnote\n' % node['number'])
def depart_collected_footnote(self, node):
self.body.append('}')
diff --git a/tests/test_build_latex.py b/tests/test_build_latex.py
index 993d89ddf..4b26611cf 100644
--- a/tests/test_build_latex.py
+++ b/tests/test_build_latex.py
@@ -406,9 +406,9 @@ def test_footnote(app, status, warning):
print(result)
print(status.getvalue())
print(warning.getvalue())
- assert '\\footnote[1]{\sphinxAtStartFootnote%\nnumbered\n}' in result
- assert '\\footnote[2]{\sphinxAtStartFootnote%\nauto numbered\n}' in result
- assert '\\footnote[3]{\sphinxAtStartFootnote%\nnamed\n}' in result
+ assert '\\footnote[1]{\sphinxAtStartFootnote\nnumbered\n}' in result
+ assert '\\footnote[2]{\sphinxAtStartFootnote\nauto numbered\n}' in result
+ assert '\\footnote[3]{\sphinxAtStartFootnote\nnamed\n}' in result
assert '{\\hyperref[footnote:bar]{\\crossref{{[}bar{]}}}}' in result
assert '\\bibitem[bar]{bar}{\\phantomsection\\label{footnote:bar} ' in result
assert '\\bibitem[bar]{bar}{\\phantomsection\\label{footnote:bar} \ncite' in result
@@ -416,8 +416,8 @@ def test_footnote(app, status, warning):
assert '\\capstart\\caption{Table caption \\protect\\footnotemark[4]}' in result
assert 'name \\protect\\footnotemark[5]' in result
assert ('\\end{threeparttable}\n\n'
- '\\footnotetext[4]{\sphinxAtStartFootnote%\nfootnotes in table caption\n}'
- '\\footnotetext[5]{\sphinxAtStartFootnote%\nfootnotes in table\n}' in result)
+ '\\footnotetext[4]{\sphinxAtStartFootnote\nfootnotes in table caption\n}'
+ '\\footnotetext[5]{\sphinxAtStartFootnote\nfootnotes in table\n}' in result)
@with_app(buildername='latex', testroot='footnotes')
@@ -434,17 +434,17 @@ def test_reference_in_caption(app, status, warning):
assert '\\paragraph{The rubric title with a reference to {[}AuthorYear{]}}' in result
assert ('\\chapter{The section with a reference to \\protect\\footnotemark[4]}\n'
'\\label{index:the-section-with-a-reference-to}'
- '\\footnotetext[4]{\sphinxAtStartFootnote%\nFootnote in section\n}' in result)
+ '\\footnotetext[4]{\sphinxAtStartFootnote\nFootnote in section\n}' in result)
assert ('\\caption{This is the figure caption with a footnote to '
'\\protect\\footnotemark[6].}\label{index:id23}\end{figure}\n'
- '\\footnotetext[6]{\sphinxAtStartFootnote%\nFootnote in caption\n}')in result
+ '\\footnotetext[6]{\sphinxAtStartFootnote\nFootnote in caption\n}')in result
assert ('\\caption{footnote \\protect\\footnotemark[7] '
'in caption of normal table}') in result
- assert ('\\end{threeparttable}\n\n\\footnotetext[7]{\sphinxAtStartFootnote%\n'
+ assert ('\\end{threeparttable}\n\n\\footnotetext[7]{\sphinxAtStartFootnote\n'
'Foot note in table\n}' in result)
assert ('\\caption{footnote \\protect\\footnotemark[8] in caption of longtable}'
in result)
- assert ('\end{longtable}\n\n\\footnotetext[8]{\sphinxAtStartFootnote%\n'
+ assert ('\end{longtable}\n\n\\footnotetext[8]{\sphinxAtStartFootnote\n'
'Foot note in longtable\n}' in result)
@@ -456,9 +456,9 @@ def test_latex_show_urls_is_inline(app, status, warning):
print(result)
print(status.getvalue())
print(warning.getvalue())
- assert ('Same footnote number \\footnote[1]{\sphinxAtStartFootnote%\n'
+ assert ('Same footnote number \\footnote[1]{\sphinxAtStartFootnote\n'
'footnote in bar\n} in bar.rst' in result)
- assert ('Auto footnote number \\footnote[1]{\sphinxAtStartFootnote%\n'
+ assert ('Auto footnote number \\footnote[1]{\sphinxAtStartFootnote\n'
'footnote in baz\n} in baz.rst' in result)
assert ('\\phantomsection\\label{index:id26}{\\hyperref[index:the\\string-section'
'\\string-with\\string-a\\string-reference\\string-to\\string-authoryear]'
@@ -467,16 +467,16 @@ def test_latex_show_urls_is_inline(app, status, warning):
assert ('\\phantomsection\\label{index:id27}{\\hyperref[index:the\\string-section'
'\\string-with\\string-a\\string-reference\\string-to]'
'{\\crossref{The section with a reference to }}}' in result)
- assert 'First footnote: \\footnote[2]{\sphinxAtStartFootnote%\nFirst\n}' in result
- assert 'Second footnote: \\footnote[1]{\sphinxAtStartFootnote%\nSecond\n}' in result
+ assert 'First footnote: \\footnote[2]{\sphinxAtStartFootnote\nFirst\n}' in result
+ assert 'Second footnote: \\footnote[1]{\sphinxAtStartFootnote\nSecond\n}' in result
assert '\\href{http://sphinx-doc.org/}{Sphinx} (http://sphinx-doc.org/)' in result
- assert 'Third footnote: \\footnote[3]{\sphinxAtStartFootnote%\nThird\n}' in result
+ assert 'Third footnote: \\footnote[3]{\sphinxAtStartFootnote\nThird\n}' in result
assert ('\\href{http://sphinx-doc.org/~test/}{URL including tilde} '
'(http://sphinx-doc.org/\\textasciitilde{}test/)' in result)
assert ('\\item[{\\href{http://sphinx-doc.org/}{URL in term} (http://sphinx-doc.org/)}] '
'\\leavevmode\nDescription' in result)
assert ('\\item[{Footnote in term \\protect\\footnotemark[5]}] '
- '\\leavevmode\\footnotetext[5]{\sphinxAtStartFootnote%\n'
+ '\\leavevmode\\footnotetext[5]{\sphinxAtStartFootnote\n'
'Footnote in term\n}\nDescription' in result)
assert ('\\item[{\\href{http://sphinx-doc.org/}{Term in deflist} '
'(http://sphinx-doc.org/)}] \\leavevmode\nDescription' in result)
@@ -493,9 +493,9 @@ def test_latex_show_urls_is_footnote(app, status, warning):
print(result)
print(status.getvalue())
print(warning.getvalue())
- assert ('Same footnote number \\footnote[1]{\sphinxAtStartFootnote%\n'
+ assert ('Same footnote number \\footnote[1]{\sphinxAtStartFootnote\n'
'footnote in bar\n} in bar.rst' in result)
- assert ('Auto footnote number \\footnote[2]{\sphinxAtStartFootnote%\n'
+ assert ('Auto footnote number \\footnote[2]{\sphinxAtStartFootnote\n'
'footnote in baz\n} in baz.rst' in result)
assert ('\\phantomsection\\label{index:id26}{\\hyperref[index:the\\string-section'
'\\string-with\\string-a\\string-reference\\string-to\\string-authoryear]'
@@ -504,24 +504,24 @@ def test_latex_show_urls_is_footnote(app, status, warning):
assert ('\\phantomsection\\label{index:id27}{\\hyperref[index:the\\string-section'
'\\string-with\\string-a\\string-reference\\string-to]'
'{\\crossref{The section with a reference to }}}' in result)
- assert 'First footnote: \\footnote[3]{\sphinxAtStartFootnote%\nFirst\n}' in result
- assert 'Second footnote: \\footnote[1]{\sphinxAtStartFootnote%\nSecond\n}' in result
+ assert 'First footnote: \\footnote[3]{\sphinxAtStartFootnote\nFirst\n}' in result
+ assert 'Second footnote: \\footnote[1]{\sphinxAtStartFootnote\nSecond\n}' in result
assert ('\\href{http://sphinx-doc.org/}{Sphinx}'
- '\\footnote[4]{\sphinxAtStartFootnote%\n'
+ '\\footnote[4]{\sphinxAtStartFootnote\n'
'\\nolinkurl{http://sphinx-doc.org/}\n}' in result)
- assert 'Third footnote: \\footnote[6]{\sphinxAtStartFootnote%\nThird\n}' in result
+ assert 'Third footnote: \\footnote[6]{\sphinxAtStartFootnote\nThird\n}' in result
assert ('\\href{http://sphinx-doc.org/~test/}{URL including tilde}'
- '\\footnote[5]{\sphinxAtStartFootnote%\n'
+ '\\footnote[5]{\sphinxAtStartFootnote\n'
'\\nolinkurl{http://sphinx-doc.org/~test/}\n}' in result)
assert ('\\item[{\\href{http://sphinx-doc.org/}{URL in term}\\protect\\footnotemark[8]}] '
- '\\leavevmode\\footnotetext[8]{\sphinxAtStartFootnote%\n'
+ '\\leavevmode\\footnotetext[8]{\sphinxAtStartFootnote\n'
'\\nolinkurl{http://sphinx-doc.org/}\n}\nDescription' in result)
assert ('\\item[{Footnote in term \\protect\\footnotemark[10]}] '
- '\\leavevmode\\footnotetext[10]{\sphinxAtStartFootnote%\n'
+ '\\leavevmode\\footnotetext[10]{\sphinxAtStartFootnote\n'
'Footnote in term\n}\nDescription' in result)
assert ('\\item[{\\href{http://sphinx-doc.org/}{Term in deflist}\\protect'
'\\footnotemark[9]}] '
- '\\leavevmode\\footnotetext[9]{\sphinxAtStartFootnote%\n'
+ '\\leavevmode\\footnotetext[9]{\sphinxAtStartFootnote\n'
'\\nolinkurl{http://sphinx-doc.org/}\n}\nDescription' in result)
assert ('\\url{https://github.com/sphinx-doc/sphinx}\n' in result)
assert ('\\href{mailto:sphinx-dev@googlegroups.com}'
@@ -536,9 +536,9 @@ def test_latex_show_urls_is_no(app, status, warning):
print(result)
print(status.getvalue())
print(warning.getvalue())
- assert ('Same footnote number \\footnote[1]{\sphinxAtStartFootnote%\n'
+ assert ('Same footnote number \\footnote[1]{\sphinxAtStartFootnote\n'
'footnote in bar\n} in bar.rst' in result)
- assert ('Auto footnote number \\footnote[1]{\sphinxAtStartFootnote%\n'
+ assert ('Auto footnote number \\footnote[1]{\sphinxAtStartFootnote\n'
'footnote in baz\n} in baz.rst' in result)
assert ('\\phantomsection\\label{index:id26}{\\hyperref[index:the\\string-section'
'\\string-with\\string-a\\string-reference\\string-to\\string-authoryear]'
@@ -547,15 +547,15 @@ def test_latex_show_urls_is_no(app, status, warning):
assert ('\\phantomsection\\label{index:id27}{\\hyperref[index:the\\string-section'
'\\string-with\\string-a\\string-reference\\string-to]'
'{\\crossref{The section with a reference to }}}' in result)
- assert 'First footnote: \\footnote[2]{\sphinxAtStartFootnote%\nFirst\n}' in result
- assert 'Second footnote: \\footnote[1]{\sphinxAtStartFootnote%\nSecond\n}' in result
+ assert 'First footnote: \\footnote[2]{\sphinxAtStartFootnote\nFirst\n}' in result
+ assert 'Second footnote: \\footnote[1]{\sphinxAtStartFootnote\nSecond\n}' in result
assert '\\href{http://sphinx-doc.org/}{Sphinx}' in result
- assert 'Third footnote: \\footnote[3]{\sphinxAtStartFootnote%\nThird\n}' in result
+ assert 'Third footnote: \\footnote[3]{\sphinxAtStartFootnote\nThird\n}' in result
assert '\\href{http://sphinx-doc.org/~test/}{URL including tilde}' in result
assert ('\\item[{\\href{http://sphinx-doc.org/}{URL in term}}] '
'\\leavevmode\nDescription' in result)
assert ('\\item[{Footnote in term \\protect\\footnotemark[5]}] '
- '\\leavevmode\\footnotetext[5]{\sphinxAtStartFootnote%\n'
+ '\\leavevmode\\footnotetext[5]{\sphinxAtStartFootnote\n'
'Footnote in term\n}\nDescription' in result)
assert ('\\item[{\\href{http://sphinx-doc.org/}{Term in deflist}}] '
'\\leavevmode\nDescription' in result)
From eb95eaf14201658f16a67aa909fdd44de53ffedf Mon Sep 17 00:00:00 2001
From: Rob Ruana
Date: Sat, 11 Jun 2016 16:12:26 -0600
Subject: [PATCH 087/217] Update #2374: [Napoleon] clarifies documentation of
napoleon_include_init_with_doc conf value
---
sphinx/ext/napoleon/__init__.py | 16 +++++++++-------
1 file changed, 9 insertions(+), 7 deletions(-)
diff --git a/sphinx/ext/napoleon/__init__.py b/sphinx/ext/napoleon/__init__.py
index 9dedc15d7..202cb259d 100644
--- a/sphinx/ext/napoleon/__init__.py
+++ b/sphinx/ext/napoleon/__init__.py
@@ -58,9 +58,10 @@ class Config(object):
True to parse `NumPy style`_ docstrings. False to disable support
for NumPy style docstrings.
napoleon_include_init_with_doc : bool, defaults to False
- True to include init methods (i.e. ``__init___``) with
- docstrings in the documentation. False to fall back to Sphinx's
- default behavior.
+ True to list ``__init___`` docstrings separately from the class
+ docstring. False to fall back to Sphinx's default behavior, which
+ considers the ``__init___`` docstring as part of the class
+ documentation.
**If True**::
@@ -206,10 +207,11 @@ class Config(object):
False to use a single ``:keyword arguments:`` role for all the
keywords.
- This behaves similarly to :attr:`napoleon_use_param`. Note unlike docutils,
- ``:keyword:`` and ``:param:`` will not be treated the same way - there will
- be a separate "Keyword Arguments" section, rendered in the same fashion as
- "Parameters" section (type links created if possible)
+ This behaves similarly to :attr:`napoleon_use_param`. Note unlike
+ docutils, ``:keyword:`` and ``:param:`` will not be treated the same
+ way - there will be a separate "Keyword Arguments" section, rendered
+ in the same fashion as "Parameters" section (type links created if
+ possible)
See Also
--------
From 32a852c1f19df6d88459d8c345a4524cc5f6cc94 Mon Sep 17 00:00:00 2001
From: Rob Ruana
Date: Sat, 11 Jun 2016 18:28:48 -0600
Subject: [PATCH 088/217] Update #2374: [Napoleon] clarifies documentation of
napoleon_include_init_with_doc conf value
---
doc/ext/napoleon.rst | 18 ++++++++++++++++++
1 file changed, 18 insertions(+)
diff --git a/doc/ext/napoleon.rst b/doc/ext/napoleon.rst
index 2f2fb4376..860faca32 100644
--- a/doc/ext/napoleon.rst
+++ b/doc/ext/napoleon.rst
@@ -208,6 +208,7 @@ enabled in `conf.py`::
# Napoleon settings
napoleon_google_docstring = True
napoleon_numpy_docstring = True
+ napoleon_include_init_with_doc = False
napoleon_include_private_with_doc = False
napoleon_include_special_with_doc = True
napoleon_use_admonition_for_examples = False
@@ -234,6 +235,23 @@ enabled in `conf.py`::
True to parse `NumPy style`_ docstrings. False to disable support
for NumPy style docstrings. *Defaults to True.*
+.. confval:: napoleon_include_init_with_doc
+
+ True to list ``__init___`` docstrings separately from the class
+ docstring. False to fall back to Sphinx's default behavior, which
+ considers the ``__init___`` docstring as part of the class
+ documentation. *Defaults to False.*
+
+ **If True**::
+
+ def __init__(self):
+ \"\"\"
+ This will be included in the docs because it has a docstring
+ \"\"\"
+
+ def __init__(self):
+ # This will NOT be included in the docs
+
.. confval:: napoleon_include_private_with_doc
True to include private members (like ``_membername``) with docstrings
From bc4148983d046dd79d329daaa75e5926f9ade016 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 12 Jun 2016 11:33:43 +0900
Subject: [PATCH 089/217] Sphinx now bundles needspace.sty
---
CHANGES | 1 +
sphinx/texinputs/needspace.sty | 35 ++++++++++++++++++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 sphinx/texinputs/needspace.sty
diff --git a/CHANGES b/CHANGES
index 0a149a3b2..efbe161b8 100644
--- a/CHANGES
+++ b/CHANGES
@@ -18,6 +18,7 @@ Bugs fixed
* #2635: Latex code directives produce inconsistent frames based on viewing resolution
* #2639: Sphinx now bundles iftex.sty
* Failed to build PDF with framed.sty 0.95
+* Sphinx now bundles needspace.sty
Release 1.4.3 (released Jun 5, 2016)
diff --git a/sphinx/texinputs/needspace.sty b/sphinx/texinputs/needspace.sty
new file mode 100644
index 000000000..113d87216
--- /dev/null
+++ b/sphinx/texinputs/needspace.sty
@@ -0,0 +1,35 @@
+
+\NeedsTeXFormat{LaTeX2e}
+\ProvidesPackage{needspace}[2010/09/12 v1.3d reserve vertical space]
+
+\newcommand{\needspace}[1]{%
+ \begingroup
+ \setlength{\dimen@}{#1}%
+ \vskip\z@\@plus\dimen@
+ \penalty -100\vskip\z@\@plus -\dimen@
+ \vskip\dimen@
+ \penalty 9999%
+ \vskip -\dimen@
+ \vskip\z@skip % hide the previous |\vskip| from |\addvspace|
+ \endgroup
+}
+
+\newcommand{\Needspace}{\@ifstar{\@sneedsp@}{\@needsp@}}
+
+\newcommand{\@sneedsp@}[1]{\par \penalty-100\begingroup
+ \setlength{\dimen@}{#1}%
+ \dimen@ii\pagegoal \advance\dimen@ii-\pagetotal
+ \ifdim \dimen@>\dimen@ii
+ \break
+ \fi\endgroup}
+
+\newcommand{\@needsp@}[1]{\par \penalty-100\begingroup
+ \setlength{\dimen@}{#1}%
+ \dimen@ii\pagegoal \advance\dimen@ii-\pagetotal
+ \ifdim \dimen@>\dimen@ii
+ \ifdim \dimen@ii>\z@
+ \vfil
+ \fi
+ \break
+ \fi\endgroup}
+
From 8dde1eb02d3f0707f41bbd4a58e78dc2b5993c68 Mon Sep 17 00:00:00 2001
From: Rob Ruana
Date: Sat, 11 Jun 2016 23:55:55 -0600
Subject: [PATCH 090/217] Fix #2541: [Napoleon] Adds a blank line before
parameter descriptions that start with a literal block
---
sphinx/ext/napoleon/docstring.py | 76 ++++++++++++++++++----------
tests/test_ext_napoleon_docstring.py | 4 +-
2 files changed, 52 insertions(+), 28 deletions(-)
diff --git a/sphinx/ext/napoleon/docstring.py b/sphinx/ext/napoleon/docstring.py
index c12b75e6d..158996fc6 100644
--- a/sphinx/ext/napoleon/docstring.py
+++ b/sphinx/ext/napoleon/docstring.py
@@ -26,6 +26,7 @@ _directive_regex = re.compile(r'\.\. \S+::')
_google_section_regex = re.compile(r'^(\s|\w)+:\s*$')
_google_typed_arg_regex = re.compile(r'\s*(.+?)\s*\(\s*(.+?)\s*\)')
_numpy_section_regex = re.compile(r'^[=\-`:\'"~^_*+#<>]{2,}\s*$')
+_single_colon_regex = re.compile(r'(? indent:
+ desc = [''] + desc
+ else:
+ desc = ['', desc[0]] + self._indent(desc_block, 4)
+ return desc
+
def _format_admonition(self, admonition, lines):
lines = self._strip_empty(lines)
if len(lines) == 1:
@@ -333,6 +347,22 @@ class GoogleDocstring(UnicodeMixin):
else:
return [prefix]
+ def _format_docutils_params(self, fields, field_role='param',
+ type_role='type'):
+ lines = []
+ for _name, _type, _desc in fields:
+ _desc = self._strip_empty(_desc)
+ if any(_desc):
+ _desc = self._fix_field_desc(_desc)
+ field = ':%s %s: ' % (field_role, _name)
+ lines.extend(self._format_block(field, _desc))
+ else:
+ lines.append(':%s %s:' % (field_role, _name))
+
+ if _type:
+ lines.append(':%s %s: %s' % (type_role, _name, _type))
+ return lines + ['']
+
def _format_field(self, _name, _type, _desc):
_desc = self._strip_empty(_desc)
has_desc = any(_desc)
@@ -354,9 +384,11 @@ class GoogleDocstring(UnicodeMixin):
field = ''
if has_desc:
- if self._is_list(_desc):
- return [field, ''] + _desc
- return [field + _desc[0]] + _desc[1:]
+ _desc = self._fix_field_desc(_desc)
+ if _desc[0]:
+ return [field + _desc[0]] + _desc[1:]
+ else:
+ return [field] + _desc
else:
return [field]
@@ -393,6 +425,12 @@ class GoogleDocstring(UnicodeMixin):
return i
return len(line)
+ def _get_initial_indent(self, lines):
+ for line in lines:
+ if line:
+ return self._get_indent(line)
+ return 0
+
def _get_min_indent(self, lines):
min_indent = None
for line in lines:
@@ -529,11 +567,10 @@ class GoogleDocstring(UnicodeMixin):
def _parse_keyword_arguments_section(self, section):
fields = self._consume_fields()
if self._config.napoleon_use_keyword:
- return self._generate_docutils_params(
+ return self._format_docutils_params(
fields,
field_role="keyword",
- type_role="kwtype"
- )
+ type_role="kwtype")
else:
return self._format_fields('Keyword Arguments', fields)
@@ -560,26 +597,10 @@ class GoogleDocstring(UnicodeMixin):
def _parse_parameters_section(self, section):
fields = self._consume_fields()
if self._config.napoleon_use_param:
- return self._generate_docutils_params(fields)
+ return self._format_docutils_params(fields)
else:
return self._format_fields('Parameters', fields)
- def _generate_docutils_params(self, fields, field_role='param', type_role='type'):
- lines = []
- for _name, _type, _desc in fields:
- _desc = self._strip_empty(_desc)
- if any(_desc):
- if self._is_list(_desc):
- _desc = [''] + _desc
- field = ':%s %s: ' % (field_role, _name)
- lines.extend(self._format_block(field, _desc))
- else:
- lines.append(':%s %s:' % (field_role, _name))
-
- if _type:
- lines.append(':%s %s: %s' % (type_role, _name, _type))
- return lines + ['']
-
def _parse_raises_section(self, section):
fields = self._consume_fields(parse_type=False, prefer_type=True)
field_type = ':raises:'
@@ -678,11 +699,12 @@ class GoogleDocstring(UnicodeMixin):
if found_colon:
after_colon.append(source)
else:
- if (i % 2) == 0 and ":" in source:
+ m = _single_colon_regex.search(source)
+ if (i % 2) == 0 and m:
found_colon = True
- before, colon, after = source.partition(":")
- before_colon.append(before)
- after_colon.append(after)
+ colon = source[m.start(): m.end()]
+ before_colon.append(source[:m.start()])
+ after_colon.append(source[m.end():])
else:
before_colon.append(source)
diff --git a/tests/test_ext_napoleon_docstring.py b/tests/test_ext_napoleon_docstring.py
index ece55ebe4..b6f16b26b 100644
--- a/tests/test_ext_napoleon_docstring.py
+++ b/tests/test_ext_napoleon_docstring.py
@@ -329,7 +329,9 @@ Returns:
codecode
"""
expected = """
-:returns: foo::
+:returns:
+
+ foo::
codecode
codecode
From 93b3860597571545d3f2d57af376562b193f9d3f Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 12 Jun 2016 21:37:52 +0900
Subject: [PATCH 091/217] Bump to 1.4.4 final
---
CHANGES | 4 ++--
sphinx/__init__.py | 6 +++---
2 files changed, 5 insertions(+), 5 deletions(-)
diff --git a/CHANGES b/CHANGES
index 4419688d3..25b628210 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,5 +1,5 @@
-Release 1.4.4 (in development)
-==============================
+Release 1.4.4 (released Jun 12, 2016)
+=====================================
Bugs fixed
----------
diff --git a/sphinx/__init__.py b/sphinx/__init__.py
index 55a13fcbb..252f24ede 100644
--- a/sphinx/__init__.py
+++ b/sphinx/__init__.py
@@ -15,13 +15,13 @@
import sys
from os import path
-__version__ = '1.4.3+'
-__released__ = '1.4.3' # used when Sphinx builds its own docs
+__version__ = '1.4.4'
+__released__ = '1.4.4' # used when Sphinx builds its own docs
# version info for better programmatic use
# possible values for 3rd element: 'alpha', 'beta', 'rc', 'final'
# 'final' has 0 as the last element
-version_info = (1, 4, 4, 'beta', 1)
+version_info = (1, 4, 4, 'final', 0)
package_dir = path.abspath(path.dirname(__file__))
From ecd2ca10d56e79455b726420e88058dba2a47e5d Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 12 Jun 2016 21:43:21 +0900
Subject: [PATCH 092/217] Bump version
---
CHANGES | 7 +++++++
sphinx/__init__.py | 4 ++--
2 files changed, 9 insertions(+), 2 deletions(-)
diff --git a/CHANGES b/CHANGES
index 25b628210..04ce97389 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,3 +1,10 @@
+Release 1.4.5 (in development)
+==============================
+
+Bugs fixed
+----------
+
+
Release 1.4.4 (released Jun 12, 2016)
=====================================
diff --git a/sphinx/__init__.py b/sphinx/__init__.py
index 252f24ede..b79961c39 100644
--- a/sphinx/__init__.py
+++ b/sphinx/__init__.py
@@ -15,13 +15,13 @@
import sys
from os import path
-__version__ = '1.4.4'
+__version__ = '1.4.4+'
__released__ = '1.4.4' # used when Sphinx builds its own docs
# version info for better programmatic use
# possible values for 3rd element: 'alpha', 'beta', 'rc', 'final'
# 'final' has 0 as the last element
-version_info = (1, 4, 4, 'final', 0)
+version_info = (1, 4, 5, 'beta', 1)
package_dir = path.abspath(path.dirname(__file__))
From 715969a6c35537a91457dc88372f63f3f0c8eb99 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 12 Jun 2016 12:50:45 +0900
Subject: [PATCH 093/217] Refactor sphinx.io.SphinxFileInput
---
sphinx/io.py | 7 +++----
1 file changed, 3 insertions(+), 4 deletions(-)
diff --git a/sphinx/io.py b/sphinx/io.py
index 56d133641..36ac7bf98 100644
--- a/sphinx/io.py
+++ b/sphinx/io.py
@@ -112,10 +112,9 @@ class SphinxFileInput(FileInput):
return data.decode(self.encoding, 'sphinx') # py2: decoding
def read(self):
- def get_parser_type(docname):
- path = self.env.doc2path(docname)
+ def get_parser_type(source_path):
for suffix in self.env.config.source_parsers:
- if path.endswith(suffix):
+ if source_path.endswith(suffix):
parser_class = self.env.config.source_parsers[suffix]
if isinstance(parser_class, string_types):
parser_class = import_object(parser_class, 'source parser')
@@ -129,7 +128,7 @@ class SphinxFileInput(FileInput):
self.app.emit('source-read', self.env.docname, arg)
data = arg[0]
docinfo, data = split_docinfo(data)
- if 'restructuredtext' in get_parser_type(self.env.docname):
+ if 'restructuredtext' in get_parser_type(self.source_path):
if self.env.config.rst_epilog:
data = data + '\n' + self.env.config.rst_epilog + '\n'
if self.env.config.rst_prolog:
From 49957210d5fd7be233c1b1265318037d44a421aa Mon Sep 17 00:00:00 2001
From: Jakob Lykke Andersen
Date: Sun, 12 Jun 2016 23:51:17 +0900
Subject: [PATCH 094/217] C++, fix missing scope info on some declarations.
See sphinx-doc/sphinx#2607
---
sphinx/domains/cpp.py | 27 +++++++++------------------
1 file changed, 9 insertions(+), 18 deletions(-)
diff --git a/sphinx/domains/cpp.py b/sphinx/domains/cpp.py
index 7d41d6570..5d15d3020 100644
--- a/sphinx/domains/cpp.py
+++ b/sphinx/domains/cpp.py
@@ -3800,6 +3800,15 @@ class CPPObject(ObjectDescription):
self.describe_signature(signode, ast)
return ast
+ def before_content(self):
+ lastSymbol = self.env.ref_context['cpp:last_symbol']
+ assert lastSymbol
+ self.oldParentSymbol = self.env.ref_context['cpp:parent_symbol']
+ self.env.ref_context['cpp:parent_symbol'] = lastSymbol
+
+ def after_content(self):
+ self.env.ref_context['cpp:parent_symbol'] = self.oldParentSymbol
+
class CPPTypeObject(CPPObject):
def get_index_text(self, name):
@@ -3838,15 +3847,6 @@ class CPPClassObject(CPPObject):
def get_index_text(self, name):
return _('%s (C++ class)') % name
- def before_content(self):
- lastSymbol = self.env.ref_context['cpp:last_symbol']
- assert lastSymbol
- self.oldParentSymbol = self.env.ref_context['cpp:parent_symbol']
- self.env.ref_context['cpp:parent_symbol'] = lastSymbol
-
- def after_content(self):
- self.env.ref_context['cpp:parent_symbol'] = self.oldParentSymbol
-
def parse_definition(self, parser):
return parser.parse_declaration("class")
@@ -3858,15 +3858,6 @@ class CPPEnumObject(CPPObject):
def get_index_text(self, name):
return _('%s (C++ enum)') % name
- def before_content(self):
- lastSymbol = self.env.ref_context['cpp:last_symbol']
- assert lastSymbol
- self.oldParentSymbol = self.env.ref_context['cpp:parent_symbol']
- self.env.ref_context['cpp:parent_symbol'] = lastSymbol
-
- def after_content(self):
- self.env.ref_context['cpp:parent_symbol'] = self.oldParentSymbol
-
def parse_definition(self, parser):
ast = parser.parse_declaration("enum")
# self.objtype is set by ObjectDescription in run()
From ff34d02beb256ac470d77a60cdc4f2bfe742ffef Mon Sep 17 00:00:00 2001
From: Rob Ruana
Date: Sun, 12 Jun 2016 14:55:39 -0600
Subject: [PATCH 095/217] Fix #2537: [Napoleon] Corrects minor formatting issue
on example NumPy Attributes section
---
doc/ext/example_numpy.py | 1 +
1 file changed, 1 insertion(+)
diff --git a/doc/ext/example_numpy.py b/doc/ext/example_numpy.py
index bb91cac82..90f182129 100644
--- a/doc/ext/example_numpy.py
+++ b/doc/ext/example_numpy.py
@@ -37,6 +37,7 @@ module_level_variable1 : int
one convention to document module level variables and be consistent
with it.
+
.. _NumPy Documentation HOWTO:
https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
From 2d20e337b3838e23c64ec6bf353509fa60b732e9 Mon Sep 17 00:00:00 2001
From: Jakob Lykke Andersen
Date: Tue, 14 Jun 2016 15:17:45 +0900
Subject: [PATCH 096/217] C++, properly look up constructors.
Fixes sphinx-doc/sphinx#2666.
---
CHANGES | 1 +
sphinx/domains/cpp.py | 5 +++++
2 files changed, 6 insertions(+)
diff --git a/CHANGES b/CHANGES
index 04ce97389..3c1b5d981 100644
--- a/CHANGES
+++ b/CHANGES
@@ -26,6 +26,7 @@ Bugs fixed
* #2639: Sphinx now bundles iftex.sty
* Failed to build PDF with framed.sty 0.95
* Sphinx now bundles needspace.sty
+* #2666: C++, properly look up nested names involving constructors.
Release 1.4.3 (released Jun 5, 2016)
diff --git a/sphinx/domains/cpp.py b/sphinx/domains/cpp.py
index 5d15d3020..a64b488cd 100644
--- a/sphinx/domains/cpp.py
+++ b/sphinx/domains/cpp.py
@@ -2660,6 +2660,10 @@ class Symbol(object):
if symbol is None:
# TODO: maybe search without template args
return None
+ # We have now matched part of a nested name, and need to match more
+ # so even if we should matchSelf before, we definitely shouldn't
+ # even more. (see also issue #2666)
+ matchSelf = False
parentSymbol = symbol
assert False # should have returned in the loop
@@ -4114,6 +4118,7 @@ class CPPDomain(Domain):
matchSelf=True)
if s is None or s.declaration is None:
return None, None
+
declaration = s.declaration
fullNestedName = s.get_full_nested_name()
name = text_type(fullNestedName).lstrip(':')
From bd342b872484574581d880ac47cd1292f8a19178 Mon Sep 17 00:00:00 2001
From: Jakob Lykke Andersen
Date: Tue, 14 Jun 2016 14:25:15 +0900
Subject: [PATCH 097/217] C++, add warnings for misleading uses of roles.
---
CHANGES | 2 ++
sphinx/domains/cpp.py | 22 ++++++++++++++++++++++
2 files changed, 24 insertions(+)
diff --git a/CHANGES b/CHANGES
index 6dddee219..88a5ede35 100644
--- a/CHANGES
+++ b/CHANGES
@@ -21,6 +21,8 @@ Features added
* #2575: Now ``sphinx.ext.graphviz`` allows ``:align:`` option
* Show warnings if unknown key is specified to `latex_elements`
* Show warnings if no domains match with `primary_domain` (ref: #2001)
+* C++, show warnings when the kind of role is misleading for the kind
+ of target it refers to (e.g., using the `class` role for a function).
Bugs fixed
----------
diff --git a/sphinx/domains/cpp.py b/sphinx/domains/cpp.py
index 7d41d6570..5bfbdb948 100644
--- a/sphinx/domains/cpp.py
+++ b/sphinx/domains/cpp.py
@@ -4123,6 +4123,28 @@ class CPPDomain(Domain):
matchSelf=True)
if s is None or s.declaration is None:
return None, None
+
+ if typ.startswith('cpp:'):
+ typ = typ[4:]
+ if typ == 'func':
+ typ = 'function'
+ declTyp = s.declaration.objectType
+
+ def checkType():
+ if typ == 'any':
+ return True
+ elif typ == 'var' or typ == 'member':
+ return declTyp == 'var' or declTyp == 'member'
+ elif typ in ['enum', 'enumerator', 'class', 'function']:
+ return declTyp == typ
+ elif typ == 'type':
+ return declTyp in ['enum', 'class', 'function', 'type']
+ else:
+ print("Type is %s" % typ)
+ assert False
+ if not checkType():
+ warner.warn("cpp:%s targets a %s." % (typ, s.declaration.objectType))
+
declaration = s.declaration
fullNestedName = s.get_full_nested_name()
name = text_type(fullNestedName).lstrip(':')
From c0df9205e6b326a36dab15d1dcf9659e7ce03796 Mon Sep 17 00:00:00 2001
From: Jakob Lykke Andersen
Date: Tue, 14 Jun 2016 15:55:01 +0900
Subject: [PATCH 098/217] C++, skip adding already used old-style ids.
See michaeljones/breathe#266.
---
sphinx/domains/cpp.py | 12 +++++++++---
1 file changed, 9 insertions(+), 3 deletions(-)
diff --git a/sphinx/domains/cpp.py b/sphinx/domains/cpp.py
index a64b488cd..46f775e44 100644
--- a/sphinx/domains/cpp.py
+++ b/sphinx/domains/cpp.py
@@ -3738,7 +3738,7 @@ class CPPObject(ObjectDescription):
id_v1 = None
id_v2 = ast.get_id_v2()
# store them in reverse order, so the newest is first
- ids = [id_v2, id_v1]
+ ids = [id_v2, id_v1]
newestId = ids[0]
assert newestId # shouldn't be None
@@ -3759,8 +3759,14 @@ class CPPObject(ObjectDescription):
else:
# print("[CPP] non-unique name:", name)
pass
- for id in ids:
- if id: # is None when the element didn't exist in that version
+ # always add the newest id
+ assert newestId
+ signode['ids'].append(newestId)
+ # only add compatibility ids when there are no conflicts
+ for id in ids[1:]:
+ if not id: # is None when the element didn't exist in that version
+ continue
+ if id not in self.state.document.ids:
signode['ids'].append(id)
signode['first'] = (not self.names) # hmm, what is this abound?
self.state.document.note_explicit_target(signode)
From 8608387585b6d24945a4ba94f80f50714425a6d4 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Tue, 14 Jun 2016 10:01:53 +0200
Subject: [PATCH 099/217] Fix #2676: (latex) Error with verbatim text in
captions
Was caused by PR#2627 due to fragile ``\@noligs`` added to ``\code``.
---
CHANGES | 2 ++
sphinx/texinputs/sphinx.sty | 8 ++++----
2 files changed, 6 insertions(+), 4 deletions(-)
diff --git a/CHANGES b/CHANGES
index 3c1b5d981..890d9bd59 100644
--- a/CHANGES
+++ b/CHANGES
@@ -4,6 +4,8 @@ Release 1.4.5 (in development)
Bugs fixed
----------
+* #2676: (latex) Error with verbatim text in captions since Sphinx 1.4.4
+
Release 1.4.4 (released Jun 12, 2016)
=====================================
diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty
index 9b09b2b51..1c98654b3 100644
--- a/sphinx/texinputs/sphinx.sty
+++ b/sphinx/texinputs/sphinx.sty
@@ -145,10 +145,10 @@
% Some custom font markup commands.
%
\newcommand{\strong}[1]{{\textbf{#1}}}
-% let \code and \bfcode use straight quotes (\@noligs patched by upquote)
-% use \scantokens to handle e.g. \item[{\code{'fontenc'}}], too late for
-% \code to change catcodes.
-\newcommand{\code}[1]{{\@noligs\scantokens{\texttt{#1}}}}
+% let \code and \bfcode use straight quotes. \@noligs patched by upquote,
+% but needs protection in "moving arguments" such as for captions.
+\newcommand{\code}{}% raise error if exists already
+\DeclareRobustCommand{\code}[1]{{\@noligs\scantokens{\texttt{#1}}}}
\newcommand{\bfcode}[1]{\code{\bfseries#1}}
\newcommand{\email}[1]{\textsf{#1}}
\newcommand{\tablecontinued}[1]{\textsf{#1}}
From 5510653d6ebe7f7f6b834879a66d18071e16a5d6 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Sun, 12 Jun 2016 19:35:47 +0200
Subject: [PATCH 100/217] Fix #2629. Add new config option
``latex_keep_old_macro_names``
The cause of the issue was a clash about ``\titleref`` macro being already
defined in memoir class context. To avoid similar problems, this makes
the text styling macros
``\strong``, ``\code``, ``\bfcode``, ``\email``, ``\tablecontinued``,
``\titleref``, ``\menuselection``, ``\accelerator``, ``\crossref``,
``\termref``, ``\optional``,
also available with ``\sphinx`` prefix, with a conf.py boolean option to
let sphinx.sty only define ``\sphinx``-prefixed macros. As default value
is False, backwards compatibility is maintained.
On this occasion, some internal non-public macros have been renamed with
prefix ``\spx@``. The command
find . -name '*.sty' -exec grep -l \\\\spx@ {} \;
has been executed in TeXLive 2015 and 2016 installations to check no
package defines macros starting with ``\spx@``.
Some internal macros having public names (because they are written by
latex.py into the body of the latex document) have been renamed to have
``\sphinx`` prefix. The macros in sphinx.sty starting with \py@, or \DU,
or \PYG have not been modified. Similarly ``\release``, ``\version``,
``\releasename``, etc... have not been renamed.
---
CHANGES | 6 +
doc/config.rst | 15 ++
sphinx/config.py | 1 +
sphinx/quickstart.py | 6 +
sphinx/texinputs/sphinx.sty | 263 +++++++++++++++++++----------------
sphinx/writers/latex.py | 52 ++++---
tests/test_build_latex.py | 31 +++--
tests/test_directive_code.py | 24 ++--
tests/test_markup.py | 14 +-
9 files changed, 235 insertions(+), 177 deletions(-)
diff --git a/CHANGES b/CHANGES
index 890d9bd59..20d49c00d 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,10 +1,16 @@
Release 1.4.5 (in development)
==============================
+Features added
+--------------
+
+* new config option ``latex_keep_old_macro_names``, defaults to True. If False, let macros (for text styling) be defined only with ``\sphinx``-prefixed names.
+
Bugs fixed
----------
* #2676: (latex) Error with verbatim text in captions since Sphinx 1.4.4
+* #2629: memoir class crashes LaTeX. Fixed ``by latex_keep_old_macro_names=False`` (ref 2675)
Release 1.4.4 (released Jun 12, 2016)
diff --git a/doc/config.rst b/doc/config.rst
index b45f9df7c..b579d7e2b 100644
--- a/doc/config.rst
+++ b/doc/config.rst
@@ -1565,6 +1565,21 @@ These options influence LaTeX output.
value selected the ``'inline'`` display. For backwards compatibility,
``True`` is still accepted.
+.. confval:: latex_keep_old_macro_names
+
+ If ``True`` (default) the ``\strong``, ``\code``, ``\bfcode``, ``\email``,
+ ``\tablecontinued``, ``\titleref``, ``\menuselection``, ``\accelerator``,
+ ``\crossref``, ``\termref``, and ``\optional`` text styling macros are
+ pre-defined by Sphinx and may be user-customized by some
+ ``\renewcommand``'s inserted either via ``'preamble'`` key or :dudir:`raw
+ ` directive. If ``False``, only ``\sphinxstrong``,
+ etc... macros are defined (and may be redefined by user). Setting to
+ ``False`` may help solve macro name conflicts caused by user-added latex
+ packages.
+
+ .. versionadded:: 1.4.5
+
+
.. confval:: latex_elements
.. versionadded:: 0.5
diff --git a/sphinx/config.py b/sphinx/config.py
index 9cbf655f8..9527d9a8d 100644
--- a/sphinx/config.py
+++ b/sphinx/config.py
@@ -209,6 +209,7 @@ class Config(object):
None),
latex_logo = (None, None, string_classes),
latex_appendices = ([], None),
+ latex_keep_old_macro_names = (True, None),
# now deprecated - use latex_toplevel_sectioning
latex_use_parts = (False, None),
latex_toplevel_sectioning = (None, None, [str]),
diff --git a/sphinx/quickstart.py b/sphinx/quickstart.py
index 1f14c0d09..4680fecd4 100644
--- a/sphinx/quickstart.py
+++ b/sphinx/quickstart.py
@@ -359,6 +359,12 @@ latex_documents = [
#
# latex_appendices = []
+# It false, will not define \strong, \code, \titleref, \crossref ... but only
+# \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added
+# packages.
+#
+# latex_keep_old_macro_names = True
+
# If false, no module index is generated.
#
# latex_domain_indices = True
diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty
index 1c98654b3..1cec7481e 100644
--- a/sphinx/texinputs/sphinx.sty
+++ b/sphinx/texinputs/sphinx.sty
@@ -20,7 +20,7 @@
\RequirePackage{makeidx}
% For framing code-blocks and warning type notices, and shadowing topics
\RequirePackage{framed}
-\newif\ifSphinx@inframed % flag set if we are in a framed environment
+\newif\ifspx@inframed % flag set if we are in a framed environment
% ifthen not used anymore and will be removed at Sphinx-1.5
\RequirePackage{ifthen}
% The xcolor package draws better fcolorboxes around verbatim code
@@ -69,7 +69,7 @@
\RequirePackage{graphicx}
% for PDF output, use colors and maximal compression
-\newif\ifsphinxpdfoutput\sphinxpdfoutputfalse
+\newif\ifsphinxpdfoutput % used in \maketitle
\ifx\pdfoutput\undefined\else\ifcase\pdfoutput
\let\py@NormalColor\relax
\let\py@TitleColor\relax
@@ -114,6 +114,7 @@
% Use this to set the font family for headers and other decor:
\newcommand{\py@HeaderFamily}{\sffamily\bfseries}
+\newcommand{\sphinxSetHeaderFamily}[1]{\renewcommand{\py@HeaderFamily}{#1}}
% Redefine the 'normal' header/footer style when using "fancyhdr" package:
\@ifundefined{fancyhf}{}{
@@ -143,23 +144,23 @@
}
% Some custom font markup commands.
-%
-\newcommand{\strong}[1]{{\textbf{#1}}}
-% let \code and \bfcode use straight quotes. \@noligs patched by upquote,
+% *** the macros without \sphinx prefix are still defined at bottom of file ***
+\newcommand{\sphinxstrong}[1]{{\textbf{#1}}}
+% let \sphinxcode and \sphinxbfcode use straight quotes. \@noligs patched by upquote,
% but needs protection in "moving arguments" such as for captions.
-\newcommand{\code}{}% raise error if exists already
-\DeclareRobustCommand{\code}[1]{{\@noligs\scantokens{\texttt{#1}}}}
-\newcommand{\bfcode}[1]{\code{\bfseries#1}}
-\newcommand{\email}[1]{\textsf{#1}}
-\newcommand{\tablecontinued}[1]{\textsf{#1}}
-\newcommand{\titleref}[1]{\emph{#1}}
-\newcommand{\menuselection}[1]{\emph{#1}}
-\newcommand{\accelerator}[1]{\underline{#1}}
-\newcommand{\crossref}[1]{\emph{#1}}
-\newcommand{\termref}[1]{\emph{#1}}
+% Use \scantokens to handle e.g. \item[{\sphinxcode{'fontenc'}}]
+\DeclareRobustCommand{\sphinxcode}[1]{{\@noligs\scantokens{\texttt{#1}}}}
+\newcommand{\sphinxbfcode}[1]{\sphinxcode{\bfseries#1}}
+\newcommand{\sphinxemail}[1]{\textsf{#1}}
+\newcommand{\sphinxtablecontinued}[1]{\textsf{#1}}
+\newcommand{\sphinxtitleref}[1]{\emph{#1}}
+\newcommand{\sphinxmenuselection}[1]{\emph{#1}}
+\newcommand{\sphinxaccelerator}[1]{\underline{#1}}
+\newcommand{\sphinxcrossref}[1]{\emph{#1}}
+\newcommand{\sphinxtermref}[1]{\emph{#1}}
+% miscellaneous related to footnotes
\newcommand*{\sphinxAtStartFootnote}{\mbox{ }}
-
% Support large numbered footnotes in minipage (cf. admonitions)
\def\thempfootnote{\arabic{mpfootnote}}
@@ -169,8 +170,8 @@
\let\OriginalVerbatim=\Verbatim
\let\endOriginalVerbatim=\endVerbatim
-\newcommand\Sphinx@colorbox [2]{%
-% #1 will be \fcolorbox or, for first part of frame: \Sphinx@fcolorbox
+\newcommand\spx@colorbox [2]{%
+% #1 will be \fcolorbox or, for first part of frame: \spx@fcolorbox
% let the framing obey the current indentation (adapted from framed.sty's code).
\hskip\@totalleftmargin
\hskip-\fboxsep\hskip-\fboxrule
@@ -179,47 +180,46 @@
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth
}
% use of \color@b@x here is compatible with both xcolor.sty and color.sty
-\def\Sphinx@fcolorbox #1#2%
- {\color@b@x {\fboxsep\z@\color{#1}\Sphinx@VerbatimFBox}{\color{#2}}}%
+\def\spx@fcolorbox #1#2%
+ {\color@b@x {\fboxsep\z@\color{#1}\spx@VerbatimFBox}{\color{#2}}}%
-% The title is specified from outside as macro \SphinxVerbatimTitle.
-% \SphinxVerbatimTitle is reset to empty after each use of Verbatim.
-\newcommand*\SphinxVerbatimTitle {}
+% The title is specified from outside as macro \sphinxVerbatimTitle.
+% \sphinxVerbatimTitle is reset to empty after each use of Verbatim.
+\newcommand*\sphinxVerbatimTitle {}
% Holder macro for labels of literal blocks. Set-up by LaTeX writer.
-\newcommand*\SphinxLiteralBlockLabel {}
-\newcommand*\SphinxSetupCaptionForVerbatim [2]
+\newcommand*\sphinxLiteralBlockLabel {}
+\newcommand*\sphinxSetupCaptionForVerbatim [2]
{%
- \needspace{\literalblockneedspace}%
-% insert a \label via \SphinxLiteralBlockLabel
+ \needspace{\sphinxliteralblockneedspace}%
+% insert a \label via \sphinxLiteralBlockLabel
% reset to normal the color for the literal block caption
% the caption inserts \abovecaptionskip whitespace above itself (usually 10pt)
% there is also \belowcaptionskip but it is usually zero, hence the \smallskip
- \def\SphinxVerbatimTitle
- {\py@NormalColor\captionof{#1}{\SphinxLiteralBlockLabel #2}\smallskip }%
+ \def\sphinxVerbatimTitle
+ {\py@NormalColor\captionof{#1}{\sphinxLiteralBlockLabel #2}\smallskip }%
}
% Inspired and adapted from framed.sty's \CustomFBox with extra handling
% of a non separable by pagebreak caption, and controlled counter stepping.
-\newif\ifSphinx@myfirstframedpass
-
-\long\def\Sphinx@VerbatimFBox#1{%
+\newif\ifspx@myfirstframedpass
+\long\def\spx@VerbatimFBox#1{%
\leavevmode
\begingroup
% framed.sty does some measuring but this macro adds possibly a caption
% use amsmath conditional to inhibit the caption counter stepping after
% first pass
- \ifSphinx@myfirstframedpass\else\firstchoice@false\fi
+ \ifspx@myfirstframedpass\else\firstchoice@false\fi
\setbox\@tempboxa\hbox{\kern\fboxsep{#1}\kern\fboxsep}%
\hbox
{\lower\dimexpr\fboxrule+\fboxsep+\dp\@tempboxa
\hbox{%
- \vbox{\ifx\SphinxVerbatimTitle\empty\else
+ \vbox{\ifx\sphinxVerbatimTitle\empty\else
% add the caption in a centered way above possibly indented frame
% hide its width from framed.sty's measuring step
% note that the caption brings \abovecaptionskip top vertical space
\moveright\dimexpr\fboxrule+.5\wd\@tempboxa
\hb@xt@\z@{\hss\begin{minipage}{\wd\@tempboxa}%
- \SphinxVerbatimTitle
+ \sphinxVerbatimTitle
\end{minipage}\hss}\fi
% draw frame border _latest_ to avoid pdf viewer issue
\kern\fboxrule
@@ -236,51 +236,51 @@
\hrule\@height\fboxrule}%
}}%
\endgroup
- \global\Sphinx@myfirstframedpassfalse
+ \global\spx@myfirstframedpassfalse
}
% For linebreaks inside Verbatim environment from package fancyvrb.
-\newbox\Sphinxcontinuationbox
-\newbox\Sphinxvisiblespacebox
+\newbox\sphinxcontinuationbox
+\newbox\sphinxvisiblespacebox
% These are user customizable e.g. from latex_elements's preamble key.
% Use of \textvisiblespace for compatibility with XeTeX/LuaTeX/fontspec.
-\newcommand*\Sphinxvisiblespace {\textcolor{red}{\textvisiblespace}}
-\newcommand*\Sphinxcontinuationsymbol {\textcolor{red}{\llap{\tiny$\m@th\hookrightarrow$}}}
-\newcommand*\Sphinxcontinuationindent {3ex }
-\newcommand*\Sphinxafterbreak {\kern\Sphinxcontinuationindent\copy\Sphinxcontinuationbox}
+\newcommand*\sphinxvisiblespace {\textcolor{red}{\textvisiblespace}}
+\newcommand*\sphinxcontinuationsymbol {\textcolor{red}{\llap{\tiny$\m@th\hookrightarrow$}}}
+\newcommand*\sphinxcontinuationindent {3ex }
+\newcommand*\sphinxafterbreak {\kern\sphinxcontinuationindent\copy\sphinxcontinuationbox}
% Take advantage of the already applied Pygments mark-up to insert
% potential linebreaks for TeX processing.
% {, <, #, %, $, ' and ": go to next line.
% _, }, ^, &, >, - and ~: stay at end of broken line.
% Use of \textquotesingle for straight quote.
-\newcommand*\Sphinxbreaksatspecials {%
- \def\PYGZus{\discretionary{\char`\_}{\Sphinxafterbreak}{\char`\_}}%
- \def\PYGZob{\discretionary{}{\Sphinxafterbreak\char`\{}{\char`\{}}%
- \def\PYGZcb{\discretionary{\char`\}}{\Sphinxafterbreak}{\char`\}}}%
- \def\PYGZca{\discretionary{\char`\^}{\Sphinxafterbreak}{\char`\^}}%
- \def\PYGZam{\discretionary{\char`\&}{\Sphinxafterbreak}{\char`\&}}%
- \def\PYGZlt{\discretionary{}{\Sphinxafterbreak\char`\<}{\char`\<}}%
- \def\PYGZgt{\discretionary{\char`\>}{\Sphinxafterbreak}{\char`\>}}%
- \def\PYGZsh{\discretionary{}{\Sphinxafterbreak\char`\#}{\char`\#}}%
- \def\PYGZpc{\discretionary{}{\Sphinxafterbreak\char`\%}{\char`\%}}%
- \def\PYGZdl{\discretionary{}{\Sphinxafterbreak\char`\$}{\char`\$}}%
- \def\PYGZhy{\discretionary{\char`\-}{\Sphinxafterbreak}{\char`\-}}%
- \def\PYGZsq{\discretionary{}{\Sphinxafterbreak\textquotesingle}{\textquotesingle}}%
- \def\PYGZdq{\discretionary{}{\Sphinxafterbreak\char`\"}{\char`\"}}%
- \def\PYGZti{\discretionary{\char`\~}{\Sphinxafterbreak}{\char`\~}}%
+\newcommand*\sphinxbreaksatspecials {%
+ \def\PYGZus{\discretionary{\char`\_}{\sphinxafterbreak}{\char`\_}}%
+ \def\PYGZob{\discretionary{}{\sphinxafterbreak\char`\{}{\char`\{}}%
+ \def\PYGZcb{\discretionary{\char`\}}{\sphinxafterbreak}{\char`\}}}%
+ \def\PYGZca{\discretionary{\char`\^}{\sphinxafterbreak}{\char`\^}}%
+ \def\PYGZam{\discretionary{\char`\&}{\sphinxafterbreak}{\char`\&}}%
+ \def\PYGZlt{\discretionary{}{\sphinxafterbreak\char`\<}{\char`\<}}%
+ \def\PYGZgt{\discretionary{\char`\>}{\sphinxafterbreak}{\char`\>}}%
+ \def\PYGZsh{\discretionary{}{\sphinxafterbreak\char`\#}{\char`\#}}%
+ \def\PYGZpc{\discretionary{}{\sphinxafterbreak\char`\%}{\char`\%}}%
+ \def\PYGZdl{\discretionary{}{\sphinxafterbreak\char`\$}{\char`\$}}%
+ \def\PYGZhy{\discretionary{\char`\-}{\sphinxafterbreak}{\char`\-}}%
+ \def\PYGZsq{\discretionary{}{\sphinxafterbreak\textquotesingle}{\textquotesingle}}%
+ \def\PYGZdq{\discretionary{}{\sphinxafterbreak\char`\"}{\char`\"}}%
+ \def\PYGZti{\discretionary{\char`\~}{\sphinxafterbreak}{\char`\~}}%
}
% Some characters . , ; ? ! / are not pygmentized.
% This macro makes them "active" and they will insert potential linebreaks
-\newcommand*\Sphinxbreaksatpunct {%
- \lccode`\~`\.\lowercase{\def~}{\discretionary{\char`\.}{\Sphinxafterbreak}{\char`\.}}%
- \lccode`\~`\,\lowercase{\def~}{\discretionary{\char`\,}{\Sphinxafterbreak}{\char`\,}}%
- \lccode`\~`\;\lowercase{\def~}{\discretionary{\char`\;}{\Sphinxafterbreak}{\char`\;}}%
- \lccode`\~`\:\lowercase{\def~}{\discretionary{\char`\:}{\Sphinxafterbreak}{\char`\:}}%
- \lccode`\~`\?\lowercase{\def~}{\discretionary{\char`\?}{\Sphinxafterbreak}{\char`\?}}%
- \lccode`\~`\!\lowercase{\def~}{\discretionary{\char`\!}{\Sphinxafterbreak}{\char`\!}}%
- \lccode`\~`\/\lowercase{\def~}{\discretionary{\char`\/}{\Sphinxafterbreak}{\char`\/}}%
+\newcommand*\sphinxbreaksatpunct {%
+ \lccode`\~`\.\lowercase{\def~}{\discretionary{\char`\.}{\sphinxafterbreak}{\char`\.}}%
+ \lccode`\~`\,\lowercase{\def~}{\discretionary{\char`\,}{\sphinxafterbreak}{\char`\,}}%
+ \lccode`\~`\;\lowercase{\def~}{\discretionary{\char`\;}{\sphinxafterbreak}{\char`\;}}%
+ \lccode`\~`\:\lowercase{\def~}{\discretionary{\char`\:}{\sphinxafterbreak}{\char`\:}}%
+ \lccode`\~`\?\lowercase{\def~}{\discretionary{\char`\?}{\sphinxafterbreak}{\char`\?}}%
+ \lccode`\~`\!\lowercase{\def~}{\discretionary{\char`\!}{\sphinxafterbreak}{\char`\!}}%
+ \lccode`\~`\/\lowercase{\def~}{\discretionary{\char`\/}{\sphinxafterbreak}{\char`\/}}%
\catcode`\.\active
\catcode`\,\active
\catcode`\;\active
@@ -297,25 +297,25 @@
% list starts new par, but we don't want it to be set apart vertically
\parskip\z@skip
% first, let's check if there is a caption
- \ifx\SphinxVerbatimTitle\empty
+ \ifx\sphinxVerbatimTitle\empty
\addvspace\z@% counteract possible previous negative skip (French lists!)
\smallskip
% there was no caption. Check if nevertheless a label was set.
- \ifx\SphinxLiteralBlockLabel\empty\else
+ \ifx\sphinxLiteralBlockLabel\empty\else
% we require some space to be sure hyperlink target from \phantomsection
% will not be separated from upcoming verbatim by a page break
- \needspace{\literalblockwithoutcaptionneedspace}%
- \phantomsection\SphinxLiteralBlockLabel
+ \needspace{\sphinxliteralblockwithoutcaptionneedspace}%
+ \phantomsection\sphinxLiteralBlockLabel
\fi
\fi
- % non-empty \SphinxVerbatimTitle has label inside it (in case there is one)
+ % non-empty \sphinxVerbatimTitle has label inside it (in case there is one)
% Customize framed.sty \MakeFramed to glue caption to literal block
- \global\Sphinx@myfirstframedpasstrue
- % via \Sphinx@fcolorbox, will use \Sphinx@VerbatimFBox which inserts title
- \def\FrameCommand {\Sphinx@colorbox\Sphinx@fcolorbox }%
+ \global\spx@myfirstframedpasstrue
+ % via \spx@fcolorbox, will use \spx@VerbatimFBox which inserts title
+ \def\FrameCommand {\spx@colorbox\spx@fcolorbox }%
\let\FirstFrameCommand\FrameCommand
% for mid pages and last page portion of (long) split frame:
- \def\MidFrameCommand{\Sphinx@colorbox\fcolorbox }%
+ \def\MidFrameCommand{\spx@colorbox\fcolorbox }%
\let\LastFrameCommand\MidFrameCommand
% fancyvrb's Verbatim puts each input line in (unbreakable) horizontal boxes.
% This customization wraps each line from the input in a \vtop, thus
@@ -323,10 +323,10 @@
% - The codeline counter will be increased only once.
% - The wrapped material will not break across pages, it is impossible
% to achieve this without extensive rewrite of fancyvrb.
- % - The (not used in Sphinx) obeytabs option to Verbatim is
+ % - The (not used in sphinx) obeytabs option to Verbatim is
% broken by this change (showtabs and tabspace work).
- \sbox\Sphinxcontinuationbox {\Sphinxcontinuationsymbol}%
- \sbox\Sphinxvisiblespacebox {\FV@SetupFont\Sphinxvisiblespace}%
+ \sbox\sphinxcontinuationbox {\sphinxcontinuationsymbol}%
+ \sbox\sphinxvisiblespacebox {\FV@SetupFont\sphinxvisiblespace}%
\def\FancyVerbFormatLine ##1{\hsize\linewidth
\vtop{\raggedright\hyphenpenalty\z@\exhyphenpenalty\z@
\doublehyphendemerits\z@\finalhyphendemerits\z@
@@ -337,7 +337,7 @@
% Stretch/shrink are however usually zero for typewriter font.
\def\FV@Space {%
\nobreak\hskip\z@ plus\fontdimen3\font minus\fontdimen4\font
- \discretionary{\copy\Sphinxvisiblespacebox}{\Sphinxafterbreak}
+ \discretionary{\copy\sphinxvisiblespacebox}{\sphinxafterbreak}
{\kern\fontdimen2\font}%
}%
% go around fancyvrb's check of @currenvir (for case of minipage below)
@@ -345,7 +345,7 @@
% go around fancyvrb's check of current list depth
\def\@toodeep {\advance\@listdepth\@ne}%
% Allow breaks at special characters using \PYG... macros.
- \Sphinxbreaksatspecials
+ \sphinxbreaksatspecials
% The list environment is needed to control perfectly the vertical space.
% Note: \OuterFrameSep used by framed.sty is later set to \topsep hence 0pt.
% - if caption: vertical space above caption = (\abovecaptionskip + D) with
@@ -360,7 +360,7 @@
\parindent \z@% becomes \itemindent. Default zero, but perhaps overwritten.
\trivlist\item\relax
% use a minipage if we are already inside a framed environment
- \ifSphinx@inframed\noindent\begin{minipage}{\linewidth}\fi
+ \ifspx@inframed\noindent\begin{minipage}{\linewidth}\fi
\MakeFramed {% adapted over from framed.sty's snugshade environment
\advance\hsize-\width\@totalleftmargin\z@\linewidth\hsize
\@setminipage }%
@@ -368,45 +368,45 @@
% For grid placement from \strut's in \FancyVerbFormatLine
\lineskip\z@skip
% Breaks at punctuation characters . , ; ? ! and / need catcode=\active
- \OriginalVerbatim[#1,codes*=\Sphinxbreaksatpunct]%
+ \OriginalVerbatim[#1,codes*=\sphinxbreaksatpunct]%
}
\renewcommand{\endVerbatim}{%
\endOriginalVerbatim
\par\unskip\@minipagefalse\endMakeFramed
- \ifSphinx@inframed\end{minipage}\fi
+ \ifspx@inframed\end{minipage}\fi
\endtrivlist
}
% define macro to frame contents and add shadow on right and bottom
-\def\Sphinx@shadowsep {5\p@} % \p@ means "pt "
-\def\Sphinx@shadowsize {4\p@}
-\def\Sphinx@shadowrule {\fboxrule}
-\long\def\Sphinx@ShadowFBox#1{%
+\def\spx@shadowsep {5\p@} % \p@ means "pt "
+\def\spx@shadowsize {4\p@}
+\def\spx@shadowrule {\fboxrule}
+\long\def\spx@ShadowFBox#1{%
\leavevmode\begingroup
% first we frame the box #1
\setbox\@tempboxa
- \hbox{\vrule\@width\Sphinx@shadowrule
- \vbox{\hrule\@height\Sphinx@shadowrule
- \kern\Sphinx@shadowsep
- \hbox{\kern\Sphinx@shadowsep #1\kern\Sphinx@shadowsep}%
- \kern\Sphinx@shadowsep
- \hrule\@height\Sphinx@shadowrule}%
- \vrule\@width\Sphinx@shadowrule}%
+ \hbox{\vrule\@width\spx@shadowrule
+ \vbox{\hrule\@height\spx@shadowrule
+ \kern\spx@shadowsep
+ \hbox{\kern\spx@shadowsep #1\kern\spx@shadowsep}%
+ \kern\spx@shadowsep
+ \hrule\@height\spx@shadowrule}%
+ \vrule\@width\spx@shadowrule}%
% Now we add the shadow, like \shadowbox from fancybox.sty would do
- \dimen@\dimexpr.5\Sphinx@shadowrule+\Sphinx@shadowsize\relax
+ \dimen@\dimexpr.5\spx@shadowrule+\spx@shadowsize\relax
\hbox{\vbox{\offinterlineskip
- \hbox{\copy\@tempboxa\kern-.5\Sphinx@shadowrule
+ \hbox{\copy\@tempboxa\kern-.5\spx@shadowrule
% add shadow on right side
- \lower\Sphinx@shadowsize
+ \lower\spx@shadowsize
\hbox{\vrule\@height\ht\@tempboxa \@width\dimen@}%
}%
\kern-\dimen@ % shift back vertically to bottom of frame
% and add shadow at bottom
- \moveright\Sphinx@shadowsize
+ \moveright\spx@shadowsize
\vbox{\hrule\@width\wd\@tempboxa \@height\dimen@}%
}%
% move left by the size of right shadow so shadow adds no width
- \kern-\Sphinx@shadowsize
+ \kern-\spx@shadowsize
}%
\endgroup
}
@@ -415,8 +415,8 @@
% works well inside Lists and Quote-like environments
% produced by ``topic'' directive (or local contents)
% could nest if LaTeX writer authorized it
-\newenvironment{SphinxShadowBox}
- {\def\FrameCommand {\Sphinx@ShadowFBox }%
+\newenvironment{sphinxShadowBox}
+ {\def\FrameCommand {\spx@ShadowFBox }%
% configure framed.sty not to add extra vertical spacing
\ifdefined\OuterFrameSep \OuterFrameSep\z@skip \fi
% the \trivlist will add the vertical spacing on top and bottom which is
@@ -427,8 +427,8 @@
\def\FrameHeightAdjust {\baselineskip}%
\trivlist\item\noindent
% use a minipage if we are already inside a framed environment
- \ifSphinx@inframed\begin{minipage}{\linewidth}\fi
- \MakeFramed {\Sphinx@inframedtrue
+ \ifspx@inframed\begin{minipage}{\linewidth}\fi
+ \MakeFramed {\spx@inframedtrue
% framed.sty puts into "\width" the added width (=2shadowsep+2shadowrule)
% adjust \hsize to what the contents must use
\advance\hsize-\width
@@ -454,7 +454,7 @@
\fi
\@minipagefalse
\endMakeFramed
- \ifSphinx@inframed\end{minipage}\fi
+ \ifspx@inframed\end{minipage}\fi
\endtrivlist
}
@@ -495,25 +495,25 @@
}{\end{list}}
% \optional is used for ``[, arg]``, i.e. desc_optional nodes.
-\newcommand{\optional}[1]{%
+\newcommand{\sphinxoptional}[1]{%
{\textnormal{\Large[}}{#1}\hspace{0.5mm}{\textnormal{\Large]}}}
\newlength{\py@argswidth}
\newcommand{\py@sigparams}[2]{%
- \parbox[t]{\py@argswidth}{#1\code{)}#2}}
+ \parbox[t]{\py@argswidth}{#1\sphinxcode{)}#2}}
\newcommand{\pysigline}[1]{\item[#1]\nopagebreak}
\newcommand{\pysiglinewithargsret}[3]{%
- \settowidth{\py@argswidth}{#1\code{(}}%
+ \settowidth{\py@argswidth}{#1\sphinxcode{(}}%
\addtolength{\py@argswidth}{-2\py@argswidth}%
\addtolength{\py@argswidth}{\linewidth}%
- \item[#1\code{(}\py@sigparams{#2}{#3}]}
+ \item[#1\sphinxcode{(}\py@sigparams{#2}{#3}]}
% Production lists
%
\newenvironment{productionlist}{
-% \def\optional##1{{\Large[}##1{\Large]}}
- \def\production##1##2{\\\code{##1}&::=&\code{##2}}
- \def\productioncont##1{\\& &\code{##1}}
+% \def\sphinxoptional##1{{\Large[}##1{\Large]}}
+ \def\production##1##2{\\\sphinxcode{##1}&::=&\sphinxcode{##2}}
+ \def\productioncont##1{\\& &\sphinxcode{##1}}
\parindent=2em
\indent
\setlength{\LTpre}{0pt}
@@ -541,7 +541,7 @@
\fboxsep\FrameSep \fboxrule\FrameRule\fbox{##1}%
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
% use a minipage if we are already inside a framed environment
- \ifSphinx@inframed
+ \ifspx@inframed
\noindent\begin{minipage}{\linewidth}
\else
% handle case where notice is first thing in a list item (or is quoted)
@@ -551,7 +551,7 @@
\vspace{\parskip}
\fi
\fi
- \MakeFramed {\Sphinx@inframedtrue
+ \MakeFramed {\spx@inframedtrue
\advance\hsize-\width \@totalleftmargin\z@ \linewidth\hsize
% minipage initialization copied from LaTeX source code.
\@pboxswfalse
@@ -570,7 +570,7 @@
\fi
\@minipagefalse
\endMakeFramed
- \ifSphinx@inframed\end{minipage}\fi
+ \ifspx@inframed\end{minipage}\fi
% arrange for similar spacing below frame as for "light" boxes.
\vskip .4\baselineskip
}
@@ -614,7 +614,7 @@
\newenvironment{notice}[2]{
\def\py@noticetype{#1}
\csname py@noticestart@#1\endcsname
- \strong{#2}
+ \sphinxstrong{#2} % <- legacy code creates a space after {#2}
}{\csname py@noticeend@\py@noticetype\endcsname}
% Allow the release number to be specified independently of the
@@ -684,7 +684,7 @@
% The following is stuff copied from docutils' latex writer.
%
-\newcommand{\optionlistlabel}[1]{\bf #1 \hfill}
+\newcommand{\optionlistlabel}[1]{\normalfont\bfseries #1 \hfill}% \bf deprecated
\newenvironment{optionlist}[1]
{\begin{list}{}
{\setlength{\labelwidth}{#1}
@@ -853,17 +853,38 @@
\RequirePackage{capt-of}
\RequirePackage{needspace}
% if the left page space is less than \literalblockneedspace, insert page-break
-\newcommand{\literalblockneedspace}{5\baselineskip}
-\newcommand{\literalblockwithoutcaptionneedspace}{1.5\baselineskip}
+\newcommand{\sphinxliteralblockneedspace}{5\baselineskip}
+\newcommand{\sphinxliteralblockwithoutcaptionneedspace}{1.5\baselineskip}
% figure in table
-\newenvironment{figure-in-table}[1][\linewidth]{%
+\newenvironment{sphinxfigure-in-table}[1][\linewidth]{%
\def\@captype{figure}%
\begin{minipage}{#1}%
}{\end{minipage}}
% store original \caption macro for use with figures in longtable and tabulary
-\AtBeginDocument{\let\Sphinx@originalcaption\caption}
-\newcommand*\figcaption
+\AtBeginDocument{\let\spx@originalcaption\caption}
+\newcommand*\sphinxfigcaption
{\ifx\equation$%$% this is trick to identify tabulary first pass
\firstchoice@false\else\firstchoice@true\fi
- \Sphinx@originalcaption }
+ \spx@originalcaption }
+
+% by default, also define macros with the no-prefix names
+\ifsphinxKeepOldNames
+ \typeout{** (sphinx) defining (legacy) text style macros without \string\sphinx\space prefix}
+ \typeout{** if clashes with packages, set latex_keep_old_macro_names=False in conf.py}
+ \@for\@tempa:=strong,bfcode,email,tablecontinued,titleref,%
+ menuselection,accelerator,crossref,termref,optional\do
+{% first, check if command with no prefix already exists
+ \expandafter\newcommand\csname\@tempa\endcsname{}%
+ % if no error give it the meaning defined so far with \sphinx prefix
+ \expandafter\let\csname\@tempa\expandafter\endcsname
+ \csname sphinx\@tempa\endcsname
+ % redefine the \sphinx prefixed macro to expand to non-prefixed one
+ \expandafter\def\csname sphinx\@tempa\expandafter\endcsname
+ \expandafter{\csname\@tempa\endcsname}%
+}
+ % robustified case needs special treatment
+ \newcommand\code{}\let\code\relax
+ \DeclareRobustCommand{\code}[1]{{\@noligs\scantokens{\texttt{#1}}}}
+ \def\sphinxcode{\code}%
+\fi
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index 5bd668572..524e035a7 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -33,6 +33,7 @@ from sphinx.util.smartypants import educate_quotes_latex
HEADER = r'''%% Generated by Sphinx.
\def\sphinxdocclass{%(docclass)s}
+\newif\ifsphinxKeepOldNames %(keepoldnames)s
\documentclass[%(papersize)s,%(pointsize)s%(classoptions)s]{%(wrapperclass)s}
\usepackage{iftex}
%(passoptionstopackages)s
@@ -391,6 +392,11 @@ class LaTeXTranslator(nodes.NodeVisitor):
'preamble': builder.config.latex_preamble,
'indexname': _('Index'),
})
+ # set-up boolean for sphinx.sty
+ if builder.config.latex_keep_old_macro_names:
+ self.elements['keepoldnames'] = '\\sphinxKeepOldNamestrue'
+ else:
+ self.elements['keepoldnames'] = '\\sphinxKeepOldNamesfalse'
if document.settings.docclass == 'howto':
docclass = builder.config.latex_docclass.get('howto', 'article')
else:
@@ -732,11 +738,11 @@ class LaTeXTranslator(nodes.NodeVisitor):
def visit_topic(self, node):
self.in_minipage = 1
- self.body.append('\n\\begin{SphinxShadowBox}\n')
+ self.body.append('\n\\begin{sphinxShadowBox}\n')
def depart_topic(self, node):
self.in_minipage = 0
- self.body.append('\\end{SphinxShadowBox}\n')
+ self.body.append('\\end{sphinxShadowBox}\n')
visit_sidebar = visit_topic
depart_sidebar = depart_topic
@@ -867,7 +873,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
self.body.append('}')
def visit_desc_addname(self, node):
- self.body.append(r'\code{')
+ self.body.append(r'\sphinxcode{')
self.literal_whitespace += 1
def depart_desc_addname(self, node):
@@ -887,7 +893,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
self.body.append(r'}')
def visit_desc_name(self, node):
- self.body.append(r'\bfcode{')
+ self.body.append(r'\sphinxbfcode{')
self.no_contractions += 1
self.literal_whitespace += 1
@@ -918,13 +924,13 @@ class LaTeXTranslator(nodes.NodeVisitor):
self.body.append('}')
def visit_desc_optional(self, node):
- self.body.append(r'\optional{')
+ self.body.append(r'\sphinxoptional{')
def depart_desc_optional(self, node):
self.body.append('}')
def visit_desc_annotation(self, node):
- self.body.append(r'\strong{')
+ self.body.append(r'\sphinxstrong{')
def depart_desc_annotation(self, node):
self.body.append('}')
@@ -938,7 +944,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
pass
def visit_seealso(self, node):
- self.body.append(u'\n\n\\strong{%s:}\n\n' % admonitionlabels['seealso'])
+ self.body.append(u'\n\n\\sphinxstrong{%s:}\n\n' % admonitionlabels['seealso'])
def depart_seealso(self, node):
self.body.append("\n\n")
@@ -1440,12 +1446,12 @@ class LaTeXTranslator(nodes.NodeVisitor):
# TODO: support align option
if 'width' in node:
length = width_to_latex_length(node['width'])
- self.body.append('\\begin{figure-in-table}[%s]\n\\centering\n' % length)
+ self.body.append('\\begin{sphinxfigure-in-table}[%s]\n\\centering\n' % length)
else:
- self.body.append('\\begin{figure-in-table}\n\\centering\n')
+ self.body.append('\\begin{sphinxfigure-in-table}\n\\centering\n')
if any(isinstance(child, nodes.caption) for child in node):
self.body.append('\\capstart')
- self.context.append(ids + '\\end{figure-in-table}\n')
+ self.context.append(ids + '\\end{sphinxfigure-in-table}\n')
elif node.get('align', '') in ('left', 'right'):
if 'width' in node:
length = width_to_latex_length(node['width'])
@@ -1487,11 +1493,11 @@ class LaTeXTranslator(nodes.NodeVisitor):
def visit_caption(self, node):
self.in_caption += 1
if self.in_container_literal_block:
- self.body.append('\\SphinxSetupCaptionForVerbatim{literal-block}{')
+ self.body.append('\\sphinxSetupCaptionForVerbatim{literal-block}{')
elif self.in_minipage and isinstance(node.parent, nodes.figure):
self.body.append('\\captionof{figure}{')
elif self.table and node.parent.tagname == 'figure':
- self.body.append('\\figcaption{')
+ self.body.append('\\sphinxfigcaption{')
else:
self.body.append('\\caption{')
@@ -1689,9 +1695,9 @@ class LaTeXTranslator(nodes.NodeVisitor):
# don't add a pageref for glossary terms
self.context.append('}}}')
# mark up as termreference
- self.body.append(r'\termref{')
+ self.body.append(r'\sphinxtermref{')
else:
- self.body.append(r'\crossref{')
+ self.body.append(r'\sphinxcrossref{')
if self.builder.config.latex_show_pagerefs and not \
self.in_production_list:
self.context.append('}}} (%s)' % self.hyperpageref(id))
@@ -1779,7 +1785,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
return self.depart_literal_emphasis(node)
def visit_title_reference(self, node):
- self.body.append(r'\titleref{')
+ self.body.append(r'\sphinxtitleref{')
def depart_title_reference(self, node):
self.body.append('}')
@@ -1807,7 +1813,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
if self.in_title:
self.body.append(r'\texttt{')
else:
- self.body.append(r'\code{')
+ self.body.append(r'\sphinxcode{')
def depart_literal(self, node):
self.no_contractions -= 1
@@ -1855,7 +1861,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
ids += self.hypertarget(node['ids'][0], anchor=False)
# LaTeX code will insert \phantomsection prior to \label
if ids:
- self.body.append('\n\\def\\SphinxLiteralBlockLabel{' + ids + '}')
+ self.body.append('\n\\def\\sphinxLiteralBlockLabel{' + ids + '}')
code = node.astext()
lang = self.hlsettingstack[-1][0]
linenos = code.count('\n') >= self.hlsettingstack[-1][1] - 1
@@ -1890,7 +1896,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
self.body.append('\n' + hlcode + '\\end{%sVerbatim}\n' %
(self.table and 'Original' or ''))
if ids:
- self.body.append('\\let\\SphinxLiteralBlockLabel\empty\n')
+ self.body.append('\\let\\sphinxLiteralBlockLabel\empty\n')
raise nodes.SkipNode
def depart_literal_block(self, node):
@@ -2016,10 +2022,10 @@ class LaTeXTranslator(nodes.NodeVisitor):
def visit_inline(self, node):
classes = node.get('classes', [])
if classes in [['menuselection'], ['guilabel']]:
- self.body.append(r'\menuselection{')
+ self.body.append(r'\sphinxmenuselection{')
self.context.append('}')
elif classes in [['accelerator']]:
- self.body.append(r'\accelerator{')
+ self.body.append(r'\sphinxaccelerator{')
self.context.append('}')
elif classes and not self.in_title:
self.body.append(r'\DUrole{%s}{' % ','.join(classes))
@@ -2053,13 +2059,13 @@ class LaTeXTranslator(nodes.NodeVisitor):
ids += self.hypertarget(node['ids'][0], anchor=False)
# define label for use in caption.
if ids:
- self.body.append('\n\\def\\SphinxLiteralBlockLabel{' + ids + '}\n')
+ self.body.append('\n\\def\\sphinxLiteralBlockLabel{' + ids + '}\n')
def depart_container(self, node):
if node.get('literal_block'):
self.in_container_literal_block -= 1
- self.body.append('\\let\\SphinxVerbatimTitle\\empty\n')
- self.body.append('\\let\\SphinxLiteralBlockLabel\\empty\n')
+ self.body.append('\\let\\sphinxVerbatimTitle\\empty\n')
+ self.body.append('\\let\\sphinxLiteralBlockLabel\\empty\n')
def visit_decoration(self, node):
pass
diff --git a/tests/test_build_latex.py b/tests/test_build_latex.py
index fdc594d09..503f41ef1 100644
--- a/tests/test_build_latex.py
+++ b/tests/test_build_latex.py
@@ -112,9 +112,9 @@ def test_writer(app, status, warning):
app.builder.build_all()
result = (app.outdir / 'SphinxTests.tex').text(encoding='utf8')
- assert ('\\begin{figure-in-table}\n\\centering\n\\capstart\n'
- '\\includegraphics{{img}.png}\n'
- '\\figcaption{figure in table}\\label{markup:id7}\\end{figure-in-table}' in result)
+ assert ('\\begin{sphinxfigure-in-table}\n\\centering\n\\capstart\n'
+ '\\includegraphics{{img}.png}\n\\sphinxfigcaption'
+ '{figure in table}\\label{markup:id7}\\end{sphinxfigure-in-table}' in result)
assert ('\\begin{wrapfigure}{r}{0pt}\n\\centering\n'
'\\includegraphics{{rimg}.png}\n\\caption{figure with align option}'
@@ -409,7 +409,7 @@ def test_footnote(app, status, warning):
assert '\\footnote[1]{\sphinxAtStartFootnote%\nnumbered\n}' in result
assert '\\footnote[2]{\sphinxAtStartFootnote%\nauto numbered\n}' in result
assert '\\footnote[3]{\sphinxAtStartFootnote%\nnamed\n}' in result
- assert '{\\hyperref[footnote:bar]{\\crossref{{[}bar{]}}}}' in result
+ assert '{\\hyperref[footnote:bar]{\\sphinxcrossref{{[}bar{]}}}}' in result
assert '\\bibitem[bar]{bar}{\\phantomsection\\label{footnote:bar} ' in result
assert '\\bibitem[bar]{bar}{\\phantomsection\\label{footnote:bar} \ncite' in result
assert '\\bibitem[bar]{bar}{\\phantomsection\\label{footnote:bar} \ncite\n}' in result
@@ -428,7 +428,7 @@ def test_reference_in_caption(app, status, warning):
print(status.getvalue())
print(warning.getvalue())
assert ('\\caption{This is the figure caption with a reference to \\label{index:id2}'
- '{\\hyperref[index:authoryear]{\\crossref{{[}AuthorYear{]}}}}.}' in result)
+ '{\\hyperref[index:authoryear]{\\sphinxcrossref{{[}AuthorYear{]}}}}.}' in result)
assert '\\chapter{The section with a reference to {[}AuthorYear{]}}' in result
assert '\\caption{The table title with a reference to {[}AuthorYear{]}}' in result
assert '\\paragraph{The rubric title with a reference to {[}AuthorYear{]}}' in result
@@ -462,11 +462,12 @@ def test_latex_show_urls_is_inline(app, status, warning):
'footnote in baz\n} in baz.rst' in result)
assert ('\\phantomsection\\label{index:id26}{\\hyperref[index:the\\string-section'
'\\string-with\\string-a\\string-reference\\string-to\\string-authoryear]'
- '{\\crossref{The section with a reference to \\phantomsection\\label{index:id1}'
- '{\\hyperref[index:authoryear]{\\crossref{{[}AuthorYear{]}}}}}}}' in result)
+ '{\\sphinxcrossref{The section with a reference to '
+ '\\phantomsection\\label{index:id1}'
+ '{\\hyperref[index:authoryear]{\\sphinxcrossref{{[}AuthorYear{]}}}}}}}' in result)
assert ('\\phantomsection\\label{index:id27}{\\hyperref[index:the\\string-section'
'\\string-with\\string-a\\string-reference\\string-to]'
- '{\\crossref{The section with a reference to }}}' in result)
+ '{\\sphinxcrossref{The section with a reference to }}}' in result)
assert 'First footnote: \\footnote[2]{\sphinxAtStartFootnote%\nFirst\n}' in result
assert 'Second footnote: \\footnote[1]{\sphinxAtStartFootnote%\nSecond\n}' in result
assert '\\href{http://sphinx-doc.org/}{Sphinx} (http://sphinx-doc.org/)' in result
@@ -499,11 +500,12 @@ def test_latex_show_urls_is_footnote(app, status, warning):
'footnote in baz\n} in baz.rst' in result)
assert ('\\phantomsection\\label{index:id26}{\\hyperref[index:the\\string-section'
'\\string-with\\string-a\\string-reference\\string-to\\string-authoryear]'
- '{\\crossref{The section with a reference to \\phantomsection\\label{index:id1}'
- '{\\hyperref[index:authoryear]{\\crossref{{[}AuthorYear{]}}}}}}}' in result)
+ '{\\sphinxcrossref{The section with a reference '
+ 'to \\phantomsection\\label{index:id1}'
+ '{\\hyperref[index:authoryear]{\\sphinxcrossref{{[}AuthorYear{]}}}}}}}' in result)
assert ('\\phantomsection\\label{index:id27}{\\hyperref[index:the\\string-section'
'\\string-with\\string-a\\string-reference\\string-to]'
- '{\\crossref{The section with a reference to }}}' in result)
+ '{\\sphinxcrossref{The section with a reference to }}}' in result)
assert 'First footnote: \\footnote[3]{\sphinxAtStartFootnote%\nFirst\n}' in result
assert 'Second footnote: \\footnote[1]{\sphinxAtStartFootnote%\nSecond\n}' in result
assert ('\\href{http://sphinx-doc.org/}{Sphinx}'
@@ -542,11 +544,12 @@ def test_latex_show_urls_is_no(app, status, warning):
'footnote in baz\n} in baz.rst' in result)
assert ('\\phantomsection\\label{index:id26}{\\hyperref[index:the\\string-section'
'\\string-with\\string-a\\string-reference\\string-to\\string-authoryear]'
- '{\\crossref{The section with a reference to \\phantomsection\\label{index:id1}'
- '{\\hyperref[index:authoryear]{\\crossref{{[}AuthorYear{]}}}}}}}' in result)
+ '{\\sphinxcrossref{The section with a reference '
+ 'to \\phantomsection\\label{index:id1}'
+ '{\\hyperref[index:authoryear]{\\sphinxcrossref{{[}AuthorYear{]}}}}}}}' in result)
assert ('\\phantomsection\\label{index:id27}{\\hyperref[index:the\\string-section'
'\\string-with\\string-a\\string-reference\\string-to]'
- '{\\crossref{The section with a reference to }}}' in result)
+ '{\\sphinxcrossref{The section with a reference to }}}' in result)
assert 'First footnote: \\footnote[2]{\sphinxAtStartFootnote%\nFirst\n}' in result
assert 'Second footnote: \\footnote[1]{\sphinxAtStartFootnote%\nSecond\n}' in result
assert '\\href{http://sphinx-doc.org/}{Sphinx}' in result
diff --git a/tests/test_directive_code.py b/tests/test_directive_code.py
index 4adb04cfb..5871f0321 100644
--- a/tests/test_directive_code.py
+++ b/tests/test_directive_code.py
@@ -65,8 +65,8 @@ def test_code_block_caption_html(app, status, warning):
def test_code_block_caption_latex(app, status, warning):
app.builder.build_all()
latex = (app.outdir / 'Python.tex').text(encoding='utf-8')
- caption = '\\SphinxSetupCaptionForVerbatim{literal-block}{caption \\emph{test} rb}'
- label = '\\def\\SphinxLiteralBlockLabel{\\label{caption:caption-test-rb}}'
+ caption = '\\sphinxSetupCaptionForVerbatim{literal-block}{caption \\emph{test} rb}'
+ label = '\\def\\sphinxLiteralBlockLabel{\\label{caption:caption-test-rb}}'
link = '\hyperref[caption:caption-test-rb]' \
'{Listing \\ref{caption:caption-test-rb}}'
assert caption in latex
@@ -78,12 +78,12 @@ def test_code_block_caption_latex(app, status, warning):
def test_code_block_namedlink_latex(app, status, warning):
app.builder.build_all()
latex = (app.outdir / 'Python.tex').text(encoding='utf-8')
- label1 = '\def\SphinxLiteralBlockLabel{\label{caption:name-test-rb}}'
+ label1 = '\def\sphinxLiteralBlockLabel{\label{caption:name-test-rb}}'
link1 = '\\hyperref[caption:name\\string-test\\string-rb]'\
- '{\\crossref{\\DUrole{std,std-ref}{Ruby}}'
- label2 = '\def\SphinxLiteralBlockLabel{\label{namedblocks:some-ruby-code}}'
+ '{\\sphinxcrossref{\\DUrole{std,std-ref}{Ruby}}'
+ label2 = '\def\sphinxLiteralBlockLabel{\label{namedblocks:some-ruby-code}}'
link2 = '\\hyperref[namedblocks:some\\string-ruby\\string-code]'\
- '{\\crossref{\\DUrole{std,std-ref}{the ruby code}}}'
+ '{\\sphinxcrossref{\\DUrole{std,std-ref}{the ruby code}}}'
assert label1 in latex
assert link1 in latex
assert label2 in latex
@@ -252,8 +252,8 @@ def test_literalinclude_caption_html(app, status, warning):
def test_literalinclude_caption_latex(app, status, warning):
app.builder.build('index')
latex = (app.outdir / 'Python.tex').text(encoding='utf-8')
- caption = '\\SphinxSetupCaptionForVerbatim{literal-block}{caption \\textbf{test} py}'
- label = '\\def\\SphinxLiteralBlockLabel{\\label{caption:caption-test-py}}'
+ caption = '\\sphinxSetupCaptionForVerbatim{literal-block}{caption \\textbf{test} py}'
+ label = '\\def\\sphinxLiteralBlockLabel{\\label{caption:caption-test-py}}'
link = '\hyperref[caption:caption-test-py]' \
'{Listing \\ref{caption:caption-test-py}}'
assert caption in latex
@@ -265,12 +265,12 @@ def test_literalinclude_caption_latex(app, status, warning):
def test_literalinclude_namedlink_latex(app, status, warning):
app.builder.build('index')
latex = (app.outdir / 'Python.tex').text(encoding='utf-8')
- label1 = '\def\SphinxLiteralBlockLabel{\label{caption:name-test-py}}'
+ label1 = '\def\sphinxLiteralBlockLabel{\label{caption:name-test-py}}'
link1 = '\\hyperref[caption:name\\string-test\\string-py]'\
- '{\\crossref{\\DUrole{std,std-ref}{Python}}'
- label2 = '\def\SphinxLiteralBlockLabel{\label{namedblocks:some-python-code}}'
+ '{\\sphinxcrossref{\\DUrole{std,std-ref}{Python}}'
+ label2 = '\def\sphinxLiteralBlockLabel{\label{namedblocks:some-python-code}}'
link2 = '\\hyperref[namedblocks:some\\string-python\\string-code]'\
- '{\\crossref{\\DUrole{std,std-ref}{the python code}}}'
+ '{\\sphinxcrossref{\\DUrole{std,std-ref}{the python code}}}'
assert label1 in latex
assert link1 in latex
assert label2 in latex
diff --git a/tests/test_markup.py b/tests/test_markup.py
index e7e343e6b..f7f639491 100644
--- a/tests/test_markup.py
+++ b/tests/test_markup.py
@@ -93,32 +93,32 @@ def test_inline():
# correct interpretation of code with whitespace
_html = ('
',
- '\\code{"John"}')
+ '\\sphinxcode{"John"}')
# verify classes for inline roles
yield (verify, ':manpage:`mp(1)`',
From f16ce14954ac855189636db2d5992a9e259ab7bb Mon Sep 17 00:00:00 2001
From: jfbu
Date: Wed, 15 Jun 2016 08:45:28 +0200
Subject: [PATCH 101/217] Make sphinxShadowBox customizable via three lengths
with public names
---
CHANGES | 1 +
sphinx/texinputs/sphinx.sty | 34 +++++++++++++++++++---------------
2 files changed, 20 insertions(+), 15 deletions(-)
diff --git a/CHANGES b/CHANGES
index 20d49c00d..5a091f3e3 100644
--- a/CHANGES
+++ b/CHANGES
@@ -5,6 +5,7 @@ Features added
--------------
* new config option ``latex_keep_old_macro_names``, defaults to True. If False, let macros (for text styling) be defined only with ``\sphinx``-prefixed names.
+* latex writer allows user customization of "shadowed" boxes (topics), via three length variables
Bugs fixed
----------
diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty
index 1cec7481e..f75a8d194 100644
--- a/sphinx/texinputs/sphinx.sty
+++ b/sphinx/texinputs/sphinx.sty
@@ -378,35 +378,39 @@
}
% define macro to frame contents and add shadow on right and bottom
-\def\spx@shadowsep {5\p@} % \p@ means "pt "
-\def\spx@shadowsize {4\p@}
-\def\spx@shadowrule {\fboxrule}
+% use public names for customizable lengths
+\newlength\sphinxshadowsep \setlength\sphinxshadowsep {5pt}
+\newlength\sphinxshadowsize \setlength\sphinxshadowsize {4pt}
+\newlength\sphinxshadowrule
+% this uses \fboxrule value at loading time of sphinx.sty (0.4pt normally)
+\setlength\sphinxshadowrule {\fboxrule}
+
\long\def\spx@ShadowFBox#1{%
\leavevmode\begingroup
% first we frame the box #1
\setbox\@tempboxa
- \hbox{\vrule\@width\spx@shadowrule
- \vbox{\hrule\@height\spx@shadowrule
- \kern\spx@shadowsep
- \hbox{\kern\spx@shadowsep #1\kern\spx@shadowsep}%
- \kern\spx@shadowsep
- \hrule\@height\spx@shadowrule}%
- \vrule\@width\spx@shadowrule}%
+ \hbox{\vrule\@width\sphinxshadowrule
+ \vbox{\hrule\@height\sphinxshadowrule
+ \kern\sphinxshadowsep
+ \hbox{\kern\sphinxshadowsep #1\kern\sphinxshadowsep}%
+ \kern\sphinxshadowsep
+ \hrule\@height\sphinxshadowrule}%
+ \vrule\@width\sphinxshadowrule}%
% Now we add the shadow, like \shadowbox from fancybox.sty would do
- \dimen@\dimexpr.5\spx@shadowrule+\spx@shadowsize\relax
+ \dimen@\dimexpr.5\sphinxshadowrule+\sphinxshadowsize\relax
\hbox{\vbox{\offinterlineskip
- \hbox{\copy\@tempboxa\kern-.5\spx@shadowrule
+ \hbox{\copy\@tempboxa\kern-.5\sphinxshadowrule
% add shadow on right side
- \lower\spx@shadowsize
+ \lower\sphinxshadowsize
\hbox{\vrule\@height\ht\@tempboxa \@width\dimen@}%
}%
\kern-\dimen@ % shift back vertically to bottom of frame
% and add shadow at bottom
- \moveright\spx@shadowsize
+ \moveright\sphinxshadowsize
\vbox{\hrule\@width\wd\@tempboxa \@height\dimen@}%
}%
% move left by the size of right shadow so shadow adds no width
- \kern-\spx@shadowsize
+ \kern-\sphinxshadowsize
}%
\endgroup
}
From c2d417a032111a69b0c4511cd7df1991c37a4fe6 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Wed, 15 Jun 2016 18:34:00 +0200
Subject: [PATCH 102/217] Rename SphinxVerbatim to sphinxVerbatim for latex
output
---
sphinx/texinputs/sphinx.sty | 6 +++---
sphinx/writers/latex.py | 4 ++--
tests/test_directive_code.py | 4 ++--
tests/test_markup.py | 4 ++--
4 files changed, 9 insertions(+), 9 deletions(-)
diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty
index bb1cc1b75..9af98827c 100644
--- a/sphinx/texinputs/sphinx.sty
+++ b/sphinx/texinputs/sphinx.sty
@@ -160,7 +160,7 @@
% Support large numbered footnotes in minipage (cf. admonitions)
\def\thempfootnote{\arabic{mpfootnote}}
-% Preparations for SphinxVerbatim environment, which is a wrapper of fancyvrb
+% Preparations for sphinxVerbatim environment, which is a wrapper of fancyvrb
% Verbatim with framing allowing pagebreaks, with border and background colors
% and possibly also a top caption, non separable by pagebreak. The original
% fancyvrb Verbatim is still used within tables.
@@ -286,7 +286,7 @@
\lccode`\~`\~
}
-\newenvironment{SphinxVerbatim}[1][1]{%
+\newenvironment{sphinxVerbatim}[1][1]{%
% quit horizontal mode if we are still in a paragraph
\par
% list starts new par, but we don't want it to be set apart vertically
@@ -336,7 +336,7 @@
{\kern\fontdimen2\font}%
}%
% go around fancyvrb's check of \@currenvir
- \renewcommand*{\VerbatimEnvironment}{\gdef\FV@EnvironName{SphinxVerbatim}}%
+ \renewcommand*{\VerbatimEnvironment}{\gdef\FV@EnvironName{sphinxVerbatim}}%
% go around fancyvrb's check of current list depth
\def\@toodeep {\advance\@listdepth\@ne}%
% Allow breaks at special characters using \PYG... macros.
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index 68073bd0b..678a8c8db 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -1909,11 +1909,11 @@ class LaTeXTranslator(nodes.NodeVisitor):
self.table.has_verbatim = True
else:
hlcode = hlcode.replace('\\begin{Verbatim}',
- '\\begin{SphinxVerbatim}')
+ '\\begin{sphinxVerbatim}')
# get consistent trailer
hlcode = hlcode.rstrip()[:-14] # strip \end{Verbatim}
self.body.append('\n' + hlcode + '\\end{%sVerbatim}\n' %
- ((not self.table) and 'Sphinx' or ''))
+ ((not self.table) and 'sphinx' or ''))
if ids:
self.body.append('\\let\\sphinxLiteralBlockLabel\empty\n')
raise nodes.SkipNode
diff --git a/tests/test_directive_code.py b/tests/test_directive_code.py
index b53145592..fa454fb7c 100644
--- a/tests/test_directive_code.py
+++ b/tests/test_directive_code.py
@@ -228,11 +228,11 @@ def test_literalinclude_file_whole_of_emptyline(app, status, warning):
app.builder.build_all()
latex = (app.outdir / 'Python.tex').text(encoding='utf-8').replace('\r\n', '\n')
includes = (
- '\\begin{SphinxVerbatim}[commandchars=\\\\\\{\\},numbers=left,firstnumber=1,stepnumber=1]\n'
+ '\\begin{sphinxVerbatim}[commandchars=\\\\\\{\\},numbers=left,firstnumber=1,stepnumber=1]\n'
'\n'
'\n'
'\n'
- '\\end{SphinxVerbatim}\n')
+ '\\end{sphinxVerbatim}\n')
assert includes in latex
diff --git a/tests/test_markup.py b/tests/test_markup.py
index 1753acb72..b41080b86 100644
--- a/tests/test_markup.py
+++ b/tests/test_markup.py
@@ -140,9 +140,9 @@ def test_latex_escaping():
r'\(\Gamma\)\textbackslash{}\(\infty\)\$')
# in verbatim code fragments
yield (verify, u'::\n\n @Γ\\∞${}', None,
- u'\\begin{SphinxVerbatim}[commandchars=\\\\\\{\\}]\n'
+ u'\\begin{sphinxVerbatim}[commandchars=\\\\\\{\\}]\n'
u'@\\(\\Gamma\\)\\PYGZbs{}\\(\\infty\\)\\PYGZdl{}\\PYGZob{}\\PYGZcb{}\n'
- u'\\end{SphinxVerbatim}')
+ u'\\end{sphinxVerbatim}')
# in URIs
yield (verify_re, u'`test `_', None,
r'\\href{http://example.com/~me/}{test}.*')
From 65dddfcd69801a49ac92e8eb9c2df7fb193dd472 Mon Sep 17 00:00:00 2001
From: Jakob Lykke Andersen
Date: Thu, 16 Jun 2016 10:54:16 +0900
Subject: [PATCH 103/217] C++, fix parsing of function types in other types.
Let all kinds of function parameters be allowed to have a name.
Fixes michaeljones/breathe#267.
---
sphinx/domains/cpp.py | 7 +++----
tests/test_domain_cpp.py | 5 +++++
2 files changed, 8 insertions(+), 4 deletions(-)
diff --git a/sphinx/domains/cpp.py b/sphinx/domains/cpp.py
index 46f775e44..a2298b7bc 100644
--- a/sphinx/domains/cpp.py
+++ b/sphinx/domains/cpp.py
@@ -3011,10 +3011,9 @@ class DefinitionParser(object):
self.fail('Expected ")" after "..." in '
'parameters_and_qualifiers.')
break
- if paramMode == 'function':
- arg = self._parse_type_with_init(outer=None, named='single')
- else:
- arg = self._parse_type(named=False)
+ # note: it seems that function arguments can always sbe named,
+ # even in function pointers and similar.
+ arg = self._parse_type_with_init(outer=None, named='single')
# TODO: parse default parameters # TODO: didn't we just do that?
args.append(ASTFunctinoParameter(arg))
diff --git a/tests/test_domain_cpp.py b/tests/test_domain_cpp.py
index f33e88128..778ac1c55 100644
--- a/tests/test_domain_cpp.py
+++ b/tests/test_domain_cpp.py
@@ -132,6 +132,11 @@ def test_type_definitions():
check('type', 'A = B', None, '1A')
+ # from breathe#267 (named function parameters for function pointers
+ check('type', 'void (*gpio_callback_t)(struct device *port, uint32_t pin)',
+ 'gpio_callback_t', '15gpio_callback_t')
+ check('type', 'void (*f)(std::function g)', 'f', '1f')
+
def test_member_definitions():
check('member', ' const std::string & name = 42',
From d4cdfc148b37a824832c732cbd0b08b098f75275 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Thu, 16 Jun 2016 16:09:05 +0200
Subject: [PATCH 104/217] Fix typo in CHANGES
---
CHANGES | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/CHANGES b/CHANGES
index 2afb0c08c..b8bf9e666 100644
--- a/CHANGES
+++ b/CHANGES
@@ -7,7 +7,7 @@ Incompatible changes
* LaTeX package fancybox is not longer a dependency of sphinx.sty
* Use ``'locales'`` as a default value of `locale_dirs`
* LaTeX package ifthen is not any longer a dependency of sphinx.sty
-* LaTeX writer produces source not modifying original fancyvrb's Verbatim but using new name SphinxVerbatim for its custom wrapper
+* LaTeX writer produces source not modifying original fancyvrb's Verbatim but using new name sphinxVerbatim for its custom wrapper
Features added
--------------
From b78d9fec2f3b39e42069ddc4bbe75df903aac050 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Sun, 12 Jun 2016 16:05:44 +0200
Subject: [PATCH 105/217] latex: let sphinx.sty use own \spx@ifundefined safer
test
---
sphinx/texinputs/sphinx.sty | 86 +++++++++++++++++++++----------------
1 file changed, 50 insertions(+), 36 deletions(-)
diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty
index f75a8d194..b2e1430ab 100644
--- a/sphinx/texinputs/sphinx.sty
+++ b/sphinx/texinputs/sphinx.sty
@@ -8,6 +8,23 @@
\NeedsTeXFormat{LaTeX2e}[1995/12/01]
\ProvidesPackage{sphinx}[2010/01/15 LaTeX package (Sphinx markup)]
+% this is the \ltx@ifundefined of ltxcmds.sty, which is loaded by
+% hyperref.sty, but we may need it before, and besides the first ltxcmds.sty
+% as in TL2009/Debian had wrong definition. To be used if a doubt exists some
+% package may have done \@ifundefined{foo}, hence a later \ifx\foo\undefined
+% may be invalidated, as formerly undefined \foo would have become \relax.
+\newcommand{\spx@ifundefined}[1]{%
+ \ifcsname #1\endcsname
+ \expandafter\ifx\csname #1\endcsname\relax
+ \expandafter\expandafter\expandafter\@firstoftwo
+ \else
+ \expandafter\expandafter\expandafter\@secondoftwo
+ \fi
+ \else
+ \expandafter\@firstoftwo
+ \fi
+}
+
\@ifclassloaded{memoir}{}{\RequirePackage{fancyhdr}}
% for \text macro and \iffirstchoice@ conditional even if amsmath not loaded
@@ -62,30 +79,32 @@
% use pdfoutput for pTeX and dvipdfmx
% when pTeX (\kanjiskip is defined), set pdfoutput to evade \include{pdfcolor}
-\ifx\kanjiskip\undefined\else
+\spx@ifundefined{kanjiskip}{}{
\newcount\pdfoutput\pdfoutput=0
-\fi
+}
\RequirePackage{graphicx}
% for PDF output, use colors and maximal compression
\newif\ifsphinxpdfoutput % used in \maketitle
-\ifx\pdfoutput\undefined\else\ifcase\pdfoutput
+\spx@ifundefined{pdfoutput}{}{
+ \ifnum\pdfoutput=\z@
\let\py@NormalColor\relax
\let\py@TitleColor\relax
-\else
+ \else
\sphinxpdfoutputtrue
\input{pdfcolor}
\def\py@NormalColor{\color[rgb]{0.0,0.0,0.0}}
\def\py@TitleColor{\color{TitleColor}}
\pdfcompresslevel=9
-\fi\fi
+ \fi
+}
% XeLaTeX can do colors, too
-\ifx\XeTeXrevision\undefined\else
+\spx@ifundefined{XeTeXrevision}{}{
\def\py@NormalColor{\color[rgb]{0.0,0.0,0.0}}
\def\py@TitleColor{\color{TitleColor}}
-\fi
+}
% Increase printable page size (copied from fullpage.sty)
\topmargin 0pt
@@ -117,7 +136,7 @@
\newcommand{\sphinxSetHeaderFamily}[1]{\renewcommand{\py@HeaderFamily}{#1}}
% Redefine the 'normal' header/footer style when using "fancyhdr" package:
-\@ifundefined{fancyhf}{}{
+\spx@ifundefined{fancyhf}{}{
% Use \pagestyle{normal} as the primary pagestyle for text.
\fancypagestyle{normal}{
\fancyhf{}
@@ -128,9 +147,8 @@
\renewcommand{\headrulewidth}{0.4pt}
\renewcommand{\footrulewidth}{0.4pt}
% define chaptermark with \@chappos when \@chappos is available for Japanese
- \ifx\@chappos\undefined\else
- \def\chaptermark##1{\markboth{\@chapapp\space\thechapter\space\@chappos\space ##1}{}}
- \fi
+ \spx@ifundefined{@chappos}{}
+ {\def\chaptermark##1{\markboth{\@chapapp\space\thechapter\space\@chappos\space ##1}{}}}
}
% Update the plain style so we get the page number & footer line,
% but not a chapter or section title. This is to keep the first
@@ -422,7 +440,7 @@
\newenvironment{sphinxShadowBox}
{\def\FrameCommand {\spx@ShadowFBox }%
% configure framed.sty not to add extra vertical spacing
- \ifdefined\OuterFrameSep \OuterFrameSep\z@skip \fi
+ \spx@ifundefined{OuterFrameSep}{}{\OuterFrameSep\z@skip}%
% the \trivlist will add the vertical spacing on top and bottom which is
% typical of center environment as used in Sphinx <= 1.4.1
% the \noindent has the effet of an extra blank line on top, to
@@ -538,7 +556,7 @@
% configure framed.sty's parameters to obtain same vertical spacing
% as for "light" boxes. We need for this to manually insert parskip glue and
% revert a skip done by framed before the frame.
- \ifdefined\OuterFrameSep \OuterFrameSep\z@skip \fi
+ \spx@ifundefined{OuterFrameSep}{}{\OuterFrameSep\z@skip}%
\vspace{\FrameHeightAdjust}
% copied/adapted from framed.sty's snugshade
\def\FrameCommand##1{\hskip\@totalleftmargin
@@ -648,7 +666,7 @@
% This sets up the fancy chapter headings that make the documents look
% at least a little better than the usual LaTeX output.
%
-\@ifundefined{ChTitleVar}{}{
+\spx@ifundefined{ChTitleVar}{}{
\ChNameVar{\raggedleft\normalsize\py@HeaderFamily}
\ChNumVar{\raggedleft \bfseries\Large\py@HeaderFamily}
\ChTitleVar{\raggedleft \textrm{\Huge\py@HeaderFamily}}
@@ -733,21 +751,19 @@
% to make pdf with correct encoded bookmarks in Japanese
% this should precede the hyperref package
-\ifx\kanjiskip\undefined
+\spx@ifundefined{kanjiskip}{
% for non-Japanese: make sure bookmarks are ok also with lualatex
\PassOptionsToPackage{pdfencoding=unicode}{hyperref}
-\else
+}{
\usepackage{atbegshi}
- \ifx\ucs\undefined
- \ifnum 42146=\euc"A4A2
+ \spx@ifundefined{ucs}
+ {\ifnum 42146=\euc"A4A2
\AtBeginShipoutFirst{\special{pdf:tounicode EUC-UCS2}}
\else
\AtBeginShipoutFirst{\special{pdf:tounicode 90ms-RKSJ-UCS2}}
- \fi
- \else
- \AtBeginShipoutFirst{\special{pdf:tounicode UTF8-UCS2}}
- \fi
-\fi
+ \fi}
+ {\AtBeginShipoutFirst{\special{pdf:tounicode UTF8-UCS2}}}
+}
% Include hyperref last.
\RequirePackage[colorlinks,breaklinks,
@@ -782,7 +798,7 @@
}
\DUprovidelength{\DUlineblockindent}{2.5em}
-\ifdefined\DUlineblock\else
+\spx@ifundefined{DUlineblock}{
\newenvironment{DUlineblock}[1]{%
\list{}{\setlength{\partopsep}{\parskip}
\addtolength{\partopsep}{\baselineskip}
@@ -793,7 +809,7 @@
\raggedright
}
{\endlist}
-\fi
+}{}
% From footmisc.sty: allows footnotes in titles
\let\FN@sf@@footnote\footnote
@@ -814,15 +830,15 @@
% adjust the margins for footer,
% this works with the jsclasses only (Japanese standard document classes)
-\ifx\@jsc@uplatextrue\undefined\else
+\spx@ifundefined{@jsc@uplatextrue}{}{
\hypersetup{setpagesize=false}
\setlength\footskip{2\baselineskip}
\addtolength{\textheight}{-2\baselineskip}
-\fi
+}
% fix the double index and bibliography on the table of contents
% in jsclasses (Japanese standard document classes)
-\ifx\@jsc@uplatextrue\undefined\else
+\spx@ifundefined{@jsc@uplatextrue}{}{
\renewcommand{\theindex}{
\cleardoublepage
\phantomsection
@@ -833,25 +849,23 @@
\phantomsection
\py@OldThebibliography{1}
}
-\fi
+}
% disable \@chappos in Appendix in pTeX
-\ifx\kanjiskip\undefined\else
+\spx@ifundefined{kanjiskip}{}{
\let\py@OldAppendix=\appendix
\renewcommand{\appendix}{
\py@OldAppendix
\gdef\@chappos{}
}
-\fi
+}
% Define literal-block environment
\RequirePackage{newfloat}
\DeclareFloatingEnvironment{literal-block}
-\ifx\c@chapter\undefined
- \SetupFloatingEnvironment{literal-block}{within=section,placement=h}
-\else
- \SetupFloatingEnvironment{literal-block}{within=chapter,placement=h}
-\fi
+\spx@ifundefined{c@chapter}
+ {\SetupFloatingEnvironment{literal-block}{within=section,placement=h}}
+ {\SetupFloatingEnvironment{literal-block}{within=chapter,placement=h}}
\SetupFloatingEnvironment{literal-block}{name=List}
% control caption around literal-block
\RequirePackage{capt-of}
From 44bd9873140fe525fa545b6ad0a322d8ccd9ee21 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Thu, 16 Jun 2016 18:22:59 +0200
Subject: [PATCH 106/217] latex: let sphinx.sty use own \spx@ifundefined for
some tests
---
sphinx/texinputs/sphinx.sty | 50 ++++++++++++++++++-------------------
1 file changed, 25 insertions(+), 25 deletions(-)
diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty
index b2e1430ab..85fc492a7 100644
--- a/sphinx/texinputs/sphinx.sty
+++ b/sphinx/texinputs/sphinx.sty
@@ -9,10 +9,8 @@
\ProvidesPackage{sphinx}[2010/01/15 LaTeX package (Sphinx markup)]
% this is the \ltx@ifundefined of ltxcmds.sty, which is loaded by
-% hyperref.sty, but we may need it before, and besides the first ltxcmds.sty
-% as in TL2009/Debian had wrong definition. To be used if a doubt exists some
-% package may have done \@ifundefined{foo}, hence a later \ifx\foo\undefined
-% may be invalidated, as formerly undefined \foo would have become \relax.
+% hyperref.sty, but we need it before, and initial ltxcmds.sty
+% as in TL2009/Debian had wrong definition.
\newcommand{\spx@ifundefined}[1]{%
\ifcsname #1\endcsname
\expandafter\ifx\csname #1\endcsname\relax
@@ -79,15 +77,15 @@
% use pdfoutput for pTeX and dvipdfmx
% when pTeX (\kanjiskip is defined), set pdfoutput to evade \include{pdfcolor}
-\spx@ifundefined{kanjiskip}{}{
+\ifx\kanjiskip\undefined\else
\newcount\pdfoutput\pdfoutput=0
-}
+\fi
\RequirePackage{graphicx}
% for PDF output, use colors and maximal compression
\newif\ifsphinxpdfoutput % used in \maketitle
-\spx@ifundefined{pdfoutput}{}{
+\ifx\pdfoutput\undefined\else
\ifnum\pdfoutput=\z@
\let\py@NormalColor\relax
\let\py@TitleColor\relax
@@ -98,13 +96,13 @@
\def\py@TitleColor{\color{TitleColor}}
\pdfcompresslevel=9
\fi
-}
+\fi
% XeLaTeX can do colors, too
-\spx@ifundefined{XeTeXrevision}{}{
+\ifx\XeTeXrevision\undefined\else
\def\py@NormalColor{\color[rgb]{0.0,0.0,0.0}}
\def\py@TitleColor{\color{TitleColor}}
-}
+\fi
% Increase printable page size (copied from fullpage.sty)
\topmargin 0pt
@@ -751,19 +749,21 @@
% to make pdf with correct encoded bookmarks in Japanese
% this should precede the hyperref package
-\spx@ifundefined{kanjiskip}{
+\ifx\kanjiskip\undefined
% for non-Japanese: make sure bookmarks are ok also with lualatex
\PassOptionsToPackage{pdfencoding=unicode}{hyperref}
-}{
+\else
\usepackage{atbegshi}
- \spx@ifundefined{ucs}
- {\ifnum 42146=\euc"A4A2
+ \ifx\ucs\undefined
+ \ifnum 42146=\euc"A4A2
\AtBeginShipoutFirst{\special{pdf:tounicode EUC-UCS2}}
\else
\AtBeginShipoutFirst{\special{pdf:tounicode 90ms-RKSJ-UCS2}}
- \fi}
- {\AtBeginShipoutFirst{\special{pdf:tounicode UTF8-UCS2}}}
-}
+ \fi
+ \else
+ \AtBeginShipoutFirst{\special{pdf:tounicode UTF8-UCS2}}
+ \fi
+\fi
% Include hyperref last.
\RequirePackage[colorlinks,breaklinks,
@@ -798,7 +798,7 @@
}
\DUprovidelength{\DUlineblockindent}{2.5em}
-\spx@ifundefined{DUlineblock}{
+\ifdefined\DUlineblock\else
\newenvironment{DUlineblock}[1]{%
\list{}{\setlength{\partopsep}{\parskip}
\addtolength{\partopsep}{\baselineskip}
@@ -809,7 +809,7 @@
\raggedright
}
{\endlist}
-}{}
+\fi
% From footmisc.sty: allows footnotes in titles
\let\FN@sf@@footnote\footnote
@@ -830,15 +830,15 @@
% adjust the margins for footer,
% this works with the jsclasses only (Japanese standard document classes)
-\spx@ifundefined{@jsc@uplatextrue}{}{
+\ifx\@jsc@uplatextrue\undefined\else
\hypersetup{setpagesize=false}
\setlength\footskip{2\baselineskip}
\addtolength{\textheight}{-2\baselineskip}
-}
+\fi
% fix the double index and bibliography on the table of contents
% in jsclasses (Japanese standard document classes)
-\spx@ifundefined{@jsc@uplatextrue}{}{
+\ifx\@jsc@uplatextrue\undefined\else
\renewcommand{\theindex}{
\cleardoublepage
\phantomsection
@@ -849,16 +849,16 @@
\phantomsection
\py@OldThebibliography{1}
}
-}
+\fi
% disable \@chappos in Appendix in pTeX
-\spx@ifundefined{kanjiskip}{}{
+\ifx\kanjiskip\undefined\else
\let\py@OldAppendix=\appendix
\renewcommand{\appendix}{
\py@OldAppendix
\gdef\@chappos{}
}
-}
+\fi
% Define literal-block environment
\RequirePackage{newfloat}
From 664e24cf86f0cd543714a4ffe596abbb7a902efd Mon Sep 17 00:00:00 2001
From: jfbu
Date: Mon, 13 Jun 2016 10:30:48 +0200
Subject: [PATCH 107/217] Fix #2671: image directive may lead to inconsistent
spacing in pdf
---
sphinx/texinputs/sphinx.sty | 37 ++++++++++++++++++++-----------------
sphinx/writers/latex.py | 13 +++++++++----
tests/test_build_latex.py | 18 +++++++++---------
3 files changed, 38 insertions(+), 30 deletions(-)
diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty
index f75a8d194..6c3365c1e 100644
--- a/sphinx/texinputs/sphinx.sty
+++ b/sphinx/texinputs/sphinx.sty
@@ -710,26 +710,29 @@
\raggedright}
{\end{list}}
-% Redefine includgraphics for avoiding images larger than the screen size
-% If the size is not specified.
+% Re-define \includegraphics to resize images larger than the line width
+% if the size is not specified.
+% Warning: future version of Sphinx will not modify original \includegraphics,
+% Below custom code will be direct definition of \sphinxincludegraphics, with
+% \py@Oldincludegraphics replaced by direct use of original \includegraphics.
\let\py@Oldincludegraphics\includegraphics
-
-\newbox\image@box%
-\newdimen\image@width%
-\renewcommand\includegraphics[2][\@empty]{%
- \ifx#1\@empty%
- \setbox\image@box=\hbox{\py@Oldincludegraphics{#2}}%
- \image@width\wd\image@box%
- \ifdim \image@width>\linewidth%
- \setbox\image@box=\hbox{\py@Oldincludegraphics[width=\linewidth]{#2}}%
- \box\image@box%
- \else%
- \py@Oldincludegraphics{#2}%
- \fi%
- \else%
+\newbox\spx@image@box
+\renewcommand*{\includegraphics}[2][\@empty]{%
+ \ifx\@empty #1% attention, #1 could be bb.., bad if first after \ifx
+ \setbox\spx@image@box=\hbox{\py@Oldincludegraphics{#2}}%
+ \ifdim \wd\spx@image@box>\linewidth
+ \py@Oldincludegraphics[width=\linewidth]{#2}%
+ \else
+ \leavevmode\box\spx@image@box
+ \fi
+ \else
\py@Oldincludegraphics[#1]{#2}%
- \fi%
+ \fi
}
+% Writer will put \sphinxincludegraphics in LaTeX source, and with this,
+% documents which used their own modified \includegraphics will compile
+% as before. But see warning above.
+\newcommand*{\sphinxincludegraphics}{\includegraphics}
% to make pdf with correct encoded bookmarks in Japanese
% this should precede the hyperref package
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index 524e035a7..d7bd3297c 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -408,7 +408,8 @@ class LaTeXTranslator(nodes.NodeVisitor):
self.elements['date'] = format_date(builder.config.today_fmt or _('%b %d, %Y'),
language=builder.config.language)
if builder.config.latex_logo:
- self.elements['logo'] = '\\includegraphics{%s}\\par' % \
+ # no need for \\noindent here, used in flushright
+ self.elements['logo'] = '\\sphinxincludegraphics{%s}\\par' % \
path.basename(builder.config.latex_logo)
# setup babel
self.babel = ExtBabel(builder.config.language)
@@ -1407,8 +1408,12 @@ class LaTeXTranslator(nodes.NodeVisitor):
except KeyError:
pass
if not is_inline:
- pre.append('\n')
- post.append('\n')
+ if isinstance(node.parent, nodes.section):
+ pre.append('\n\\noindent')
+ post.append('\n')
+ else:
+ pre.append('\n')
+ post.append('\n')
pre.reverse()
if node['uri'] in self.builder.images:
uri = self.builder.images[node['uri']]
@@ -1425,7 +1430,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
if include_graphics_options:
options = '[%s]' % ','.join(include_graphics_options)
base, ext = path.splitext(uri)
- self.body.append('\\includegraphics%s{{%s}%s}' % (options, base, ext))
+ self.body.append('\\sphinxincludegraphics%s{{%s}%s}' % (options, base, ext))
self.body.extend(post)
def depart_image(self, node):
diff --git a/tests/test_build_latex.py b/tests/test_build_latex.py
index 503f41ef1..f7479f545 100644
--- a/tests/test_build_latex.py
+++ b/tests/test_build_latex.py
@@ -113,19 +113,19 @@ def test_writer(app, status, warning):
result = (app.outdir / 'SphinxTests.tex').text(encoding='utf8')
assert ('\\begin{sphinxfigure-in-table}\n\\centering\n\\capstart\n'
- '\\includegraphics{{img}.png}\n\\sphinxfigcaption'
+ '\\sphinxincludegraphics{{img}.png}\n\\sphinxfigcaption'
'{figure in table}\\label{markup:id7}\\end{sphinxfigure-in-table}' in result)
assert ('\\begin{wrapfigure}{r}{0pt}\n\\centering\n'
- '\\includegraphics{{rimg}.png}\n\\caption{figure with align option}'
+ '\\sphinxincludegraphics{{rimg}.png}\n\\caption{figure with align option}'
'\\label{markup:id8}\\end{wrapfigure}' in result)
assert ('\\begin{wrapfigure}{r}{0.500\\linewidth}\n\\centering\n'
- '\\includegraphics{{rimg}.png}\n\\caption{figure with align \\& figwidth option}'
+ '\\sphinxincludegraphics{{rimg}.png}\n\\caption{figure with align \\& figwidth option}'
'\\label{markup:id9}\\end{wrapfigure}' in result)
assert ('\\begin{wrapfigure}{r}{3cm}\n\\centering\n'
- '\\includegraphics[width=3cm]{{rimg}.png}\n'
+ '\\sphinxincludegraphics[width=3cm]{{rimg}.png}\n'
'\\caption{figure with align \\& width option}'
'\\label{markup:id10}\\end{wrapfigure}' in result)
@@ -574,12 +574,12 @@ def test_image_in_section(app, status, warning):
print(result)
print(status.getvalue())
print(warning.getvalue())
- assert ('\chapter[Test section]'
- '{\includegraphics[width=15pt,height=15pt]{{pic}.png} Test section}'
+ assert ('\\chapter[Test section]'
+ '{\\sphinxincludegraphics[width=15pt,height=15pt]{{pic}.png} Test section}'
in result)
- assert ('\chapter[Other {[}blah{]} section]{Other {[}blah{]} '
- '\includegraphics[width=15pt,height=15pt]{{pic}.png} section}' in result)
- assert ('\chapter{Another section}' in result)
+ assert ('\\chapter[Other {[}blah{]} section]{Other {[}blah{]} '
+ '\\sphinxincludegraphics[width=15pt,height=15pt]{{pic}.png} section}' in result)
+ assert ('\\chapter{Another section}' in result)
@with_app(buildername='latex', confoverrides={'latex_logo': 'notfound.jpg'})
From c2ba7832e268a9e1cbd70a7bea431e39fe5ada7c Mon Sep 17 00:00:00 2001
From: Gabi Davar
Date: Fri, 10 Jun 2016 12:00:57 +0300
Subject: [PATCH 108/217] add --pdb support to setuptools command
---
sphinx/setup_command.py | 21 ++++++++++++++++-----
1 file changed, 16 insertions(+), 5 deletions(-)
diff --git a/sphinx/setup_command.py b/sphinx/setup_command.py
index 128c1415c..0a29685a4 100644
--- a/sphinx/setup_command.py
+++ b/sphinx/setup_command.py
@@ -15,6 +15,8 @@ from __future__ import print_function
import sys
import os
+import traceback
+
from distutils.cmd import Command
from distutils.errors import DistutilsOptionError, DistutilsExecError
@@ -78,11 +80,13 @@ class BuildDoc(Command):
'replacement for |today|'),
('link-index', 'i', 'Link index.html to the master doc'),
('copyright', None, 'The copyright string'),
+ ('pdb', None, 'Start pdb on exception'),
]
boolean_options = ['fresh-env', 'all-files', 'link-index']
def initialize_options(self):
self.fresh_env = self.all_files = False
+ self.pdb = False
self.source_dir = self.build_dir = None
self.builder = 'html'
self.project = ''
@@ -166,13 +170,20 @@ class BuildDoc(Command):
raise DistutilsExecError(
'caused by %s builder.' % app.builder.name)
except Exception as err:
- from docutils.utils import SystemMessage
- if isinstance(err, SystemMessage):
- print(darkred('reST markup error:'), file=sys.stderr)
- print(err.args[0].encode('ascii', 'backslashreplace'),
+ if self.pdb:
+ import pdb
+ print(darkred('Exception occurred while building, starting debugger:'),
file=sys.stderr)
+ traceback.print_exc()
+ pdb.post_mortem(sys.exc_info()[2])
else:
- raise
+ from docutils.utils import SystemMessage
+ if isinstance(err, SystemMessage):
+ print(darkred('reST markup error:'), file=sys.stderr)
+ print(err.args[0].encode('ascii', 'backslashreplace'),
+ file=sys.stderr)
+ else:
+ raise
if self.link_index:
src = app.config.master_doc + app.builder.out_suffix
From b3d8961ca8109b091b587af6055799e64b740218 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Fri, 17 Jun 2016 19:32:16 +0200
Subject: [PATCH 109/217] Enhance latex text styling customizability
---
CHANGES | 4 +++
sphinx/texinputs/sphinx.sty | 16 ++++++++++
sphinx/writers/latex.py | 58 +++++++++++++++++++++++++-----------
tests/test_directive_code.py | 6 ++--
tests/test_markup.py | 4 +--
5 files changed, 66 insertions(+), 22 deletions(-)
diff --git a/CHANGES b/CHANGES
index b8bf9e666..ccb40dc5c 100644
--- a/CHANGES
+++ b/CHANGES
@@ -23,6 +23,10 @@ Features added
* Show warnings if no domains match with `primary_domain` (ref: #2001)
* C++, show warnings when the kind of role is misleading for the kind
of target it refers to (e.g., using the `class` role for a function).
+* latex writer abstracts more of text styling into customizable macros, e.g.
+ the ``visit_emphasis`` will output ``\sphinxstyleemphasis`` rather than
+ ``\\emph`` (which may be in use elsewhere or in an added LaTeX package). See
+ list at end of ``sphinx.sty`` (ref: #2686)
Bugs fixed
----------
diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty
index 9af98827c..848d0a771 100644
--- a/sphinx/texinputs/sphinx.sty
+++ b/sphinx/texinputs/sphinx.sty
@@ -887,3 +887,19 @@
\DeclareRobustCommand{\code}[1]{{\@noligs\scantokens{\texttt{#1}}}}
\def\sphinxcode{\code}%
\fi
+
+% additional customizable styling
+\let\sphinxstyleindexentry\texttt
+\newcommand{\sphinxstyleindexextra}[1]{ \emph{(#1)}}
+\newcommand*{\sphinxstyleindexpageref}{, \pageref}
+\newcommand{\sphinxstyletopictitle}[1]{\textbf{#1}\par\medskip}
+\let\sphinxstylesidebartitle\sphinxstyletopictitle
+\let\sphinxstyleothertitle\textbf
+\newcommand{\sphinxstylesidebarsubtitle}[1]{~\\\textbf{#1} \smallskip}
+\let\sphinxstylethead\textsf
+\let\sphinxstyleemphasis\emph
+\newcommand{\sphinxstyleliteralemphasis}[1]{\emph{\texttt{#1}}}
+\let\sphinxstylestrong\textbf
+\newcommand{\sphinxstyleliteralstrong}[1]{\textbf{\texttt{#1}}}
+\let\sphinxstyleabbreviation\textsc
+\let\sphinxstyleliteralintitle\texttt
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index 678a8c8db..ba477fb43 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -638,11 +638,14 @@ class LaTeXTranslator(nodes.NodeVisitor):
for entry in entries:
if not entry[3]:
continue
- ret.append('\\item {\\texttt{%s}}' % self.encode(entry[0]))
+ # ret.append('\\item {\\texttt{%s}}' % self.encode(entry[0]))
+ ret.append('\\item {\\sphinxstyleindexentry{%s}}' % self.encode(entry[0]))
if entry[4]:
# add "extra" info
- ret.append(' \\emph{(%s)}' % self.encode(entry[4]))
- ret.append(', \\pageref{%s:%s}\n' %
+ # ret.append(' \\emph{(%s)}' % self.encode(entry[4]))
+ ret.append('\\sphinxstyleindexextra{%s}' % self.encode(entry[4]))
+ # ret.append(', \\pageref{%s:%s}\n' %
+ ret.append('\\sphinxstyleindexpageref{%s:%s}\n' %
(entry[2], self.idescape(entry[3])))
ret.append('\\end{theindex}\n')
@@ -830,9 +833,16 @@ class LaTeXTranslator(nodes.NodeVisitor):
self.context[-1] += self.hypertarget(id, anchor=False)
self.next_section_ids.clear()
- elif isinstance(parent, (nodes.topic, nodes.sidebar)):
- self.body.append(r'\textbf{')
- self.context.append('}\n\n\medskip\n\n')
+ elif isinstance(parent, nodes.topic):
+ # self.body.append(r'\textbf{')
+ self.body.append(r'\sphinxstyletopictitle{')
+ # self.context.append('}\n\n\medskip\n\n')
+ self.context.append('}\n')
+ elif isinstance(parent, nodes.sidebar):
+ # self.body.append(r'\textbf{')
+ self.body.append(r'\sphinxstylesidebartitle{')
+ # self.context.append('}\n\n\medskip\n\n')
+ self.context.append('}\n')
elif isinstance(parent, nodes.Admonition):
self.body.append('{')
self.context.append('}\n')
@@ -844,7 +854,8 @@ class LaTeXTranslator(nodes.NodeVisitor):
'encountered title node not in section, topic, table, '
'admonition or sidebar',
(self.curfilestack[-1], node.line or ''))
- self.body.append('\\textbf{')
+# self.body.append('\\textbf{')
+ self.body.append('\\sphinxstyleothertitle{')
self.context.append('}\n')
self.in_title = 1
@@ -858,8 +869,10 @@ class LaTeXTranslator(nodes.NodeVisitor):
def visit_subtitle(self, node):
if isinstance(node.parent, nodes.sidebar):
- self.body.append('~\\\\\n\\textbf{')
- self.context.append('}\n\\smallskip\n')
+ # self.body.append('~\\\\\n\\textbf{')
+ # self.context.append('}\n\\smallskip\n')
+ self.body.append('\\sphinxstylesidebarsubtitle{')
+ self.context.append('}\n')
else:
self.context.append('')
@@ -1194,7 +1207,8 @@ class LaTeXTranslator(nodes.NodeVisitor):
if len(node) == 1 and isinstance(node[0], nodes.paragraph) and node.astext() == '':
pass
else:
- self.body.append('\\textsf{\\relax ')
+ # self.body.append('\\textsf{\\relax ')
+ self.body.append('\\sphinxstylethead{\\relax ')
context += '}'
while self.remember_multirow.get(self.table.col + 1, 0):
self.table.col += 1
@@ -1756,36 +1770,43 @@ class LaTeXTranslator(nodes.NodeVisitor):
pass
def visit_emphasis(self, node):
- self.body.append(r'\emph{')
+ # self.body.append(r'\emph{')
+ self.body.append(r'\sphinxstyleemphasis{')
def depart_emphasis(self, node):
self.body.append('}')
def visit_literal_emphasis(self, node):
- self.body.append(r'\emph{\texttt{')
+ # self.body.append(r'\emph{\texttt{')
+ self.body.append(r'\sphinxstyleliteralemphasis{')
self.no_contractions += 1
def depart_literal_emphasis(self, node):
- self.body.append('}}')
+ # self.body.append('}}')
+ self.body.append('}')
self.no_contractions -= 1
def visit_strong(self, node):
- self.body.append(r'\textbf{')
+ # self.body.append(r'\textbf{')
+ self.body.append(r'\sphinxstylestrong{')
def depart_strong(self, node):
self.body.append('}')
def visit_literal_strong(self, node):
- self.body.append(r'\textbf{\texttt{')
+ # self.body.append(r'\textbf{\texttt{')
+ self.body.append(r'\sphinxstyleliteralstrong{')
self.no_contractions += 1
def depart_literal_strong(self, node):
- self.body.append('}}')
+ # self.body.append('}}')
+ self.body.append('}')
self.no_contractions -= 1
def visit_abbreviation(self, node):
abbr = node.astext()
- self.body.append(r'\textsc{')
+ # self.body.append(r'\textsc{')
+ self.body.append(r'\sphinxstyleabbreviation{')
# spell out the explanation once
if node.hasattr('explanation') and abbr not in self.handled_abbrs:
self.context.append('} (%s)' % self.encode(node['explanation']))
@@ -1829,7 +1850,8 @@ class LaTeXTranslator(nodes.NodeVisitor):
def visit_literal(self, node):
self.no_contractions += 1
if self.in_title:
- self.body.append(r'\texttt{')
+ # self.body.append(r'\texttt{')
+ self.body.append(r'\sphinxstyleliteralintitle{')
else:
self.body.append(r'\sphinxcode{')
diff --git a/tests/test_directive_code.py b/tests/test_directive_code.py
index fa454fb7c..0f1e98f7e 100644
--- a/tests/test_directive_code.py
+++ b/tests/test_directive_code.py
@@ -65,7 +65,8 @@ def test_code_block_caption_html(app, status, warning):
def test_code_block_caption_latex(app, status, warning):
app.builder.build_all()
latex = (app.outdir / 'Python.tex').text(encoding='utf-8')
- caption = '\\sphinxSetupCaptionForVerbatim{literal-block}{caption \\emph{test} rb}'
+ caption = '\\sphinxSetupCaptionForVerbatim{literal-block}' \
+ '{caption \\sphinxstyleemphasis{test} rb}'
label = '\\def\\sphinxLiteralBlockLabel{\\label{caption:caption-test-rb}}'
link = '\hyperref[caption:caption-test-rb]' \
'{Listing \\ref{caption:caption-test-rb}}'
@@ -252,7 +253,8 @@ def test_literalinclude_caption_html(app, status, warning):
def test_literalinclude_caption_latex(app, status, warning):
app.builder.build('index')
latex = (app.outdir / 'Python.tex').text(encoding='utf-8')
- caption = '\\sphinxSetupCaptionForVerbatim{literal-block}{caption \\textbf{test} py}'
+ caption = '\\sphinxSetupCaptionForVerbatim{literal-block}' \
+ '{caption \\sphinxstylestrong{test} py}'
label = '\\def\\sphinxLiteralBlockLabel{\\label{caption:caption-test-py}}'
link = '\hyperref[caption:caption-test-py]' \
'{Listing \\ref{caption:caption-test-py}}'
diff --git a/tests/test_markup.py b/tests/test_markup.py
index b41080b86..102235e1d 100644
--- a/tests/test_markup.py
+++ b/tests/test_markup.py
@@ -101,7 +101,7 @@ def test_inline():
'
',
- '\\emph{\\texttt{mp(1)}}')
+ '\\sphinxstyleliteralemphasis{mp(1)}')
def test_latex_escaping():
From 7586297d6df6fbae4b860a604422d4eddc40b32e Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sat, 18 Jun 2016 10:25:43 +0900
Subject: [PATCH 110/217] Fix #2684: `sphinx.ext.intersphinx` crashes with
six-1.4.1
---
CHANGES | 1 +
sphinx/ext/intersphinx.py | 11 ++++++-----
2 files changed, 7 insertions(+), 5 deletions(-)
diff --git a/CHANGES b/CHANGES
index 5a091f3e3..3d36e00c5 100644
--- a/CHANGES
+++ b/CHANGES
@@ -12,6 +12,7 @@ Bugs fixed
* #2676: (latex) Error with verbatim text in captions since Sphinx 1.4.4
* #2629: memoir class crashes LaTeX. Fixed ``by latex_keep_old_macro_names=False`` (ref 2675)
+* #2684: `sphinx.ext.intersphinx` crashes with six-1.4.1
Release 1.4.4 (released Jun 12, 2016)
diff --git a/sphinx/ext/intersphinx.py b/sphinx/ext/intersphinx.py
index 350121190..617220c5f 100644
--- a/sphinx/ext/intersphinx.py
+++ b/sphinx/ext/intersphinx.py
@@ -34,7 +34,8 @@ from os import path
import re
from six import iteritems, string_types
-from six.moves.urllib import parse, request
+from six.moves.urllib import request
+from six.moves.urllib.parse import urlsplit, urlunsplit
from docutils import nodes
from docutils.utils import relative_path
@@ -145,7 +146,7 @@ def _strip_basic_auth(url):
:rtype: ``tuple``
"""
- url_parts = parse.urlsplit(url)
+ url_parts = urlsplit(url)
username = url_parts.username
password = url_parts.password
frags = list(url_parts)
@@ -154,7 +155,7 @@ def _strip_basic_auth(url):
frags[1] = "%s:%s" % (url_parts.hostname, url_parts.port)
else:
frags[1] = url_parts.hostname
- url = parse.urlunsplit(frags)
+ url = urlunsplit(frags)
return (url, username, password)
@@ -208,12 +209,12 @@ def _get_safe_url(url):
url, username, _ = _strip_basic_auth(url)
if username is not None:
# case: url contained basic auth creds; obscure password
- url_parts = parse.urlsplit(url)
+ url_parts = urlsplit(url)
safe_netloc = '{0}@{1}'.format(username, url_parts.hostname)
# replace original netloc w/ obscured version
frags = list(url_parts)
frags[1] = safe_netloc
- safe_url = parse.urlunsplit(frags)
+ safe_url = urlunsplit(frags)
return safe_url
From 80a1ad5a5ad2e195cf590e61a8a1a25e00c04d5f Mon Sep 17 00:00:00 2001
From: jfbu
Date: Sat, 18 Jun 2016 10:09:51 +0200
Subject: [PATCH 111/217] Fix typo in CHANGES
---
CHANGES | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/CHANGES b/CHANGES
index ccb40dc5c..af4983708 100644
--- a/CHANGES
+++ b/CHANGES
@@ -25,7 +25,7 @@ Features added
of target it refers to (e.g., using the `class` role for a function).
* latex writer abstracts more of text styling into customizable macros, e.g.
the ``visit_emphasis`` will output ``\sphinxstyleemphasis`` rather than
- ``\\emph`` (which may be in use elsewhere or in an added LaTeX package). See
+ ``\emph`` (which may be in use elsewhere or in an added LaTeX package). See
list at end of ``sphinx.sty`` (ref: #2686)
Bugs fixed
From 6929d546c8ce556dc9ded3bb7db76c4a72ffa144 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Sat, 18 Jun 2016 12:18:59 +0200
Subject: [PATCH 112/217] Hard-wrap some long lines in CHANGES
Seems longer lines are more frequent since 1.4. I hard-wrapped at 80
chars the ones I committed which sometimes exceeded 100 chars. Other
long lines remain (one has 108 chars).
---
CHANGES | 27 ++++++++++++++++++---------
1 file changed, 18 insertions(+), 9 deletions(-)
diff --git a/CHANGES b/CHANGES
index 3d36e00c5..50a66de92 100644
--- a/CHANGES
+++ b/CHANGES
@@ -4,8 +4,10 @@ Release 1.4.5 (in development)
Features added
--------------
-* new config option ``latex_keep_old_macro_names``, defaults to True. If False, let macros (for text styling) be defined only with ``\sphinx``-prefixed names.
-* latex writer allows user customization of "shadowed" boxes (topics), via three length variables
+* new config option ``latex_keep_old_macro_names``, defaults to True. If False,
+ let macros (for text styling) be defined only with ``\sphinx``-prefixed names.
+* latex writer allows user customization of "shadowed" boxes (topics), via
+ three length variables
Bugs fixed
----------
@@ -31,8 +33,10 @@ Bugs fixed
* #2351: latex crashes if enumerated lists are placed on footnotes
* #2646: latex crashes if math contains twice empty lines
* #2480: `sphinx.ext.autodoc`: memory addresses were shown
-* latex: allow code-blocks appearing inside lists and quotes at maximal nesting depth (ref #777, #2624, #2651)
-* #2635: Latex code directives produce inconsistent frames based on viewing resolution
+* latex: allow code-blocks appearing inside lists and quotes at maximal nesting
+ depth (ref #777, #2624, #2651)
+* #2635: Latex code directives produce inconsistent frames based on viewing
+ resolution
* #2639: Sphinx now bundles iftex.sty
* Failed to build PDF with framed.sty 0.95
* Sphinx now bundles needspace.sty
@@ -45,15 +49,18 @@ Release 1.4.3 (released Jun 5, 2016)
Bugs fixed
----------
-* #2530: got "Counter too large" error on building PDF if large numbered footnotes existed in admonitions
+* #2530: got "Counter too large" error on building PDF if large numbered
+ footnotes existed in admonitions
* ``width`` option of figure directive does not work if ``align`` option specified at same time (ref: #2595)
* #2590: The ``inputenc`` package breaks compiling under lualatex and xelatex
* #2540: date on latex front page use different font
* Suppress "document isn't included in any toctree" warning if the document is included (ref: #2603)
-* #2614: Some tables in PDF output will end up shifted if user sets non zero \parindent in preamble
+* #2614: Some tables in PDF output will end up shifted if user sets non zero
+ \parindent in preamble
* #2602: URL redirection breaks the hyperlinks generated by `sphinx.ext.intersphinx`
* #2613: Show warnings if merged extensions are loaded
-* #2619: make sure amstext LaTeX package always loaded (ref: d657225, 488ee52, 9d82cad and #2615)
+* #2619: make sure amstext LaTeX package always loaded (ref: d657225, 488ee52,
+ 9d82cad and #2615)
* #2593: latex crashes if any figures in the table
@@ -94,7 +101,8 @@ Bugs fixed
* #2397: Setup shorthandoff for turkish documents
* #2447: VerbatimBorderColor wrongly used also for captions of PDF
* #2456: C++, fix crash related to document merging (e.g., singlehtml and Latex builders).
-* #2446: latex(pdf) sets local tables of contents (or more generally topic nodes) in unbreakable boxes, causes overflow at bottom
+* #2446: latex(pdf) sets local tables of contents (or more generally topic
+ nodes) in unbreakable boxes, causes overflow at bottom
* #2476: Omit MathJax markers if :nowrap: is given
* #2465: latex builder fails in case no caption option is provided to toctree directive
* Sphinx crashes if self referenced toctree found
@@ -303,7 +311,8 @@ Bugs fixed
is highlighted as Python 3 (which is mostly a superset of Python 2) if possible.
To get the old behavior back, add ``highlight_language = "python"`` to conf.py.
* #2329: Refresh environment forcely if source directory has changed.
-* #2331: Fix code-blocks are filled by block in dvi; remove ``xcdraw`` option from xcolor package
+* #2331: Fix code-blocks are filled by block in dvi; remove ``xcdraw`` option from
+ xcolor package
* Fix the confval type checker emits warnings if unicode is given to confvals which expects string value
* #2360: Fix numref in LaTeX output is broken
* #2361: Fix additional paragraphs inside the "compound" directive are indented
From c7c07db86b30b811bd8cbd31e6b2a26224c675e4 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Sat, 18 Jun 2016 15:32:50 +0200
Subject: [PATCH 113/217] Fix #2694: LaTeX error because of
\sphinxstyleliteralintitle
---
sphinx/texinputs/sphinx.sty | 14 +++++++-------
1 file changed, 7 insertions(+), 7 deletions(-)
diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty
index 160bd99f0..4f1b37dcc 100644
--- a/sphinx/texinputs/sphinx.sty
+++ b/sphinx/texinputs/sphinx.sty
@@ -903,17 +903,17 @@
\fi
% additional customizable styling
-\let\sphinxstyleindexentry\texttt
+\newcommand*{\sphinxstyleindexentry}{\texttt}
\newcommand{\sphinxstyleindexextra}[1]{ \emph{(#1)}}
\newcommand*{\sphinxstyleindexpageref}{, \pageref}
\newcommand{\sphinxstyletopictitle}[1]{\textbf{#1}\par\medskip}
\let\sphinxstylesidebartitle\sphinxstyletopictitle
-\let\sphinxstyleothertitle\textbf
+\newcommand*{\sphinxstyleothertitle}{\textbf}
\newcommand{\sphinxstylesidebarsubtitle}[1]{~\\\textbf{#1} \smallskip}
-\let\sphinxstylethead\textsf
-\let\sphinxstyleemphasis\emph
+\newcommand*{\sphinxstylethead}{\textsf}
+\newcommand*{\sphinxstyleemphasis}{\emph}
\newcommand{\sphinxstyleliteralemphasis}[1]{\emph{\texttt{#1}}}
-\let\sphinxstylestrong\textbf
+\newcommand*{\sphinxstylestrong}{\textbf}
\newcommand{\sphinxstyleliteralstrong}[1]{\textbf{\texttt{#1}}}
-\let\sphinxstyleabbreviation\textsc
-\let\sphinxstyleliteralintitle\texttt
+\newcommand*{\sphinxstyleabbreviation}{\textsc}
+\newcommand*{\sphinxstyleliteralintitle}{\texttt}
From beeeb56c27233d1deb956abe1d4cf00990ba6284 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Sun, 19 Jun 2016 11:02:39 +0200
Subject: [PATCH 114/217] latex ``\noindent`` for non-inline images, not only
if top level
---
sphinx/writers/latex.py | 10 +++-------
tests/test_build_latex.py | 21 ++++++++++++---------
2 files changed, 15 insertions(+), 16 deletions(-)
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index d7bd3297c..229e62902 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -1408,12 +1408,8 @@ class LaTeXTranslator(nodes.NodeVisitor):
except KeyError:
pass
if not is_inline:
- if isinstance(node.parent, nodes.section):
- pre.append('\n\\noindent')
- post.append('\n')
- else:
- pre.append('\n')
- post.append('\n')
+ pre.append('\n\\noindent')
+ post.append('\n')
pre.reverse()
if node['uri'] in self.builder.images:
uri = self.builder.images[node['uri']]
@@ -1456,7 +1452,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
self.body.append('\\begin{sphinxfigure-in-table}\n\\centering\n')
if any(isinstance(child, nodes.caption) for child in node):
self.body.append('\\capstart')
- self.context.append(ids + '\\end{sphinxfigure-in-table}\n')
+ self.context.append(ids + '\\end{sphinxfigure-in-table}\\relax\n')
elif node.get('align', '') in ('left', 'right'):
if 'width' in node:
length = width_to_latex_length(node['width'])
diff --git a/tests/test_build_latex.py b/tests/test_build_latex.py
index f7479f545..4ef83165f 100644
--- a/tests/test_build_latex.py
+++ b/tests/test_build_latex.py
@@ -113,21 +113,24 @@ def test_writer(app, status, warning):
result = (app.outdir / 'SphinxTests.tex').text(encoding='utf8')
assert ('\\begin{sphinxfigure-in-table}\n\\centering\n\\capstart\n'
- '\\sphinxincludegraphics{{img}.png}\n\\sphinxfigcaption'
- '{figure in table}\\label{markup:id7}\\end{sphinxfigure-in-table}' in result)
+ '\\noindent\\sphinxincludegraphics{{img}.png}\n'
+ '\\sphinxfigcaption{figure in table}\\label{markup:id7}'
+ '\\end{sphinxfigure-in-table}\\relax' in result)
assert ('\\begin{wrapfigure}{r}{0pt}\n\\centering\n'
- '\\sphinxincludegraphics{{rimg}.png}\n\\caption{figure with align option}'
- '\\label{markup:id8}\\end{wrapfigure}' in result)
+ '\\noindent\\sphinxincludegraphics{{rimg}.png}\n'
+ '\\caption{figure with align option}\\label{markup:id8}'
+ '\\end{wrapfigure}' in result)
assert ('\\begin{wrapfigure}{r}{0.500\\linewidth}\n\\centering\n'
- '\\sphinxincludegraphics{{rimg}.png}\n\\caption{figure with align \\& figwidth option}'
- '\\label{markup:id9}\\end{wrapfigure}' in result)
+ '\\noindent\\sphinxincludegraphics{{rimg}.png}\n'
+ '\\caption{figure with align \\& figwidth option}\\label{markup:id9}'
+ '\\end{wrapfigure}' in result)
assert ('\\begin{wrapfigure}{r}{3cm}\n\\centering\n'
- '\\sphinxincludegraphics[width=3cm]{{rimg}.png}\n'
- '\\caption{figure with align \\& width option}'
- '\\label{markup:id10}\\end{wrapfigure}' in result)
+ '\\noindent\\sphinxincludegraphics[width=3cm]{{rimg}.png}\n'
+ '\\caption{figure with align \\& width option}\\label{markup:id10}'
+ '\\end{wrapfigure}' in result)
@with_app(buildername='latex', freshenv=True, # use freshenv to check warnings
From 50dbfec05b37a53df15e3e8b1035416045c93f32 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Sun, 19 Jun 2016 14:35:47 +0200
Subject: [PATCH 115/217] Remove commented-out lines in latex.py used for
review of #2691
Functionality is now at bottom of sphinx.sty. For case of
``\sphinxstylesidebarsubtitle`` from b3d8961, there should probably be a
``\par`` before the ``\smallskip`` but current code is exact transfer of
original from latex.py to sphinx.sty.
---
sphinx/writers/latex.py | 19 -------------------
1 file changed, 19 deletions(-)
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index ba477fb43..a55e02488 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -638,13 +638,10 @@ class LaTeXTranslator(nodes.NodeVisitor):
for entry in entries:
if not entry[3]:
continue
- # ret.append('\\item {\\texttt{%s}}' % self.encode(entry[0]))
ret.append('\\item {\\sphinxstyleindexentry{%s}}' % self.encode(entry[0]))
if entry[4]:
# add "extra" info
- # ret.append(' \\emph{(%s)}' % self.encode(entry[4]))
ret.append('\\sphinxstyleindexextra{%s}' % self.encode(entry[4]))
- # ret.append(', \\pageref{%s:%s}\n' %
ret.append('\\sphinxstyleindexpageref{%s:%s}\n' %
(entry[2], self.idescape(entry[3])))
ret.append('\\end{theindex}\n')
@@ -834,14 +831,10 @@ class LaTeXTranslator(nodes.NodeVisitor):
self.next_section_ids.clear()
elif isinstance(parent, nodes.topic):
- # self.body.append(r'\textbf{')
self.body.append(r'\sphinxstyletopictitle{')
- # self.context.append('}\n\n\medskip\n\n')
self.context.append('}\n')
elif isinstance(parent, nodes.sidebar):
- # self.body.append(r'\textbf{')
self.body.append(r'\sphinxstylesidebartitle{')
- # self.context.append('}\n\n\medskip\n\n')
self.context.append('}\n')
elif isinstance(parent, nodes.Admonition):
self.body.append('{')
@@ -854,7 +847,6 @@ class LaTeXTranslator(nodes.NodeVisitor):
'encountered title node not in section, topic, table, '
'admonition or sidebar',
(self.curfilestack[-1], node.line or ''))
-# self.body.append('\\textbf{')
self.body.append('\\sphinxstyleothertitle{')
self.context.append('}\n')
self.in_title = 1
@@ -869,8 +861,6 @@ class LaTeXTranslator(nodes.NodeVisitor):
def visit_subtitle(self, node):
if isinstance(node.parent, nodes.sidebar):
- # self.body.append('~\\\\\n\\textbf{')
- # self.context.append('}\n\\smallskip\n')
self.body.append('\\sphinxstylesidebarsubtitle{')
self.context.append('}\n')
else:
@@ -1207,7 +1197,6 @@ class LaTeXTranslator(nodes.NodeVisitor):
if len(node) == 1 and isinstance(node[0], nodes.paragraph) and node.astext() == '':
pass
else:
- # self.body.append('\\textsf{\\relax ')
self.body.append('\\sphinxstylethead{\\relax ')
context += '}'
while self.remember_multirow.get(self.table.col + 1, 0):
@@ -1770,42 +1759,35 @@ class LaTeXTranslator(nodes.NodeVisitor):
pass
def visit_emphasis(self, node):
- # self.body.append(r'\emph{')
self.body.append(r'\sphinxstyleemphasis{')
def depart_emphasis(self, node):
self.body.append('}')
def visit_literal_emphasis(self, node):
- # self.body.append(r'\emph{\texttt{')
self.body.append(r'\sphinxstyleliteralemphasis{')
self.no_contractions += 1
def depart_literal_emphasis(self, node):
- # self.body.append('}}')
self.body.append('}')
self.no_contractions -= 1
def visit_strong(self, node):
- # self.body.append(r'\textbf{')
self.body.append(r'\sphinxstylestrong{')
def depart_strong(self, node):
self.body.append('}')
def visit_literal_strong(self, node):
- # self.body.append(r'\textbf{\texttt{')
self.body.append(r'\sphinxstyleliteralstrong{')
self.no_contractions += 1
def depart_literal_strong(self, node):
- # self.body.append('}}')
self.body.append('}')
self.no_contractions -= 1
def visit_abbreviation(self, node):
abbr = node.astext()
- # self.body.append(r'\textsc{')
self.body.append(r'\sphinxstyleabbreviation{')
# spell out the explanation once
if node.hasattr('explanation') and abbr not in self.handled_abbrs:
@@ -1850,7 +1832,6 @@ class LaTeXTranslator(nodes.NodeVisitor):
def visit_literal(self, node):
self.no_contractions += 1
if self.in_title:
- # self.body.append(r'\texttt{')
self.body.append(r'\sphinxstyleliteralintitle{')
else:
self.body.append(r'\sphinxcode{')
From 0b2a4e907352a3438b990939c14524a607472a82 Mon Sep 17 00:00:00 2001
From: Dmitry Shachnev
Date: Sun, 19 Jun 2016 16:40:42 +0300
Subject: [PATCH 116/217] Fix LocalTimeZone.utcoffset return value when
SOURCE_DATE_EPOCH is set
Subclasses of tzinfo should follow the parent class and return offset either
as None (when unknown) or as timedelta.
Otherwise datetime.fromtimestamp() will raise a TypeError:
tzinfo.utcoffset() must return None or timedelta, not 'int'.
---
sphinx/builders/gettext.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/sphinx/builders/gettext.py b/sphinx/builders/gettext.py
index 1c4789392..a7fea86fa 100644
--- a/sphinx/builders/gettext.py
+++ b/sphinx/builders/gettext.py
@@ -135,7 +135,7 @@ tzdelta = datetime.fromtimestamp(timestamp) - \
source_date_epoch = getenv('SOURCE_DATE_EPOCH')
if source_date_epoch is not None:
timestamp = float(source_date_epoch)
- tzdelta = 0
+ tzdelta = timedelta(0)
class LocalTimeZone(tzinfo):
From 01f1696d9b69a10a45a6e500d3f3e6c186dc0dfb Mon Sep 17 00:00:00 2001
From: jfbu
Date: Sat, 11 Jun 2016 19:15:47 +0200
Subject: [PATCH 117/217] Remove usage by sphinx.sty of latex package
newfloat.sty
---
CHANGES | 5 +-
sphinx/texinputs/newfloat.sty | 737 ----------------------------------
sphinx/texinputs/sphinx.sty | 28 +-
sphinx/writers/latex.py | 8 +-
tests/test_build_latex.py | 8 +-
tests/test_directive_code.py | 6 +-
6 files changed, 34 insertions(+), 758 deletions(-)
delete mode 100644 sphinx/texinputs/newfloat.sty
diff --git a/CHANGES b/CHANGES
index 65fb40ca4..88d71a135 100644
--- a/CHANGES
+++ b/CHANGES
@@ -7,7 +7,10 @@ Incompatible changes
* LaTeX package fancybox is not longer a dependency of sphinx.sty
* Use ``'locales'`` as a default value of `locale_dirs`
* LaTeX package ifthen is not any longer a dependency of sphinx.sty
-* LaTeX writer produces source not modifying original fancyvrb's Verbatim but using new name sphinxVerbatim for its custom wrapper
+* LaTeX writer produces source not modifying original fancyvrb's Verbatim but
+ using new name sphinxVerbatim for its custom wrapper
+* LaTeX package newfloat (which was shipped with Sphinx since 1.3.4) is no
+ longer a dependency of sphinx.sty (ref #2660)
Features added
--------------
diff --git a/sphinx/texinputs/newfloat.sty b/sphinx/texinputs/newfloat.sty
deleted file mode 100644
index 47ac5e568..000000000
--- a/sphinx/texinputs/newfloat.sty
+++ /dev/null
@@ -1,737 +0,0 @@
-%%
-%% This is file `newfloat.sty',
-%% generated with the docstrip utility.
-%%
-%% The original source files were:
-%%
-%% newfloat.dtx (with options: `package')
-%%
-%% Copyright (C) 1994-2016 Axel Sommerfeldt (axel.sommerfeldt@f-m.fm)
-%%
-%% http://sourceforge.net/projects/latex-caption/
-%%
-%% --------------------------------------------------------------------------
-%%
-%% This work may be distributed and/or modified under the
-%% conditions of the LaTeX Project Public License, either version 1.3
-%% of this license or (at your option) any later version.
-%% The latest version of this license is in
-%% http://www.latex-project.org/lppl.txt
-%% and version 1.3 or later is part of all distributions of LaTeX
-%% version 2003/12/01 or later.
-%%
-%% This work has the LPPL maintenance status "maintained".
-%%
-%% This Current Maintainer of this work is Axel Sommerfeldt.
-%%
-%% This work consists of the files
-%% CHANGELOG, README, SUMMARY, caption.ins,
-%% caption.dtx, caption2.dtx, caption3.dtx,
-%% bicaption.dtx, ltcaption.dtx, subcaption.dtx,
-%% newfloat.dtx, and totalcount.dtx
-%% the derived files
-%% caption.sty, caption2.sty, caption3.sty,
-%% bicaption.sty, ltcaption.sty, subcaption.sty,
-%% newfloat.sty, and totalcount.sty
-%% and the user manuals
-%% caption-deu.tex, caption-eng.tex, and caption-rus.tex.
-%%
-\NeedsTeXFormat{LaTeX2e}[1994/12/01]
-\def\caption@tempa$Id: #1 #2 #3-#4-#5 #6${%
- \def\caption@tempa{#3/#4/#5 }\def\caption@tempb{#2 }}
-\caption@tempa $Id: newfloat.dtx 109 2015-09-17 09:29:07Z sommerfeldt $
-\ProvidesPackage{newfloat}[\caption@tempa v1.1-\caption@tempb Defining new floating environments (AR)]
-\newcommand*\newfloat@Info[1]{%
- \PackageInfo{newfloat}{#1}}
-\newcommand*\newfloat@InfoNoLine[1]{%
- \newfloat@Info{#1\@gobble}}
-\newcommand*\newfloat@Error[1]{%
- \PackageError{newfloat}{#1}\newfloat@eh}
-\newcommand*\newfloat@eh{%
- If you do not understand this error, please take a closer look\MessageBreak
- at the documentation of the `newfloat' package.\MessageBreak\@ehc}
-\RequirePackage{keyval}[1997/11/10]
-\newcommand*\newfloat@def[2]{%
- \newfloat@ifundefined{#1}{%
- \@namedef{#1}{#2}}}
-\newcommand*\newfloat@let[2]{%
- \newfloat@ifundefined{#1}{%
- \expandafter\let\csname #1\endcsname#2}}
-\newcommand*\newfloat@ifundefined[2]{%
- \@ifundefined{#1}{#2}{%
- \newfloat@Info{%
- \expandafter\string\csname#1\endcsname\space is already defined}}}
-\newcommand*\DeclareFloatingEnvironment{%
- \@testopt\@DeclareFloatingEnvironment{}}
-\@onlypreamble\DeclareFloatingEnvironment
-\def\@DeclareFloatingEnvironment[#1]#2{%
- \newfloat@Info{New float `#2' with options `#1'}%
- \newfloat@ifundefined{c@#2}{\newcounter{#2}}%
- \ifdefined\c@float@type % from float package
- \expandafter\edef\csname ftype@#2\endcsname{\the\value{float@type}}%
- \addtocounter{float@type}{\value{float@type}}%
- \else\ifdefined\c@newflo@tctr % from memoir document class
- \expandafter\edef\csname ftype@#2\endcsname{\the\c@newflo@tctr}%
- \advance\c@newflo@tctr \c@newflo@tctr
- \else
- \ifdefined\newfloat@ftype \else
- \newcount\newfloat@ftype
- \newfloat@ftype=8\relax
- \fi
- \expandafter\xdef\csname ftype@#2\endcsname{\the\newfloat@ftype}%
- \advance\newfloat@ftype\newfloat@ftype
- \fi\fi
- \newfloat@Info{float type `#2'=\@nameuse{ftype@#2}}%
- \newfloat@def{fnum@#2}%
- {\@nameuse{#2name}\nobreakspace\@nameuse{the#2}\@nameuse{autodot}}%
- \newfloat@capitalize\newfloat@Type{#2}%
- \newfloat@let{#2name}{\newfloat@Type}%
- \newfloat@def{fleg#2}{\@nameuse{#2name}}% legend naming (memoir)
- \newfloat@ifundefined{flegtoc#2}{\@namedef{flegtoc#2}##1{}}%
- \ifcsname @tufte@float\endcsname
- \newenvironment{#2}[1][htbp]%
- {\begin{@tufte@float}[##1]{#2}{}}%
- {\end{@tufte@float}}%
- \newenvironment{#2*}[1][htbp]%
- {\begin{@tufte@float}[##1]{#2}{star}}%
- {\end{@tufte@float}}%
- \else
- \newenvironment{#2}{\@float{#2}}{\end@float}%
- \newenvironment{#2*}{\@dblfloat{#2}}{\end@dblfloat}%
- \fi
- \newfloat@def{listof#2}{\newfloat@listof{#2}}%
- \newfloat@def{listof#2s}{\@nameuse{listof#2}}%
- \newfloat@def{listof#2es}{\@nameuse{listof#2s}}%
- \newfloat@def{newfloat@listof#2@hook}{}%
- \ifdefined\l@figure
- \newfloat@let{l@#2}{\l@figure}%
- \else
- \newfloat@def{l@#2}{\@dottedtocline{1}{1.5em}{2.3em}}%
- \fi
- \edef\newfloat@tempa{List of \newfloat@Type s}%
- \newfloat@let{list#2name}{\newfloat@tempa}%
- \expandafter\let\csname fst@#2\endcsname\@undefined
- \newfloat@ifundefined{fps@#2}{\newfloat@setplacement{#2}{tbp}}%
- \newfloat@ifundefined{ext@#2}{\newfloat@setfileext{#2}{lo#2}}%
- \newfloat@setoptions*{#2}{#1}%
- \@expandtwoargs\newfloat@announce{#2}{\@nameuse{ext@#2}}%
- \@ifnextchar[\newfloat@DFE@setname\relax}
-\@onlypreamble\@DeclareFloatingEnvironment
-\def\newfloat@DFE@setname[#1]{%
- \KV@@newfloat@name{#1}%
- \@ifnextchar[\newfloat@DFE@setlistname\relax}
-\@onlypreamble\newfloat@DFE@setname
-\def\newfloat@DFE@setlistname[#1]{%
- \KV@@newfloat@listname{#1}}
-\@onlypreamble\newfloat@DFE@setlistname
-\newcommand*\newfloat@capitalize[2]{%
- \edef\newfloat@tempa{\gdef\noexpand#1{\@car#2\@nil}}%
- \uppercase\expandafter{\newfloat@tempa}%
- \edef\newfloat@tempa{%
- \noexpand\g@addto@macro\noexpand#1{\@cdr#2\@nil}}%
- \newfloat@tempa}
-\newcommand*\newfloat@listof[1]{%
- \@expandtwoargs\newfloat@list@of{#1}{\@nameuse{ext@#1}}}
-\newcommand*\newfloat@list@of[2]{%
- \begingroup
- \expandafter\let\expandafter\listfigurename\csname list#1name\endcsname
- \def\ext@figure{#2}%
- \let\newfloat@starttoc\@starttoc
- \def\@starttoc##1{\newfloat@starttoc{#2}}%
- \let\newfloat@listoftoc\listoftoc
- \def\listoftoc##1{\newfloat@listoftoc{#2}}%
- \@nameuse{newfloat@listof#1@hook}%
- \listoffigures
- \endgroup}
-\newcommand*\newfloat@setoptions{%
- \@ifstar
- {\newfloat@@setoptions\@firstofone}%
- {\newfloat@@setoptions\@gobble}}
-\newcommand*\newfloat@@setoptions[3]{%
- \let\newfloat@within@value\@undefined
- \let\newfloat@chapterlistsgaps@value\@undefined
- #1{\KV@@newfloat@within\newfloat@within@default}% set default value for new floats
- \def\newfloat@type{#2}%
- \setkeys{@newfloat}{#3}%
- \ifx\newfloat@within@value\@undefined \else
- \newfloat@setoption{within}\newfloat@within@value
- \fi
- \ifx\newfloat@chapterlistsgaps@value\@undefined \else
- \newfloat@setoption{chapterlistsgaps}\newfloat@chapterlistsgaps@value
- \fi}
-\newcommand*\newfloat@within@default{%
- \ifcsname c@chapter\endcsname chapter\else none\fi}
-\@onlypreamble\newfloat@within@default
-\newcommand*\newfloat@setoption[1]{%
- \edef\caption@tempa{\noexpand\@nameuse{newfloat@set#1}{\newfloat@type}}%
- \caption@tempa}
-\newcommand*\newfloat@setfileext[2]{%
- \@namedef{ext@#1}{#2}}
-\define@key{@newfloat}{fileext}{%
- \newfloat@setoption{fileext}{#1}}
-\newcommand*\newfloat@setlistname[2]{%
- \@namedef{list#1name}{#2}}
-\define@key{@newfloat}{listname}{%
- \newfloat@setoption{listname}{#1}}
-\newcommand*\newfloat@setname[2]{%
- \newfloat@@setname{#1}{#2}%
- \begingroup
- \ifcsname languagename\endcsname
- \ifcsname captions\languagename\endcsname
- \expandafter\g@addto@macro\csname captions\languagename\endcsname
- {\newfloat@@setname{#1}{#2}}%
- \fi
- \fi
- \endgroup}
-%%\AtBeginDocument{\let\newfloat@setname\newfloat@@setname}
-\newcommand*\newfloat@@setname[2]{%
- \@namedef{#1name}{#2}}
-\define@key{@newfloat}{name}{%
- \newfloat@setoption{name}{#1}}
-\newcommand*\newfloat@setplacement[2]{%
- \@namedef{fps@#1}{#2}}
-\define@key{@newfloat}{placement}{%
- \newfloat@setoption{placement}{#1}}
-\newcommand*\newfloat@setwithin[2]{%
- \ifcsname c@chapter\endcsname
- \@removefromreset{#1}{chapter}%
- \fi
- \@removefromreset{#1}{section}%
- \edef\@tempa{#2}%
- \ifx\@tempa\@empty
- \def\@tempa{none}%
- \fi
- \def\@tempb{none}%
- \ifx\@tempa\@tempb
- \ifcsname c@chapter\endcsname
- \@chapterlistsgap@off{#1}%
- \fi
- \newfloat@@setwithin{#1}{}{}%
- \else
- \def\@tempb{chapter}%
- \ifx\@tempa\@tempb
- \@addtoreset{#1}{chapter}%
- \@chapterlistsgap@on{#1}%
- \newfloat@@setwithin{#1}{\ifnum\c@chapter>\z@ \thechapter.\fi}{\theHchapter.}%
- \else
- \def\@tempb{section}%
- \ifx\@tempa\@tempb
- \@addtoreset{#1}{section}%
- \ifcsname c@chapter\endcsname
- \@addtoreset{#1}{chapter}%
- \@chapterlistsgap@on{#1}%
- \newfloat@@setwithin{#1}{\thesection.}{\theHsection.}%
- \else
- \newfloat@@setwithin{#1}{\ifnum\c@section>\z@ \thesection.\fi}{\theHsection.}%
- \fi
- \else
- \newfloat@Error{Invalid value `#2' for option `within'}%
- \fi
- \fi
- \fi}
-\newcommand*\newfloat@@setwithin[3]{%
- \global\@namedef{the#1}{#2\arabic{#1}}%
- \global\@namedef{theH#1}{#3\arabic{#1}}}
-\define@key{@newfloat}{within}{%
- \def\newfloat@within@value{#1}}
-\newcommand*\newfloat@setwithout[1]{%
- \newfloat@setwithin{#1}{none}}
-\define@key{@newfloat}{without}[]{%
- \def\newfloat@within@value{none}}
-\newcommand*\newfloat@setchapterlistsgaps[2]{%
- \edef\@tempa{#2}%
- \def\@tempb{off}%
- \ifx\@tempa\@tempb
- \@chapterlistsgap@off{#1}%
- \else
- \def\@tempb{on}%
- \ifx\@tempa\@tempb
- \@chapterlistsgap@on{#1}%
- \else
- \newfloat@Error{Invalid value `#2' for option `chapterlistsgaps'}%
- \fi
- \fi}
-\define@key{@newfloat}{chapterlistsgaps}{%
- \def\newfloat@chapterlistsgaps@value{#1}}
-\providecommand*\@removefromreset[2]{{%
- \expandafter\let\csname c@#1\endcsname\@removefromreset
- \def\@elt##1{%
- \expandafter\ifx\csname c@##1\endcsname\@removefromreset
- \else
- \noexpand\@elt{##1}%
- \fi}%
- \expandafter\xdef\csname cl@#2\endcsname{%
- \csname cl@#2\endcsname}}}
-\newcommand*\newfloat@announce[2]{%
- \@cons\newfloat@list{{#1}}%
- \@cons\newfloat@@list{{#1}}%
- \newfloat@ifundefined{newfloat@ext@#2}{%
- \@namedef{newfloat@ext@#2}{#1}%
- \ifcsname c@lofdepth\endcsname
- \newfloat@ifundefined{c@#2depth}{%
- \newcounter{#2depth}%
- \setcounter{#2depth}{1}}%
- \fi
- \ifcsname addtotoclist\endcsname
- \addtotoclist[float]{#2}%
- \newfloat@def{listof#2name}{\@nameuse{list#1name}}%
- \fi
- }%
- \ifcsname contentsuse\endcsname
- \contentsuse{#1}{#2}%
- \fi
- \newfloat@hook{#1}}
-\@onlypreamble\newfloat@announce
-\newcommand*\newfloat@@list{}
-\newcommand*\SetupFloatingEnvironment[1]{%
- \newfloat@addtolist{#1}%
- \newfloat@setoptions{#1}}
-\newcommand\ForEachFloatingEnvironment{%
- \@ifstar
- {\@ForEachFloatingEnvironment\@gobble}%
- {\@ForEachFloatingEnvironment\@iden}}
-\newcommand\@ForEachFloatingEnvironment[2]{%
- \def\@elt##1{#2}%
- \newfloat@list
- \let\@elt\relax
- #1{\newfloat@addtohook{#2}}}
-\providecommand\newfloat@addtohook[1]{%
- \toks@=\expandafter{\newfloat@hook{##1}#1}%
- \edef\@tempa{\def\noexpand\newfloat@hook####1{\the\toks@}}%
- \@tempa}
-\providecommand*\newfloat@hook[1]{}
-\newcommand\PrepareListOf[1]{%
- \expandafter\g@addto@macro\csname newfloat@listof#1@hook\endcsname}
-\@onlypreamble\PrepareListOf
-\newcommand*\newfloat@list{}
-\newcommand*\newfloat@addtolist[1]{%
- \newfloat@ifinlist{#1}{}{%
- \ifcsname ext@#1\endcsname
- \@cons\newfloat@list{{#1}}%
- \@namedef{newfloat@ext@\@nameuse{ext@#1}}{#1}%
- \newfloat@let{@ifchapterlistsgap@#1}{\@iden}%
- \else
- \newfloat@Error{`#1' does not seem to be a floating environment}%
- \fi}}
-\newcommand*\newfloat@ifinlist[1]{%
- \let\next\@secondoftwo
- \begingroup
- \expandafter\let\csname c@#1\endcsname\newfloat@ifinlist
- \def\@elt##1{%
- \expandafter\ifx\csname c@##1\endcsname\newfloat@ifinlist
- \global\let\next\@firstoftwo
- \fi}%
- \newfloat@list
- \endgroup
- \next}
-\ifcsname ext@figure\endcsname
- \newfloat@addtolist{figure}
-\fi
-\ifcsname ext@table\endcsname
- \newfloat@addtolist{table}
-\fi
-\ifcsname @chapter\endcsname
- \providecommand*\@chapterlistsgap{10\p@}%
- \providecommand*\@addchapterlistsgap[2]{%
- \@nameuse{@ifchapterlistsgap@#1}{% if switched on
- \@@addchapterlistsgap{#1}{#2}}}
- \providecommand*\@@addchapterlistsgap[2]{%
- \@ifundefined{@addchapterlistsgap@#2}{% only once per extension
- \@namedef{@addchapterlistsgap@#2}{#1}%
- \@@@addchapterlistsgap{#2}}{}}
- \providecommand*\@@@addchapterlistsgap[1]{%
- \ifdim \@chapterlistsgap>\z@
- \addtocontents{#1}{\protect\addvspace{\@chapterlistsgap}}%
- \fi}
- \providecommand*\@addchapterlistsgaps{%
- \begingroup
- \def\@elt##1{%
- \@expandtwoargs\@addchapterlistsgap{##1}{\@nameuse{ext@##1}}}%
- \newfloat@list
- \endgroup}
- \providecommand*\@chapterlistsgap@off[1]{%
- \expandafter\let\csname @ifchapterlistsgap@#1\endcsname\@gobble
- \ifcsname unsettoc\endcsname
- \@expandtwoargs\unsettoc{\@nameuse{ext@#1}}{chapteratlist}%
- \fi}
- \providecommand*\@chapterlistsgap@on[1]{%
- \expandafter\let\csname @ifchapterlistsgap@#1\endcsname\@iden
- \ifcsname setuptoc\endcsname
- \@expandtwoargs\setuptoc{\@nameuse{ext@#1}}{chapteratlist}%
- \fi}
-\fi
-\define@key{newfloat}{chapterlistsgap}{%
- \renewcommand*\@chapterlistsgap{#1}}
-\define@key{newfloat}{within}{%
- \def\newfloat@within@default{#1}% set new default value
- \def\@elt##1{\newfloat@setwithin{##1}{#1}}%
- \newfloat@list
- \let\@elt\relax}
-\define@key{newfloat}{without}[]{%
- \KV@newfloat@within{none}}
-\def\@elt#1{%
- \define@key{newfloat}{#1name}{%
- \newfloat@setname{#1}{##1}}%
- \define@key{newfloat}{list#1name}{%
- \newfloat@setname{list#1}{##1}}%
- \define@key{newfloat}{#1within}{%
- \newfloat@setwithin{#1}{##1}}%
- \define@key{newfloat}{#1without}[]{%
- \newfloat@setwithout{#1}}%
-}%
-\newfloat@list
-\let\@elt\relax
-\define@key{newfloat}{planb}[true]{%
- \def\@tempa{#1}%
- \def\@tempb{false}%
- \ifx\@tempa\@tempb
- \let\newfloat@ifplanb\@gobble
- \else
- \def\@tempb{true}%
- \ifx\@tempa\@tempb
- \let\newfloat@ifplanb\@iden
- \else
- \newfloat@Error{Invalid value `#1' for option `planb'}%
- \fi
- \fi}
-\define@key{newfloat}{planb-fileext}{%
- \newfloat@Info{Setting Plan B file extension to `#1'}
- \xdef\newfloat@addtocontents@ext{#1}}
-
-\let\@tempc\relax
-\@expandtwoargs\setkeys{newfloat}{planb,\@ptionlist{\@currname.\@currext}}%
-\AtEndOfPackage{\let\@unprocessedoptions\relax}
-\newcommand*\newfloatsetup{\setkeys{newfloat}}
-\newcommand\newfloat@replace@chapter[2]{%
- \begingroup
- \let\if@twocolumn\iffalse
- \let\if@mainmatter\iffalse
- \let\if@thema\iffalse
- \def\@tempa[##1]##2{#1}%
- \ifx\@tempa\@chapter
- \gdef\@chapter[##1]##2{#2}%
- \global\let\newfloat@replace@chapter\@gobbletwo
- \else\ifx\@tempa\Hy@org@chapter
- \gdef\Hy@org@chapter[##1]##2{#2}%
- \global\let\newfloat@replace@chapter\@gobbletwo
- \fi\fi
- \endgroup}
-\ifcsname @chapter\endcsname \else
- \let\newfloat@replace@chapter\@gobbletwo
-\fi
-\newfloat@replace@chapter{%
- \ifnum \c@secnumdepth >\m@ne
- \refstepcounter{chapter}%
- \typeout{\@chapapp\space\thechapter.}%
- \addcontentsline{toc}{chapter}%
- {\protect\numberline{\thechapter}#1}%
- \else
- \addcontentsline{toc}{chapter}{#1}%
- \fi
- \chaptermark{#1}%
- \addtocontents{lof}{\protect\addvspace{10\p@}}%
- \addtocontents{lot}{\protect\addvspace{10\p@}}%
- \if@twocolumn
- \@topnewpage[\@makechapterhead{#2}]%
- \else
- \@makechapterhead{#2}%
- \@afterheading
- \fi
-}{%
- \ifnum \c@secnumdepth >\m@ne
- \refstepcounter{chapter}%
- \typeout{\@chapapp\space\thechapter.}%
- \addcontentsline{toc}{chapter}%
- {\protect\numberline{\thechapter}#1}%
- \else
- \addcontentsline{toc}{chapter}{#1}%
- \fi
- \chaptermark{#1}%
- \@addchapterlistsgaps
- \if@twocolumn
- \@topnewpage[\@makechapterhead{#2}]%
- \else
- \@makechapterhead{#2}%
- \@afterheading
- \fi}
-\newfloat@replace@chapter{%
- \ifnum \c@secnumdepth >\m@ne
- \if@mainmatter
- \refstepcounter{chapter}%
- \typeout{\@chapapp\space\thechapter.}%
- \addcontentsline{toc}{chapter}%
- {\protect\numberline{\thechapter}#1}%
- \else
- \addcontentsline{toc}{chapter}{#1}%
- \fi
- \else
- \addcontentsline{toc}{chapter}{#1}%
- \fi
- \chaptermark{#1}%
- \addtocontents{lof}{\protect\addvspace{10\p@}}%
- \addtocontents{lot}{\protect\addvspace{10\p@}}%
- \if@twocolumn
- \@topnewpage[\@makechapterhead{#2}]%
- \else
- \@makechapterhead{#2}%
- \@afterheading
- \fi
-}{%
- \ifnum \c@secnumdepth >\m@ne
- \if@mainmatter
- \refstepcounter{chapter}%
- \typeout{\@chapapp\space\thechapter.}%
- \addcontentsline{toc}{chapter}%
- {\protect\numberline{\thechapter}#1}%
- \else
- \addcontentsline{toc}{chapter}{#1}%
- \fi
- \else
- \addcontentsline{toc}{chapter}{#1}%
- \fi
- \chaptermark{#1}%
- \@addchapterlistsgaps
- \if@twocolumn
- \@topnewpage[\@makechapterhead{#2}]%
- \else
- \@makechapterhead{#2}%
- \@afterheading
- \fi}
-\newfloat@replace@chapter{%
- \refstepcounter{chapter}%
- \ifnum\c@secnumdepth<\z@ \let\@secnumber\@empty
- \else \let\@secnumber\thechapter \fi
- \typeout{\chaptername\space\@secnumber}%
- \def\@toclevel{0}%
- \ifx\chaptername\appendixname \@tocwriteb\tocappendix{chapter}{#2}%
- \else \@tocwriteb\tocchapter{chapter}{#2}\fi
- \chaptermark{#1}%
- \addtocontents{lof}{\protect\addvspace{10\p@}}%
- \addtocontents{lot}{\protect\addvspace{10\p@}}%
- \@makechapterhead{#2}\@afterheading
-}{%
- \refstepcounter{chapter}%
- \ifnum\c@secnumdepth<\z@ \let\@secnumber\@empty
- \else \let\@secnumber\thechapter \fi
- \typeout{\chaptername\space\@secnumber}%
- \def\@toclevel{0}%
- \ifx\chaptername\appendixname \@tocwriteb\tocappendix{chapter}{#2}%
- \else \@tocwriteb\tocchapter{chapter}{#2}\fi
- \chaptermark{#1}%
- \@addchapterlistsgaps
- \@makechapterhead{#2}\@afterheading}
-\@ifpackageloaded{tocbasic}{%
- \let\newfloat@replace@chapter\@gobbletwo}{}
-\ifcsname insertchapterspace\endcsname
- \renewcommand*\insertchapterspace{\@addchapterlistsgaps}
- \let\newfloat@replace@chapter\@gobbletwo
-\fi
-\newfloat@replace@chapter{%
- \ifnum \c@secnumdepth >\m@ne
- \refstepcounter{chapter}%
- \typeout{\@chapapp\space\thechapter.}%
- \addcontentsline{toc}{chapter}%
- {\protect\numberline{\thechapter}\toc@font0 #1}%
- \else
- \addcontentsline{toc}{chapter}{\toc@font0 #1}%
- \fi
- \chaptermark{#1}%
- \addtocontents{lof}{\protect\addvspace{10\p@}}%
- \addtocontents{lot}{\protect\addvspace{10\p@}}%
- \if@twocolumn
- \@topnewpage[\@makechapterhead{#2}]%
- \else
- \@makechapterhead{#2}%
- \@afterheading
- \fi
-}{%
- \ifnum \c@secnumdepth >\m@ne
- \refstepcounter{chapter}%
- \typeout{\@chapapp\space\thechapter.}%
- \addcontentsline{toc}{chapter}%
- {\protect\numberline{\thechapter}\toc@font0 #1}%
- \else
- \addcontentsline{toc}{chapter}{\toc@font0 #1}%
- \fi
- \chaptermark{#1}%
- \@addchapterlistsgaps
- \if@twocolumn
- \@topnewpage[\@makechapterhead{#2}]%
- \else
- \@makechapterhead{#2}%
- \@afterheading
- \fi}
- % boek(3).cls [2004/06/07 v2.1a NTG LaTeX document class]
-\newfloat@replace@chapter{%
- \ifnum \c@secnumdepth >\m@ne
- \if@mainmatter
- \refstepcounter{chapter}%
- \typeout{\@chapapp\space\thechapter.}%
- \addcontentsline{toc}{chapter}%
- {\protect\numberline{\thechapter}\toc@font0 #1}%
- \else
- \addcontentsline{toc}{chapter}{\toc@font0 #1}%
- \fi
- \else
- \addcontentsline{toc}{chapter}{\toc@font0 #1}%
- \fi
- \chaptermark{#1}%
- \addtocontents{lof}{\protect\addvspace{10\p@}}%
- \addtocontents{lot}{\protect\addvspace{10\p@}}%
- \if@twocolumn
- \@topnewpage[\@makechapterhead{#2}]%
- \else
- \@makechapterhead{#2}%
- \@afterheading
- \fi
-}{%
- \ifnum \c@secnumdepth >\m@ne
- \if@mainmatter
- \refstepcounter{chapter}%
- \typeout{\@chapapp\space\thechapter.}%
- \addcontentsline{toc}{chapter}%
- {\protect\numberline{\thechapter}\toc@font0 #1}%
- \else
- \addcontentsline{toc}{chapter}{\toc@font0 #1}%
- \fi
- \else
- \addcontentsline{toc}{chapter}{\toc@font0 #1}%
- \fi
- \chaptermark{#1}%
- \@addchapterlistsgaps
- \if@twocolumn
- \@topnewpage[\@makechapterhead{#2}]%
- \else
- \@makechapterhead{#2}%
- \@afterheading
- \fi}
-\newfloat@replace@chapter{%
- \ifnum \c@secnumdepth >\m@ne
- \if@mainmatter
- \refstepcounter{chapter}%
- \typeout{\chaptername\space\thechapter.}
- \if@thema
- \ifx\@shortauthor\@empty
- \addcontentsline{toc}{chapter}{%
- \protect\numberline{\thechapter.}#1}%
- \else
- \addcontentsline{toc}{chapter}{%
- \protect\numberline{\thechapter.}%
- \@shortauthor\hfill\mbox{}\vskip\normallineskip #1}%
- \fi
- \else
- \addcontentsline{toc}{chapter}{%
- \protect\numberline{\thechapter.}#1}%
- \fi
- \else
- \addcontentsline{toc}{chapter}{#1}
- \fi
- \else
- \addcontentsline{toc}{chapter}{#1}
- \fi
- \chaptermark{#1}
- \addtocontents{lof}{\protect\addvspace{10pt}}
- \addtocontents{lot}{\protect\addvspace{10pt}}
- \if@twocolumn
- \@topnewpage[\@makechapterhead{#2}]
- \else
- \@makechapterhead{#2}
- \@afterheading
- \fi
-}{%
- \ifnum \c@secnumdepth >\m@ne
- \if@mainmatter
- \refstepcounter{chapter}%
- \typeout{\chaptername\space\thechapter.}%
- \if@thema
- \ifx\@shortauthor\@empty
- \addcontentsline{toc}{chapter}{%
- \protect\numberline{\thechapter.}#1}%
- \else
- \addcontentsline{toc}{chapter}{%
- \protect\numberline{\thechapter.}%
- \@shortauthor\hfill\mbox{}\vskip\normallineskip #1}%
- \fi
- \else
- \addcontentsline{toc}{chapter}{%
- \protect\numberline{\thechapter.}#1}%
- \fi
- \else
- \addcontentsline{toc}{chapter}{#1}%
- \fi
- \else
- \addcontentsline{toc}{chapter}{#1}%
- \fi
- \chaptermark{#1}%
- \@addchapterlistsgaps
- \if@twocolumn
- \@topnewpage[\@makechapterhead{#2}]%
- \else
- \@makechapterhead{#2}%
- \@afterheading
- \fi}
-\ifx\newfloat@replace@chapter\@gobbletwo \else
- \newfloat@InfoNoLine{%
- Unsupported document class, or \noexpand\@chapter\MessageBreak
- was already redefined by another package}
- \newfloat@InfoNoLine{\string\@chapter\space=\space\meaning\@chapter}
- \newfloat@InfoNoLine{\string\Hy@org@chapter\space=\space\meaning\Hy@org@chapter}
- \newfloat@ifplanb{%
- \newfloat@InfoNoLine{Trying Plan B..}%
- \let\newfloat@addtocontents@ORI\addtocontents
- \long\def\addtocontents#1#2{%
- \newfloat@addtocontents{#1}{#2}#2\addvspace\newfloat@nil}%
- \long\def\newfloat@addtocontents#1#2#3\addvspace#4\newfloat@nil{%
- \def\newfloat@tempa{#4}%
- \ifx\newfloat@tempa\@empty
- \newfloat@addtocontents@ORI{#1}{#2}%
- \else
- \ifx\newfloat@addtocontents@ext\@undefined
- \newfloat@Info{Setting Plan B file extension to `#1'...}%
- \xdef\newfloat@addtocontents@ext{#1}%
- \fi
- \edef\newfloat@tempa{#1}%
- \ifx\newfloat@tempa\newfloat@addtocontents@ext
- \begingroup
- \let\addtocontents\newfloat@addtocontents@ORI
- \@addchapterlistsgaps
- \endgroup
- \fi
- \fi}}
-\fi
-\newcommand\newfloat@ForEachNew[2][newfloat@@list]{%
- \AtBeginDocument{%
- \ifcsname#1\endcsname
- \def\@elt##1{#2}%
- \newfloat@@list
- \let\@elt\relax
- \fi}}%
-\@onlypreamble\newfloat@ForEachNew
-%% \begin{macrocode}
-\newfloat@ForEachNew[float@exts]{%
- \@nameuse{@ifchapterlistsgap@#1}{% if switched on
- \let\float@do=\relax
- \edef\@tempa{%
- \noexpand\float@exts{\the\float@exts\float@do{\@nameuse{ext@#1}}}}%
- \@tempa}}
-\newfloat@ForEachNew[FP@floatBegin]{%
- \newcounter{FP@#1C}%
- \newenvironment{FP#1}{\FP@floatBegin{#1}}{\FP@floatEnd}}
-\providecommand*\ext@lstlisting{lol}%
-\newfloat@ForEachNew[@rotfloat]{%
- \newenvironment{sideways#1}{\@rotfloat{#1}}{\end@rotfloat}%
- \newenvironment{sideways#1*}{\@rotdblfloat{#1}}{\end@rotdblfloat}}
-\newcommand*\newfloat@For@SC[2]{%
- \def#1{b}% = \sidecaptionvpos{#2}{b} (v1.6)
- \newenvironment{SC#2}%
- {\SC@float[#1]{#2}}{\endSC@float}%
- \newenvironment{SC#2*}%
- {\SC@dblfloat[#1]{#2}}{\endSC@dblfloat}}
-\@onlypreamble\newfloat@For@SC
-\newfloat@ForEachNew[SC@float]{%
- \expandafter\newfloat@For@SC\csname SC@#1@vpos\endcsname{#1}}
-\newfloat@ForEachNew[wrapfloat]{%
- \newenvironment{wrap#1}{\wrapfloat{#1}}{\endwrapfloat}}
-\endinput
-%%
-%% End of file `newfloat.sty'.
diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty
index 4f1b37dcc..2aa452800 100644
--- a/sphinx/texinputs/sphinx.sty
+++ b/sphinx/texinputs/sphinx.sty
@@ -199,7 +199,7 @@
\newcommand*\sphinxVerbatimTitle {}
% Holder macro for labels of literal blocks. Set-up by LaTeX writer.
\newcommand*\sphinxLiteralBlockLabel {}
-\newcommand*\sphinxSetupCaptionForVerbatim [2]
+\newcommand*\sphinxSetupCaptionForVerbatim [1]
{%
\needspace{\sphinxliteralblockneedspace}%
% insert a \label via \sphinxLiteralBlockLabel
@@ -207,7 +207,8 @@
% the caption inserts \abovecaptionskip whitespace above itself (usually 10pt)
% there is also \belowcaptionskip but it is usually zero, hence the \smallskip
\def\sphinxVerbatimTitle
- {\py@NormalColor\captionof{#1}{\sphinxLiteralBlockLabel #2}\smallskip }%
+ {\py@NormalColor
+ \captionof{literalblock}{\sphinxLiteralBlockLabel #1}\smallskip }%
}
% Inspired and adapted from framed.sty's \CustomFBox with extra handling
@@ -855,13 +856,24 @@
}
\fi
-% Define literal-block environment
-\RequirePackage{newfloat}
-\DeclareFloatingEnvironment{literal-block}
+% for captions of literal blocks
+\newcounter{literalblock}
\spx@ifundefined{c@chapter}
- {\SetupFloatingEnvironment{literal-block}{within=section,placement=h}}
- {\SetupFloatingEnvironment{literal-block}{within=chapter,placement=h}}
-\SetupFloatingEnvironment{literal-block}{name=List}
+ {\@addtoreset{literalblock}{section}
+ \def\theliteralblock {\ifnum\c@section>\z@ \thesection.\fi\arabic{literalblock}}
+ \def\theHliteralblock {\theHsection.\arabic{literalblock}}}
+ {\@addtoreset{literalblock}{chapter}
+ \def\theliteralblock {\ifnum\c@chapter>\z@ \thechapter.\fi\arabic{literalblock}}
+ \def\theHliteralblock {\theHchapter.\arabic{literalblock}}}
+% at start of caption title
+\newcommand*{\fnum@literalblock}{\literalblockname\nobreakspace\theliteralblock}
+% this will be overwritten in document preamble by Babel translation
+\newcommand*{\literalblockname}{Listing }
+% file extension needed for \caption's good functioning, but file isn't
+% created without \listofliteralblocks. The latter macro could be defined
+% on model of \listoffigures.
+\newcommand*{\ext@literalblock}{lol}
+
% control caption around literal-block
\RequirePackage{capt-of}
\RequirePackage{needspace}
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index a55e02488..bdfaaf69c 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -618,9 +618,9 @@ class LaTeXTranslator(nodes.NodeVisitor):
if len(codeblock) == 1:
pass # FIXME
else:
- ret.append('\\SetupFloatingEnvironment{literal-block}{name=%s}\n' %
- escape_abbr(text_type(codeblock[0]).translate(tex_escape_map)))
- if table[1]:
+ definition = escape_abbr(text_type(codeblock[0]).translate(tex_escape_map))
+ ret.append(self.babel_renewcommand('\\literalblockname', definition))
+ if codeblock[1]:
pass # FIXME
return ''.join(ret)
@@ -1514,7 +1514,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
def visit_caption(self, node):
self.in_caption += 1
if self.in_container_literal_block:
- self.body.append('\\sphinxSetupCaptionForVerbatim{literal-block}{')
+ self.body.append('\\sphinxSetupCaptionForVerbatim{')
elif self.in_minipage and isinstance(node.parent, nodes.figure):
self.body.append('\\captionof{figure}{')
elif self.table and node.parent.tagname == 'figure':
diff --git a/tests/test_build_latex.py b/tests/test_build_latex.py
index b4064f231..199162d95 100644
--- a/tests/test_build_latex.py
+++ b/tests/test_build_latex.py
@@ -189,7 +189,7 @@ def test_numref(app, status, warning):
print(warning.getvalue())
assert '\\addto\\captionsenglish{\\renewcommand{\\figurename}{Fig.\\@ }}' in result
assert '\\addto\\captionsenglish{\\renewcommand{\\tablename}{Table }}' in result
- assert '\\SetupFloatingEnvironment{literal-block}{name=Listing }' in result
+ assert '\\addto\\captionsenglish{\\renewcommand{\\literalblockname}{Listing }}' in result
assert '\\hyperref[index:fig1]{Fig.\\@ \\ref{index:fig1}}' in result
assert '\\hyperref[baz:fig22]{Figure\\ref{baz:fig22}}' in result
assert '\\hyperref[index:table-1]{Table \\ref{index:table-1}}' in result
@@ -211,7 +211,7 @@ def test_numref_with_prefix1(app, status, warning):
print(warning.getvalue())
assert '\\addto\\captionsenglish{\\renewcommand{\\figurename}{Figure:}}' in result
assert '\\addto\\captionsenglish{\\renewcommand{\\tablename}{Tab\\_}}' in result
- assert '\\SetupFloatingEnvironment{literal-block}{name=Code-}' in result
+ assert '\\addto\\captionsenglish{\\renewcommand{\\literalblockname}{Code-}}' in result
assert '\\ref{index:fig1}' in result
assert '\\ref{baz:fig22}' in result
assert '\\ref{index:table-1}' in result
@@ -241,7 +241,7 @@ def test_numref_with_prefix2(app, status, warning):
assert '\\def\\fnum@figure{\\figurename\\thefigure.\\@}' in result
assert '\\addto\\captionsenglish{\\renewcommand{\\tablename}{Tab\\_}}' in result
assert '\\def\\fnum@table{\\tablename\\thetable:}' in result
- assert '\\SetupFloatingEnvironment{literal-block}{name=Code-}' in result
+ assert '\\addto\\captionsenglish{\\renewcommand{\\literalblockname}{Code-}}' in result
assert '\\hyperref[index:fig1]{Figure:\\ref{index:fig1}.\\@}' in result
assert '\\hyperref[baz:fig22]{Figure\\ref{baz:fig22}}' in result
assert '\\hyperref[index:table-1]{Tab\\_\\ref{index:table-1}:}' in result
@@ -260,7 +260,7 @@ def test_numref_with_language_ja(app, status, warning):
print(warning.getvalue())
assert u'\\renewcommand{\\figurename}{\u56f3 }' in result
assert '\\renewcommand{\\tablename}{TABLE }' in result
- assert '\\SetupFloatingEnvironment{literal-block}{name=LIST }' in result
+ assert '\\renewcommand{\\literalblockname}{LIST }' in result
assert u'\\hyperref[index:fig1]{\u56f3 \\ref{index:fig1}}' in result
assert '\\hyperref[baz:fig22]{Figure\\ref{baz:fig22}}' in result
assert '\\hyperref[index:table-1]{TABLE \\ref{index:table-1}}' in result
diff --git a/tests/test_directive_code.py b/tests/test_directive_code.py
index 0f1e98f7e..f4abab935 100644
--- a/tests/test_directive_code.py
+++ b/tests/test_directive_code.py
@@ -65,8 +65,7 @@ def test_code_block_caption_html(app, status, warning):
def test_code_block_caption_latex(app, status, warning):
app.builder.build_all()
latex = (app.outdir / 'Python.tex').text(encoding='utf-8')
- caption = '\\sphinxSetupCaptionForVerbatim{literal-block}' \
- '{caption \\sphinxstyleemphasis{test} rb}'
+ caption = '\\sphinxSetupCaptionForVerbatim{caption \\sphinxstyleemphasis{test} rb}'
label = '\\def\\sphinxLiteralBlockLabel{\\label{caption:caption-test-rb}}'
link = '\hyperref[caption:caption-test-rb]' \
'{Listing \\ref{caption:caption-test-rb}}'
@@ -253,8 +252,7 @@ def test_literalinclude_caption_html(app, status, warning):
def test_literalinclude_caption_latex(app, status, warning):
app.builder.build('index')
latex = (app.outdir / 'Python.tex').text(encoding='utf-8')
- caption = '\\sphinxSetupCaptionForVerbatim{literal-block}' \
- '{caption \\sphinxstylestrong{test} py}'
+ caption = '\\sphinxSetupCaptionForVerbatim{caption \\sphinxstylestrong{test} py}'
label = '\\def\\sphinxLiteralBlockLabel{\\label{caption:caption-test-py}}'
link = '\hyperref[caption:caption-test-py]' \
'{Listing \\ref{caption:caption-test-py}}'
From 3650663bb3712ec5994b07657484a7eba92c6f83 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Sun, 19 Jun 2016 20:50:50 +0200
Subject: [PATCH 118/217] Fix #2679: (latex) load package float for 'H' value
of 'figure_align'
---
CHANGES | 1 +
sphinx/texinputs/sphinx.sty | 3 +++
2 files changed, 4 insertions(+)
diff --git a/CHANGES b/CHANGES
index 50a66de92..deb1313fb 100644
--- a/CHANGES
+++ b/CHANGES
@@ -15,6 +15,7 @@ Bugs fixed
* #2676: (latex) Error with verbatim text in captions since Sphinx 1.4.4
* #2629: memoir class crashes LaTeX. Fixed ``by latex_keep_old_macro_names=False`` (ref 2675)
* #2684: `sphinx.ext.intersphinx` crashes with six-1.4.1
+* #2679: ``float`` package needed for ``'figure_align': 'H'`` latex option
Release 1.4.4 (released Jun 12, 2016)
diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty
index 85fc492a7..a049c504b 100644
--- a/sphinx/texinputs/sphinx.sty
+++ b/sphinx/texinputs/sphinx.sty
@@ -59,6 +59,9 @@
\RequirePackage{alltt}
% Display "real" single quotes in literal blocks.
\RequirePackage{upquote}
+% For the H specifier. Do not \restylefloat{figure}, it breaks Sphinx code
+% for allowing figures in tables.
+\RequirePackage{float}
% Redefine these colors to your liking in the preamble.
\definecolor{TitleColor}{rgb}{0.126,0.263,0.361}
From c59734c9f4154c485028503fea3407d95474d14a Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Mon, 20 Jun 2016 10:58:06 +0900
Subject: [PATCH 119/217] Fix descriptions of make targets
---
sphinx/quickstart.py | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/sphinx/quickstart.py b/sphinx/quickstart.py
index 408c4a430..5aa47cb61 100644
--- a/sphinx/quickstart.py
+++ b/sphinx/quickstart.py
@@ -565,8 +565,8 @@ help:
\t@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
\t@echo " latexpdf to make LaTeX files and run them through pdflatex"
\t@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
-\t@echo " lualatexpdf to make LaTeX files and run them through pdflatex"
-\t@echo " xelatexpdf to make LaTeX files and run them through pdflatex"
+\t@echo " lualatexpdf to make LaTeX files and run them through lualatex"
+\t@echo " xelatexpdf to make LaTeX files and run them through xelatex"
\t@echo " text to make text files"
\t@echo " man to make manual pages"
\t@echo " texinfo to make Texinfo files"
From e5db9da45d31014b99615748b5611892a8f9a35d Mon Sep 17 00:00:00 2001
From: jfbu
Date: Mon, 13 Jun 2016 19:01:20 +0200
Subject: [PATCH 120/217] latex: fully customizable notices/admonitions
The refactoring maintains backwards compatibility for the non-customized
usage: but macros such as ``\py@noticesstart@note`` have been removed
and any customization by extension or user will be without effect.
However the ``notice`` environment is still used, hence customization or
modified usage of it will work as before.
The LaTeX writer now uses ``sphinxadmonition``. Currently it is a
wrapper of ``notice`` environment. At some future release ``>1.5`` of
Sphinx it is planned to remove definition of ``notice`` environment, and
rename it directly to ``sphinxadmonition``. In the transition period
both will work, but at end of transition period extensions using only
``notice`` will stop working and those using ``sphinxadmonition`` will
require at least Sphinx ``1.5``.
---
CHANGES | 3 +
sphinx/texinputs/sphinx.sty | 143 ++++++++++++++++++++++++------------
sphinx/writers/latex.py | 8 +-
3 files changed, 104 insertions(+), 50 deletions(-)
diff --git a/CHANGES b/CHANGES
index 88d71a135..11c9b4135 100644
--- a/CHANGES
+++ b/CHANGES
@@ -30,6 +30,9 @@ Features added
the ``visit_emphasis`` will output ``\sphinxstyleemphasis`` rather than
``\emph`` (which may be in use elsewhere or in an added LaTeX package). See
list at end of ``sphinx.sty`` (ref: #2686)
+* public names for latex environments and parameters used by note, warning,
+ and other admonition types, allowing full customizability from the
+ ``'preamble'`` key (ref: feature request #2674, #2685)
Bugs fixed
----------
diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty
index 2aa452800..e7004f880 100644
--- a/sphinx/texinputs/sphinx.sty
+++ b/sphinx/texinputs/sphinx.sty
@@ -540,12 +540,56 @@
}
% Notices / Admonitions
-%
+% Some are quite plain
+\newenvironment{sphinxlightbox}{%
+ \par\allowbreak
+ \noindent{\color{spx@notice@bordercolor}%
+ \rule{\linewidth}{\spx@notice@border}}\par\nobreak
+ {\parskip\z@skip\noindent}%
+ }
+ {%
+ \par
+ % counteract previous possible negative skip (French lists!):
+ % (we can't cancel that any earlier \vskip introduced a potential pagebreak)
+ \ifdim\lastskip<\z@\vskip-\lastskip\fi
+ \nobreak\vbox{\noindent\kern\@totalleftmargin
+ {\color{spx@notice@bordercolor}%
+ \rule[\dimexpr.4\baselineskip-\spx@notice@border\relax]
+ {\linewidth}{\spx@notice@border}}\hss}\allowbreak
+ }% end of sphinxlightbox environment definition
+% may be renewenvironment'd by user for complete customization
+\newenvironment{sphinxnote}[1]
+ {\begin{sphinxlightbox}\sphinxstrong{#1} }{\end{sphinxlightbox}}
+\newenvironment{sphinxhint}[1]
+ {\begin{sphinxlightbox}\sphinxstrong{#1} }{\end{sphinxlightbox}}
+\newenvironment{sphinximportant}[1]
+ {\begin{sphinxlightbox}\sphinxstrong{#1} }{\end{sphinxlightbox}}
+\newenvironment{sphinxtip}[1]
+ {\begin{sphinxlightbox}\sphinxstrong{#1} }{\end{sphinxlightbox}}
+% or user may just customize the bordercolor and the border width
+% re-use \definecolor if change needed, and \renewcommand for rule width
+\definecolor{sphinxnotebordercolor}{rgb}{0,0,0}
+\definecolor{sphinxhintbordercolor}{rgb}{0,0,0}
+\definecolor{sphinximportantbordercolor}{rgb}{0,0,0}
+\definecolor{sphinxtipbordercolor}{rgb}{0,0,0}
+\newcommand{\sphinxnoteborder}{0.5pt}
+\newcommand{\sphinxhintborder}{0.5pt}
+\newcommand{\sphinximportantborder}{0.5pt}
+\newcommand{\sphinxtipborder}{0.5pt}
+% these are needed for common handling by notice environment of lightbox
+% and heavybox but they are currently not used by lightbox environment
+\definecolor{sphinxnotebgcolor}{rgb}{1,1,1}
+\definecolor{sphinxhintbgcolor}{rgb}{1,1,1}
+\definecolor{sphinximportantbgcolor}{rgb}{1,1,1}
+\definecolor{sphinxtipbgcolor}{rgb}{1,1,1}
+
+% Others get more distinction
+\newdimen\spx@notice@border
% Code adapted from framed.sty's "snugshade" environment.
% Nesting works (inner frames do not allow page breaks).
-\newcommand{\py@heavybox}{\par
- \setlength{\FrameRule}{\p@}% 1pt
+\newenvironment{sphinxheavybox}{\par
+ \setlength{\FrameRule}{\spx@notice@border}%
\setlength{\FrameSep}{\dimexpr.6\baselineskip-\FrameRule\relax}
% configure framed.sty's parameters to obtain same vertical spacing
% as for "light" boxes. We need for this to manually insert parskip glue and
@@ -554,7 +598,8 @@
\vspace{\FrameHeightAdjust}
% copied/adapted from framed.sty's snugshade
\def\FrameCommand##1{\hskip\@totalleftmargin
- \fboxsep\FrameSep \fboxrule\FrameRule\fbox{##1}%
+ \fboxsep\FrameSep \fboxrule\FrameRule
+ \fcolorbox{spx@notice@bordercolor}{spx@notice@bgcolor}{##1}%
\hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
% use a minipage if we are already inside a framed environment
\ifspx@inframed
@@ -578,7 +623,7 @@
\@minipagerestore
\@setminipage }%
}
-\newcommand{\py@endheavybox}{%
+ {%
\par\unskip
% handles footnotes
\ifvoid\@mpfootins\else
@@ -589,49 +634,55 @@
\ifspx@inframed\end{minipage}\fi
% arrange for similar spacing below frame as for "light" boxes.
\vskip .4\baselineskip
- }
+ }% end of sphinxheavybox environment definition
+% may be renewenvironment'd by user for complete customization
+\newenvironment{sphinxwarning}[1]
+ {\begin{sphinxheavybox}\sphinxstrong{#1} }{\end{sphinxheavybox}}
+\newenvironment{sphinxcaution}[1]
+ {\begin{sphinxheavybox}\sphinxstrong{#1} }{\end{sphinxheavybox}}
+\newenvironment{sphinxattention}[1]
+ {\begin{sphinxheavybox}\sphinxstrong{#1} }{\end{sphinxheavybox}}
+\newenvironment{sphinxdanger}[1]
+ {\begin{sphinxheavybox}\sphinxstrong{#1} }{\end{sphinxheavybox}}
+\newenvironment{sphinxerror}[1]
+ {\begin{sphinxheavybox}\sphinxstrong{#1} }{\end{sphinxheavybox}}
+% or just re-do \definecolor for colours, \renewcommand for frame width
+\definecolor{sphinxwarningbordercolor}{rgb}{0,0,0}
+\definecolor{sphinxcautionbordercolor}{rgb}{0,0,0}
+\definecolor{sphinxattentionbordercolor}{rgb}{0,0,0}
+\definecolor{sphinxdangerbordercolor}{rgb}{0,0,0}
+\definecolor{sphinxerrorbordercolor}{rgb}{0,0,0}
+\definecolor{sphinxwarningbgcolor}{rgb}{1,1,1}
+\definecolor{sphinxcautionbgcolor}{rgb}{1,1,1}
+\definecolor{sphinxattentionbgcolor}{rgb}{1,1,1}
+\definecolor{sphinxdangerbgcolor}{rgb}{1,1,1}
+\definecolor{sphinxerrorbgcolor}{rgb}{1,1,1}
+\newcommand{\sphinxwarningborder}{1pt}
+\newcommand{\sphinxcautionborder}{1pt}
+\newcommand{\sphinxattentionborder}{1pt}
+\newcommand{\sphinxdangerborder}{1pt}
+\newcommand{\sphinxerrorborder}{1pt}
-\newcommand{\py@lightbox}{%
- \par\allowbreak
- \noindent\rule{\linewidth}{0.5pt}\par\nobreak
- {\parskip\z@skip\noindent}%
- }
-\newcommand{\py@endlightbox}{%
- \par
- % counteract previous possible negative skip (French lists!):
- % (we can't cancel that any earlier \vskip introduced a potential pagebreak)
- \ifdim\lastskip<\z@\vskip-\lastskip\fi
- \nobreak\vbox{\noindent\kern\@totalleftmargin
- \rule[.4\baselineskip]{\linewidth}{0.5pt}\hss}\allowbreak
- }
+% the \colorlet of xcolor (if at all loaded) is overkill for our use case
+\newcommand{\sphinxcolorlet}[2]
+ {\expandafter\let\csname\@backslashchar color@#1\expandafter\endcsname
+ \csname\@backslashchar color@#2\endcsname }
-% Some are quite plain:
-\newcommand{\py@noticestart@note}{\py@lightbox}
-\newcommand{\py@noticeend@note}{\py@endlightbox}
-\newcommand{\py@noticestart@hint}{\py@lightbox}
-\newcommand{\py@noticeend@hint}{\py@endlightbox}
-\newcommand{\py@noticestart@important}{\py@lightbox}
-\newcommand{\py@noticeend@important}{\py@endlightbox}
-\newcommand{\py@noticestart@tip}{\py@lightbox}
-\newcommand{\py@noticeend@tip}{\py@endlightbox}
-
-% Others gets more visible distinction:
-\newcommand{\py@noticestart@warning}{\py@heavybox}
-\newcommand{\py@noticeend@warning}{\py@endheavybox}
-\newcommand{\py@noticestart@caution}{\py@heavybox}
-\newcommand{\py@noticeend@caution}{\py@endheavybox}
-\newcommand{\py@noticestart@attention}{\py@heavybox}
-\newcommand{\py@noticeend@attention}{\py@endheavybox}
-\newcommand{\py@noticestart@danger}{\py@heavybox}
-\newcommand{\py@noticeend@danger}{\py@endheavybox}
-\newcommand{\py@noticestart@error}{\py@heavybox}
-\newcommand{\py@noticeend@error}{\py@endheavybox}
-
-\newenvironment{notice}[2]{
- \def\py@noticetype{#1}
- \csname py@noticestart@#1\endcsname
- \sphinxstrong{#2} % <- legacy code creates a space after {#2}
-}{\csname py@noticeend@\py@noticetype\endcsname}
+% the main dispatch for all types of notices
+\newenvironment{sphinxadmonition}{\begin{notice}}{\end{notice}}
+% use of ``notice'' is for backwards compatibility and will be removed in
+% future release; sphinxadmonition environment will be defined directly.
+\newenvironment{notice}[2]{% #1=type, #2=heading
+ % can't use #1 directly in definition of end part
+ \def\spx@noticetype {#1}%
+ % set parameters of heavybox/lightbox
+ \sphinxcolorlet{spx@notice@bordercolor}{sphinx#1bordercolor}%
+ \sphinxcolorlet{spx@notice@bgcolor}{sphinx#1bgcolor}%
+ \setlength\spx@notice@border {\dimexpr\csname sphinx#1border\endcsname\relax}%
+ % start specific environment, passing the heading as argument
+ \begin{sphinx#1}{#2}}
+ % in end part, need to go around a LaTeX's "feature"
+ {\edef\spx@temp{\noexpand\end{sphinx\spx@noticetype}}\spx@temp}
% Allow the release number to be specified independently of the
% \date{}. This allows the date to reflect the document's date and
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index bdfaaf69c..e6199bc1b 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -1533,19 +1533,19 @@ class LaTeXTranslator(nodes.NodeVisitor):
self.body.append('}')
def visit_admonition(self, node):
- self.body.append('\n\\begin{notice}{note}')
+ self.body.append('\n\\begin{sphinxadmonition}{note}')
def depart_admonition(self, node):
- self.body.append('\\end{notice}\n')
+ self.body.append('\\end{sphinxadmonition}\n')
def _make_visit_admonition(name):
def visit_admonition(self, node):
- self.body.append(u'\n\\begin{notice}{%s}{%s:}' %
+ self.body.append(u'\n\\begin{sphinxadmonition}{%s}{%s:}' %
(name, admonitionlabels[name]))
return visit_admonition
def _depart_named_admonition(self, node):
- self.body.append('\\end{notice}\n')
+ self.body.append('\\end{sphinxadmonition}\n')
visit_attention = _make_visit_admonition('attention')
depart_attention = _depart_named_admonition
From 12ade10d5593a07beab438140f0b27a390a84fff Mon Sep 17 00:00:00 2001
From: jfbu
Date: Sat, 18 Jun 2016 20:25:48 +0200
Subject: [PATCH 121/217] New latex.rst for extended documentation of LaTeX's
customizing.
---
doc/config.rst | 4 +-
doc/contents.rst | 2 +
doc/latex.rst | 126 +++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 130 insertions(+), 2 deletions(-)
create mode 100644 doc/latex.rst
diff --git a/doc/config.rst b/doc/config.rst
index 560d3a900..fda7596e6 100644
--- a/doc/config.rst
+++ b/doc/config.rst
@@ -1460,7 +1460,7 @@ the `Dublin Core metadata `_.
Options for LaTeX output
------------------------
-These options influence LaTeX output.
+These options influence LaTeX output. See further :doc:`latex`.
.. confval:: latex_documents
@@ -1623,7 +1623,7 @@ These options influence LaTeX output.
.. versionadded:: 1.4
``'preamble'``
- Additional preamble content, default empty.
+ Additional preamble content, default empty. See :doc:`latex`.
``'figure_align'``
Latex figure float alignment, default 'htbp' (here, top, bottom, page).
Whenever an image doesn't fit into the current page, it will be
diff --git a/doc/contents.rst b/doc/contents.rst
index a51910b81..79a10493d 100644
--- a/doc/contents.rst
+++ b/doc/contents.rst
@@ -1,3 +1,4 @@
+
.. _contents:
Sphinx documentation contents
@@ -17,6 +18,7 @@ Sphinx documentation contents
intl
theming
templating
+ latex
extensions
extdev/index
websupport
diff --git a/doc/latex.rst b/doc/latex.rst
new file mode 100644
index 000000000..7165ff778
--- /dev/null
+++ b/doc/latex.rst
@@ -0,0 +1,126 @@
+.. highlightlang:: python
+
+.. _latex:
+
+LaTeX customization
+===================
+
+.. module:: latex
+ :synopsis: LaTeX specifics.
+
+The *latex* target does not (yet) benefit from pre-prepared themes like the
+*html* target does (see :doc:`theming`).
+
+There are two principal means of setting up customization:
+
+#. usage of the :ref:`latex-options` as described in :doc:`config`, particularly the
+ various keys of :confval:`latex_elements`, to modify the loaded packages,
+ for example::
+
+ 'fontpkg': '\\usepackage{times}', # can load other font
+ 'fncychap': '\\usepackage[Bjarne]{fncychap}', # can use other option
+
+ .. tip::
+
+ It is not mandatory to load *fncychap*. Naturally, without it and in
+ absence of further customizations, the chapter headings will revert to
+ LaTeX's default for the *report* class.
+
+#. usage of LaTeX ``\renewcommand``, ``\renewenvironment``, ``\setlength``,
+ ``\definecolor`` to modify the defaults from package file :file:`sphinx.sty`
+ and class files :file:`sphinxhowto.cls` and :file:`sphinxmanual.cls`. If such
+ definitions are few, they can be located inside the ``'preamble'`` key of
+ :confval:`latex_elements`. In case of many it may prove more convenient to
+ assemble them into a specialized file :file:`customizedmacros.tex` and use::
+
+ 'preamble': '\\makeatletter\\input{customizedmacros.tex}\\makeatother',
+
+ More advanced LaTeX users will set up a style file
+ :file:`customizedmacros.sty`, which can then be loaded via::
+
+ 'preamble': '\\usepackage{customizedmacros}',
+
+ The :ref:`build configuration file ` file will then have its variable
+ :confval:`latex_additional_files` appropriately configured, for example::
+
+ latex_additional_files = ["customizedmacros.sty"]
+
+ Such *LaTeX Sphinx theme* files could possibly be contributed in the
+ future by advanced users for wider use.
+
+Let us illustrate here what can be modified by the second method.
+
+- text styling commands (they have one argument): ``\sphinx`` with
+ ```` being one of ``strong``, ``bfcode``, ``email``, ``tablecontinued``,
+ ``titleref``, ``menuselection``, ``accelerator``, ``crossref``, ``termref``,
+ ``optional``. By default and for backwards compatibility the ``\sphinx``
+ expands to ``\`` hence the user can choose to customize rather the latter
+ (the non-prefixed macros will be left undefined if option
+ :confval:`latex_keep_old_macro_names` is set to ``False`` in :file:`conf.py`.)
+
+ .. versionchanged:: 1.4.5
+ use of ``\sphinx`` prefixed macro names to limit possibilities of conflict
+ with user added packages. The LaTeX writer uses always the prefixed names.
+- more text styling commands: ``\sphinxstyle`` with ```` one of
+ ``indexentry``, ``indexextra``, ``indexpageref``, ``topictitle``,
+ ``sidebartitle``, ``othertitle``, ``sidebarsubtitle``, ``thead``,
+ ``emphasis``, ``literalemphasis``, ``strong``, ``literalstrong``,
+ ``abbreviation``, ``literalintitle``.
+
+ .. versionadded:: 1.5
+ earlier, the LaTeX writer used hard-coded ``\texttt``, ``\emph``, etc...
+- parameters for paragraph level environments: with ```` one of
+ :dudir:`warning`, :dudir:`caution`, :dudir:`attention`,
+ :dudir:`danger`, :dudir:`error`, the colours
+ *sphinxbordercolor* and *sphinxbgcolor* can be
+ re-defined using ``\definecolor`` command. The
+ ``\sphinxborder`` is a command (not a LaTeX length) which
+ specifies the thickness of the frame (default ``1pt``) and can be
+ ``\renewcommand`` 'd. The same applies with ```` one of
+ :dudir:`note`, :dudir:`hint`, :dudir:`important`, :dudir:`tip`, but
+ the background colour is not implemented by the default environments
+ and the top and bottom rule thickness default is ``0.5pt``.
+
+ .. versionchanged:: 1.5
+ customizability of the parameters for each type of admonition.
+- paragraph level environments: for each admonition as in the previous item, the
+ used environment is named ``sphinx``. They may be ``\renewenvironment``
+ 'd individually, and must then be defined with one argument (it is the heading
+ of the notice, for example ``Warning:`` for :dudir:`warning` directive, if
+ English is the document language). Their default definitions use either the
+ *sphinxheavybox* (for the first listed directives) or the *sphinxlightbox*
+ environments, configured to use the parameters (colours, border thickness)
+ specific to each type, as mentioned in the previous item.
+
+ .. versionchanged:: 1.5
+ use of public environment names, separate customizability of the parameters.
+- the :dudir:`contents` directive (with ``:local:`` option) and the
+ :dudir:`topic` directive are implemented by environment ``sphinxShadowBox``.
+ Its default definition obeys three LaTeX lengths (not commands) as parameters:
+ ``\sphinxshadowsep`` (distance from contents), ``\sphinxshadowsize`` (width of
+ lateral shadow), ``\sphinxshadowrule`` (thickness of the frame).
+
+ .. versionchanged:: 1.5
+ use of public names for the three lengths. The environment itself was
+ redefined to allow page breaks at release 1.4.2.
+- miscellaneous colours: *TitleColor*, *InnerLinkColor*, *OuterLinkColor*,
+ *VerbatimColor* (this is a background colour), *VerbatimBorderColor*.
+- the ``\sphinxAtStartFootnote`` is inserted between footnote numbers and their
+ texts, by default it does ``\mbox{ }``.
+- use ``\sphinxSetHeaderFamily`` to set the font used by headings
+ (default is ``\sffamily\bfseries``).
+
+ .. versionadded:: 1.5
+- the section, subsection, ... headings are set using *titlesec*'s
+ ``\titleformat`` command.
+- for the ``'manual'`` class, the chapter headings can be customized using
+ *fncychap*'s commands ``\ChNameVar``, ``\ChNumVar``, ``\ChTitleVar``. Or, if
+ the loading of this package has been removed from ``'fncychap'`` key, one can
+ use the *titlesec* ``\titleformat`` command.
+
+.. note::
+
+ It is impossible to revert or prevent the loading of a package that results
+ from a ``\usepackage`` executed from inside the :file:`sphinx.sty` style
+ file. Sphinx aims at loading as few packages as are really needed for its
+ default design.
From 65653db4799f5f592b73eb97aab61b66053dc96c Mon Sep 17 00:00:00 2001
From: jfbu
Date: Mon, 20 Jun 2016 11:40:26 +0200
Subject: [PATCH 122/217] latex #2698: restore usage of OriginalVerbatim name
for ``<1.5`` compat
---
sphinx/texinputs/sphinx.sty | 10 ++++++++--
sphinx/writers/latex.py | 4 +++-
2 files changed, 11 insertions(+), 3 deletions(-)
diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty
index e7004f880..d89f68946 100644
--- a/sphinx/texinputs/sphinx.sty
+++ b/sphinx/texinputs/sphinx.sty
@@ -181,6 +181,12 @@
% and possibly also a top caption, non separable by pagebreak. The original
% fancyvrb Verbatim is still used within tables.
+% For maintaining compatibility with Sphinx < 1.5, we define and use these
+% when (unmodified) Verbatim will be needed. But Sphinx >= 1.5 does not modify
+% original Verbatim anyhow.
+\let\OriginalVerbatim \Verbatim
+\let\endOriginalVerbatim\endVerbatim
+
\newcommand\spx@colorbox [2]{%
% #1 will be \fcolorbox or, for first part of frame: \spx@fcolorbox
% let the framing obey the current indentation (adapted from framed.sty's code).
@@ -380,10 +386,10 @@
% For grid placement from \strut's in \FancyVerbFormatLine
\lineskip\z@skip
% Breaks at punctuation characters . , ; ? ! and / need catcode=\active
- \Verbatim[#1,codes*=\sphinxbreaksatpunct]%
+ \OriginalVerbatim[#1,codes*=\sphinxbreaksatpunct]%
}
{%
- \endVerbatim
+ \endOriginalVerbatim
\par\unskip\@minipagefalse\endMakeFramed
\ifspx@inframed\end{minipage}\fi
\endtrivlist
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index e6199bc1b..ce1ff4eda 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -1908,6 +1908,8 @@ class LaTeXTranslator(nodes.NodeVisitor):
hlcode = hlcode.replace(u'€', u'@texteuro[]')
# must use original Verbatim environment and "tabular" environment
if self.table:
+ hlcode = hlcode.replace('\\begin{Verbatim}',
+ '\\begin{OriginalVerbatim}')
self.table.has_problematic = True
self.table.has_verbatim = True
else:
@@ -1916,7 +1918,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
# get consistent trailer
hlcode = hlcode.rstrip()[:-14] # strip \end{Verbatim}
self.body.append('\n' + hlcode + '\\end{%sVerbatim}\n' %
- ((not self.table) and 'sphinx' or ''))
+ ((not self.table) and 'sphinx' or 'Original'))
if ids:
self.body.append('\\let\\sphinxLiteralBlockLabel\empty\n')
raise nodes.SkipNode
From 303f163b0a9ddf15ce425c171dc4c84158c59d2d Mon Sep 17 00:00:00 2001
From: jfbu
Date: Tue, 21 Jun 2016 22:37:41 +0200
Subject: [PATCH 123/217] Fix #2707: (latex) the column width is badly computed
for tabular
MEMO: the used formula is correct as long as package array is loaded.
Package array (which modifies how the width of vertical rules is counted
in the total width of the tabular) is a dependency of packages tabulary,
and eqparbox, and possibly others which are currently loaded by
sphinx.sty. Even if usage of package tabulary is dropped in future
version of sphinx.sty, there would still remain the dependency on array
via eqparbox, and the formula configured in latex.py will remain
correct.
---
sphinx/writers/latex.py | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index e6199bc1b..ef1dd744d 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -1052,9 +1052,9 @@ class LaTeXTranslator(nodes.NodeVisitor):
self.body.append(self.table.colspec)
else:
if self.table.has_problematic:
- colwidth = 0.95 / self.table.colcount
- colspec = ('p{%.3f\\linewidth}|' % colwidth) * \
- self.table.colcount
+ colspec = ('p{\\dimexpr(\\linewidth-\\arrayrulewidth)/%d'
+ '-2\\tabcolsep-\\arrayrulewidth\\relax}|' % \
+ self.table.colcount) * self.table.colcount
self.body.append('{|' + colspec + '}\n')
elif self.table.longtable:
self.body.append('{|' + ('l|' * self.table.colcount) + '}\n')
From 8e45f54d0705b9558f52078ad8c8b48554589c8b Mon Sep 17 00:00:00 2001
From: jfbu
Date: Tue, 21 Jun 2016 23:19:56 +0200
Subject: [PATCH 124/217] Fix #2707: output more compact ``*{N}{p{...}}``
notation
---
sphinx/writers/latex.py | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index ef1dd744d..6b6b33368 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -1052,9 +1052,9 @@ class LaTeXTranslator(nodes.NodeVisitor):
self.body.append(self.table.colspec)
else:
if self.table.has_problematic:
- colspec = ('p{\\dimexpr(\\linewidth-\\arrayrulewidth)/%d'
- '-2\\tabcolsep-\\arrayrulewidth\\relax}|' % \
- self.table.colcount) * self.table.colcount
+ colspec = ('*{%d}{p{\\dimexpr(\\linewidth-\\arrayrulewidth)/%d'
+ '-2\\tabcolsep-\\arrayrulewidth\\relax}|}' % \
+ (self.table.colcount, self.table.colcount))
self.body.append('{|' + colspec + '}\n')
elif self.table.longtable:
self.body.append('{|' + ('l|' * self.table.colcount) + '}\n')
From c88193e3dfd5e689976fa080f0a789f1bf25d6d2 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Tue, 21 Jun 2016 23:25:06 +0200
Subject: [PATCH 125/217] fix flake8 violation
---
sphinx/writers/latex.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index 6b6b33368..84c21e8b3 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -1053,7 +1053,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
else:
if self.table.has_problematic:
colspec = ('*{%d}{p{\\dimexpr(\\linewidth-\\arrayrulewidth)/%d'
- '-2\\tabcolsep-\\arrayrulewidth\\relax}|}' % \
+ '-2\\tabcolsep-\\arrayrulewidth\\relax}|}' %
(self.table.colcount, self.table.colcount))
self.body.append('{|' + colspec + '}\n')
elif self.table.longtable:
From 4ab9854483ded6a4ae451f99a7ee70c0f1d6a1df Mon Sep 17 00:00:00 2001
From: jfbu
Date: Wed, 22 Jun 2016 09:36:10 +0200
Subject: [PATCH 126/217] Update CHANGES for PR#2708
---
CHANGES | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/CHANGES b/CHANGES
index 11c9b4135..9432c8cb9 100644
--- a/CHANGES
+++ b/CHANGES
@@ -12,6 +12,7 @@ Incompatible changes
* LaTeX package newfloat (which was shipped with Sphinx since 1.3.4) is no
longer a dependency of sphinx.sty (ref #2660)
+
Features added
--------------
@@ -33,10 +34,14 @@ Features added
* public names for latex environments and parameters used by note, warning,
and other admonition types, allowing full customizability from the
``'preamble'`` key (ref: feature request #2674, #2685)
+* latex better computes column widths of some tables (as a result, there will
+ be slight changes as tables now correctly fill the line with; ref: #2708)
Bugs fixed
----------
+* #2707: (latex) the column width is badly computed for tabular
+
Documentation
-------------
From f1cc694af719b687a184978477b2dda96d3cae1c Mon Sep 17 00:00:00 2001
From: jfbu
Date: Mon, 20 Jun 2016 16:09:19 +0200
Subject: [PATCH 127/217] latex: customizable literal blocks
- new dimensions ``\sphinxverbatimsep`` and ``\sphinxverbatimborder``
configure the frame width and its separation from contents,
- new ``\ifsphinxverbatimwithframe`` and ``\ifsphinxverbatimwrapslines``
to customize behaviour of sphinxVerbatim or define wrapper
environments, such as sphinxVerbatimNoFrame and sphinxVerbatimintable,
- the latter is used in table cells, in place of OriginalVerbatim, thus
allowing to handle captions for code-blocks in tables (issue #2706).
On this occasion, a bit of refactoring in sphinx Verbatim code,
particularly the caption is typeset in advance to its insertion in
non-breakable from code location (this avoids using the amstext
``\iffirstchoice@`` conditional), and the sphinxVerbatim is usable
without any optional argument (but currently option is always present
and contains at least ``commandchars=\\\{\}`` to activate syntax
highlighting).
---
CHANGES | 11 ++++-
sphinx/texinputs/sphinx.sty | 86 ++++++++++++++++++++++++++-----------
sphinx/writers/latex.py | 8 ++--
3 files changed, 75 insertions(+), 30 deletions(-)
diff --git a/CHANGES b/CHANGES
index 9432c8cb9..8c5510d2e 100644
--- a/CHANGES
+++ b/CHANGES
@@ -11,6 +11,8 @@ Incompatible changes
using new name sphinxVerbatim for its custom wrapper
* LaTeX package newfloat (which was shipped with Sphinx since 1.3.4) is no
longer a dependency of sphinx.sty (ref #2660)
+* latex, writer does not use OriginalVerbatim for literal blocks in tables but
+ sphinxVerbatimintable (ref #2704)
Features added
@@ -33,9 +35,16 @@ Features added
list at end of ``sphinx.sty`` (ref: #2686)
* public names for latex environments and parameters used by note, warning,
and other admonition types, allowing full customizability from the
- ``'preamble'`` key (ref: feature request #2674, #2685)
+ ``'preamble'`` key or an input file (ref: feature request #2674, #2685)
* latex better computes column widths of some tables (as a result, there will
be slight changes as tables now correctly fill the line with; ref: #2708)
+* latex, sphinxVerbatim environment is more easily customizable (ref: #2704).
+ In addition to already existing VerbatimColor and VerbatimBorderColor:
+
+ - two lengths ``\sphinxverbatimsep`` and ``\sphinxverbatimborder``,
+ - booleans ``\ifsphinxverbatimwithframe`` and ``\ifsphinxverbatimwrapslines``.
+* latex, captions for literal blocks inside tables are handled, and long code
+ lines wrapped to fit table cell (ref: #2704)
Bugs fixed
----------
diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty
index d89f68946..905fc37e1 100644
--- a/sphinx/texinputs/sphinx.sty
+++ b/sphinx/texinputs/sphinx.sty
@@ -23,6 +23,7 @@
\fi
}
+\RequirePackage{graphicx}
\@ifclassloaded{memoir}{}{\RequirePackage{fancyhdr}}
% for \text macro and \iffirstchoice@ conditional even if amsmath not loaded
@@ -33,7 +34,6 @@
\RequirePackage{makeidx}
% For framing code-blocks and warning type notices, and shadowing topics
\RequirePackage{framed}
-\newif\ifspx@inframed % flag set if we are in a framed environment
% The xcolor package draws better fcolorboxes around verbatim code
\IfFileExists{xcolor.sty}{
\RequirePackage{xcolor}
@@ -77,8 +77,6 @@
\newcount\pdfoutput\pdfoutput=0
\fi
-\RequirePackage{graphicx}
-
% for PDF output, use colors and maximal compression
\newif\ifsphinxpdfoutput % used in \maketitle
\ifx\pdfoutput\undefined\else
@@ -187,6 +185,13 @@
\let\OriginalVerbatim \Verbatim
\let\endOriginalVerbatim\endVerbatim
+\newif\ifspx@inframed % flag set if we are already in a framed environment
+\newdimen\sphinxverbatimsep \sphinxverbatimsep \fboxsep % default 3pt
+\newdimen\sphinxverbatimborder\sphinxverbatimborder\fboxrule % default 0.4pt
+\newif\ifsphinxverbatimwithframe \sphinxverbatimwithframetrue
+\newif\ifsphinxverbatimwrapslines \sphinxverbatimwrapslinestrue
+% if forced use of minipage encapsulation is needed (e.g. table cells)
+\newif\ifsphinxverbatimwithminipage \sphinxverbatimwithminipagefalse
\newcommand\spx@colorbox [2]{%
% #1 will be \fcolorbox or, for first part of frame: \spx@fcolorbox
% let the framing obey the current indentation (adapted from framed.sty's code).
@@ -200,9 +205,11 @@
\def\spx@fcolorbox #1#2%
{\color@b@x {\fboxsep\z@\color{#1}\spx@VerbatimFBox}{\color{#2}}}%
-% The title is specified from outside as macro \sphinxVerbatimTitle.
+% The title (caption) is specified from outside as macro \sphinxVerbatimTitle.
% \sphinxVerbatimTitle is reset to empty after each use of Verbatim.
\newcommand*\sphinxVerbatimTitle {}
+% This box to typeset the caption before framed.sty multiple passes for framing.
+\newbox\spx@VerbatimTitleBox
% Holder macro for labels of literal blocks. Set-up by LaTeX writer.
\newcommand*\sphinxLiteralBlockLabel {}
\newcommand*\sphinxSetupCaptionForVerbatim [1]
@@ -218,27 +225,23 @@
}
% Inspired and adapted from framed.sty's \CustomFBox with extra handling
-% of a non separable by pagebreak caption, and controlled counter stepping.
-\newif\ifspx@myfirstframedpass
+% of a non separable by pagebreak caption.
\long\def\spx@VerbatimFBox#1{%
\leavevmode
\begingroup
% framed.sty does some measuring but this macro adds possibly a caption
% use amsmath conditional to inhibit the caption counter stepping after
% first pass
- \ifspx@myfirstframedpass\else\firstchoice@false\fi
\setbox\@tempboxa\hbox{\kern\fboxsep{#1}\kern\fboxsep}%
\hbox
{\lower\dimexpr\fboxrule+\fboxsep+\dp\@tempboxa
\hbox{%
- \vbox{\ifx\sphinxVerbatimTitle\empty\else
+ \vbox{\ifvoid\spx@VerbatimTitleBox\else
% add the caption in a centered way above possibly indented frame
% hide its width from framed.sty's measuring step
% note that the caption brings \abovecaptionskip top vertical space
\moveright\dimexpr\fboxrule+.5\wd\@tempboxa
- \hb@xt@\z@{\hss\begin{minipage}{\wd\@tempboxa}%
- \sphinxVerbatimTitle
- \end{minipage}\hss}\fi
+ \hb@xt@\z@{\hss\unhcopy\spx@VerbatimTitleBox\hss}\fi
% draw frame border _latest_ to avoid pdf viewer issue
\kern\fboxrule
\hbox{\kern\fboxrule
@@ -254,7 +257,6 @@
\hrule\@height\fboxrule}%
}}%
\endgroup
- \global\spx@myfirstframedpassfalse
}
% For linebreaks inside Verbatim environment from package fancyvrb.
@@ -309,7 +311,11 @@
\lccode`\~`\~
}
-\newenvironment{sphinxVerbatim}[1][1]{%
+% needed to create wrapper environments of fancyvrb's Verbatim
+\newcommand*{\sphinxVerbatimEnvironment}{\gdef\FV@EnvironName{sphinxVerbatim}}
+% Sphinx <1.5 optional argument was in fact mandatory. It is now really
+% optional and handled by original Verbatim.
+\newenvironment{sphinxVerbatim}{%
% quit horizontal mode if we are still in a paragraph
\par
% list starts new par, but we don't want it to be set apart vertically
@@ -325,16 +331,25 @@
\needspace{\sphinxliteralblockwithoutcaptionneedspace}%
\phantomsection\sphinxLiteralBlockLabel
\fi
- \fi
+ \setbox\spx@VerbatimTitleBox\box\voidb@x
+ \else
% non-empty \sphinxVerbatimTitle has label inside it (in case there is one)
+ \setbox\spx@VerbatimTitleBox
+ \hbox{\begin{minipage}{\linewidth}%
+ \sphinxVerbatimTitle
+ \end{minipage}}%
+ \fi
+ \fboxsep\sphinxverbatimsep \fboxrule\sphinxverbatimborder
+ % setting borderwidth to zero is simplest for no-frame effect with same pagebreaks
+ \ifsphinxverbatimwithframe\else\fboxrule\z@\fi
% Customize framed.sty \MakeFramed to glue caption to literal block
- \global\spx@myfirstframedpasstrue
% via \spx@fcolorbox, will use \spx@VerbatimFBox which inserts title
\def\FrameCommand {\spx@colorbox\spx@fcolorbox }%
\let\FirstFrameCommand\FrameCommand
% for mid pages and last page portion of (long) split frame:
\def\MidFrameCommand{\spx@colorbox\fcolorbox }%
\let\LastFrameCommand\MidFrameCommand
+ \ifsphinxverbatimwrapslines
% fancyvrb's Verbatim puts each input line in (unbreakable) horizontal boxes.
% This customization wraps each line from the input in a \vtop, thus
% allowing it to wrap and display on two or more lines in the latex output.
@@ -358,12 +373,15 @@
\discretionary{\copy\sphinxvisiblespacebox}{\sphinxafterbreak}
{\kern\fontdimen2\font}%
}%
- % go around fancyvrb's check of \@currenvir
- \renewcommand*{\VerbatimEnvironment}{\gdef\FV@EnvironName{sphinxVerbatim}}%
- % go around fancyvrb's check of current list depth
- \def\@toodeep {\advance\@listdepth\@ne}%
% Allow breaks at special characters using \PYG... macros.
\sphinxbreaksatspecials
+ % Breaks at punctuation characters . , ; ? ! and / (needs catcode activation)
+ \def\FancyVerbCodes{\sphinxbreaksatpunct}%
+ \fi % end of conditional code for wrapping long code lines
+ % go around fancyvrb's check of \@currenvir
+ \let\VerbatimEnvironment\sphinxVerbatimEnvironment
+ % go around fancyvrb's check of current list depth
+ \def\@toodeep {\advance\@listdepth\@ne}%
% The list environment is needed to control perfectly the vertical space.
% Note: \OuterFrameSep used by framed.sty is later set to \topsep hence 0pt.
% - if caption: vertical space above caption = (\abovecaptionskip + D) with
@@ -377,23 +395,41 @@
\rightmargin\z@
\parindent \z@% becomes \itemindent. Default zero, but perhaps overwritten.
\trivlist\item\relax
- % use a minipage if we are already inside a framed environment
+ \ifsphinxverbatimwithminipage\spx@inframedtrue\fi
+ % use a minipage if we are already inside a framed environment
\ifspx@inframed\noindent\begin{minipage}{\linewidth}\fi
\MakeFramed {% adapted over from framed.sty's snugshade environment
- \advance\hsize-\width\@totalleftmargin\z@\linewidth\hsize
- \@setminipage }%
+ \advance\hsize-\width\@totalleftmargin\z@\linewidth\hsize\@setminipage
+ }%
\small
% For grid placement from \strut's in \FancyVerbFormatLine
\lineskip\z@skip
- % Breaks at punctuation characters . , ; ? ! and / need catcode=\active
- \OriginalVerbatim[#1,codes*=\sphinxbreaksatpunct]%
+ % will fetch its optional arguments if any
+ \OriginalVerbatim
}
{%
\endOriginalVerbatim
- \par\unskip\@minipagefalse\endMakeFramed
+ \par\unskip\@minipagefalse\endMakeFramed % from framed.sty snugshade
\ifspx@inframed\end{minipage}\fi
\endtrivlist
}
+\newenvironment {sphinxVerbatimNoFrame}
+ {\sphinxverbatimwithframefalse
+ % needed for fancyvrb as literal code will end in \end{sphinxVerbatimNoFrame}
+ \def\sphinxVerbatimEnvironment{\gdef\FV@EnvironName{sphinxVerbatimNoFrame}}%
+ \begin{sphinxVerbatim}}
+ {\end{sphinxVerbatim}}
+\newenvironment {sphinxVerbatimintable}
+ {% don't use a frame if in a table cell
+ \sphinxverbatimwithframefalse
+ \sphinxverbatimwithminipagetrue
+ % counteract longtable/tabulary redefinition of caption
+ \let\caption\sphinxfigcaption
+ % reduce above caption space if in a table cell
+ \abovecaptionskip\smallskipamount
+ \def\sphinxVerbatimEnvironment{\gdef\FV@EnvironName{sphinxVerbatimintable}}%
+ \begin{sphinxVerbatim}}
+ {\end{sphinxVerbatim}}
% define macro to frame contents and add shadow on right and bottom
% use public names for customizable lengths
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index b42d06330..51ce701c1 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -1908,17 +1908,17 @@ class LaTeXTranslator(nodes.NodeVisitor):
hlcode = hlcode.replace(u'€', u'@texteuro[]')
# must use original Verbatim environment and "tabular" environment
if self.table:
- hlcode = hlcode.replace('\\begin{Verbatim}',
- '\\begin{OriginalVerbatim}')
self.table.has_problematic = True
self.table.has_verbatim = True
+ hlcode = hlcode.replace('\\begin{Verbatim}',
+ '\\begin{sphinxVerbatimintable}')
else:
hlcode = hlcode.replace('\\begin{Verbatim}',
'\\begin{sphinxVerbatim}')
# get consistent trailer
hlcode = hlcode.rstrip()[:-14] # strip \end{Verbatim}
- self.body.append('\n' + hlcode + '\\end{%sVerbatim}\n' %
- ((not self.table) and 'sphinx' or 'Original'))
+ self.body.append('\n' + hlcode + '\\end{sphinxVerbatim%s}\n' %
+ (self.table and 'intable' or ''))
if ids:
self.body.append('\\let\\sphinxLiteralBlockLabel\empty\n')
raise nodes.SkipNode
From a4296a04d1a14bb54e425b50a83f11772214502d Mon Sep 17 00:00:00 2001
From: jfbu
Date: Wed, 22 Jun 2016 16:15:05 +0200
Subject: [PATCH 128/217] A bit of refactoring of latex entries in CHANGES for
1.5
---
CHANGES | 22 +++++++++++-----------
1 file changed, 11 insertions(+), 11 deletions(-)
diff --git a/CHANGES b/CHANGES
index 8c5510d2e..128d66250 100644
--- a/CHANGES
+++ b/CHANGES
@@ -4,15 +4,15 @@ Release 1.5 (in development)
Incompatible changes
--------------------
-* LaTeX package fancybox is not longer a dependency of sphinx.sty
+* latex, package fancybox is not longer a dependency of sphinx.sty
* Use ``'locales'`` as a default value of `locale_dirs`
-* LaTeX package ifthen is not any longer a dependency of sphinx.sty
-* LaTeX writer produces source not modifying original fancyvrb's Verbatim but
- using new name sphinxVerbatim for its custom wrapper
-* LaTeX package newfloat (which was shipped with Sphinx since 1.3.4) is no
- longer a dependency of sphinx.sty (ref #2660)
-* latex, writer does not use OriginalVerbatim for literal blocks in tables but
- sphinxVerbatimintable (ref #2704)
+* latex, package ifthen is not any longer a dependency of sphinx.sty
+* latex, style file does not modify fancyvrb's Verbatim (also available as
+ OriginalVerbatim) but uses sphinxVerbatim for name of custom wrapper.
+* latex, package newfloat is no longer a dependency of sphinx.sty (ref #2660;
+ it was shipped with Sphinx since 1.3.4).
+* latex, literal blocks in tables do not use OriginalVerbatim but
+ sphinxVerbatimintable which handles captions and wraps lines(ref #2704).
Features added
@@ -29,14 +29,14 @@ Features added
* Show warnings if no domains match with `primary_domain` (ref: #2001)
* C++, show warnings when the kind of role is misleading for the kind
of target it refers to (e.g., using the `class` role for a function).
-* latex writer abstracts more of text styling into customizable macros, e.g.
+* latex, writer abstracts more of text styling into customizable macros, e.g.
the ``visit_emphasis`` will output ``\sphinxstyleemphasis`` rather than
``\emph`` (which may be in use elsewhere or in an added LaTeX package). See
list at end of ``sphinx.sty`` (ref: #2686)
-* public names for latex environments and parameters used by note, warning,
+* latex, public names for environments and parameters used by note, warning,
and other admonition types, allowing full customizability from the
``'preamble'`` key or an input file (ref: feature request #2674, #2685)
-* latex better computes column widths of some tables (as a result, there will
+* latex, better computes column widths of some tables (as a result, there will
be slight changes as tables now correctly fill the line with; ref: #2708)
* latex, sphinxVerbatim environment is more easily customizable (ref: #2704).
In addition to already existing VerbatimColor and VerbatimBorderColor:
From 8feb92dd2dc919266e0d8a377160e305c0aafb18 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Wed, 22 Jun 2016 18:33:43 +0200
Subject: [PATCH 129/217] Update CHANGES for PR #2672
---
CHANGES | 11 +++++++++++
1 file changed, 11 insertions(+)
diff --git a/CHANGES b/CHANGES
index deb1313fb..978ff7b1e 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,6 +1,16 @@
Release 1.4.5 (in development)
==============================
+Incompatible changes
+--------------------
+
+* latex, inclusion of non-inline images from image directive resulted in
+ non-coherent whitespaces depending on original image width; new behaviour
+ by necessity from earlier one in some cases. (ref: #2672)
+* latex, use of ``\includegraphics`` to refer to Sphinx custom variant is
+ deprecated; in future it will revert to original LaTeX macro, custom one has
+ already alternative name ``\sphinxincludegraphics``.
+
Features added
--------------
@@ -16,6 +26,7 @@ Bugs fixed
* #2629: memoir class crashes LaTeX. Fixed ``by latex_keep_old_macro_names=False`` (ref 2675)
* #2684: `sphinx.ext.intersphinx` crashes with six-1.4.1
* #2679: ``float`` package needed for ``'figure_align': 'H'`` latex option
+* #2671: image directive may lead to inconsistent spacing in pdf
Release 1.4.4 (released Jun 12, 2016)
From 77ea9daf430a2b4efa46458d7387856c13e05c6c Mon Sep 17 00:00:00 2001
From: jfbu
Date: Wed, 22 Jun 2016 18:50:12 +0200
Subject: [PATCH 130/217] Fix comments in sphinx.sty after merge of 'stable'
---
sphinx/texinputs/sphinx.sty | 6 +-----
1 file changed, 1 insertion(+), 5 deletions(-)
diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty
index cf3d6e154..e344d0cb3 100644
--- a/sphinx/texinputs/sphinx.sty
+++ b/sphinx/texinputs/sphinx.sty
@@ -179,8 +179,7 @@
% Preparations for sphinxVerbatim environment, which is a wrapper of fancyvrb
% Verbatim with framing allowing pagebreaks, with border and background colors
-% and possibly also a top caption, non separable by pagebreak. The original
-% fancyvrb Verbatim is still used within tables.
+% and possibly also a top caption, non separable by pagebreak.
% For maintaining compatibility with Sphinx < 1.5, we define and use these
% when (unmodified) Verbatim will be needed. But Sphinx >= 1.5 does not modify
@@ -232,9 +231,6 @@
\long\def\spx@VerbatimFBox#1{%
\leavevmode
\begingroup
- % framed.sty does some measuring but this macro adds possibly a caption
- % use amsmath conditional to inhibit the caption counter stepping after
- % first pass
\setbox\@tempboxa\hbox{\kern\fboxsep{#1}\kern\fboxsep}%
\hbox
{\lower\dimexpr\fboxrule+\fboxsep+\dp\@tempboxa
From 3bce72f49b5e7dee13e4b8daed10ae14095522de Mon Sep 17 00:00:00 2001
From: jfbu
Date: Wed, 22 Jun 2016 19:12:08 +0200
Subject: [PATCH 131/217] Update a comment in latex.py
---
sphinx/writers/latex.py | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index 22737074e..c0da5118b 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -1907,7 +1907,8 @@ class LaTeXTranslator(nodes.NodeVisitor):
**highlight_args)
# workaround for Unicode issue
hlcode = hlcode.replace(u'€', u'@texteuro[]')
- # must use original Verbatim environment and "tabular" environment
+ # if in table raise verbatim flag to avoid "tabulary" environment
+ # and opt for sphinxVerbatimintable to handle caption & long lines
if self.table:
self.table.has_problematic = True
self.table.has_verbatim = True
From 4919406f9415353333ab5b9d445f045c446ae214 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Wed, 22 Jun 2016 19:26:11 +0200
Subject: [PATCH 132/217] Fix a comment in sphinx.sty
---
sphinx/texinputs/sphinx.sty | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty
index e344d0cb3..c926fc1f7 100644
--- a/sphinx/texinputs/sphinx.sty
+++ b/sphinx/texinputs/sphinx.sty
@@ -422,7 +422,7 @@
{% don't use a frame if in a table cell
\sphinxverbatimwithframefalse
\sphinxverbatimwithminipagetrue
- % counteract longtable/tabulary redefinition of caption
+ % counteract longtable redefinition of caption
\let\caption\sphinxfigcaption
% reduce above caption space if in a table cell
\abovecaptionskip\smallskipamount
From 5bd76815ffd0c40404f9f68a5dbf0ee7798c6abe Mon Sep 17 00:00:00 2001
From: jfbu
Date: Wed, 22 Jun 2016 22:30:58 +0200
Subject: [PATCH 133/217] Added an item about sphinxVerbatim to doc/latex.rst
---
doc/latex.rst | 17 +++++++++++++++++
1 file changed, 17 insertions(+)
diff --git a/doc/latex.rst b/doc/latex.rst
index 7165ff778..aec566301 100644
--- a/doc/latex.rst
+++ b/doc/latex.rst
@@ -103,6 +103,23 @@ Let us illustrate here what can be modified by the second method.
.. versionchanged:: 1.5
use of public names for the three lengths. The environment itself was
redefined to allow page breaks at release 1.4.2.
+- the literal blocks (:rst:dir:`code-block` directives, etc ...), are
+ implemented using ``sphinxVerbatim`` environment which is a wrapper of
+ ``Verbatim`` environment from package ``fancyvrb.sty``. It adds the handling
+ of the top caption and the wrapping of long lines, and a frame which allows
+ pagebreaks. The LaTeX lengths (not commands) ``\sphinxverbatimsep`` and
+ ``\sphinxverbatimborder`` customize the framing. Inside tables the used
+ environment is ``sphinxVerbatimintable`` (it does not draw a frame, but
+ allows a caption).
+
+ .. versionchanged:: 1.5
+ ``Verbatim`` keeps exact same meaning as in ``fancyvrb.sty`` (meaning
+ which is the one of ``OriginalVerbatim`` too), and custom one is called
+ ``sphinxVerbatim``. Also, earlier version of Sphinx used
+ ``OriginalVerbatim`` inside tables (captions were lost, long code lines
+ were not wrapped), they now use ``sphinxVerbatimintable``.
+ .. versionadded:: 1.5
+ the two customizable lengths, the ``sphinxVerbatimintable``.
- miscellaneous colours: *TitleColor*, *InnerLinkColor*, *OuterLinkColor*,
*VerbatimColor* (this is a background colour), *VerbatimBorderColor*.
- the ``\sphinxAtStartFootnote`` is inserted between footnote numbers and their
From 1e979091f25f5d20bb9b64d554183fcb0f2f37e4 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Thu, 23 Jun 2016 11:56:11 +0900
Subject: [PATCH 134/217] Fix #2705: `toctree` generates empty bullet_list if
``:titlesonly:`` specified
---
CHANGES | 1 +
sphinx/environment.py | 8 +++++++-
2 files changed, 8 insertions(+), 1 deletion(-)
diff --git a/CHANGES b/CHANGES
index 978ff7b1e..6f1745e5e 100644
--- a/CHANGES
+++ b/CHANGES
@@ -27,6 +27,7 @@ Bugs fixed
* #2684: `sphinx.ext.intersphinx` crashes with six-1.4.1
* #2679: ``float`` package needed for ``'figure_align': 'H'`` latex option
* #2671: image directive may lead to inconsistent spacing in pdf
+* #2705: `toctree` generates empty bullet_list if ``:titlesonly:`` specified
Release 1.4.4 (released Jun 12, 2016)
diff --git a/sphinx/environment.py b/sphinx/environment.py
index 9d4c174cc..0ff9b781a 100644
--- a/sphinx/environment.py
+++ b/sphinx/environment.py
@@ -1453,7 +1453,10 @@ class BuildEnvironment:
# nodes with length 1 don't have any children anyway
if len(toplevel) > 1:
subtrees = toplevel.traverse(addnodes.toctree)
- toplevel[1][:] = subtrees
+ if subtrees:
+ toplevel[1][:] = subtrees
+ else:
+ toplevel.pop(1)
# resolve all sub-toctrees
for subtocnode in toc.traverse(addnodes.toctree):
if not (subtocnode.get('hidden', False) and
@@ -1499,6 +1502,9 @@ class BuildEnvironment:
_toctree_add_classes(newnode, 1)
self._toctree_prune(newnode, 1, prune and maxdepth or 0, collapse)
+ if len(newnode[-1]) == 0: # No titles found
+ return None
+
# set the target paths in the toctrees (they are not known at TOC
# generation time)
for refnode in newnode.traverse(nodes.reference):
From 2b60fc202795d5351e13a6da98b4d046fe0c3be8 Mon Sep 17 00:00:00 2001
From: Rob Ruana
Date: Thu, 23 Jun 2016 15:25:00 -0400
Subject: [PATCH 135/217] Fixes #2688: [Napoleon] Updates to Napoleon
documentation to fix intersphinx links and demonstrate PEP 484 type
annotations
---
doc/ext/example_google.py | 65 ++++++++++++++++----------
doc/ext/example_numpy.py | 78 ++++++++++++++++++++++----------
doc/ext/napoleon.rst | 65 +++++++++++++++++++++++++-
sphinx/ext/napoleon/__init__.py | 55 +++++++++++-----------
sphinx/ext/napoleon/docstring.py | 38 +++++++---------
5 files changed, 206 insertions(+), 95 deletions(-)
diff --git a/doc/ext/example_google.py b/doc/ext/example_google.py
index 81a312cfd..c3ba273b8 100644
--- a/doc/ext/example_google.py
+++ b/doc/ext/example_google.py
@@ -43,6 +43,39 @@ on the first line, separated by a colon.
"""
+def function_with_types_in_docstring(param1, param2):
+ """Example function with types documented in the docstring.
+
+ `PEP 484`_ type annotations are supported. If attribute, parameter, and
+ return types are annotated according to `PEP 484`_, they do not need to be
+ included in the docstring:
+
+ Args:
+ param1 (int): The first parameter.
+ param2 (str): The second parameter.
+
+ Returns:
+ bool: The return value. True for success, False otherwise.
+
+ .. _PEP 484:
+ https://www.python.org/dev/peps/pep-0484/
+
+ """
+
+
+def function_with_pep484_type_annotations(param1: int, param2: str) -> bool:
+ """Example function with PEP 484 type annotations.
+
+ Args:
+ param1: The first parameter.
+ param2: The second parameter.
+
+ Returns:
+ The return value. True for success, False otherwise.
+
+ """
+
+
def module_level_function(param1, param2=None, *args, **kwargs):
"""This is an example of a module level function.
@@ -50,9 +83,6 @@ def module_level_function(param1, param2=None, *args, **kwargs):
of each parameter is required. The type and description of each parameter
is optional, but should be included if not obvious.
- Parameter types -- if given -- should be specified according to
- `PEP 484`_, though `PEP 484`_ conformance isn't required or enforced.
-
If \*args or \*\*kwargs are accepted,
they should be listed as ``*args`` and ``**kwargs``.
@@ -67,7 +97,7 @@ def module_level_function(param1, param2=None, *args, **kwargs):
Args:
param1 (int): The first parameter.
- param2 (Optional[str]): The second parameter. Defaults to None.
+ param2 (:obj:`str`, optional): The second parameter. Defaults to None.
Second line of description should be indented.
*args: Variable length argument list.
**kwargs: Arbitrary keyword arguments.
@@ -94,10 +124,6 @@ def module_level_function(param1, param2=None, *args, **kwargs):
that are relevant to the interface.
ValueError: If `param2` is equal to `param1`.
-
- .. _PEP 484:
- https://www.python.org/dev/peps/pep-0484/
-
"""
if param1 == param2:
raise ValueError('param1 may not be equal to param2')
@@ -139,7 +165,7 @@ class ExampleError(Exception):
Args:
msg (str): Human readable string describing the exception.
- code (Optional[int]): Error code.
+ code (:obj:`int`, optional): Error code.
Attributes:
msg (str): Human readable string describing the exception.
@@ -163,16 +189,9 @@ class ExampleClass(object):
Properties created with the ``@property`` decorator should be documented
in the property's getter method.
- Attribute and property types -- if given -- should be specified according
- to `PEP 484`_, though `PEP 484`_ conformance isn't required or enforced.
-
Attributes:
attr1 (str): Description of `attr1`.
- attr2 (Optional[int]): Description of `attr2`.
-
-
- .. _PEP 484:
- https://www.python.org/dev/peps/pep-0484/
+ attr2 (:obj:`int`, optional): Description of `attr2`.
"""
@@ -190,20 +209,20 @@ class ExampleClass(object):
Args:
param1 (str): Description of `param1`.
- param2 (Optional[int]): Description of `param2`. Multiple
+ param2 (:obj:`int`, optional): Description of `param2`. Multiple
lines are supported.
- param3 (List[str]): Description of `param3`.
+ param3 (:obj:`list` of :obj:`str`): Description of `param3`.
"""
self.attr1 = param1
self.attr2 = param2
self.attr3 = param3 #: Doc comment *inline* with attribute
- #: List[str]: Doc comment *before* attribute, with type specified
+ #: list of str: Doc comment *before* attribute, with type specified
self.attr4 = ['attr4']
self.attr5 = None
- """Optional[str]: Docstring *after* attribute, with type specified."""
+ """str: Docstring *after* attribute, with type specified."""
@property
def readonly_property(self):
@@ -212,8 +231,8 @@ class ExampleClass(object):
@property
def readwrite_property(self):
- """List[str]: Properties with both a getter and setter should only
- be documented in their getter method.
+ """:obj:`list` of :obj:`str`: Properties with both a getter and setter
+ should only be documented in their getter method.
If the setter method contains notable behavior, it should be
mentioned here.
diff --git a/doc/ext/example_numpy.py b/doc/ext/example_numpy.py
index 90f182129..0e71008e1 100644
--- a/doc/ext/example_numpy.py
+++ b/doc/ext/example_numpy.py
@@ -53,6 +53,52 @@ on the first line, separated by a colon.
"""
+def function_with_types_in_docstring(param1, param2):
+ """Example function with types documented in the docstring.
+
+ `PEP 484`_ type annotations are supported. If attribute, parameter, and
+ return types are annotated according to `PEP 484`_, they do not need to be
+ included in the docstring:
+
+ Parameters
+ ----------
+ param1 : int
+ The first parameter.
+ param2 : str
+ The second parameter.
+
+ Returns
+ -------
+ bool
+ True if successful, False otherwise.
+
+ .. _PEP 484:
+ https://www.python.org/dev/peps/pep-0484/
+
+ """
+
+
+def function_with_pep484_type_annotations(param1: int, param2: str) -> bool:
+ """Example function with PEP 484 type annotations.
+
+ The return type must be duplicated in the docstring to comply
+ with the NumPy docstring style.
+
+ Parameters
+ ----------
+ param1
+ The first parameter.
+ param2
+ The second parameter.
+
+ Returns
+ -------
+ bool
+ True if successful, False otherwise.
+
+ """
+
+
def module_level_function(param1, param2=None, *args, **kwargs):
"""This is an example of a module level function.
@@ -60,9 +106,6 @@ def module_level_function(param1, param2=None, *args, **kwargs):
The name of each parameter is required. The type and description of each
parameter is optional, but should be included if not obvious.
- Parameter types -- if given -- should be specified according to
- `PEP 484`_, though `PEP 484`_ conformance isn't required or enforced.
-
If \*args or \*\*kwargs are accepted,
they should be listed as ``*args`` and ``**kwargs``.
@@ -82,7 +125,7 @@ def module_level_function(param1, param2=None, *args, **kwargs):
----------
param1 : int
The first parameter.
- param2 : Optional[str]
+ param2 : :obj:`str`, optional
The second parameter.
*args
Variable length argument list.
@@ -114,10 +157,6 @@ def module_level_function(param1, param2=None, *args, **kwargs):
ValueError
If `param2` is equal to `param1`.
-
- .. _PEP 484:
- https://www.python.org/dev/peps/pep-0484/
-
"""
if param1 == param2:
raise ValueError('param1 may not be equal to param2')
@@ -167,7 +206,7 @@ class ExampleError(Exception):
----------
msg : str
Human readable string describing the exception.
- code : Optional[int]
+ code : :obj:`int`, optional
Numeric error code.
Attributes
@@ -195,20 +234,13 @@ class ExampleClass(object):
Properties created with the ``@property`` decorator should be documented
in the property's getter method.
- Attribute and property types -- if given -- should be specified according
- to `PEP 484`_, though `PEP 484`_ conformance isn't required or enforced.
-
Attributes
----------
attr1 : str
Description of `attr1`.
- attr2 : Optional[int]
+ attr2 : :obj:`int`, optional
Description of `attr2`.
-
- .. _PEP 484:
- https://www.python.org/dev/peps/pep-0484/
-
"""
def __init__(self, param1, param2, param3):
@@ -228,10 +260,10 @@ class ExampleClass(object):
----------
param1 : str
Description of `param1`.
- param2 : List[str]
+ param2 : :obj:`list` of :obj:`str`
Description of `param2`. Multiple
lines are supported.
- param3 : Optional[int]
+ param3 : :obj:`int`, optional
Description of `param3`.
"""
@@ -239,11 +271,11 @@ class ExampleClass(object):
self.attr2 = param2
self.attr3 = param3 #: Doc comment *inline* with attribute
- #: List[str]: Doc comment *before* attribute, with type specified
+ #: list of str: Doc comment *before* attribute, with type specified
self.attr4 = ["attr4"]
self.attr5 = None
- """Optional[str]: Docstring *after* attribute, with type specified."""
+ """str: Docstring *after* attribute, with type specified."""
@property
def readonly_property(self):
@@ -252,8 +284,8 @@ class ExampleClass(object):
@property
def readwrite_property(self):
- """List[str]: Properties with both a getter and setter should only
- be documented in their getter method.
+ """:obj:`list` of :obj:`str`: Properties with both a getter and setter
+ should only be documented in their getter method.
If the setter method contains notable behavior, it should be
mentioned here.
diff --git a/doc/ext/napoleon.rst b/doc/ext/napoleon.rst
index 860faca32..8b11ab98e 100644
--- a/doc/ext/napoleon.rst
+++ b/doc/ext/napoleon.rst
@@ -186,11 +186,74 @@ not be mixed. Choose one style for your project and be consistent with it.
* :ref:`example_google`
* :ref:`example_numpy`
- For Python type annotations, see `PEP 484`_.
+
+Type Annotations
+----------------
+
+`PEP 484`_ introduced a standard way to express types in Python code.
+This is an alternative to expressing types directly in docstrings.
+One benefit of expressing types according to `PEP 484`_ is that
+type checkers and IDEs can take advantage of them for static code
+analysis.
+
+Google style with Python 3 type annotations::
+
+ def func(arg1: int, arg2: str) -> bool:
+ """Summary line.
+
+ Extended description of function.
+
+ Args:
+ arg1: Description of arg1
+ arg2: Description of arg2
+
+ Returns:
+ Description of return value
+
+ """
+ return True
+
+Google style with `Python 2/3 compatible annotations`_::
+
+ def func(arg1, arg2):
+ # type: (int, str) -> bool
+ """Summary line.
+
+ Extended description of function.
+
+ Args:
+ arg1: Description of arg1
+ arg2: Description of arg2
+
+ Returns:
+ Description of return value
+
+ """
+ return True
+
+Google style with types in docstrings::
+
+ def func(arg1, arg2):
+ """Summary line.
+
+ Extended description of function.
+
+ Args:
+ arg1 (int): Description of arg1
+ arg2 (str): Description of arg2
+
+ Returns:
+ bool: Description of return value
+
+ """
+ return True
.. _PEP 484:
https://www.python.org/dev/peps/pep-0484/
+.. _Python 2/3 compatible annotations:
+ https://www.python.org/dev/peps/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code
+
Configuration
=============
diff --git a/sphinx/ext/napoleon/__init__.py b/sphinx/ext/napoleon/__init__.py
index 202cb259d..651355c57 100644
--- a/sphinx/ext/napoleon/__init__.py
+++ b/sphinx/ext/napoleon/__init__.py
@@ -51,13 +51,13 @@ class Config(object):
Attributes
----------
- napoleon_google_docstring : bool, defaults to True
+ napoleon_google_docstring : :obj:`bool` (Defaults to True)
True to parse `Google style`_ docstrings. False to disable support
for Google style docstrings.
- napoleon_numpy_docstring : bool, defaults to True
+ napoleon_numpy_docstring : :obj:`bool` (Defaults to True)
True to parse `NumPy style`_ docstrings. False to disable support
for NumPy style docstrings.
- napoleon_include_init_with_doc : bool, defaults to False
+ napoleon_include_init_with_doc : :obj:`bool` (Defaults to False)
True to list ``__init___`` docstrings separately from the class
docstring. False to fall back to Sphinx's default behavior, which
considers the ``__init___`` docstring as part of the class
@@ -73,7 +73,7 @@ class Config(object):
def __init__(self):
# This will NOT be included in the docs
- napoleon_include_private_with_doc : bool, defaults to False
+ napoleon_include_private_with_doc : :obj:`bool` (Defaults to False)
True to include private members (like ``_membername``) with docstrings
in the documentation. False to fall back to Sphinx's default behavior.
@@ -89,7 +89,7 @@ class Config(object):
# This will NOT be included in the docs
pass
- napoleon_include_special_with_doc : bool, defaults to False
+ napoleon_include_special_with_doc : :obj:`bool` (Defaults to False)
True to include special members (like ``__membername__``) with
docstrings in the documentation. False to fall back to Sphinx's
default behavior.
@@ -106,7 +106,7 @@ class Config(object):
# This will NOT be included in the docs
return unicode(self.__class__.__name__)
- napoleon_use_admonition_for_examples : bool, defaults to False
+ napoleon_use_admonition_for_examples : :obj:`bool` (Defaults to False)
True to use the ``.. admonition::`` directive for the **Example** and
**Examples** sections. False to use the ``.. rubric::`` directive
instead. One may look better than the other depending on what HTML
@@ -130,7 +130,7 @@ class Config(object):
This is just a quick example
- napoleon_use_admonition_for_notes : bool, defaults to False
+ napoleon_use_admonition_for_notes : :obj:`bool` (Defaults to False)
True to use the ``.. admonition::`` directive for **Notes** sections.
False to use the ``.. rubric::`` directive instead.
@@ -143,7 +143,7 @@ class Config(object):
--------
:attr:`napoleon_use_admonition_for_examples`
- napoleon_use_admonition_for_references : bool, defaults to False
+ napoleon_use_admonition_for_references : :obj:`bool` (Defaults to False)
True to use the ``.. admonition::`` directive for **References**
sections. False to use the ``.. rubric::`` directive instead.
@@ -151,7 +151,7 @@ class Config(object):
--------
:attr:`napoleon_use_admonition_for_examples`
- napoleon_use_ivar : bool, defaults to False
+ napoleon_use_ivar : :obj:`bool` (Defaults to False)
True to use the ``:ivar:`` role for instance variables. False to use
the ``.. attribute::`` directive instead.
@@ -175,7 +175,7 @@ class Config(object):
Description of `attr1`
- napoleon_use_param : bool, defaults to True
+ napoleon_use_param : :obj:`bool` (Defaults to True)
True to use a ``:param:`` role for each function parameter. False to
use a single ``:parameters:`` role for all the parameters.
@@ -202,7 +202,7 @@ class Config(object):
* **arg2** (*int, optional*) --
Description of `arg2`, defaults to 0
- napoleon_use_keyword : bool, defaults to True
+ napoleon_use_keyword : :obj:`bool` (Defaults to True)
True to use a ``:keyword:`` role for each function keyword argument.
False to use a single ``:keyword arguments:`` role for all the
keywords.
@@ -217,7 +217,7 @@ class Config(object):
--------
:attr:`napoleon_use_param`
- napoleon_use_rtype : bool, defaults to True
+ napoleon_use_rtype : :obj:`bool` (Defaults to True)
True to use the ``:rtype:`` role for the return type. False to output
the return type inline with the description.
@@ -297,20 +297,23 @@ def setup(app):
def _patch_python_domain():
- import sphinx.domains.python
- from sphinx.domains.python import PyTypedField
- import sphinx.locale
- l_ = sphinx.locale.lazy_gettext
- for doc_field in sphinx.domains.python.PyObject.doc_field_types:
- if doc_field.name == 'parameter':
- doc_field.names = ('param', 'parameter', 'arg', 'argument')
- break
- sphinx.domains.python.PyObject.doc_field_types.append(
- PyTypedField('keyword', label=l_('Keyword Arguments'),
- names=('keyword', 'kwarg', 'kwparam'),
- typerolename='obj', typenames=('paramtype', 'kwtype'),
- can_collapse=True),
- )
+ try:
+ from sphinx.domains.python import PyTypedField
+ except ImportError:
+ pass
+ else:
+ import sphinx.domains.python
+ import sphinx.locale
+ l_ = sphinx.locale.lazy_gettext
+ for doc_field in sphinx.domains.python.PyObject.doc_field_types:
+ if doc_field.name == 'parameter':
+ doc_field.names = ('param', 'parameter', 'arg', 'argument')
+ break
+ sphinx.domains.python.PyObject.doc_field_types.append(
+ PyTypedField('keyword', label=l_('Keyword Arguments'),
+ names=('keyword', 'kwarg', 'kwparam'),
+ typerolename='obj', typenames=('paramtype', 'kwtype'),
+ can_collapse=True))
def _process_docstring(app, what, name, obj, options, lines):
diff --git a/sphinx/ext/napoleon/docstring.py b/sphinx/ext/napoleon/docstring.py
index 158996fc6..c3d5bb3d0 100644
--- a/sphinx/ext/napoleon/docstring.py
+++ b/sphinx/ext/napoleon/docstring.py
@@ -40,31 +40,28 @@ class GoogleDocstring(UnicodeMixin):
Parameters
----------
- docstring : str or List[str]
+ docstring : :obj:`str` or :obj:`list` of :obj:`str`
The docstring to parse, given either as a string or split into
individual lines.
- config : Optional[sphinx.ext.napoleon.Config or sphinx.config.Config]
+ config: :obj:`sphinx.ext.napoleon.Config` or :obj:`sphinx.config.Config`
The configuration settings to use. If not given, defaults to the
config object on `app`; or if `app` is not given defaults to the
- a new `sphinx.ext.napoleon.Config` object.
+ a new :class:`sphinx.ext.napoleon.Config` object.
- See Also
- --------
- :class:`sphinx.ext.napoleon.Config`
Other Parameters
----------------
- app : Optional[sphinx.application.Sphinx]
+ app : :class:`sphinx.application.Sphinx`, optional
Application object representing the Sphinx process.
- what : Optional[str]
+ what : :obj:`str`, optional
A string specifying the type of the object to which the docstring
belongs. Valid values: "module", "class", "exception", "function",
"method", "attribute".
- name : Optional[str]
+ name : :obj:`str`, optional
The fully qualified name of the object.
obj : module, class, exception, function, method, or attribute
The object to which the docstring belongs.
- options : Optional[sphinx.ext.autodoc.Options]
+ options : :class:`sphinx.ext.autodoc.Options`, optional
The options given to the directive: an object with attributes
inherited_members, undoc_members, show_inheritance and noindex that
are True if the flag option of same name was given to the auto
@@ -175,7 +172,7 @@ class GoogleDocstring(UnicodeMixin):
Returns
-------
- List[str]
+ :obj:`list` of :obj:`str`
The lines of the docstring in a list.
"""
@@ -737,31 +734,28 @@ class NumpyDocstring(GoogleDocstring):
Parameters
----------
- docstring : str or List[str]
+ docstring : :obj:`str` or :obj:`list` of :obj:`str`
The docstring to parse, given either as a string or split into
individual lines.
- config : Optional[sphinx.ext.napoleon.Config or sphinx.config.Config]
+ config: :obj:`sphinx.ext.napoleon.Config` or :obj:`sphinx.config.Config`
The configuration settings to use. If not given, defaults to the
config object on `app`; or if `app` is not given defaults to the
- a new `sphinx.ext.napoleon.Config` object.
+ a new :class:`sphinx.ext.napoleon.Config` object.
- See Also
- --------
- :class:`sphinx.ext.napoleon.Config`
Other Parameters
----------------
- app : Optional[sphinx.application.Sphinx]
+ app : :class:`sphinx.application.Sphinx`, optional
Application object representing the Sphinx process.
- what : Optional[str]
+ what : :obj:`str`, optional
A string specifying the type of the object to which the docstring
belongs. Valid values: "module", "class", "exception", "function",
"method", "attribute".
- name : Optional[str]
+ name : :obj:`str`, optional
The fully qualified name of the object.
obj : module, class, exception, function, method, or attribute
The object to which the docstring belongs.
- options : Optional[sphinx.ext.autodoc.Options]
+ options : :class:`sphinx.ext.autodoc.Options`, optional
The options given to the directive: an object with attributes
inherited_members, undoc_members, show_inheritance and noindex that
are True if the flag option of same name was given to the auto
@@ -823,7 +817,7 @@ class NumpyDocstring(GoogleDocstring):
Returns
-------
- List[str]
+ :obj:`list` of :obj:`str`
The lines of the docstring in a list.
"""
From 04723c1175b856d309a2e6ce18835ae675311ba3 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Fri, 24 Jun 2016 11:35:15 +0900
Subject: [PATCH 136/217] Fix #2479: `sphinx.ext.viewcode` uses python2
highlighter by default
---
CHANGES | 1 +
sphinx/ext/viewcode.py | 4 ++--
2 files changed, 3 insertions(+), 2 deletions(-)
diff --git a/CHANGES b/CHANGES
index 6f1745e5e..230be37c9 100644
--- a/CHANGES
+++ b/CHANGES
@@ -28,6 +28,7 @@ Bugs fixed
* #2679: ``float`` package needed for ``'figure_align': 'H'`` latex option
* #2671: image directive may lead to inconsistent spacing in pdf
* #2705: `toctree` generates empty bullet_list if ``:titlesonly:`` specified
+* #2479: `sphinx.ext.viewcode` uses python2 highlighter by default
Release 1.4.4 (released Jun 12, 2016)
diff --git a/sphinx/ext/viewcode.py b/sphinx/ext/viewcode.py
index 89e7a9965..a071c5533 100644
--- a/sphinx/ext/viewcode.py
+++ b/sphinx/ext/viewcode.py
@@ -139,8 +139,8 @@ def collect_pages(app):
# construct a page name for the highlighted source
pagename = '_modules/' + modname.replace('.', '/')
# highlight the source using the builder's highlighter
- if env.config.highlight_language == 'python3':
- lexer = 'python3'
+ if env.config.highlight_language in ('python3', 'default'):
+ lexer = env.config.highlight_language
else:
lexer = 'python'
highlighted = highlighter.highlight_block(code, lexer, linenos=False)
From bf692e2f342df2d3870623b862078369057f1e18 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Fri, 24 Jun 2016 12:35:44 +0900
Subject: [PATCH 137/217] Fix #2700: HtmlHelp builder has hard coded index.html
---
CHANGES | 1 +
sphinx/builders/htmlhelp.py | 9 +++++----
2 files changed, 6 insertions(+), 4 deletions(-)
diff --git a/CHANGES b/CHANGES
index 230be37c9..ae86fabdb 100644
--- a/CHANGES
+++ b/CHANGES
@@ -29,6 +29,7 @@ Bugs fixed
* #2671: image directive may lead to inconsistent spacing in pdf
* #2705: `toctree` generates empty bullet_list if ``:titlesonly:`` specified
* #2479: `sphinx.ext.viewcode` uses python2 highlighter by default
+* #2700: HtmlHelp builder has hard coded index.html
Release 1.4.4 (released Jun 12, 2016)
diff --git a/sphinx/builders/htmlhelp.py b/sphinx/builders/htmlhelp.py
index f4003c4c9..382067794 100644
--- a/sphinx/builders/htmlhelp.py
+++ b/sphinx/builders/htmlhelp.py
@@ -63,7 +63,7 @@ Binary Index=No
Compiled file=%(outname)s.chm
Contents file=%(outname)s.hhc
Default Window=%(outname)s
-Default topic=index.html
+Default topic=%(master_doc)s
Display compile progress=No
Full text search stop list file=%(outname)s.stp
Full-text search=Yes
@@ -73,7 +73,7 @@ Title=%(title)s
[WINDOWS]
%(outname)s="%(title)s","%(outname)s.hhc","%(outname)s.hhk",\
-"index.html","index.html",,,,,0x63520,220,0x10384e,[0,0,1024,768],,,,,,,0
+"%(master_doc)s","%(master_doc)s",,,,,0x63520,220,0x10384e,[0,0,1024,768],,,,,,,0
[FILES]
'''
@@ -212,7 +212,8 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder):
'title': self.config.html_title,
'version': self.config.version,
'project': self.config.project,
- 'lcid': self.lcid})
+ 'lcid': self.lcid,
+ 'master_doc': self.config.master_doc + self.out_suffix})
if not outdir.endswith(os.sep):
outdir += os.sep
olen = len(outdir)
@@ -232,7 +233,7 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder):
f.write(contents_header)
# special books
f.write('
' + object_sitemap % (self.config.html_short_title,
- 'index.html'))
+ self.config.master_doc + self.out_suffix))
for indexname, indexcls, content, collapse in self.domain_indices:
f.write('
' + object_sitemap % (indexcls.localname,
'%s.html' % indexname))
From 51937f80894632e48cb9947a81c1698f8a831972 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Mon, 30 May 2016 19:53:59 +0900
Subject: [PATCH 138/217] #2597: Show warning messages as darkred
---
CHANGES | 1 +
sphinx/application.py | 7 ++++---
tests/test_application.py | 9 +++++----
tests/test_build_html.py | 4 ++--
tests/test_build_latex.py | 6 +++---
tests/test_build_texinfo.py | 4 ++--
tests/util.py | 4 ++++
7 files changed, 21 insertions(+), 14 deletions(-)
diff --git a/CHANGES b/CHANGES
index d7c1ad4f4..64f3097bb 100644
--- a/CHANGES
+++ b/CHANGES
@@ -45,6 +45,7 @@ Features added
- booleans ``\ifsphinxverbatimwithframe`` and ``\ifsphinxverbatimwrapslines``.
* latex, captions for literal blocks inside tables are handled, and long code
lines wrapped to fit table cell (ref: #2704)
+* #2597: Show warning messages as darkred
Bugs fixed
----------
diff --git a/sphinx/application.py b/sphinx/application.py
index 343f678ba..81a735e33 100644
--- a/sphinx/application.py
+++ b/sphinx/application.py
@@ -42,7 +42,7 @@ from sphinx.util import import_object
from sphinx.util.tags import Tags
from sphinx.util.osutil import ENOENT
from sphinx.util.logging import is_suppressed_warning
-from sphinx.util.console import bold, lightgray, darkgray, darkgreen, \
+from sphinx.util.console import bold, lightgray, darkgray, darkred, darkgreen, \
term_width_line
from sphinx.util.i18n import find_catalog_source_files
@@ -334,7 +334,8 @@ class Sphinx(object):
wfile.flush()
self.messagelog.append(message)
- def warn(self, message, location=None, prefix='WARNING: ', type=None, subtype=None):
+ def warn(self, message, location=None, prefix='WARNING: ',
+ type=None, subtype=None, colorfunc=darkred):
"""Emit a warning.
If *location* is given, it should either be a tuple of (docname, lineno)
@@ -364,7 +365,7 @@ class Sphinx(object):
if self.warningiserror:
raise SphinxWarning(warntext)
self._warncount += 1
- self._log(warntext, self._warning, True)
+ self._log(colorfunc(warntext), self._warning, True)
def info(self, message='', nonl=False):
"""Emit an informational message.
diff --git a/tests/test_application.py b/tests/test_application.py
index 420680451..ad4f84870 100644
--- a/tests/test_application.py
+++ b/tests/test_application.py
@@ -14,7 +14,7 @@ from docutils import nodes
from sphinx.application import ExtensionError
from sphinx.domains import Domain
-from util import with_app, raises_msg
+from util import with_app, raises_msg, strip_escseq
@with_app()
@@ -60,20 +60,21 @@ def test_output(app, status, warning):
old_count = app._warncount
app.warn("Bad news!")
- assert warning.getvalue() == "WARNING: Bad news!\n"
+ assert strip_escseq(warning.getvalue()) == "WARNING: Bad news!\n"
assert app._warncount == old_count + 1
@with_app()
def test_extensions(app, status, warning):
app.setup_extension('shutil')
- assert warning.getvalue().startswith("WARNING: extension 'shutil'")
+ assert strip_escseq(warning.getvalue()).startswith("WARNING: extension 'shutil'")
@with_app()
def test_extension_in_blacklist(app, status, warning):
app.setup_extension('sphinxjp.themecore')
- assert warning.getvalue().startswith("WARNING: the extension 'sphinxjp.themecore' was")
+ msg = strip_escseq(warning.getvalue())
+ assert msg.startswith("WARNING: the extension 'sphinxjp.themecore' was")
@with_app()
diff --git a/tests/test_build_html.py b/tests/test_build_html.py
index c5176d33a..f45b56066 100644
--- a/tests/test_build_html.py
+++ b/tests/test_build_html.py
@@ -15,7 +15,7 @@ import re
from six import PY3, iteritems
from sphinx import __display_version__
-from util import remove_unicode_literals, gen_with_app, with_app
+from util import remove_unicode_literals, gen_with_app, with_app, strip_escseq
from etree13 import ElementTree
from html5lib import getTreeBuilder, HTMLParser
@@ -384,7 +384,7 @@ def check_extra_entries(outdir):
tags=['testtag'])
def test_html_output(app, status, warning):
app.builder.build_all()
- html_warnings = warning.getvalue().replace(os.sep, '/')
+ html_warnings = strip_escseq(warning.getvalue().replace(os.sep, '/'))
html_warnings_exp = HTML_WARNINGS % {
'root': re.escape(app.srcdir.replace(os.sep, '/'))}
assert re.match(html_warnings_exp + '$', html_warnings), \
diff --git a/tests/test_build_latex.py b/tests/test_build_latex.py
index 2d963f376..816779d9f 100644
--- a/tests/test_build_latex.py
+++ b/tests/test_build_latex.py
@@ -19,7 +19,7 @@ from six import PY3
from sphinx.errors import SphinxError
from sphinx.writers.latex import LaTeXTranslator
-from util import SkipTest, remove_unicode_literals, with_app
+from util import SkipTest, remove_unicode_literals, with_app, strip_escseq
from test_build_html import ENV_WARNINGS
@@ -67,7 +67,7 @@ def run_latex(outdir):
def test_latex(app, status, warning):
LaTeXTranslator.ignore_missing_images = True
app.builder.build_all()
- latex_warnings = warning.getvalue().replace(os.sep, '/')
+ latex_warnings = strip_escseq(warning.getvalue().replace(os.sep, '/'))
latex_warnings_exp = LATEX_WARNINGS % {
'root': re.escape(app.srcdir.replace(os.sep, '/'))}
assert re.match(latex_warnings_exp + '$', latex_warnings), \
@@ -142,7 +142,7 @@ def test_writer(app, status, warning):
def test_latex_howto(app, status, warning):
LaTeXTranslator.ignore_missing_images = True
app.builder.build_all()
- latex_warnings = warning.getvalue().replace(os.sep, '/')
+ latex_warnings = strip_escseq(warning.getvalue().replace(os.sep, '/'))
latex_warnings_exp = LATEX_WARNINGS % {
'root': re.escape(app.srcdir.replace(os.sep, '/'))}
assert re.match(latex_warnings_exp + '$', latex_warnings), \
diff --git a/tests/test_build_texinfo.py b/tests/test_build_texinfo.py
index 7f7570fd2..691a96f86 100644
--- a/tests/test_build_texinfo.py
+++ b/tests/test_build_texinfo.py
@@ -18,7 +18,7 @@ from six import PY3
from sphinx.writers.texinfo import TexinfoTranslator
-from util import SkipTest, remove_unicode_literals, with_app
+from util import SkipTest, remove_unicode_literals, with_app, strip_escseq
from test_build_html import ENV_WARNINGS
@@ -37,7 +37,7 @@ if PY3:
def test_texinfo(app, status, warning):
TexinfoTranslator.ignore_missing_images = True
app.builder.build_all()
- texinfo_warnings = warning.getvalue().replace(os.sep, '/')
+ texinfo_warnings = strip_escseq(warning.getvalue().replace(os.sep, '/'))
texinfo_warnings_exp = TEXINFO_WARNINGS % {
'root': re.escape(app.srcdir.replace(os.sep, '/'))}
assert re.match(texinfo_warnings_exp + '$', texinfo_warnings), \
diff --git a/tests/util.py b/tests/util.py
index cb0d3f7a0..27b41bc15 100644
--- a/tests/util.py
+++ b/tests/util.py
@@ -309,3 +309,7 @@ def find_files(root, suffix=None):
for f in [f for f in files if not suffix or f.endswith(suffix)]:
fpath = dirpath / f
yield os.path.relpath(fpath, root)
+
+
+def strip_escseq(text):
+ return re.sub('\x1b.*?m', '', text)
From ce1b9e3192bab359bfe2de2e233292d11b9a7fbd Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Fri, 24 Jun 2016 14:51:25 +0900
Subject: [PATCH 139/217] Fix flake8 violation
---
sphinx/builders/htmlhelp.py | 14 ++++++++------
1 file changed, 8 insertions(+), 6 deletions(-)
diff --git a/sphinx/builders/htmlhelp.py b/sphinx/builders/htmlhelp.py
index 382067794..405e4f01b 100644
--- a/sphinx/builders/htmlhelp.py
+++ b/sphinx/builders/htmlhelp.py
@@ -208,12 +208,14 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder):
self.info('writing project file...')
f = self.open_file(outdir, outname+'.hhp')
try:
- f.write(project_template % {'outname': outname,
- 'title': self.config.html_title,
- 'version': self.config.version,
- 'project': self.config.project,
- 'lcid': self.lcid,
- 'master_doc': self.config.master_doc + self.out_suffix})
+ f.write(project_template % {
+ 'outname': outname,
+ 'title': self.config.html_title,
+ 'version': self.config.version,
+ 'project': self.config.project,
+ 'lcid': self.lcid,
+ 'master_doc': self.config.master_doc + self.out_suffix
+ })
if not outdir.endswith(os.sep):
outdir += os.sep
olen = len(outdir)
From 4be597bb349e3bd61feaf23ee13d703e43316f52 Mon Sep 17 00:00:00 2001
From: Jakob Lykke Andersen
Date: Fri, 24 Jun 2016 09:15:31 +0200
Subject: [PATCH 140/217] C++, fix role mismatch warnings for templateParam
---
sphinx/domains/cpp.py | 15 ++++++++-------
1 file changed, 8 insertions(+), 7 deletions(-)
diff --git a/sphinx/domains/cpp.py b/sphinx/domains/cpp.py
index a9b1f263a..cf935bf22 100644
--- a/sphinx/domains/cpp.py
+++ b/sphinx/domains/cpp.py
@@ -4133,15 +4133,16 @@ class CPPDomain(Domain):
def checkType():
if typ == 'any':
return True
- elif typ == 'var' or typ == 'member':
- return declTyp == 'var' or declTyp == 'member'
- elif typ in ['enum', 'enumerator', 'class', 'function']:
+ if declTyp == 'templateParam':
+ return True
+ if typ == 'var' or typ == 'member':
+ return declTyp in ['var', 'member']
+ if typ in ['enum', 'enumerator', 'function', 'class']:
return declTyp == typ
- elif typ == 'type':
+ if typ == 'type':
return declTyp in ['enum', 'class', 'function', 'type']
- else:
- print("Type is %s" % typ)
- assert False
+ print("Type is %s" % typ)
+ assert False
if not checkType():
warner.warn("cpp:%s targets a %s." % (typ, s.declaration.objectType))
From fab5911004dfdb96ec9a6125a65ba40a903e6b71 Mon Sep 17 00:00:00 2001
From: Jakob Lykke Andersen
Date: Tue, 19 Apr 2016 18:49:29 +0900
Subject: [PATCH 141/217] C, neutralize xrefs to fundamental types.
TypedFields generate xrefs to whatever it gets.
See sphinx-doc/sphinx#2439.
---
sphinx/domains/c.py | 3 +++
1 file changed, 3 insertions(+)
diff --git a/sphinx/domains/c.py b/sphinx/domains/c.py
index c7fd0681e..8ba159d32 100644
--- a/sphinx/domains/c.py
+++ b/sphinx/domains/c.py
@@ -279,6 +279,9 @@ class CDomain(Domain):
typ, target, node, contnode):
# strip pointer asterisk
target = target.rstrip(' *')
+ # becase TypedField can generate xrefs
+ if target in CObject.stopwords:
+ return contnode
if target not in self.data['objects']:
return None
obj = self.data['objects'][target]
From 211fd352ae80f5c901b5c539a7c86348e8941094 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Fri, 24 Jun 2016 21:01:35 +0900
Subject: [PATCH 142/217] Fix #2579: Could not refer a label including both
spaces and colons via `sphinx.ext.intersphinx`
This fixes only the case the label including both spaces and colons as
ad-hoc. There is still a bug if a label having spaces, colons and
numbers like "foo bar:baz 1234".
Note: To support the case, we have to improve the inventory format.
---
CHANGES | 2 ++
sphinx/ext/intersphinx.py | 2 +-
tests/test_ext_intersphinx.py | 3 +++
3 files changed, 6 insertions(+), 1 deletion(-)
diff --git a/CHANGES b/CHANGES
index ae86fabdb..12e4692ee 100644
--- a/CHANGES
+++ b/CHANGES
@@ -56,6 +56,8 @@ Bugs fixed
* Failed to build PDF with framed.sty 0.95
* Sphinx now bundles needspace.sty
* #2666: C++, properly look up nested names involving constructors.
+* #2579: Could not refer a label including both spaces and colons via
+ `sphinx.ext.intersphinx`
Release 1.4.3 (released Jun 5, 2016)
diff --git a/sphinx/ext/intersphinx.py b/sphinx/ext/intersphinx.py
index 617220c5f..c43b8ae6a 100644
--- a/sphinx/ext/intersphinx.py
+++ b/sphinx/ext/intersphinx.py
@@ -106,7 +106,7 @@ def read_inventory_v2(f, uri, join, bufsize=16*1024):
for line in split_lines(read_chunks()):
# be careful to handle names with embedded spaces correctly
- m = re.match(r'(?x)(.+?)\s+(\S*:\S*)\s+(\S+)\s+(\S+)\s+(.*)',
+ m = re.match(r'(?x)(.+?)\s+(\S*:\S*)\s+(-?\d+)\s+(\S+)\s+(.*)',
line.rstrip())
if not m:
continue
diff --git a/tests/test_ext_intersphinx.py b/tests/test_ext_intersphinx.py
index 13b5d1aff..90987a3ef 100644
--- a/tests/test_ext_intersphinx.py
+++ b/tests/test_ext_intersphinx.py
@@ -43,6 +43,7 @@ module2 py:module 0 foo.html#module-$ -
module1.func py:function 1 sub/foo.html#$ -
CFunc c:function 2 cfunc.html#CFunc -
a term std:term -1 glossary.html#term-a-term -
+a term including:colon std:term -1 glossary.html#term-a-term-including-colon -
'''.encode('utf-8'))
@@ -78,6 +79,8 @@ def test_read_inventory_v2():
assert invdata1['c:function']['CFunc'][2] == '/util/cfunc.html#CFunc'
assert invdata1['std:term']['a term'][2] == \
'/util/glossary.html#term-a-term'
+ assert invdata1['std:term']['a term including:colon'][2] == \
+ '/util/glossary.html#term-a-term-including-colon'
@with_app()
From b6daf6be56df7cad3a315135238a69328f6311da Mon Sep 17 00:00:00 2001
From: jfbu
Date: Fri, 24 Jun 2016 15:14:37 +0200
Subject: [PATCH 143/217] fix latex, since 1.4.4 inline literal text is
followed by spurious space
ref: a51681b use of ``\scantokens`` has a quirk with adding a space in
some cases which we fix by inserting a ``\relax`` at the end of the
argument.
---
CHANGES | 1 +
sphinx/texinputs/sphinx.sty | 4 ++--
2 files changed, 3 insertions(+), 2 deletions(-)
diff --git a/CHANGES b/CHANGES
index ae86fabdb..9b5407c90 100644
--- a/CHANGES
+++ b/CHANGES
@@ -30,6 +30,7 @@ Bugs fixed
* #2705: `toctree` generates empty bullet_list if ``:titlesonly:`` specified
* #2479: `sphinx.ext.viewcode` uses python2 highlighter by default
* #2700: HtmlHelp builder has hard coded index.html
+* latex, since 1.4.4 inline literal text is followed by spurious space
Release 1.4.4 (released Jun 12, 2016)
diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty
index b992e9f82..a64583650 100644
--- a/sphinx/texinputs/sphinx.sty
+++ b/sphinx/texinputs/sphinx.sty
@@ -168,7 +168,7 @@
% let \sphinxcode and \sphinxbfcode use straight quotes. \@noligs patched by upquote,
% but needs protection in "moving arguments" such as for captions.
% Use \scantokens to handle e.g. \item[{\sphinxcode{'fontenc'}}]
-\DeclareRobustCommand{\sphinxcode}[1]{{\@noligs\scantokens{\texttt{#1}}}}
+\DeclareRobustCommand{\sphinxcode}[1]{{\@noligs\scantokens{\texttt{#1}\relax}}}
\newcommand{\sphinxbfcode}[1]{\sphinxcode{\bfseries#1}}
\newcommand{\sphinxemail}[1]{\textsf{#1}}
\newcommand{\sphinxtablecontinued}[1]{\textsf{#1}}
@@ -909,6 +909,6 @@
}
% robustified case needs special treatment
\newcommand\code{}\let\code\relax
- \DeclareRobustCommand{\code}[1]{{\@noligs\scantokens{\texttt{#1}}}}
+ \DeclareRobustCommand{\code}[1]{{\@noligs\scantokens{\texttt{#1}\relax}}}
\def\sphinxcode{\code}%
\fi
From 45ddb6387c34cb49eb14b0e03c7a8bb5e01526c7 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Fri, 24 Jun 2016 19:18:56 +0200
Subject: [PATCH 144/217] Add a missing word in CHANGES and fix minor other
issues there
---
CHANGES | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
diff --git a/CHANGES b/CHANGES
index 266603a30..5f2272a4f 100644
--- a/CHANGES
+++ b/CHANGES
@@ -6,18 +6,18 @@ Incompatible changes
* latex, inclusion of non-inline images from image directive resulted in
non-coherent whitespaces depending on original image width; new behaviour
- by necessity from earlier one in some cases. (ref: #2672)
+ by necessity differs from earlier one in some cases. (ref: #2672)
* latex, use of ``\includegraphics`` to refer to Sphinx custom variant is
- deprecated; in future it will revert to original LaTeX macro, custom one has
- already alternative name ``\sphinxincludegraphics``.
+ deprecated; in future it will revert to original LaTeX macro, custom one
+ already has alternative name ``\sphinxincludegraphics``.
Features added
--------------
* new config option ``latex_keep_old_macro_names``, defaults to True. If False,
- let macros (for text styling) be defined only with ``\sphinx``-prefixed names.
+ lets macros (for text styling) be defined only with ``\sphinx``-prefixed names.
* latex writer allows user customization of "shadowed" boxes (topics), via
- three length variables
+ three length variables.
Bugs fixed
----------
From f6b0ae903d1783f416666df5806adcaf2d71e8a0 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Fri, 3 Jun 2016 23:44:31 +0200
Subject: [PATCH 145/217] latex, allow image dimensions using px unit
(96px=1in)
New key ``'pixelsize'`` in ``latex_elements`` dictionary.
---
CHANGES | 1 +
doc/config.rst | 8 ++++++++
sphinx/writers/latex.py | 9 +++++++--
3 files changed, 16 insertions(+), 2 deletions(-)
diff --git a/CHANGES b/CHANGES
index 64f3097bb..86de8d96d 100644
--- a/CHANGES
+++ b/CHANGES
@@ -46,6 +46,7 @@ Features added
* latex, captions for literal blocks inside tables are handled, and long code
lines wrapped to fit table cell (ref: #2704)
* #2597: Show warning messages as darkred
+* latex, allow image dimensions using px unit (default is 96px=1in)
Bugs fixed
----------
diff --git a/doc/config.rst b/doc/config.rst
index fda7596e6..006f1f899 100644
--- a/doc/config.rst
+++ b/doc/config.rst
@@ -1601,6 +1601,14 @@ These options influence LaTeX output. See further :doc:`latex`.
``'pointsize'``
Point size option of the document class (``'10pt'``, ``'11pt'`` or
``'12pt'``), default ``'10pt'``.
+ ``'pixelsize'``
+ px unit size, default ``'49336sp'`` which achieves ``96px=1in`` (as
+ ``1in = 72.27*65536 = 4736286.72sp``, and all dimensions in TeX are
+ internally integer multiples of ``sp``). To obtain for example
+ ``100px=1in``, one can use ``'0.01in'`` but it is more precise to issue
+ ``'pixelsize':'47363sp',``.
+
+ .. versionadded:: 1.5
``'babel'``
"babel" package inclusion, default ``'\\usepackage{babel}'``.
``'fontpkg'``
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index c0da5118b..5ac343e62 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -35,6 +35,9 @@ HEADER = r'''%% Generated by Sphinx.
\def\sphinxdocclass{%(docclass)s}
\newif\ifsphinxKeepOldNames %(keepoldnames)s
\documentclass[%(papersize)s,%(pointsize)s%(classoptions)s]{%(wrapperclass)s}
+\ifdefined\pdfpxdimen
+ \let\sphinxpxdimen\pdfpxdimen\else\newdimen\sphinxpxdimen
+\fi \sphinxpxdimen=%(pixelsize)s\relax
\usepackage{iftex}
%(passoptionstopackages)s
%(inputenc)s
@@ -299,6 +302,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
default_elements = {
'papersize': 'letterpaper',
'pointsize': '10pt',
+ 'pixelsize': '49336sp',
'classoptions': '',
'extraclassoptions': '',
'passoptionstopackages': '',
@@ -1380,9 +1384,10 @@ class LaTeXTranslator(nodes.NodeVisitor):
return width_str
res = width_str
amount, unit = match.groups()[:2]
- if not unit or unit == "px":
- # pixels: let LaTeX alone
+ if not unit:
return None
+ elif unit == "px":
+ res = "%.3f\\sphinxpxdimen" % (float(amount))
elif unit == "%":
res = "%.3f\\linewidth" % (float(amount) / 100.0)
return res
From fc2202fd2a94d480a691ed1a6d5e5ee628df0858 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Sat, 25 Jun 2016 10:32:48 +0200
Subject: [PATCH 146/217] latex, replace ``'pixelsize'`` by more precise
``'pxunit'`` name
---
doc/config.rst | 13 +++++++------
sphinx/writers/latex.py | 4 ++--
2 files changed, 9 insertions(+), 8 deletions(-)
diff --git a/doc/config.rst b/doc/config.rst
index 006f1f899..2a6651c2d 100644
--- a/doc/config.rst
+++ b/doc/config.rst
@@ -1601,12 +1601,13 @@ These options influence LaTeX output. See further :doc:`latex`.
``'pointsize'``
Point size option of the document class (``'10pt'``, ``'11pt'`` or
``'12pt'``), default ``'10pt'``.
- ``'pixelsize'``
- px unit size, default ``'49336sp'`` which achieves ``96px=1in`` (as
- ``1in = 72.27*65536 = 4736286.72sp``, and all dimensions in TeX are
- internally integer multiples of ``sp``). To obtain for example
- ``100px=1in``, one can use ``'0.01in'`` but it is more precise to issue
- ``'pixelsize':'47363sp',``.
+ ``'pxunit'``
+ the value of the ``px`` when used in image attributes ``width`` and
+ ``height``. The default value is ``'49336sp'`` which achieves
+ ``96px=1in`` (``1in = 72.27*65536 = 4736286.72sp``, and all dimensions
+ in TeX are internally integer multiples of ``sp``). To obtain for
+ example ``100px=1in``, one can use ``'0.01in'`` but it is more precise
+ to use ``'47363sp'``.
.. versionadded:: 1.5
``'babel'``
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index 5ac343e62..74d6c1f41 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -37,7 +37,7 @@ HEADER = r'''%% Generated by Sphinx.
\documentclass[%(papersize)s,%(pointsize)s%(classoptions)s]{%(wrapperclass)s}
\ifdefined\pdfpxdimen
\let\sphinxpxdimen\pdfpxdimen\else\newdimen\sphinxpxdimen
-\fi \sphinxpxdimen=%(pixelsize)s\relax
+\fi \sphinxpxdimen=%(pxunit)s\relax
\usepackage{iftex}
%(passoptionstopackages)s
%(inputenc)s
@@ -302,7 +302,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
default_elements = {
'papersize': 'letterpaper',
'pointsize': '10pt',
- 'pixelsize': '49336sp',
+ 'pxunit': '49336sp',
'classoptions': '',
'extraclassoptions': '',
'passoptionstopackages': '',
From 71e1aaf3770831df1b5b7f36aaadb789176a2927 Mon Sep 17 00:00:00 2001
From: Matthias Geier
Date: Sat, 25 Jun 2016 15:39:25 +0200
Subject: [PATCH 147/217] searchtools: Add .txt only if suffix isn't already
.txt
---
sphinx/themes/basic/static/searchtools.js_t | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/sphinx/themes/basic/static/searchtools.js_t b/sphinx/themes/basic/static/searchtools.js_t
index 68a194820..000722f03 100644
--- a/sphinx/themes/basic/static/searchtools.js_t
+++ b/sphinx/themes/basic/static/searchtools.js_t
@@ -256,7 +256,7 @@ var Search = {
displayNextItem();
});
} else if (DOCUMENTATION_OPTIONS.HAS_SOURCE) {
- $.ajax({url: DOCUMENTATION_OPTIONS.URL_ROOT + '_sources/' + item[5] + '.txt',
+ $.ajax({url: DOCUMENTATION_OPTIONS.URL_ROOT + '_sources/' + item[5] + (item[5].endsWith('.txt') ? '' : '.txt'),
dataType: "text",
complete: function(jqxhr, textstatus) {
var data = jqxhr.responseText;
From 71dd8bfbf94417ad55b2444e1dbd219db266f335 Mon Sep 17 00:00:00 2001
From: Matthias Geier
Date: Sat, 25 Jun 2016 16:46:25 +0200
Subject: [PATCH 148/217] HTML: Add sourcelink_suffix to globalcontext
---
sphinx/builders/html.py | 1 +
sphinx/themes/basic/layout.html | 3 ++-
sphinx/themes/basic/static/searchtools.js_t | 3 ++-
3 files changed, 5 insertions(+), 2 deletions(-)
diff --git a/sphinx/builders/html.py b/sphinx/builders/html.py
index 880f021bc..09fe96be0 100644
--- a/sphinx/builders/html.py
+++ b/sphinx/builders/html.py
@@ -339,6 +339,7 @@ class StandaloneHTMLBuilder(Builder):
show_sphinx = self.config.html_show_sphinx,
has_source = self.config.html_copy_source,
show_source = self.config.html_show_sourcelink,
+ sourcelink_suffix = self.config.html_sourcelink_suffix,
file_suffix = self.out_suffix,
script_files = self.script_files,
language = self.config.language,
diff --git a/sphinx/themes/basic/layout.html b/sphinx/themes/basic/layout.html
index 1afc4a0bf..f8ff477c7 100644
--- a/sphinx/themes/basic/layout.html
+++ b/sphinx/themes/basic/layout.html
@@ -91,7 +91,8 @@
VERSION: '{{ release|e }}',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '{{ '' if no_search_suffix else file_suffix }}',
- HAS_SOURCE: {{ has_source|lower }}
+ HAS_SOURCE: {{ has_source|lower }},
+ SOURCELINK_SUFFIX: '{{ sourcelink_suffix }}'
};
{%- for scriptfile in script_files %}
diff --git a/sphinx/themes/basic/static/searchtools.js_t b/sphinx/themes/basic/static/searchtools.js_t
index 000722f03..9d70f4303 100644
--- a/sphinx/themes/basic/static/searchtools.js_t
+++ b/sphinx/themes/basic/static/searchtools.js_t
@@ -256,7 +256,8 @@ var Search = {
displayNextItem();
});
} else if (DOCUMENTATION_OPTIONS.HAS_SOURCE) {
- $.ajax({url: DOCUMENTATION_OPTIONS.URL_ROOT + '_sources/' + item[5] + (item[5].endsWith('.txt') ? '' : '.txt'),
+ var suffix = DOCUMENTATION_OPTIONS.SOURCELINK_SUFFIX;
+ $.ajax({url: DOCUMENTATION_OPTIONS.URL_ROOT + '_sources/' + item[5] + (item[5].endsWith(suffix) ? '' : suffix),
dataType: "text",
complete: function(jqxhr, textstatus) {
var data = jqxhr.responseText;
From 830ffc7738bdd204f202a509e8b3eba8b74cbb7d Mon Sep 17 00:00:00 2001
From: jfbu
Date: Sat, 25 Jun 2016 18:26:25 +0200
Subject: [PATCH 149/217] latex, load float package before wrapfig package
This should not change anything for Sphinx produced documents without
extra custom use of float package by user, and is recommended by wrapfig
doc for good functioning.
---
sphinx/texinputs/sphinx.sty | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty
index 4321d513f..d66fe34fe 100644
--- a/sphinx/texinputs/sphinx.sty
+++ b/sphinx/texinputs/sphinx.sty
@@ -47,7 +47,10 @@
% Handle footnotes in tables.
\RequirePackage{footnote}
\makesavenoteenv{tabulary}
-% For floating figures in the text.
+% For the H specifier. Do not \restylefloat{figure}, it breaks Sphinx code
+% for allowing figures in tables.
+\RequirePackage{float}
+% For floating figures in the text. Better to load after float.
\RequirePackage{wrapfig}
% Separate paragraphs by space by default.
\RequirePackage{parskip}
@@ -55,9 +58,6 @@
\RequirePackage{alltt}
% Display "real" single quotes in literal blocks.
\RequirePackage{upquote}
-% For the H specifier. Do not \restylefloat{figure}, it breaks Sphinx code
-% for allowing figures in tables.
-\RequirePackage{float}
% Redefine these colors to your liking in the preamble.
\definecolor{TitleColor}{rgb}{0.126,0.263,0.361}
From 6caf0b2a8857f2f0844922b8f3a67f0ae58dafb1 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Sat, 25 Jun 2016 18:50:24 +0200
Subject: [PATCH 150/217] latex, add comment on the possibility of
``\listof{literalblock}{foo}``
Memo: this command produces a list of the code listings in the document
(with chosen title foo), analogous to ``\listoffigures``, and it comes
from LaTeX package float.sty.
---
sphinx/texinputs/sphinx.sty | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty
index d66fe34fe..e7e319c4f 100644
--- a/sphinx/texinputs/sphinx.sty
+++ b/sphinx/texinputs/sphinx.sty
@@ -964,9 +964,9 @@
\newcommand*{\fnum@literalblock}{\literalblockname\nobreakspace\theliteralblock}
% this will be overwritten in document preamble by Babel translation
\newcommand*{\literalblockname}{Listing }
-% file extension needed for \caption's good functioning, but file isn't
-% created without \listofliteralblocks. The latter macro could be defined
-% on model of \listoffigures.
+% file extension needed for \caption's good functioning, the file is created
+% only if a \listof{literalblock}{foo} command is encountered, which is
+% analogous to \listoffigures, but for the code listings (foo = chosen title.)
\newcommand*{\ext@literalblock}{lol}
% control caption around literal-block
From 0859b338d8a2f5b1a2d5165b89842b6cda6a6166 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 26 Jun 2016 11:28:54 +0900
Subject: [PATCH 151/217] LaTeX writer: Integerate width_to_latex_length() and
latex_image_length() (ref: #2714)
---
sphinx/writers/latex.py | 35 +++++++++++++----------------------
1 file changed, 13 insertions(+), 22 deletions(-)
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index 229e62902..60430d216 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -265,24 +265,6 @@ class Table(object):
self.longtable = False
-def width_to_latex_length(length_str):
- """Convert `length_str` with rst length to LaTeX length.
-
- This function is copied from docutils' latex writer
- """
- match = re.match('(\d*\.?\d*)\s*(\S*)', length_str)
- if not match:
- return length_str
- value, unit = match.groups()[:2]
- if unit in ('', 'pt'):
- length_str = '%sbp' % value # convert to 'bp'
- # percentage: relate to current line width
- elif unit == '%':
- length_str = '%.3f\\linewidth' % (float(value)/100.0)
-
- return length_str
-
-
def escape_abbr(text):
"""Adjust spacing after abbreviations."""
return re.sub('\.(?=\s|$)', '.\\@', text)
@@ -1352,13 +1334,22 @@ class LaTeXTranslator(nodes.NodeVisitor):
def depart_hlistcol(self, node):
pass
- def latex_image_length(self, width_str):
+ def latex_image_length(self, width_str, figure=False):
+ """Convert `width_str` with rst length to LaTeX length.
+
+ This function is copied from docutils' latex writer
+
+ The last parameter, ``figure`` is only for compatibility with 1.4.4.
+ It will be removed at Sphinx-1.5.
+ """
match = re.match('(\d*\.?\d*)\s*(\S*)', width_str)
if not match:
# fallback
return width_str
res = width_str
amount, unit = match.groups()[:2]
+ if figure and unit in ('', 'pt'):
+ res = '%sbp' % amount # convert to 'bp'
if not unit or unit == "px":
# pixels: let LaTeX alone
return None
@@ -1446,7 +1437,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
if self.table:
# TODO: support align option
if 'width' in node:
- length = width_to_latex_length(node['width'])
+ length = self.latex_image_length(node['width'], figure=True)
self.body.append('\\begin{sphinxfigure-in-table}[%s]\n\\centering\n' % length)
else:
self.body.append('\\begin{sphinxfigure-in-table}\n\\centering\n')
@@ -1455,9 +1446,9 @@ class LaTeXTranslator(nodes.NodeVisitor):
self.context.append(ids + '\\end{sphinxfigure-in-table}\\relax\n')
elif node.get('align', '') in ('left', 'right'):
if 'width' in node:
- length = width_to_latex_length(node['width'])
+ length = self.latex_image_length(node['width'], figure=True)
elif 'width' in node[0]:
- length = width_to_latex_length(node[0]['width'])
+ length = self.latex_image_length(node[0]['width'], figure=True)
else:
length = '0pt'
self.body.append('\\begin{wrapfigure}{%s}{%s}\n\\centering' %
From 593f12060c7a032ba5fd5b75dbb742fd4d17c0ed Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 26 Jun 2016 11:40:08 +0900
Subject: [PATCH 152/217] Fix warning in CHANGES
---
CHANGES | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/CHANGES b/CHANGES
index 5f2272a4f..b46b51648 100644
--- a/CHANGES
+++ b/CHANGES
@@ -27,7 +27,7 @@ Bugs fixed
* #2684: `sphinx.ext.intersphinx` crashes with six-1.4.1
* #2679: ``float`` package needed for ``'figure_align': 'H'`` latex option
* #2671: image directive may lead to inconsistent spacing in pdf
-* #2705: `toctree` generates empty bullet_list if ``:titlesonly:`` specified
+* #2705: ``toctree`` generates empty bullet_list if ``:titlesonly:`` specified
* #2479: `sphinx.ext.viewcode` uses python2 highlighter by default
* #2700: HtmlHelp builder has hard coded index.html
* latex, since 1.4.4 inline literal text is followed by spurious space
From e134dc6f5795b486482cbc44964b2c8f6f03eb1d Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 26 Jun 2016 11:44:11 +0900
Subject: [PATCH 153/217] Fix a condition in latex_image_length()
---
sphinx/writers/latex.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index 60430d216..a3477c9c6 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -1350,7 +1350,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
amount, unit = match.groups()[:2]
if figure and unit in ('', 'pt'):
res = '%sbp' % amount # convert to 'bp'
- if not unit or unit == "px":
+ elif not unit or unit == "px":
# pixels: let LaTeX alone
return None
elif unit == "%":
From efd74a9e14a1ae2398a78faf97b9d146dfc5d6b2 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 26 Jun 2016 12:01:14 +0900
Subject: [PATCH 154/217] latex, replace ``pt`` by TeX equivalent ``bp`` if
found in ``width`` or ``height`` attribute of an image (ref: #2714)
---
CHANGES | 2 ++
sphinx/writers/latex.py | 17 +++++++----------
tests/test_build_latex.py | 4 ++--
3 files changed, 11 insertions(+), 12 deletions(-)
diff --git a/CHANGES b/CHANGES
index 4d48c5c5f..4cb4d08c9 100644
--- a/CHANGES
+++ b/CHANGES
@@ -13,6 +13,8 @@ Incompatible changes
it was shipped with Sphinx since 1.3.4).
* latex, literal blocks in tables do not use OriginalVerbatim but
sphinxVerbatimintable which handles captions and wraps lines(ref #2704).
+* latex, replace ``pt`` by TeX equivalent ``bp`` if found in ``width`` or
+ ``height`` attribute of an image.
Features added
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index e0df99651..56cd97308 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -1359,13 +1359,10 @@ class LaTeXTranslator(nodes.NodeVisitor):
def depart_hlistcol(self, node):
pass
- def latex_image_length(self, width_str, figure=False):
+ def latex_image_length(self, width_str):
"""Convert `width_str` with rst length to LaTeX length.
This function is copied from docutils' latex writer
-
- The last parameter, ``figure`` is only for compatibility with 1.4.4.
- It will be removed at Sphinx-1.5.
"""
match = re.match('(\d*\.?\d*)\s*(\S*)', width_str)
if not match:
@@ -1373,10 +1370,10 @@ class LaTeXTranslator(nodes.NodeVisitor):
return width_str
res = width_str
amount, unit = match.groups()[:2]
- if figure and unit in ('', 'pt'):
- res = '%sbp' % amount # convert to 'bp'
- elif not unit:
+ if not unit:
return None
+ elif unit == 'pt':
+ res = '%sbp' % amount # convert to 'bp'
elif unit == "px":
res = "%.3f\\sphinxpxdimen" % (float(amount))
elif unit == "%":
@@ -1463,7 +1460,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
if self.table:
# TODO: support align option
if 'width' in node:
- length = self.latex_image_length(node['width'], figure=True)
+ length = self.latex_image_length(node['width'])
self.body.append('\\begin{sphinxfigure-in-table}[%s]\n\\centering\n' % length)
else:
self.body.append('\\begin{sphinxfigure-in-table}\n\\centering\n')
@@ -1472,9 +1469,9 @@ class LaTeXTranslator(nodes.NodeVisitor):
self.context.append(ids + '\\end{sphinxfigure-in-table}\\relax\n')
elif node.get('align', '') in ('left', 'right'):
if 'width' in node:
- length = self.latex_image_length(node['width'], figure=True)
+ length = self.latex_image_length(node['width'])
elif 'width' in node[0]:
- length = self.latex_image_length(node[0]['width'], figure=True)
+ length = self.latex_image_length(node[0]['width'])
else:
length = '0pt'
self.body.append('\\begin{wrapfigure}{%s}{%s}\n\\centering' %
diff --git a/tests/test_build_latex.py b/tests/test_build_latex.py
index 816779d9f..b71d3a650 100644
--- a/tests/test_build_latex.py
+++ b/tests/test_build_latex.py
@@ -578,10 +578,10 @@ def test_image_in_section(app, status, warning):
print(status.getvalue())
print(warning.getvalue())
assert ('\\chapter[Test section]'
- '{\\sphinxincludegraphics[width=15pt,height=15pt]{{pic}.png} Test section}'
+ '{\\sphinxincludegraphics[width=15bp,height=15bp]{{pic}.png} Test section}'
in result)
assert ('\\chapter[Other {[}blah{]} section]{Other {[}blah{]} '
- '\\sphinxincludegraphics[width=15pt,height=15pt]{{pic}.png} section}' in result)
+ '\\sphinxincludegraphics[width=15bp,height=15bp]{{pic}.png} section}' in result)
assert ('\\chapter{Another section}' in result)
From 4bc5a242cec8cd05a6fc120833eee2e8b866d149 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 26 Jun 2016 13:15:07 +0900
Subject: [PATCH 155/217] Show warnings if invalid dimension units found
---
CHANGES | 2 ++
sphinx/writers/latex.py | 41 ++++++++++++++++++++------------------
tests/test_writer_latex.py | 28 ++++++++++++++++++++++++++
3 files changed, 52 insertions(+), 19 deletions(-)
create mode 100644 tests/test_writer_latex.py
diff --git a/CHANGES b/CHANGES
index 4cb4d08c9..726d38024 100644
--- a/CHANGES
+++ b/CHANGES
@@ -49,6 +49,8 @@ Features added
lines wrapped to fit table cell (ref: #2704)
* #2597: Show warning messages as darkred
* latex, allow image dimensions using px unit (default is 96px=1in)
+* Show warnings if invalid dimension units found
+
Bugs fixed
----------
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index 56cd97308..140ee2136 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -275,6 +275,24 @@ def escape_abbr(text):
return re.sub('\.(?=\s|$)', '.\\@', text)
+def rstdim_to_latexdim(width_str):
+ """Convert `width_str` with rst length to LaTeX length."""
+ match = re.match('(\d*\.?\d*)\s*(\S*)', width_str)
+ if not match:
+ raise ValueError
+ res = width_str
+ amount, unit = match.groups()[:2]
+ if not unit:
+ return None
+ elif unit == 'pt':
+ res = '%sbp' % amount # convert to 'bp'
+ elif unit == "px":
+ res = "%.3f\\sphinxpxdimen" % (float(amount))
+ elif unit == "%":
+ res = "%.3f\\linewidth" % (float(amount) / 100.0)
+ return res
+
+
class LaTeXTranslator(nodes.NodeVisitor):
sectionnames = ["part", "chapter", "section", "subsection",
"subsubsection", "paragraph", "subparagraph"]
@@ -1360,25 +1378,10 @@ class LaTeXTranslator(nodes.NodeVisitor):
pass
def latex_image_length(self, width_str):
- """Convert `width_str` with rst length to LaTeX length.
-
- This function is copied from docutils' latex writer
- """
- match = re.match('(\d*\.?\d*)\s*(\S*)', width_str)
- if not match:
- # fallback
- return width_str
- res = width_str
- amount, unit = match.groups()[:2]
- if not unit:
- return None
- elif unit == 'pt':
- res = '%sbp' % amount # convert to 'bp'
- elif unit == "px":
- res = "%.3f\\sphinxpxdimen" % (float(amount))
- elif unit == "%":
- res = "%.3f\\linewidth" % (float(amount) / 100.0)
- return res
+ try:
+ return rstdim_to_latexdim(width_str)
+ except ValueError:
+ self.builder.warn('dimension unit %s is invalid. Ignored.' % width_str)
def is_inline(self, node):
"""Check whether a node represents an inline element."""
diff --git a/tests/test_writer_latex.py b/tests/test_writer_latex.py
new file mode 100644
index 000000000..4ef1cdda8
--- /dev/null
+++ b/tests/test_writer_latex.py
@@ -0,0 +1,28 @@
+# -*- coding: utf-8 -*-
+"""
+ test_writer_latex
+ ~~~~~~~~~~~~~~~~
+
+ Test the LaTeX writer
+
+ :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+from __future__ import print_function
+from sphinx.writers.latex import rstdim_to_latexdim
+
+
+def test_rstdim_to_latexdim():
+ # Length units docutils supported
+ # http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#length-units
+ assert rstdim_to_latexdim('160em') == '160em'
+ assert rstdim_to_latexdim('160px') == '160.000\\sphinxpxdimen'
+ assert rstdim_to_latexdim('160in') == '160in'
+ assert rstdim_to_latexdim('160cm') == '160cm'
+ assert rstdim_to_latexdim('160mm') == '160mm'
+ assert rstdim_to_latexdim('160pt') == '160bp'
+ assert rstdim_to_latexdim('160pc') == '160pc'
+ assert rstdim_to_latexdim('30%') == '0.300\\linewidth'
+ assert rstdim_to_latexdim('160') is None
+
+ assert rstdim_to_latexdim('160.0em') == '160.0em'
From cb00f51328cf9e2d9c3340dd9441e37837862dc2 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 26 Jun 2016 13:31:07 +0900
Subject: [PATCH 156/217] latex: Raise error if invalid dimension value
---
sphinx/writers/latex.py | 3 ++-
tests/test_writer_latex.py | 6 ++++++
2 files changed, 8 insertions(+), 1 deletion(-)
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index 140ee2136..56b3736db 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -277,11 +277,12 @@ def escape_abbr(text):
def rstdim_to_latexdim(width_str):
"""Convert `width_str` with rst length to LaTeX length."""
- match = re.match('(\d*\.?\d*)\s*(\S*)', width_str)
+ match = re.match('^(\d*\.?\d*)\s*(\S*)$', width_str)
if not match:
raise ValueError
res = width_str
amount, unit = match.groups()[:2]
+ float(amount) # validate amount is float
if not unit:
return None
elif unit == 'pt':
diff --git a/tests/test_writer_latex.py b/tests/test_writer_latex.py
index 4ef1cdda8..667b5e98d 100644
--- a/tests/test_writer_latex.py
+++ b/tests/test_writer_latex.py
@@ -11,6 +11,8 @@
from __future__ import print_function
from sphinx.writers.latex import rstdim_to_latexdim
+from util import raises
+
def test_rstdim_to_latexdim():
# Length units docutils supported
@@ -26,3 +28,7 @@ def test_rstdim_to_latexdim():
assert rstdim_to_latexdim('160') is None
assert rstdim_to_latexdim('160.0em') == '160.0em'
+
+ # unknown values (it might be generated by 3rd party extension)
+ raises(ValueError, rstdim_to_latexdim, 'unknown')
+ assert rstdim_to_latexdim('160.0unknown') == '160.0unknown'
From fe3f2a4a3f8419f3aebfc78022eac6731dd6b5ca Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 26 Jun 2016 13:44:48 +0900
Subject: [PATCH 157/217] latex: Do not convert px to float
---
sphinx/writers/latex.py | 2 +-
tests/test_writer_latex.py | 4 +++-
2 files changed, 4 insertions(+), 2 deletions(-)
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index 56b3736db..bfb8f0e3b 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -288,7 +288,7 @@ def rstdim_to_latexdim(width_str):
elif unit == 'pt':
res = '%sbp' % amount # convert to 'bp'
elif unit == "px":
- res = "%.3f\\sphinxpxdimen" % (float(amount))
+ res = "%s\\sphinxpxdimen" % amount
elif unit == "%":
res = "%.3f\\linewidth" % (float(amount) / 100.0)
return res
diff --git a/tests/test_writer_latex.py b/tests/test_writer_latex.py
index 667b5e98d..a98873b80 100644
--- a/tests/test_writer_latex.py
+++ b/tests/test_writer_latex.py
@@ -18,7 +18,7 @@ def test_rstdim_to_latexdim():
# Length units docutils supported
# http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#length-units
assert rstdim_to_latexdim('160em') == '160em'
- assert rstdim_to_latexdim('160px') == '160.000\\sphinxpxdimen'
+ assert rstdim_to_latexdim('160px') == '160\\sphinxpxdimen'
assert rstdim_to_latexdim('160in') == '160in'
assert rstdim_to_latexdim('160cm') == '160cm'
assert rstdim_to_latexdim('160mm') == '160mm'
@@ -27,7 +27,9 @@ def test_rstdim_to_latexdim():
assert rstdim_to_latexdim('30%') == '0.300\\linewidth'
assert rstdim_to_latexdim('160') is None
+ # flaot values
assert rstdim_to_latexdim('160.0em') == '160.0em'
+ assert rstdim_to_latexdim('.5em') == '.5em'
# unknown values (it might be generated by 3rd party extension)
raises(ValueError, rstdim_to_latexdim, 'unknown')
From cd093fb0cac764e57b4dd71a31fd2cc3f5b8f9e8 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 26 Jun 2016 13:56:19 +0900
Subject: [PATCH 158/217] latex writer considers unitless dimensions as px
based
---
CHANGES | 2 ++
sphinx/writers/latex.py | 6 ++----
tests/test_writer_latex.py | 2 +-
3 files changed, 5 insertions(+), 5 deletions(-)
diff --git a/CHANGES b/CHANGES
index 726d38024..cc8b3a108 100644
--- a/CHANGES
+++ b/CHANGES
@@ -15,6 +15,8 @@ Incompatible changes
sphinxVerbatimintable which handles captions and wraps lines(ref #2704).
* latex, replace ``pt`` by TeX equivalent ``bp`` if found in ``width`` or
``height`` attribute of an image.
+* latex, if ``width`` or ``height`` attribute of an image is given with no unit,
+ use ``px`` rather than ignore it.
Features added
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index bfb8f0e3b..ca3df78de 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -283,12 +283,10 @@ def rstdim_to_latexdim(width_str):
res = width_str
amount, unit = match.groups()[:2]
float(amount) # validate amount is float
- if not unit:
- return None
+ if unit in ('', "px"):
+ res = "%s\\sphinxpxdimen" % amount
elif unit == 'pt':
res = '%sbp' % amount # convert to 'bp'
- elif unit == "px":
- res = "%s\\sphinxpxdimen" % amount
elif unit == "%":
res = "%.3f\\linewidth" % (float(amount) / 100.0)
return res
diff --git a/tests/test_writer_latex.py b/tests/test_writer_latex.py
index a98873b80..72eb7ed2a 100644
--- a/tests/test_writer_latex.py
+++ b/tests/test_writer_latex.py
@@ -25,7 +25,7 @@ def test_rstdim_to_latexdim():
assert rstdim_to_latexdim('160pt') == '160bp'
assert rstdim_to_latexdim('160pc') == '160pc'
assert rstdim_to_latexdim('30%') == '0.300\\linewidth'
- assert rstdim_to_latexdim('160') is None
+ assert rstdim_to_latexdim('160') == '160\\sphinxpxdimen'
# flaot values
assert rstdim_to_latexdim('160.0em') == '160.0em'
From d76e9d48a5d2b96974ec5acaf5f6860fa979ab43 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Sat, 25 Jun 2016 22:55:47 +0200
Subject: [PATCH 159/217] Update doc/rest.rst
---
doc/rest.rst | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
diff --git a/doc/rest.rst b/doc/rest.rst
index 293b2ea02..7b2b92ddc 100644
--- a/doc/rest.rst
+++ b/doc/rest.rst
@@ -363,8 +363,9 @@ directory on building (e.g. the ``_static`` directory for HTML output.)
Interpretation of image size options (``width`` and ``height``) is as follows:
if the size has no unit or the unit is pixels, the given size will only be
-respected for output channels that support pixels (i.e. not in LaTeX output).
-Other units (like ``pt`` for points) will be used for HTML and LaTeX output.
+respected for output channels that support pixels. Other units (like ``pt``
+for points) will be used for HTML and LaTeX output (the latter replaces ``pt``
+by ``bp`` as this is the TeX unit such that ``72bp=1in``).
Sphinx extends the standard docutils behavior by allowing an asterisk for the
extension::
@@ -386,6 +387,9 @@ Note that image file names should not contain spaces.
.. versionchanged:: 0.6
Image paths can now be absolute.
+.. versionchanged:: 1.5
+ latex target supports pixels (default is ``96px=1in``).
+
Footnotes
---------
From b1c6717743ca70322c3f1fc9ca954b6720f9cf05 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 26 Jun 2016 23:19:57 +0900
Subject: [PATCH 160/217] Check latex_image_length() returns none value
---
sphinx/writers/latex.py | 9 +++++----
1 file changed, 5 insertions(+), 4 deletions(-)
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index ca3df78de..db8fae0dc 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -1463,21 +1463,22 @@ class LaTeXTranslator(nodes.NodeVisitor):
# TODO: support align option
if 'width' in node:
length = self.latex_image_length(node['width'])
- self.body.append('\\begin{sphinxfigure-in-table}[%s]\n\\centering\n' % length)
+ if length:
+ self.body.append('\\begin{sphinxfigure-in-table}[%s]\n'
+ '\\centering\n' % length)
else:
self.body.append('\\begin{sphinxfigure-in-table}\n\\centering\n')
if any(isinstance(child, nodes.caption) for child in node):
self.body.append('\\capstart')
self.context.append(ids + '\\end{sphinxfigure-in-table}\\relax\n')
elif node.get('align', '') in ('left', 'right'):
+ length = None
if 'width' in node:
length = self.latex_image_length(node['width'])
elif 'width' in node[0]:
length = self.latex_image_length(node[0]['width'])
- else:
- length = '0pt'
self.body.append('\\begin{wrapfigure}{%s}{%s}\n\\centering' %
- (node['align'] == 'right' and 'r' or 'l', length))
+ (node['align'] == 'right' and 'r' or 'l', length or '0pt'))
self.context.append(ids + '\\end{wrapfigure}\n')
elif self.in_minipage:
if ('align' not in node.attributes or
From 68a32a2bffe9d8e3e7c2b4bcd821a41cce63dd34 Mon Sep 17 00:00:00 2001
From: Jakob Lykke Andersen
Date: Wed, 29 Jun 2016 09:02:35 +0200
Subject: [PATCH 161/217] C++, fix id generation of var/member declarations.
Namespaces not in the declaration are now properly included in the id.
Fixes sphinx-doc/sphinx#2722.
---
CHANGES | 1 +
sphinx/domains/cpp.py | 2 +-
2 files changed, 2 insertions(+), 1 deletion(-)
diff --git a/CHANGES b/CHANGES
index b46b51648..e8bf624f1 100644
--- a/CHANGES
+++ b/CHANGES
@@ -31,6 +31,7 @@ Bugs fixed
* #2479: `sphinx.ext.viewcode` uses python2 highlighter by default
* #2700: HtmlHelp builder has hard coded index.html
* latex, since 1.4.4 inline literal text is followed by spurious space
+* #2722: C++, fix id generation for var/member declarations to include namespaces.
Release 1.4.4 (released Jun 12, 2016)
diff --git a/sphinx/domains/cpp.py b/sphinx/domains/cpp.py
index a2298b7bc..323905256 100644
--- a/sphinx/domains/cpp.py
+++ b/sphinx/domains/cpp.py
@@ -1977,7 +1977,7 @@ class ASTTypeWithInit(ASTBase):
def get_id_v2(self, objectType=None, symbol=None):
if objectType == 'member':
- return symbol.declaration.name.get_id_v2()
+ return symbol.get_full_nested_name().get_id_v2()
else:
return self.type.get_id_v2()
From a20533540bb7bb41d8fd924fef1e664a2d87da2c Mon Sep 17 00:00:00 2001
From: jfbu
Date: Wed, 29 Jun 2016 20:54:57 +0200
Subject: [PATCH 162/217] Add a sentence in doc/config.rst on ``'pxunit'`` key
---
doc/config.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/doc/config.rst b/doc/config.rst
index 2a6651c2d..a19ca5d29 100644
--- a/doc/config.rst
+++ b/doc/config.rst
@@ -1607,7 +1607,7 @@ These options influence LaTeX output. See further :doc:`latex`.
``96px=1in`` (``1in = 72.27*65536 = 4736286.72sp``, and all dimensions
in TeX are internally integer multiples of ``sp``). To obtain for
example ``100px=1in``, one can use ``'0.01in'`` but it is more precise
- to use ``'47363sp'``.
+ to use ``'47363sp'``. To obtain ``72px=1in``, use ``'1bp'``.
.. versionadded:: 1.5
``'babel'``
From 2a1826022d396621e4fc8a0f7618c77d000b3ece Mon Sep 17 00:00:00 2001
From: jfbu
Date: Thu, 30 Jun 2016 00:03:06 +0200
Subject: [PATCH 163/217] Update to CHANGES
---
CHANGES | 2 ++
1 file changed, 2 insertions(+)
diff --git a/CHANGES b/CHANGES
index e8bf624f1..b208265b5 100644
--- a/CHANGES
+++ b/CHANGES
@@ -32,6 +32,8 @@ Bugs fixed
* #2700: HtmlHelp builder has hard coded index.html
* latex, since 1.4.4 inline literal text is followed by spurious space
* #2722: C++, fix id generation for var/member declarations to include namespaces.
+* latex, images (from image directive) in lists or quoted blocks did not obey
+ indentation (fixed together with #2671)
Release 1.4.4 (released Jun 12, 2016)
From 446e93aca7ab8a706dfc7d79102b5aa474a749d2 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Thu, 30 Jun 2016 00:08:40 +0200
Subject: [PATCH 164/217] fix a typo in CHANGES
---
CHANGES | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/CHANGES b/CHANGES
index cc8b3a108..d9ea1fbac 100644
--- a/CHANGES
+++ b/CHANGES
@@ -41,7 +41,7 @@ Features added
and other admonition types, allowing full customizability from the
``'preamble'`` key or an input file (ref: feature request #2674, #2685)
* latex, better computes column widths of some tables (as a result, there will
- be slight changes as tables now correctly fill the line with; ref: #2708)
+ be slight changes as tables now correctly fill the line width; ref: #2708)
* latex, sphinxVerbatim environment is more easily customizable (ref: #2704).
In addition to already existing VerbatimColor and VerbatimBorderColor:
From 2a5e5a553041f048da9de7634a67c30fb61fc58f Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Thu, 30 Jun 2016 10:55:02 +0900
Subject: [PATCH 165/217] Update CHANGES for PR#2650
---
CHANGES | 1 +
1 file changed, 1 insertion(+)
diff --git a/CHANGES b/CHANGES
index d9ea1fbac..1963e281b 100644
--- a/CHANGES
+++ b/CHANGES
@@ -52,6 +52,7 @@ Features added
* #2597: Show warning messages as darkred
* latex, allow image dimensions using px unit (default is 96px=1in)
* Show warnings if invalid dimension units found
+* #2650: Add ``--warning-is-error`` option to setup.py command
Bugs fixed
From a9ffcf0d601b18d1d8e4b9b401a0f04a518b6029 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Tadej=20Jane=C5=BE?=
Date: Fri, 10 Jun 2016 09:45:22 +0200
Subject: [PATCH 166/217] Add ``--warning-is-error`` option to setup.py command
---
CHANGES | 2 +-
sphinx/setup_command.py | 8 ++++++--
tests/test_setup_command.py | 22 ++++++++++++++++++++++
3 files changed, 29 insertions(+), 3 deletions(-)
diff --git a/CHANGES b/CHANGES
index 1963e281b..4304e49ea 100644
--- a/CHANGES
+++ b/CHANGES
@@ -52,7 +52,7 @@ Features added
* #2597: Show warning messages as darkred
* latex, allow image dimensions using px unit (default is 96px=1in)
* Show warnings if invalid dimension units found
-* #2650: Add ``--warning-is-error`` option to setup.py command
+* #2663: Add ``--warning-is-error`` option to setup.py command
Bugs fixed
diff --git a/sphinx/setup_command.py b/sphinx/setup_command.py
index 0a29685a4..7df8bd6e8 100644
--- a/sphinx/setup_command.py
+++ b/sphinx/setup_command.py
@@ -73,6 +73,7 @@ class BuildDoc(Command):
('build-dir=', None, 'Build directory'),
('config-dir=', 'c', 'Location of the configuration directory'),
('builder=', 'b', 'The builder to use. Defaults to "html"'),
+ ('warning-is-error', 'W', 'Turn warning into errors'),
('project=', None, 'The documented project\'s name'),
('version=', None, 'The short X.Y version'),
('release=', None, 'The full version, including alpha/beta/rc tags'),
@@ -82,13 +83,15 @@ class BuildDoc(Command):
('copyright', None, 'The copyright string'),
('pdb', None, 'Start pdb on exception'),
]
- boolean_options = ['fresh-env', 'all-files', 'link-index']
+ boolean_options = ['fresh-env', 'all-files', 'warning-is-error',
+ 'link-index']
def initialize_options(self):
self.fresh_env = self.all_files = False
self.pdb = False
self.source_dir = self.build_dir = None
self.builder = 'html'
+ self.warning_is_error = False
self.project = ''
self.version = ''
self.release = ''
@@ -162,7 +165,8 @@ class BuildDoc(Command):
app = Sphinx(self.source_dir, self.config_dir,
self.builder_target_dir, self.doctree_dir,
self.builder, confoverrides, status_stream,
- freshenv=self.fresh_env)
+ freshenv=self.fresh_env,
+ warningiserror=self.warning_is_error)
try:
app.build(force_all=self.all_files)
diff --git a/tests/test_setup_command.py b/tests/test_setup_command.py
index 77c9ade46..c92f6220f 100644
--- a/tests/test_setup_command.py
+++ b/tests/test_setup_command.py
@@ -108,3 +108,25 @@ def test_build_sphinx_return_nonzero_status(pkgroot, proc):
print(out)
print(err)
assert proc.returncode != 0, 'expect non-zero status for setup.py'
+
+
+@with_setup_command(root)
+def test_build_sphinx_warning_return_zero_status(pkgroot, proc):
+ srcdir = (pkgroot / 'doc')
+ (srcdir / 'contents.txt').write_text(
+ 'See :ref:`unexisting-reference-label`')
+ out, err = proc.communicate()
+ print(out)
+ print(err)
+ assert proc.returncode == 0
+
+
+@with_setup_command(root, '--warning-is-error')
+def test_build_sphinx_warning_is_error_return_nonzero_status(pkgroot, proc):
+ srcdir = (pkgroot / 'doc')
+ (srcdir / 'contents.txt').write_text(
+ 'See :ref:`unexisting-reference-label`')
+ out, err = proc.communicate()
+ print(out)
+ print(err)
+ assert proc.returncode != 0, 'expect non-zero status for setup.py'
From f30a8d5a3644e1db35ca66486276253ee22dc1b0 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Thu, 30 Jun 2016 11:10:58 +0200
Subject: [PATCH 167/217] fix a mark-up typo in doc/install.rst
---
doc/install.rst | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/doc/install.rst b/doc/install.rst
index 0ecd73609..a2aeaf9cb 100644
--- a/doc/install.rst
+++ b/doc/install.rst
@@ -135,7 +135,7 @@ install.
.. note::
``pip`` has been contained in the Python official installation after version
- of Python-3.4.0 or Python-2.7.9.
+ of Python-3.4.0 or Python-2.7.9.
Installing Sphinx with pip
From 067d3cabf0c7a09589dbd0920955f0f490ea8fbd Mon Sep 17 00:00:00 2001
From: jfbu
Date: Tue, 28 Jun 2016 19:14:21 +0200
Subject: [PATCH 168/217] latex, make use of ``\small`` for code listings
customizable
---
CHANGES | 1 +
doc/latex.rst | 8 ++++++++
sphinx/texinputs/sphinx.sty | 2 +-
3 files changed, 10 insertions(+), 1 deletion(-)
diff --git a/CHANGES b/CHANGES
index 1963e281b..3e5ff332d 100644
--- a/CHANGES
+++ b/CHANGES
@@ -53,6 +53,7 @@ Features added
* latex, allow image dimensions using px unit (default is 96px=1in)
* Show warnings if invalid dimension units found
* #2650: Add ``--warning-is-error`` option to setup.py command
+* latex, make the use of ``\small`` for code listings customizable (ref #2721)
Bugs fixed
diff --git a/doc/latex.rst b/doc/latex.rst
index aec566301..826a715c6 100644
--- a/doc/latex.rst
+++ b/doc/latex.rst
@@ -120,6 +120,14 @@ Let us illustrate here what can be modified by the second method.
were not wrapped), they now use ``sphinxVerbatimintable``.
.. versionadded:: 1.5
the two customizable lengths, the ``sphinxVerbatimintable``.
+- by default the Sphinx style file ``sphinx.sty`` includes the command
+ ``\fvset{fontsize=\small}`` as part of its configuration of
+ ``fancyvrb.sty``. The user may override this for example via
+ ``\fvset{fontsize=auto}`` which will use for listings the ambient
+ font size. Refer to ``fancyvrb.sty``'s documentation for further keys.
+
+ .. versionadded:: 1.5
+ formerly, the use of ``\small`` for code listings was not customizable.
- miscellaneous colours: *TitleColor*, *InnerLinkColor*, *OuterLinkColor*,
*VerbatimColor* (this is a background colour), *VerbatimBorderColor*.
- the ``\sphinxAtStartFootnote`` is inserted between footnote numbers and their
diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty
index e7e319c4f..b3218c818 100644
--- a/sphinx/texinputs/sphinx.sty
+++ b/sphinx/texinputs/sphinx.sty
@@ -42,6 +42,7 @@
}
% For highlighted code.
\RequirePackage{fancyvrb}
+\fvset{fontsize=\small}
% For table captions.
\RequirePackage{threeparttable}
% Handle footnotes in tables.
@@ -400,7 +401,6 @@
\MakeFramed {% adapted over from framed.sty's snugshade environment
\advance\hsize-\width\@totalleftmargin\z@\linewidth\hsize\@setminipage
}%
- \small
% For grid placement from \strut's in \FancyVerbFormatLine
\lineskip\z@skip
% will fetch its optional arguments if any
From 1eaa412372d72bfd5b866aca47934517be55fd1d Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Thu, 30 Jun 2016 20:06:18 +0900
Subject: [PATCH 169/217] Fix CHANGES for PR#2650 (again)
---
CHANGES | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/CHANGES b/CHANGES
index 8a8cd81db..4b158ddbb 100644
--- a/CHANGES
+++ b/CHANGES
@@ -52,7 +52,7 @@ Features added
* #2597: Show warning messages as darkred
* latex, allow image dimensions using px unit (default is 96px=1in)
* Show warnings if invalid dimension units found
-* #2650: Add ``--warning-is-error`` option to setup.py command
+* #2650: Add ``--pdf`` option to setup.py command
* latex, make the use of ``\small`` for code listings customizable (ref #2721)
* #2663: Add ``--warning-is-error`` option to setup.py command
From b25dc5ef4cc526d75bf1834303282249ca398914 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Wed, 29 Jun 2016 14:25:58 +0200
Subject: [PATCH 170/217] Fix #2723: extra spaces in latex pdf output from
multirow cell
Adds some ``\relax``/``\unskip`` and removes spaces from ``visit_entry``
generated latex code. Earlier, multirow cell inherited one extra space
token at begin and one at end, making left or right alignment with other
cells fail because the native LaTeX space removal mechanism for table
cells could not apply there.
Memo: the ``\eqparbox`` part of ``visit_entry`` from e41f831f is left
untouched; separate analysis required.
---
sphinx/writers/latex.py | 30 +++++++++++++++---------------
1 file changed, 15 insertions(+), 15 deletions(-)
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index a3477c9c6..21368a5a0 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -1121,28 +1121,28 @@ class LaTeXTranslator(nodes.NodeVisitor):
self.remember_multirow[self.table.col] -= 1
if self.remember_multirowcol.get(self.table.col, 0):
extracols = self.remember_multirowcol[self.table.col]
- self.body.append(' \\multicolumn{')
+ self.body.append('\\multicolumn{')
self.body.append(str(extracols + 1))
- self.body.append('}{|l|}{}')
+ self.body.append('}{|l|}{}\\relax ')
self.table.col += extracols
- self.body.append(' & ')
+ self.body.append('&')
else:
- self.body.append(' & ')
+ self.body.append('&')
self.table.col += 1
context = ''
if 'morecols' in node:
- self.body.append(' \\multicolumn{')
+ self.body.append('\\multicolumn{')
self.body.append(str(node.get('morecols') + 1))
if self.table.col == 1:
- self.body.append('}{|l|}{')
+ self.body.append('}{|l|}{\\relax ')
else:
- self.body.append('}{l|}{')
- context += '}'
+ self.body.append('}{l|}{\\relax ')
+ context += '\\unskip}\\relax '
if 'morerows' in node:
- self.body.append(' \\multirow{')
+ self.body.append('\\multirow{')
self.body.append(str(node.get('morerows') + 1))
- self.body.append('}{*}{')
- context += '}'
+ self.body.append('}{*}{\\relax ')
+ context += '\\unskip}\\relax '
self.remember_multirow[self.table.col] = node.get('morerows')
if 'morecols' in node:
if 'morerows' in node:
@@ -1160,16 +1160,16 @@ class LaTeXTranslator(nodes.NodeVisitor):
pass
else:
self.body.append('\\textsf{\\relax ')
- context += '}'
+ context += '\\unskip}\\relax '
while self.remember_multirow.get(self.table.col + 1, 0):
self.table.col += 1
self.remember_multirow[self.table.col] -= 1
- context += ' & '
+ context += '&'
if self.remember_multirowcol.get(self.table.col, 0):
extracols = self.remember_multirowcol[self.table.col]
- context += ' \\multicolumn{'
+ context += '\\multicolumn{'
context += str(extracols + 1)
- context += '}{l|}{}'
+ context += '}{l|}{}\\relax '
self.table.col += extracols
if len(node.traverse(nodes.paragraph)) >= 2:
self.table.has_problematic = True
From 6f058ba173712f260b37c600d0a0bd94438b59d0 Mon Sep 17 00:00:00 2001
From: Sean Farley
Date: Sat, 11 Jun 2016 13:52:12 -0700
Subject: [PATCH 171/217] inspect: return obj.__dict__[name] if there is an
exception
When using a cached property, Sphinx tries to access the actual property
of an object which raises NotImplementedError. In these cases, we fall
back to inspecting the __dict__ and returning that instead.
---
sphinx/util/inspect.py | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/sphinx/util/inspect.py b/sphinx/util/inspect.py
index dbd578ec4..1c6e4e151 100644
--- a/sphinx/util/inspect.py
+++ b/sphinx/util/inspect.py
@@ -108,6 +108,10 @@ def safe_getattr(obj, name, *defargs):
try:
return getattr(obj, name, *defargs)
except Exception:
+ # sometimes accessing a property raises an exception (e.g.
+ # NotImplementedError), so let's try to read the attribute directly
+ if name in obj.__dict__:
+ return obj.__dict__[name]
# this is a catch-all for all the weird things that some modules do
# with attribute access
if defargs:
From 2b85a2a3bea08c370d574fc27d31567cc7fa664d Mon Sep 17 00:00:00 2001
From: mixmastamyk
Date: Thu, 30 Jun 2016 13:51:34 -0700
Subject: [PATCH 172/217] Update epub.py
---
sphinx/builders/epub.py | 1 +
1 file changed, 1 insertion(+)
diff --git a/sphinx/builders/epub.py b/sphinx/builders/epub.py
index cc839d757..378072701 100644
--- a/sphinx/builders/epub.py
+++ b/sphinx/builders/epub.py
@@ -152,6 +152,7 @@ MEDIA_TYPES = {
'.jpeg': 'image/jpeg',
'.otf': 'application/x-font-otf',
'.ttf': 'application/x-font-ttf',
+ '.woff': 'application/font-woff',
}
VECTOR_GRAPHICS_EXTENSIONS = ('.svg',)
From c80db568ebf1b3f64336752f9910a74d6c4a4249 Mon Sep 17 00:00:00 2001
From: mixmastamyk
Date: Thu, 30 Jun 2016 13:57:25 -0700
Subject: [PATCH 173/217] Update CHANGES
---
CHANGES | 1 +
1 file changed, 1 insertion(+)
diff --git a/CHANGES b/CHANGES
index b208265b5..ab3432fac 100644
--- a/CHANGES
+++ b/CHANGES
@@ -18,6 +18,7 @@ Features added
lets macros (for text styling) be defined only with ``\sphinx``-prefixed names.
* latex writer allows user customization of "shadowed" boxes (topics), via
three length variables.
+* woff-format web font files now supported by the epub builder.
Bugs fixed
----------
From 5a034854326cb114597d92d3f5a00e757821745b Mon Sep 17 00:00:00 2001
From: mixmastamyk
Date: Thu, 30 Jun 2016 19:49:09 -0700
Subject: [PATCH 174/217] Update epub.py
rm trailing whitespace
---
sphinx/builders/epub.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/sphinx/builders/epub.py b/sphinx/builders/epub.py
index 378072701..faa587a17 100644
--- a/sphinx/builders/epub.py
+++ b/sphinx/builders/epub.py
@@ -152,7 +152,7 @@ MEDIA_TYPES = {
'.jpeg': 'image/jpeg',
'.otf': 'application/x-font-otf',
'.ttf': 'application/x-font-ttf',
- '.woff': 'application/font-woff',
+ '.woff': 'application/font-woff',
}
VECTOR_GRAPHICS_EXTENSIONS = ('.svg',)
From 35214d45185ad88de4f8833a455a304207235064 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Fri, 1 Jul 2016 19:15:31 +0200
Subject: [PATCH 175/217] Fix #2733: ``make latexpdf`` generates lots of
hyperref warnings
---
CHANGES | 1 +
sphinx/texinputs/sphinxmanual.cls | 2 +-
2 files changed, 2 insertions(+), 1 deletion(-)
diff --git a/CHANGES b/CHANGES
index ab3432fac..94e1bbc1e 100644
--- a/CHANGES
+++ b/CHANGES
@@ -35,6 +35,7 @@ Bugs fixed
* #2722: C++, fix id generation for var/member declarations to include namespaces.
* latex, images (from image directive) in lists or quoted blocks did not obey
indentation (fixed together with #2671)
+* #2733: since Sphinx-1.4.4 ``make latexpdf`` generates lots of hyperref warnings
Release 1.4.4 (released Jun 12, 2016)
diff --git a/sphinx/texinputs/sphinxmanual.cls b/sphinx/texinputs/sphinxmanual.cls
index 69d057343..898afe3ac 100644
--- a/sphinx/texinputs/sphinxmanual.cls
+++ b/sphinx/texinputs/sphinxmanual.cls
@@ -97,7 +97,7 @@
\pagenumbering{arabic}%
\ifdefined\fancyhf\pagestyle{normal}\fi
}
-%\pagenumbering{alph}%
+\pagenumbering{alph}% avoid hyperref "duplicate destination" warnings
% This is needed to get the width of the section # area wide enough in the
% library reference. Doing it here keeps it the same for all the manuals.
From e6b545c2f2a1e2c4f8860ff80b23003238e1fb98 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sat, 2 Jul 2016 10:26:57 +0900
Subject: [PATCH 176/217] Update CHANGES for PR#2731
---
CHANGES | 2 ++
1 file changed, 2 insertions(+)
diff --git a/CHANGES b/CHANGES
index 94e1bbc1e..24a3f39d8 100644
--- a/CHANGES
+++ b/CHANGES
@@ -36,6 +36,8 @@ Bugs fixed
* latex, images (from image directive) in lists or quoted blocks did not obey
indentation (fixed together with #2671)
* #2733: since Sphinx-1.4.4 ``make latexpdf`` generates lots of hyperref warnings
+* #2731: `sphinx.ext.autodoc` does not access propertymethods which raises any
+ exceptions
Release 1.4.4 (released Jun 12, 2016)
From 2ebeff67765a14fb35b18d4e75d5234a1eef93fb Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sat, 2 Jul 2016 10:29:26 +0900
Subject: [PATCH 177/217] Fix CHANGES
---
CHANGES | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/CHANGES b/CHANGES
index 24a3f39d8..c62472244 100644
--- a/CHANGES
+++ b/CHANGES
@@ -38,6 +38,9 @@ Bugs fixed
* #2733: since Sphinx-1.4.4 ``make latexpdf`` generates lots of hyperref warnings
* #2731: `sphinx.ext.autodoc` does not access propertymethods which raises any
exceptions
+* #2666: C++, properly look up nested names involving constructors.
+* #2579: Could not refer a label including both spaces and colons via
+ `sphinx.ext.intersphinx`
Release 1.4.4 (released Jun 12, 2016)
@@ -63,9 +66,6 @@ Bugs fixed
* #2639: Sphinx now bundles iftex.sty
* Failed to build PDF with framed.sty 0.95
* Sphinx now bundles needspace.sty
-* #2666: C++, properly look up nested names involving constructors.
-* #2579: Could not refer a label including both spaces and colons via
- `sphinx.ext.intersphinx`
Release 1.4.3 (released Jun 5, 2016)
From b30d4f488284bfeaf3979d2c58a3582c2927ddb0 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sat, 2 Jul 2016 13:54:45 +0900
Subject: [PATCH 178/217] Fix #2718: Sphinx crashes if the document file is not
readable
---
CHANGES | 1 +
sphinx/application.py | 7 +++----
sphinx/environment.py | 9 +++++++--
3 files changed, 11 insertions(+), 6 deletions(-)
diff --git a/CHANGES b/CHANGES
index c62472244..69ecd4959 100644
--- a/CHANGES
+++ b/CHANGES
@@ -41,6 +41,7 @@ Bugs fixed
* #2666: C++, properly look up nested names involving constructors.
* #2579: Could not refer a label including both spaces and colons via
`sphinx.ext.intersphinx`
+* #2718: Sphinx crashes if the document file is not readable
Release 1.4.4 (released Jun 12, 2016)
diff --git a/sphinx/application.py b/sphinx/application.py
index 6bb35a08a..5fa018210 100644
--- a/sphinx/application.py
+++ b/sphinx/application.py
@@ -239,8 +239,8 @@ class Sphinx(object):
def _init_env(self, freshenv):
if freshenv:
- self.env = BuildEnvironment(self.srcdir, self.doctreedir,
- self.config)
+ self.env = BuildEnvironment(self.srcdir, self.doctreedir, self.config)
+ self.env.set_warnfunc(self.warn)
self.env.find_files(self.config)
for domain in self.domains.keys():
self.env.domains[domain] = self.domains[domain](self.env)
@@ -249,6 +249,7 @@ class Sphinx(object):
self.info(bold('loading pickled environment... '), nonl=True)
self.env = BuildEnvironment.frompickle(
self.srcdir, self.config, path.join(self.doctreedir, ENV_PICKLE_FILENAME))
+ self.env.set_warnfunc(self.warn)
self.env.domains = {}
for domain in self.domains.keys():
# this can raise if the data version doesn't fit
@@ -261,8 +262,6 @@ class Sphinx(object):
self.info('failed: %s' % err)
return self._init_env(freshenv=True)
- self.env.set_warnfunc(self.warn)
-
def _init_builder(self, buildername):
if buildername is None:
print('No builder selected, using default: html', file=self._status)
diff --git a/sphinx/environment.py b/sphinx/environment.py
index 0ff9b781a..e71d8c585 100644
--- a/sphinx/environment.py
+++ b/sphinx/environment.py
@@ -409,8 +409,13 @@ class BuildEnvironment:
config.html_extra_path +
['**/_sources', '.#*', '**/.#*', '*.lproj/**']
)
- self.found_docs = set(get_matching_docs(
- self.srcdir, config.source_suffix, exclude_matchers=matchers))
+ self.found_docs = set()
+ for docname in get_matching_docs(self.srcdir, config.source_suffix,
+ exclude_matchers=matchers):
+ if os.access(self.doc2path(docname), os.R_OK):
+ self.found_docs.add(docname)
+ else:
+ self.warn(docname, "document not readable. Ignored.")
# add catalog mo file dependency
for docname in self.found_docs:
From 1142a7f43ff16623503aabd160700239ba51ecbf Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sat, 2 Jul 2016 14:14:17 +0900
Subject: [PATCH 179/217] Fix CHANGES for #2650 (again)
---
CHANGES | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/CHANGES b/CHANGES
index 4b158ddbb..59659bd6a 100644
--- a/CHANGES
+++ b/CHANGES
@@ -52,7 +52,7 @@ Features added
* #2597: Show warning messages as darkred
* latex, allow image dimensions using px unit (default is 96px=1in)
* Show warnings if invalid dimension units found
-* #2650: Add ``--pdf`` option to setup.py command
+* #2650: Add ``--pdb`` option to setup.py command
* latex, make the use of ``\small`` for code listings customizable (ref #2721)
* #2663: Add ``--warning-is-error`` option to setup.py command
From bd2ad1bc687425768f16f3dd47cd960cee0d162e Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sat, 2 Jul 2016 14:30:38 +0900
Subject: [PATCH 180/217] Fix #2699: hyperlinks in help HTMLs are broken if
`html_file_suffix` is set
---
CHANGES | 1 +
sphinx/builders/applehelp.py | 1 +
sphinx/builders/devhelp.py | 1 +
sphinx/builders/htmlhelp.py | 1 +
sphinx/builders/qthelp.py | 1 +
5 files changed, 5 insertions(+)
diff --git a/CHANGES b/CHANGES
index 69ecd4959..4748a3a29 100644
--- a/CHANGES
+++ b/CHANGES
@@ -42,6 +42,7 @@ Bugs fixed
* #2579: Could not refer a label including both spaces and colons via
`sphinx.ext.intersphinx`
* #2718: Sphinx crashes if the document file is not readable
+* #2699: hyperlinks in help HTMLs are broken if `html_file_suffix` is set
Release 1.4.4 (released Jun 12, 2016)
diff --git a/sphinx/builders/applehelp.py b/sphinx/builders/applehelp.py
index 53a0c99ad..ee5c1ada6 100644
--- a/sphinx/builders/applehelp.py
+++ b/sphinx/builders/applehelp.py
@@ -84,6 +84,7 @@ class AppleHelpBuilder(StandaloneHTMLBuilder):
super(AppleHelpBuilder, self).init()
# the output files for HTML help must be .html only
self.out_suffix = '.html'
+ self.link_suffix = '.html'
if self.config.applehelp_bundle_id is None:
raise SphinxError('You must set applehelp_bundle_id before '
diff --git a/sphinx/builders/devhelp.py b/sphinx/builders/devhelp.py
index 62e2c9843..523941110 100644
--- a/sphinx/builders/devhelp.py
+++ b/sphinx/builders/devhelp.py
@@ -59,6 +59,7 @@ class DevhelpBuilder(StandaloneHTMLBuilder):
def init(self):
StandaloneHTMLBuilder.init(self)
self.out_suffix = '.html'
+ self.link_suffix = '.html'
def handle_finish(self):
self.build_devhelp(self.outdir, self.config.devhelp_basename)
diff --git a/sphinx/builders/htmlhelp.py b/sphinx/builders/htmlhelp.py
index 405e4f01b..f1626321e 100644
--- a/sphinx/builders/htmlhelp.py
+++ b/sphinx/builders/htmlhelp.py
@@ -183,6 +183,7 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder):
StandaloneHTMLBuilder.init(self)
# the output files for HTML help must be .html only
self.out_suffix = '.html'
+ self.link_suffix = '.html'
# determine the correct locale setting
locale = chm_locales.get(self.config.language)
if locale is not None:
diff --git a/sphinx/builders/qthelp.py b/sphinx/builders/qthelp.py
index 0a7e85c92..e02985b94 100644
--- a/sphinx/builders/qthelp.py
+++ b/sphinx/builders/qthelp.py
@@ -111,6 +111,7 @@ class QtHelpBuilder(StandaloneHTMLBuilder):
StandaloneHTMLBuilder.init(self)
# the output files for HTML help must be .html only
self.out_suffix = '.html'
+ self.link_suffix = '.html'
# self.config.html_style = 'traditional.css'
def handle_finish(self):
From 7796a553d36b793f0b4d29907c704e6161d24e00 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Sat, 2 Jul 2016 07:41:43 +0200
Subject: [PATCH 181/217] Update CHANGES for PR#2726
---
CHANGES | 1 +
1 file changed, 1 insertion(+)
diff --git a/CHANGES b/CHANGES
index 4748a3a29..10641e589 100644
--- a/CHANGES
+++ b/CHANGES
@@ -43,6 +43,7 @@ Bugs fixed
`sphinx.ext.intersphinx`
* #2718: Sphinx crashes if the document file is not readable
* #2699: hyperlinks in help HTMLs are broken if `html_file_suffix` is set
+* #2723: extra spaces in latex pdf output from multirow cell
Release 1.4.4 (released Jun 12, 2016)
From d57b395502ce4a63c8896996225ea4cb4ae55783 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sat, 2 Jul 2016 16:35:16 +0900
Subject: [PATCH 182/217] Add a release signature to README (ref: #2612)
---
README.rst | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/README.rst b/README.rst
index 391d0bd1a..384e2cc6a 100644
--- a/README.rst
+++ b/README.rst
@@ -33,6 +33,12 @@ Install from cloned source as editable::
pip install -e .
+Release signatures
+==================
+
+Releases are signed with `498D6B9E `_
+
+
Reading the docs
================
From 0ecfa8e8e957982cd0a2b398d8cb1e33e48f7c0f Mon Sep 17 00:00:00 2001
From: jfbu
Date: Sat, 2 Jul 2016 10:54:00 +0200
Subject: [PATCH 183/217] Fix #2735: latexpdf ``Underfull \hbox`` warnings from
title page
This came from the spurious space tokens following a fullwidth rule at
top of ``\maketitle`` in ``sphinxhowto.cls`` and ``sphinxmanual.cls``.
The ``\newline\null\par`` incantation recreates the extra empty line
which originated in these spurious space tokens, but it avoids the
Underfull latex warning. Nothing is changed to layout from this fix.
---
CHANGES | 1 +
sphinx/texinputs/sphinxhowto.cls | 10 +++++-----
sphinx/texinputs/sphinxmanual.cls | 8 ++++----
3 files changed, 10 insertions(+), 9 deletions(-)
diff --git a/CHANGES b/CHANGES
index 10641e589..4a4b74c04 100644
--- a/CHANGES
+++ b/CHANGES
@@ -44,6 +44,7 @@ Bugs fixed
* #2718: Sphinx crashes if the document file is not readable
* #2699: hyperlinks in help HTMLs are broken if `html_file_suffix` is set
* #2723: extra spaces in latex pdf output from multirow cell
+* #2735: latexpdf ``Underfull \hbox (badness 10000)`` warnings from title page
Release 1.4.4 (released Jun 12, 2016)
diff --git a/sphinx/texinputs/sphinxhowto.cls b/sphinx/texinputs/sphinxhowto.cls
index 193e36734..80d69fb7e 100644
--- a/sphinx/texinputs/sphinxhowto.cls
+++ b/sphinx/texinputs/sphinxhowto.cls
@@ -35,19 +35,19 @@
% Change the title page to look a bit better, and fit in with the fncychap
% ``Bjarne'' style a bit better.
%
-\renewcommand{\maketitle}{
- \rule{\textwidth}{1pt}
+\renewcommand{\maketitle}{%
+ \noindent\rule{\textwidth}{1pt}\newline\null\par
\ifsphinxpdfoutput
\begingroup
% These \defs are required to deal with multi-line authors; it
% changes \\ to ', ' (comma-space), making it pass muster for
% generating document info in the PDF file.
- \def\\{, }
- \def\and{and }
+ \def\\{, }%
+ \def\and{and }%
\pdfinfo{
/Author (\@author)
/Title (\@title)
- }
+ }%
\endgroup
\fi
\begin{flushright}
diff --git a/sphinx/texinputs/sphinxmanual.cls b/sphinx/texinputs/sphinxmanual.cls
index 898afe3ac..31a57b851 100644
--- a/sphinx/texinputs/sphinxmanual.cls
+++ b/sphinx/texinputs/sphinxmanual.cls
@@ -43,18 +43,18 @@
\begin{titlepage}%
\let\footnotesize\small
\let\footnoterule\relax
- \rule{\textwidth}{1pt}%
+ \noindent\rule{\textwidth}{1pt}\newline\null\par
\ifsphinxpdfoutput
\begingroup
% These \defs are required to deal with multi-line authors; it
% changes \\ to ', ' (comma-space), making it pass muster for
% generating document info in the PDF file.
- \def\\{, }
- \def\and{and }
+ \def\\{, }%
+ \def\and{and }%
\pdfinfo{
/Author (\@author)
/Title (\@title)
- }
+ }%
\endgroup
\fi
\begin{flushright}%
From 8eecdbd7155782d8b1b854e254417e40498c8434 Mon Sep 17 00:00:00 2001
From: Rob Ruana
Date: Sat, 2 Jul 2016 11:43:55 -0400
Subject: [PATCH 184/217] [Napoleon] Removes Python 2/3 compatible type
annotation doc example, because they aren't current supported by Sphinx
---
doc/ext/napoleon.rst | 22 ++++------------------
1 file changed, 4 insertions(+), 18 deletions(-)
diff --git a/doc/ext/napoleon.rst b/doc/ext/napoleon.rst
index 8b11ab98e..ea3e4042f 100644
--- a/doc/ext/napoleon.rst
+++ b/doc/ext/napoleon.rst
@@ -213,24 +213,6 @@ Google style with Python 3 type annotations::
"""
return True
-Google style with `Python 2/3 compatible annotations`_::
-
- def func(arg1, arg2):
- # type: (int, str) -> bool
- """Summary line.
-
- Extended description of function.
-
- Args:
- arg1: Description of arg1
- arg2: Description of arg2
-
- Returns:
- Description of return value
-
- """
- return True
-
Google style with types in docstrings::
def func(arg1, arg2):
@@ -248,6 +230,10 @@ Google style with types in docstrings::
"""
return True
+.. Note::
+ `Python 2/3 compatible annotations`_ aren't currently
+ supported by Sphinx and won't show up in the docs.
+
.. _PEP 484:
https://www.python.org/dev/peps/pep-0484/
From 00af06af8f0755b930f464150e729ac2e32044e7 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Mon, 30 May 2016 20:20:50 +0900
Subject: [PATCH 185/217] latex: Separate stylesheets of pygments to .sty file
To improve readability of generated LaTeX source code, separate
stylesheets of pygments into independent .sty file.
---
CHANGES | 1 +
sphinx/builders/latex.py | 13 ++++++++++++-
sphinx/texinputs/sphinx.sty | 3 +++
sphinx/writers/latex.py | 1 -
4 files changed, 16 insertions(+), 2 deletions(-)
diff --git a/CHANGES b/CHANGES
index 66242c4f8..871fbdce4 100644
--- a/CHANGES
+++ b/CHANGES
@@ -17,6 +17,7 @@ Incompatible changes
``height`` attribute of an image.
* latex, if ``width`` or ``height`` attribute of an image is given with no unit,
use ``px`` rather than ignore it.
+* latex: Separate stylesheets of pygments to independent .sty file
Features added
diff --git a/sphinx/builders/latex.py b/sphinx/builders/latex.py
index ac26e33c9..f864a58c8 100644
--- a/sphinx/builders/latex.py
+++ b/sphinx/builders/latex.py
@@ -19,7 +19,7 @@ from docutils.io import FileOutput
from docutils.utils import new_document
from docutils.frontend import OptionParser
-from sphinx import package_dir, addnodes
+from sphinx import package_dir, addnodes, highlighting
from sphinx.util import texescape
from sphinx.errors import SphinxError
from sphinx.locale import _
@@ -92,6 +92,16 @@ class LaTeXBuilder(Builder):
docname = docname[:-5]
self.titles.append((docname, entry[2]))
+ def write_stylesheet(self):
+ highlighter = highlighting.PygmentsBridge(
+ 'latex', self.config.pygments_style, self.config.trim_doctest_flags)
+ stylesheet = path.join(self.outdir, 'sphinxhighlight.sty')
+ with open(stylesheet, 'w') as f:
+ f.write('\\NeedsTeXFormat{LaTeX2e}[1995/12/01]\n')
+ f.write('\\ProvidesPackage{sphinxhighlight}'
+ '[2016/05/29 stylesheet for highlighting with pygments]\n\n')
+ f.write(highlighter.get_stylesheet())
+
def write(self, *ignored):
docwriter = LaTeXWriter(self)
docsettings = OptionParser(
@@ -100,6 +110,7 @@ class LaTeXBuilder(Builder):
read_config_files=True).get_default_values()
self.init_document_data()
+ self.write_stylesheet()
for entry in self.document_data:
docname, targetname, title, author, docclass = entry[:5]
diff --git a/sphinx/texinputs/sphinx.sty b/sphinx/texinputs/sphinx.sty
index b3218c818..e612cf5ef 100644
--- a/sphinx/texinputs/sphinx.sty
+++ b/sphinx/texinputs/sphinx.sty
@@ -1024,3 +1024,6 @@
\newcommand{\sphinxstyleliteralstrong}[1]{\textbf{\texttt{#1}}}
\newcommand*{\sphinxstyleabbreviation}{\textsc}
\newcommand*{\sphinxstyleliteralintitle}{\texttt}
+
+% stylesheet for highlighting with pygments
+\RequirePackage{sphinxhighlight}
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index 97d85ec25..528aca192 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -544,7 +544,6 @@ class LaTeXTranslator(nodes.NodeVisitor):
def astext(self):
return (HEADER % self.elements +
- self.highlighter.get_stylesheet() +
u''.join(self.body) +
'\n' + self.elements['footer'] + '\n' +
self.generate_indices() +
From 16e1378bcaad74134e963efbf6a3cb5f943c1721 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 3 Jul 2016 12:11:36 +0900
Subject: [PATCH 186/217] Refactor sphinx.domains.std: Separate xref resolvers
to each types
---
sphinx/domains/std.py | 197 +++++++++++++++++++++++-------------------
1 file changed, 106 insertions(+), 91 deletions(-)
diff --git a/sphinx/domains/std.py b/sphinx/domains/std.py
index 997d95ba3..de93ebf28 100644
--- a/sphinx/domains/std.py
+++ b/sphinx/domains/std.py
@@ -585,106 +585,121 @@ class StandardDomain(Domain):
newnode.append(innernode)
return newnode
- def resolve_xref(self, env, fromdocname, builder,
- typ, target, node, contnode):
+ def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
if typ == 'ref':
- if node['refexplicit']:
- # reference to anonymous label; the reference uses
- # the supplied link caption
- docname, labelid = self.data['anonlabels'].get(target, ('', ''))
- sectname = node.astext()
- else:
- # reference to named label; the final node will
- # contain the section name after the label
- docname, labelid, sectname = self.data['labels'].get(target,
- ('', '', ''))
- if not docname:
- return None
-
- return self.build_reference_node(fromdocname, builder,
- docname, labelid, sectname, 'ref')
+ resolver = self._resolve_ref_xref
elif typ == 'numref':
- docname, labelid = self.data['anonlabels'].get(target, ('', ''))
- if not docname:
- return None
-
- if env.config.numfig is False:
- env.warn(fromdocname, 'numfig is disabled. :numref: is ignored.',
- lineno=node.line)
- return contnode
-
- target_node = env.get_doctree(docname).ids.get(labelid)
- figtype = self.get_figtype(target_node)
- if figtype is None:
- return None
-
- try:
- figure_id = target_node['ids'][0]
- fignumber = env.toc_fignumbers[docname][figtype][figure_id]
- except (KeyError, IndexError):
- # target_node is found, but fignumber is not assigned.
- # Maybe it is defined in orphaned document.
- env.warn(fromdocname, "no number is assigned for %s: %s" % (figtype, labelid),
- lineno=node.line)
- return contnode
-
- title = contnode.astext()
- if target == fully_normalize_name(title):
- title = env.config.numfig_format.get(figtype, '')
-
- try:
- newtitle = title % '.'.join(map(str, fignumber))
- except TypeError:
- env.warn(fromdocname, 'invalid numfig_format: %s' % title,
- lineno=node.line)
- return None
-
- return self.build_reference_node(fromdocname, builder,
- docname, labelid, newtitle, 'numref',
- nodeclass=addnodes.number_reference,
- title=title)
+ resolver = self._resolve_numref_xref
elif typ == 'keyword':
- # keywords are oddballs: they are referenced by named labels
- docname, labelid, _ = self.data['labels'].get(target, ('', '', ''))
- if not docname:
- return None
- return make_refnode(builder, fromdocname, docname,
- labelid, contnode)
+ resolver = self._resolve_keyword_xref
elif typ == 'option':
- progname = node.get('std:program')
- target = target.strip()
- docname, labelid = self.data['progoptions'].get((progname, target), ('', ''))
- if not docname:
- commands = []
- while ws_re.search(target):
- subcommand, target = ws_re.split(target, 1)
- commands.append(subcommand)
- progname = "-".join(commands)
-
- docname, labelid = self.data['progoptions'].get((progname, target),
- ('', ''))
- if docname:
- break
- else:
- return None
-
- return make_refnode(builder, fromdocname, docname,
- labelid, contnode)
+ resolver = self._resolve_option_xref
else:
- objtypes = self.objtypes_for_role(typ) or []
- for objtype in objtypes:
- if (objtype, target) in self.data['objects']:
- docname, labelid = self.data['objects'][objtype, target]
+ resolver = self._resolve_obj_xref
+
+ return resolver(env, fromdocname, builder, typ, target, node, contnode)
+
+ def _resolve_ref_xref(self, env, fromdocname, builder, typ, target, node, contnode):
+ if node['refexplicit']:
+ # reference to anonymous label; the reference uses
+ # the supplied link caption
+ docname, labelid = self.data['anonlabels'].get(target, ('', ''))
+ sectname = node.astext()
+ else:
+ # reference to named label; the final node will
+ # contain the section name after the label
+ docname, labelid, sectname = self.data['labels'].get(target,
+ ('', '', ''))
+ if not docname:
+ return None
+
+ return self.build_reference_node(fromdocname, builder,
+ docname, labelid, sectname, 'ref')
+
+ def _resolve_numref_xref(self, env, fromdocname, builder, typ, target, node, contnode):
+ docname, labelid = self.data['anonlabels'].get(target, ('', ''))
+ if not docname:
+ return None
+
+ if env.config.numfig is False:
+ env.warn(fromdocname, 'numfig is disabled. :numref: is ignored.',
+ lineno=node.line)
+ return contnode
+
+ target_node = env.get_doctree(docname).ids.get(labelid)
+ figtype = self.get_figtype(target_node)
+ if figtype is None:
+ return None
+
+ try:
+ figure_id = target_node['ids'][0]
+ fignumber = env.toc_fignumbers[docname][figtype][figure_id]
+ except (KeyError, IndexError):
+ # target_node is found, but fignumber is not assigned.
+ # Maybe it is defined in orphaned document.
+ env.warn(fromdocname, "no number is assigned for %s: %s" % (figtype, labelid),
+ lineno=node.line)
+ return contnode
+
+ title = contnode.astext()
+ if target == fully_normalize_name(title):
+ title = env.config.numfig_format.get(figtype, '')
+
+ try:
+ newtitle = title % '.'.join(map(str, fignumber))
+ except TypeError:
+ env.warn(fromdocname, 'invalid numfig_format: %s' % title,
+ lineno=node.line)
+ return None
+
+ return self.build_reference_node(fromdocname, builder,
+ docname, labelid, newtitle, 'numref',
+ nodeclass=addnodes.number_reference,
+ title=title)
+
+ def _resolve_keyword_xref(self, env, fromdocname, builder, typ, target, node, contnode):
+ # keywords are oddballs: they are referenced by named labels
+ docname, labelid, _ = self.data['labels'].get(target, ('', '', ''))
+ if not docname:
+ return None
+ return make_refnode(builder, fromdocname, docname,
+ labelid, contnode)
+
+ def _resolve_option_xref(self, env, fromdocname, builder, typ, target, node, contnode):
+ progname = node.get('std:program')
+ target = target.strip()
+ docname, labelid = self.data['progoptions'].get((progname, target), ('', ''))
+ if not docname:
+ commands = []
+ while ws_re.search(target):
+ subcommand, target = ws_re.split(target, 1)
+ commands.append(subcommand)
+ progname = "-".join(commands)
+
+ docname, labelid = self.data['progoptions'].get((progname, target),
+ ('', ''))
+ if docname:
break
else:
- docname, labelid = '', ''
- if not docname:
return None
- return make_refnode(builder, fromdocname, docname,
- labelid, contnode)
- def resolve_any_xref(self, env, fromdocname, builder, target,
- node, contnode):
+ return make_refnode(builder, fromdocname, docname,
+ labelid, contnode)
+
+ def _resolve_obj_xref(self, env, fromdocname, builder, typ, target, node, contnode):
+ objtypes = self.objtypes_for_role(typ) or []
+ for objtype in objtypes:
+ if (objtype, target) in self.data['objects']:
+ docname, labelid = self.data['objects'][objtype, target]
+ break
+ else:
+ docname, labelid = '', ''
+ if not docname:
+ return None
+ return make_refnode(builder, fromdocname, docname,
+ labelid, contnode)
+
+ def resolve_any_xref(self, env, fromdocname, builder, target, node, contnode):
results = []
ltarget = target.lower() # :ref: lowercases its target automatically
for role in ('ref', 'option'): # do not try "keyword"
From e4799323fb8d3c83704e4e816dffb82d5bb93f8f Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 3 Jul 2016 13:22:20 +0900
Subject: [PATCH 187/217] Refactor: refer refexplicit attr on fetching title
---
sphinx/domains/std.py | 9 +++++----
1 file changed, 5 insertions(+), 4 deletions(-)
diff --git a/sphinx/domains/std.py b/sphinx/domains/std.py
index de93ebf28..8bdd3c09c 100644
--- a/sphinx/domains/std.py
+++ b/sphinx/domains/std.py
@@ -641,11 +641,12 @@ class StandardDomain(Domain):
lineno=node.line)
return contnode
- title = contnode.astext()
- if target == fully_normalize_name(title):
- title = env.config.numfig_format.get(figtype, '')
-
try:
+ if node['refexplicit']:
+ title = contnode.astext()
+ else:
+ title = env.config.numfig_format.get(figtype, '')
+
newtitle = title % '.'.join(map(str, fignumber))
except TypeError:
env.warn(fromdocname, 'invalid numfig_format: %s' % title,
From 5c83d84d76627acafed7a41d2c1f843db8a9b902 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 3 Jul 2016 13:36:50 +0900
Subject: [PATCH 188/217] Fix flake8 violation
---
sphinx/domains/std.py | 1 -
1 file changed, 1 deletion(-)
diff --git a/sphinx/domains/std.py b/sphinx/domains/std.py
index 8bdd3c09c..b1939be82 100644
--- a/sphinx/domains/std.py
+++ b/sphinx/domains/std.py
@@ -14,7 +14,6 @@ import unicodedata
from six import iteritems
from docutils import nodes
-from docutils.nodes import fully_normalize_name
from docutils.parsers.rst import directives
from docutils.statemachine import ViewList
From e355dde954de9862f7140a03e2712a0a5ba1e1ed Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 3 Jul 2016 13:50:52 +0900
Subject: [PATCH 189/217] Refactor: Use warn_node() instead of warn()
---
sphinx/domains/std.py | 9 +++------
1 file changed, 3 insertions(+), 6 deletions(-)
diff --git a/sphinx/domains/std.py b/sphinx/domains/std.py
index b1939be82..e59b41a09 100644
--- a/sphinx/domains/std.py
+++ b/sphinx/domains/std.py
@@ -621,8 +621,7 @@ class StandardDomain(Domain):
return None
if env.config.numfig is False:
- env.warn(fromdocname, 'numfig is disabled. :numref: is ignored.',
- lineno=node.line)
+ env.warn_node('numfig is disabled. :numref: is ignored.', node)
return contnode
target_node = env.get_doctree(docname).ids.get(labelid)
@@ -636,8 +635,7 @@ class StandardDomain(Domain):
except (KeyError, IndexError):
# target_node is found, but fignumber is not assigned.
# Maybe it is defined in orphaned document.
- env.warn(fromdocname, "no number is assigned for %s: %s" % (figtype, labelid),
- lineno=node.line)
+ env.warn_node("no number is assigned for %s: %s" % (figtype, labelid), node)
return contnode
try:
@@ -648,8 +646,7 @@ class StandardDomain(Domain):
newtitle = title % '.'.join(map(str, fignumber))
except TypeError:
- env.warn(fromdocname, 'invalid numfig_format: %s' % title,
- lineno=node.line)
+ env.warn_node('invalid numfig_format: %s' % title, node)
return None
return self.build_reference_node(fromdocname, builder,
From 7db8141238c5d9ce6c93d6f85c8820ed218fd158 Mon Sep 17 00:00:00 2001
From: jfbu
Date: Sun, 3 Jul 2016 10:49:05 +0200
Subject: [PATCH 190/217] Amend merged PR#2736 to maintain strict stability of
pdf title page
This maintains for the time being the diverging behaviour between
engines regarding the top of title page, as discussed at
https://github.com/sphinx-doc/sphinx/pull/2736#issuecomment-230140016
---
sphinx/texinputs/sphinxhowto.cls | 2 +-
sphinx/texinputs/sphinxmanual.cls | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/sphinx/texinputs/sphinxhowto.cls b/sphinx/texinputs/sphinxhowto.cls
index 80d69fb7e..8d5c59232 100644
--- a/sphinx/texinputs/sphinxhowto.cls
+++ b/sphinx/texinputs/sphinxhowto.cls
@@ -36,7 +36,7 @@
% ``Bjarne'' style a bit better.
%
\renewcommand{\maketitle}{%
- \noindent\rule{\textwidth}{1pt}\newline\null\par
+ \noindent\rule{\textwidth}{1pt}\ifsphinxpdfoutput\newline\null\fi\par
\ifsphinxpdfoutput
\begingroup
% These \defs are required to deal with multi-line authors; it
diff --git a/sphinx/texinputs/sphinxmanual.cls b/sphinx/texinputs/sphinxmanual.cls
index 31a57b851..f20449449 100644
--- a/sphinx/texinputs/sphinxmanual.cls
+++ b/sphinx/texinputs/sphinxmanual.cls
@@ -43,7 +43,7 @@
\begin{titlepage}%
\let\footnotesize\small
\let\footnoterule\relax
- \noindent\rule{\textwidth}{1pt}\newline\null\par
+ \noindent\rule{\textwidth}{1pt}\ifsphinxpdfoutput\newline\null\fi\par
\ifsphinxpdfoutput
\begingroup
% These \defs are required to deal with multi-line authors; it
From 7eca745b5c1fbd64ec4dd443409a32615ed40724 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 3 Jul 2016 00:58:27 +0900
Subject: [PATCH 191/217] Fix #2667: latex crashes if resized images appeared
in section title
---
CHANGES | 1 +
sphinx/writers/latex.py | 9 ++++++++-
tests/test_build_latex.py | 7 ++++---
3 files changed, 13 insertions(+), 4 deletions(-)
diff --git a/CHANGES b/CHANGES
index 4a4b74c04..ae1d52246 100644
--- a/CHANGES
+++ b/CHANGES
@@ -45,6 +45,7 @@ Bugs fixed
* #2699: hyperlinks in help HTMLs are broken if `html_file_suffix` is set
* #2723: extra spaces in latex pdf output from multirow cell
* #2735: latexpdf ``Underfull \hbox (badness 10000)`` warnings from title page
+* #2667: latex crashes if resized images appeared in section title
Release 1.4.4 (released Jun 12, 2016)
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index 21368a5a0..d46d65bb1 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -1417,7 +1417,14 @@ class LaTeXTranslator(nodes.NodeVisitor):
if include_graphics_options:
options = '[%s]' % ','.join(include_graphics_options)
base, ext = path.splitext(uri)
- self.body.append('\\sphinxincludegraphics%s{{%s}%s}' % (options, base, ext))
+ if self.in_title and base:
+ # Lowercase tokens forcely because some fncychap themes capitalize
+ # the options of \sphinxincludegraphics unexpectly (ex. WIDTH=...).
+ self.body.append('\\lowercase{\\sphinxincludegraphics%s}{{%s}%s}' %
+ (options, base, ext))
+ else:
+ self.body.append('\\sphinxincludegraphics%s{{%s}%s}' %
+ (options, base, ext))
self.body.extend(post)
def depart_image(self, node):
diff --git a/tests/test_build_latex.py b/tests/test_build_latex.py
index 4ef83165f..28899a7f4 100644
--- a/tests/test_build_latex.py
+++ b/tests/test_build_latex.py
@@ -577,11 +577,12 @@ def test_image_in_section(app, status, warning):
print(result)
print(status.getvalue())
print(warning.getvalue())
- assert ('\\chapter[Test section]'
- '{\\sphinxincludegraphics[width=15pt,height=15pt]{{pic}.png} Test section}'
+ assert ('\\chapter[Test section]{\\lowercase{\\sphinxincludegraphics'
+ '[width=15pt,height=15pt]}{{pic}.png} Test section}'
in result)
assert ('\\chapter[Other {[}blah{]} section]{Other {[}blah{]} '
- '\\sphinxincludegraphics[width=15pt,height=15pt]{{pic}.png} section}' in result)
+ '\\lowercase{\\sphinxincludegraphics[width=15pt,height=15pt]}'
+ '{{pic}.png} section}' in result)
assert ('\\chapter{Another section}' in result)
From fb7e6a22acc20bbd8c0824e22f6a89cac85281ec Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Wed, 6 Jul 2016 01:59:43 +0900
Subject: [PATCH 192/217] Update CHANGES for PR#2454
---
CHANGES | 3 +++
1 file changed, 3 insertions(+)
diff --git a/CHANGES b/CHANGES
index 871fbdce4..1f007c479 100644
--- a/CHANGES
+++ b/CHANGES
@@ -18,6 +18,9 @@ Incompatible changes
* latex, if ``width`` or ``height`` attribute of an image is given with no unit,
use ``px`` rather than ignore it.
* latex: Separate stylesheets of pygments to independent .sty file
+* #2454: The filename of sourcelink is now changed. The value of
+ `html_sourcelink_suffix` will be appended to the original filename (like
+ ``index.rst.txt``).
Features added
From 8a45aa5e59b87703803bfb44c696afd06b609335 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Mon, 4 Jul 2016 10:46:27 +0900
Subject: [PATCH 193/217] Now all builders and domains work as built-in
extensions
---
sphinx/application.py | 51 +++++++---
sphinx/builders/__init__.py | 26 -----
sphinx/builders/applehelp.py | 38 ++++++-
sphinx/builders/changes.py | 4 +
sphinx/builders/devhelp.py | 8 ++
sphinx/builders/dummy.py | 4 +
sphinx/builders/epub.py | 32 +++++-
sphinx/builders/epub3.py | 10 ++
sphinx/builders/gettext.py | 10 ++
sphinx/builders/html.py | 52 +++++++++-
sphinx/builders/htmlhelp.py | 8 ++
sphinx/builders/latex.py | 31 +++++-
sphinx/builders/linkcheck.py | 10 ++
sphinx/builders/manpage.py | 11 ++
sphinx/builders/qthelp.py | 8 ++
sphinx/builders/texinfo.py | 19 +++-
sphinx/builders/text.py | 7 ++
sphinx/builders/websupport.py | 4 +
sphinx/builders/xml.py | 7 ++
sphinx/config.py | 182 +---------------------------------
sphinx/domains/__init__.py | 17 ----
sphinx/domains/c.py | 4 +
sphinx/domains/cpp.py | 4 +
sphinx/domains/javascript.py | 4 +
sphinx/domains/python.py | 4 +
sphinx/domains/rst.py | 4 +
sphinx/domains/std.py | 4 +
27 files changed, 318 insertions(+), 245 deletions(-)
diff --git a/sphinx/application.py b/sphinx/application.py
index 09f8da065..8a23cddd7 100644
--- a/sphinx/application.py
+++ b/sphinx/application.py
@@ -32,9 +32,8 @@ from sphinx.roles import XRefRole
from sphinx.config import Config
from sphinx.errors import SphinxError, SphinxWarning, ExtensionError, \
VersionRequirementError, ConfigError
-from sphinx.domains import ObjType, BUILTIN_DOMAINS
+from sphinx.domains import ObjType
from sphinx.domains.std import GenericObject, Target, StandardDomain
-from sphinx.builders import BUILTIN_BUILDERS
from sphinx.environment import BuildEnvironment
from sphinx.io import SphinxStandaloneReader
from sphinx.util import pycompat # noqa: imported for side-effects
@@ -65,6 +64,31 @@ events = {
'html-page-context': 'pagename, context, doctree or None',
'build-finished': 'exception',
}
+builtin_extensions = (
+ 'sphinx.builders.applehelp',
+ 'sphinx.builders.changes',
+ 'sphinx.builders.epub',
+ 'sphinx.builders.epub3',
+ 'sphinx.builders.devhelp',
+ 'sphinx.builders.dummy',
+ 'sphinx.builders.gettext',
+ 'sphinx.builders.html',
+ 'sphinx.builders.htmlhelp',
+ 'sphinx.builders.latex',
+ 'sphinx.builders.linkcheck',
+ 'sphinx.builders.manpage',
+ 'sphinx.builders.qthelp',
+ 'sphinx.builders.texinfo',
+ 'sphinx.builders.text',
+ 'sphinx.builders.websupport',
+ 'sphinx.builders.xml',
+ 'sphinx.domains.c',
+ 'sphinx.domains.cpp',
+ 'sphinx.domains.javascript',
+ 'sphinx.domains.python',
+ 'sphinx.domains.rst',
+ 'sphinx.domains.std',
+)
CONFIG_FILENAME = 'conf.py'
ENV_PICKLE_FILENAME = 'environment.pickle'
@@ -87,9 +111,9 @@ class Sphinx(object):
self._additional_source_parsers = {}
self._listeners = {}
self._setting_up_extension = ['?']
- self.domains = BUILTIN_DOMAINS.copy()
+ self.domains = {}
self.buildername = buildername
- self.builderclasses = BUILTIN_BUILDERS.copy()
+ self.builderclasses = {}
self.builder = None
self.env = None
self.enumerable_nodes = {}
@@ -152,6 +176,10 @@ class Sphinx(object):
if self.confdir is None:
self.confdir = self.srcdir
+ # load all built-in extension modules
+ for extension in builtin_extensions:
+ self.setup_extension(extension)
+
# extension loading support for alabaster theme
# self.config.html_theme is not set from conf.py at here
# for now, sphinx always load a 'alabaster' extension.
@@ -274,11 +302,6 @@ class Sphinx(object):
raise SphinxError('Builder name %s not registered' % buildername)
builderclass = self.builderclasses[buildername]
- if isinstance(builderclass, tuple):
- # builtin builder
- mod, cls = builderclass
- builderclass = getattr(
- __import__('sphinx.builders.' + mod, None, None, [cls]), cls)
self.builder = builderclass(self)
self.emit('builder-inited')
@@ -570,13 +593,9 @@ class Sphinx(object):
raise ExtensionError('Builder class %s has no "name" attribute'
% builder)
if builder.name in self.builderclasses:
- if isinstance(self.builderclasses[builder.name], tuple):
- raise ExtensionError('Builder %r is a builtin builder' %
- builder.name)
- else:
- raise ExtensionError(
- 'Builder %r already exists (in module %s)' % (
- builder.name, self.builderclasses[builder.name].__module__))
+ raise ExtensionError(
+ 'Builder %r already exists (in module %s)' % (
+ builder.name, self.builderclasses[builder.name].__module__))
self.builderclasses[builder.name] = builder
def add_config_value(self, name, default, rebuild, types=()):
diff --git a/sphinx/builders/__init__.py b/sphinx/builders/__init__.py
index 8863050ba..fe0c9c665 100644
--- a/sphinx/builders/__init__.py
+++ b/sphinx/builders/__init__.py
@@ -451,29 +451,3 @@ class Builder(object):
except AttributeError:
optname = '%s_%s' % (default, option)
return getattr(self.config, optname)
-
-BUILTIN_BUILDERS = {
- 'dummy': ('dummy', 'DummyBuilder'),
- 'html': ('html', 'StandaloneHTMLBuilder'),
- 'dirhtml': ('html', 'DirectoryHTMLBuilder'),
- 'singlehtml': ('html', 'SingleFileHTMLBuilder'),
- 'pickle': ('html', 'PickleHTMLBuilder'),
- 'json': ('html', 'JSONHTMLBuilder'),
- 'web': ('html', 'PickleHTMLBuilder'),
- 'htmlhelp': ('htmlhelp', 'HTMLHelpBuilder'),
- 'devhelp': ('devhelp', 'DevhelpBuilder'),
- 'qthelp': ('qthelp', 'QtHelpBuilder'),
- 'applehelp': ('applehelp', 'AppleHelpBuilder'),
- 'epub': ('epub', 'EpubBuilder'),
- 'epub3': ('epub3', 'Epub3Builder'),
- 'latex': ('latex', 'LaTeXBuilder'),
- 'text': ('text', 'TextBuilder'),
- 'man': ('manpage', 'ManualPageBuilder'),
- 'texinfo': ('texinfo', 'TexinfoBuilder'),
- 'changes': ('changes', 'ChangesBuilder'),
- 'linkcheck': ('linkcheck', 'CheckExternalLinksBuilder'),
- 'websupport': ('websupport', 'WebSupportBuilder'),
- 'gettext': ('gettext', 'MessageCatalogBuilder'),
- 'xml': ('xml', 'XMLBuilder'),
- 'pseudoxml': ('xml', 'PseudoXMLBuilder'),
-}
diff --git a/sphinx/builders/applehelp.py b/sphinx/builders/applehelp.py
index 8116623b0..095457b80 100644
--- a/sphinx/builders/applehelp.py
+++ b/sphinx/builders/applehelp.py
@@ -13,11 +13,13 @@ from __future__ import print_function
import codecs
import pipes
-from os import path
+from os import path, environ
+import shlex
from sphinx.builders.html import StandaloneHTMLBuilder
+from sphinx.config import string_classes
from sphinx.util import copy_static_entry
-from sphinx.util.osutil import copyfile, ensuredir
+from sphinx.util.osutil import copyfile, ensuredir, make_filename
from sphinx.util.console import bold
from sphinx.util.pycompat import htmlescape
from sphinx.util.matching import compile_matchers
@@ -255,3 +257,35 @@ class AppleHelpBuilder(StandaloneHTMLBuilder):
raise AppleHelpCodeSigningFailed(output)
else:
self.info('done')
+
+
+def setup(app):
+ app.setup_extension('sphinx.builders.html')
+ app.add_builder(AppleHelpBuilder)
+
+ app.add_config_value('applehelp_bundle_name',
+ lambda self: make_filename(self.project), 'applehelp')
+ app.add_config_value('applehelp_bundle_id', None, 'applehelp', string_classes)
+ app.add_config_value('applehelp_dev_region', 'en-us', 'applehelp')
+ app.add_config_value('applehelp_bundle_version', '1', 'applehelp')
+ app.add_config_value('applehelp_icon', None, 'applehelp', string_classes)
+ app.add_config_value('applehelp_kb_product',
+ lambda self: '%s-%s' % (make_filename(self.project), self.release),
+ 'applehelp')
+ app.add_config_value('applehelp_kb_url', None, 'applehelp', string_classes)
+ app.add_config_value('applehelp_remote_url', None, 'applehelp', string_classes)
+ app.add_config_value('applehelp_index_anchors', False, 'applehelp', string_classes)
+ app.add_config_value('applehelp_min_term_length', None, 'applehelp', string_classes)
+ app.add_config_value('applehelp_stopwords',
+ lambda self: self.language or 'en', 'applehelp')
+ app.add_config_value('applehelp_locale', lambda self: self.language or 'en', 'applehelp')
+ app.add_config_value('applehelp_title', lambda self: self.project + ' Help', 'applehelp')
+ app.add_config_value('applehelp_codesign_identity',
+ lambda self: environ.get('CODE_SIGN_IDENTITY', None),
+ 'applehelp'),
+ app.add_config_value('applehelp_codesign_flags',
+ lambda self: shlex.split(environ.get('OTHER_CODE_SIGN_FLAGS', '')),
+ 'applehelp'),
+ app.add_config_value('applehelp_indexer_path', '/usr/bin/hiutil', 'applehelp')
+ app.add_config_value('applehelp_codesign_path', '/usr/bin/codesign', 'applehelp')
+ app.add_config_value('applehelp_disable_external_tools', False, None)
diff --git a/sphinx/builders/changes.py b/sphinx/builders/changes.py
index ed9edc403..18f94adca 100644
--- a/sphinx/builders/changes.py
+++ b/sphinx/builders/changes.py
@@ -154,3 +154,7 @@ class ChangesBuilder(Builder):
def finish(self):
pass
+
+
+def setup(app):
+ app.add_builder(ChangesBuilder)
diff --git a/sphinx/builders/devhelp.py b/sphinx/builders/devhelp.py
index 5382a828a..0f88e9f38 100644
--- a/sphinx/builders/devhelp.py
+++ b/sphinx/builders/devhelp.py
@@ -18,6 +18,7 @@ from os import path
from docutils import nodes
from sphinx import addnodes
+from sphinx.util.osutil import make_filename
from sphinx.builders.html import StandaloneHTMLBuilder
try:
@@ -130,3 +131,10 @@ class DevhelpBuilder(StandaloneHTMLBuilder):
# Dump the XML file
with comp_open(path.join(outdir, outname + '.devhelp'), 'w') as f:
tree.write(f, 'utf-8')
+
+
+def setup(app):
+ app.setup_extension('sphinx.builders.html')
+ app.add_builder(DevhelpBuilder)
+
+ app.add_config_value('devhelp_basename', lambda self: make_filename(self.project), None)
diff --git a/sphinx/builders/dummy.py b/sphinx/builders/dummy.py
index 75b834c2b..b119d9687 100644
--- a/sphinx/builders/dummy.py
+++ b/sphinx/builders/dummy.py
@@ -34,3 +34,7 @@ class DummyBuilder(Builder):
def finish(self):
pass
+
+
+def setup(app):
+ app.add_builder(DummyBuilder)
diff --git a/sphinx/builders/epub.py b/sphinx/builders/epub.py
index 70abf832b..e46d2cba0 100644
--- a/sphinx/builders/epub.py
+++ b/sphinx/builders/epub.py
@@ -29,7 +29,7 @@ from docutils import nodes
from sphinx import addnodes
from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.util.i18n import format_date
-from sphinx.util.osutil import ensuredir, copyfile, EEXIST
+from sphinx.util.osutil import ensuredir, copyfile, make_filename, EEXIST
from sphinx.util.smartypants import sphinx_smarty_pants as ssp
from sphinx.util.console import brown
@@ -761,3 +761,33 @@ class EpubBuilder(StandaloneHTMLBuilder):
fp = path.join(outdir, file)
epub.write(fp, file, zipfile.ZIP_DEFLATED)
epub.close()
+
+
+def setup(app):
+ app.setup_extension('sphinx.builders.html')
+ app.add_builder(EpubBuilder)
+
+ # config values
+ app.add_config_value('epub_basename', lambda self: make_filename(self.project), None)
+ app.add_config_value('epub_theme', 'epub', 'html')
+ app.add_config_value('epub_theme_options', {}, 'html')
+ app.add_config_value('epub_title', lambda self: self.html_title, 'html')
+ app.add_config_value('epub_author', 'unknown', 'html')
+ app.add_config_value('epub_language', lambda self: self.language or 'en', 'html')
+ app.add_config_value('epub_publisher', 'unknown', 'html')
+ app.add_config_value('epub_copyright', lambda self: self.copyright, 'html')
+ app.add_config_value('epub_identifier', 'unknown', 'html')
+ app.add_config_value('epub_scheme', 'unknown', 'html')
+ app.add_config_value('epub_uid', 'unknown', 'env')
+ app.add_config_value('epub_cover', (), 'env')
+ app.add_config_value('epub_guide', (), 'env')
+ app.add_config_value('epub_pre_files', [], 'env')
+ app.add_config_value('epub_post_files', [], 'env')
+ app.add_config_value('epub_exclude_files', [], 'env')
+ app.add_config_value('epub_tocdepth', 3, 'env')
+ app.add_config_value('epub_tocdup', True, 'env')
+ app.add_config_value('epub_tocscope', 'default', 'env')
+ app.add_config_value('epub_fix_images', False, 'env')
+ app.add_config_value('epub_max_image_width', 0, 'env')
+ app.add_config_value('epub_show_urls', 'inline', 'html')
+ app.add_config_value('epub_use_index', lambda self: self.html_use_index, 'html')
diff --git a/sphinx/builders/epub3.py b/sphinx/builders/epub3.py
index b243486f6..57ed1abbe 100644
--- a/sphinx/builders/epub3.py
+++ b/sphinx/builders/epub3.py
@@ -13,6 +13,7 @@
import codecs
from os import path
+from sphinx.config import string_classes
from sphinx.builders.epub import EpubBuilder
@@ -209,3 +210,12 @@ class Epub3Builder(EpubBuilder):
# Add nav.xhtml to epub file
self.files.append(outname)
+
+
+def setup(app):
+ app.setup_extension('sphinx.builders.epub')
+ app.add_builder(Epub3Builder)
+
+ app.add_config_value('epub3_description', '', 'epub3', string_classes)
+ app.add_config_value('epub3_contributor', 'unknown', 'epub3', string_classes)
+ app.add_config_value('epub3_page_progression_direction', 'ltr', 'epub3', string_classes)
diff --git a/sphinx/builders/gettext.py b/sphinx/builders/gettext.py
index a45fd173c..aa9400575 100644
--- a/sphinx/builders/gettext.py
+++ b/sphinx/builders/gettext.py
@@ -233,3 +233,13 @@ class MessageCatalogBuilder(I18nBuilder):
replace('"', r'\"'). \
replace('\n', '\\n"\n"')
pofile.write('msgid "%s"\nmsgstr ""\n\n' % message)
+
+
+def setup(app):
+ app.add_builder(MessageCatalogBuilder)
+
+ app.add_config_value('gettext_compact', True, 'gettext')
+ app.add_config_value('gettext_location', True, 'gettext')
+ app.add_config_value('gettext_uuid', False, 'gettext')
+ app.add_config_value('gettext_auto_build', True, 'env')
+ app.add_config_value('gettext_additional_targets', [], 'env')
diff --git a/sphinx/builders/html.py b/sphinx/builders/html.py
index 09fe96be0..27e961bd9 100644
--- a/sphinx/builders/html.py
+++ b/sphinx/builders/html.py
@@ -33,7 +33,8 @@ from sphinx.util.osutil import SEP, os_path, relative_uri, ensuredir, \
movefile, copyfile
from sphinx.util.nodes import inline_all_toctrees
from sphinx.util.matching import patmatch, compile_matchers
-from sphinx.locale import _
+from sphinx.config import string_classes
+from sphinx.locale import _, l_
from sphinx.search import js_index
from sphinx.theming import Theme
from sphinx.builders import Builder
@@ -1160,3 +1161,52 @@ class JSONHTMLBuilder(SerializingHTMLBuilder):
def init(self):
SerializingHTMLBuilder.init(self)
+
+
+def setup(app):
+ # builders
+ app.add_builder(StandaloneHTMLBuilder)
+ app.add_builder(DirectoryHTMLBuilder)
+ app.add_builder(SingleFileHTMLBuilder)
+ app.add_builder(PickleHTMLBuilder)
+ app.add_builder(JSONHTMLBuilder)
+
+ # config values
+ app.add_config_value('html_theme', 'alabaster', 'html')
+ app.add_config_value('html_theme_path', [], 'html')
+ app.add_config_value('html_theme_options', {}, 'html')
+ app.add_config_value('html_title',
+ lambda self: l_('%s %s documentation') % (self.project, self.release),
+ 'html', string_classes)
+ app.add_config_value('html_short_title', lambda self: self.html_title, 'html')
+ app.add_config_value('html_style', None, 'html', string_classes)
+ app.add_config_value('html_logo', None, 'html', string_classes)
+ app.add_config_value('html_favicon', None, 'html', string_classes)
+ app.add_config_value('html_static_path', [], 'html')
+ app.add_config_value('html_extra_path', [], 'html')
+ app.add_config_value('html_last_updated_fmt', None, 'html', string_classes)
+ app.add_config_value('html_use_smartypants', True, 'html')
+ app.add_config_value('html_translator_class', None, 'html', string_classes)
+ app.add_config_value('html_sidebars', {}, 'html')
+ app.add_config_value('html_additional_pages', {}, 'html')
+ app.add_config_value('html_use_modindex', True, 'html') # deprecated
+ app.add_config_value('html_domain_indices', True, 'html', [list])
+ app.add_config_value('html_add_permalinks', u'\u00B6', 'html')
+ app.add_config_value('html_use_index', True, 'html')
+ app.add_config_value('html_split_index', False, 'html')
+ app.add_config_value('html_copy_source', True, 'html')
+ app.add_config_value('html_show_sourcelink', True, 'html')
+ app.add_config_value('html_sourcelink_suffix', '.txt', 'html')
+ app.add_config_value('html_use_opensearch', '', 'html')
+ app.add_config_value('html_file_suffix', None, 'html', string_classes)
+ app.add_config_value('html_link_suffix', None, 'html', string_classes)
+ app.add_config_value('html_show_copyright', True, 'html')
+ app.add_config_value('html_show_sphinx', True, 'html')
+ app.add_config_value('html_context', {}, 'html')
+ app.add_config_value('html_output_encoding', 'utf-8', 'html')
+ app.add_config_value('html_compact_lists', True, 'html')
+ app.add_config_value('html_secnumber_suffix', '. ', 'html')
+ app.add_config_value('html_search_language', None, 'html', string_classes)
+ app.add_config_value('html_search_options', {}, 'html')
+ app.add_config_value('html_search_scorer', '', None)
+ app.add_config_value('html_scaled_image_link', True, 'html')
diff --git a/sphinx/builders/htmlhelp.py b/sphinx/builders/htmlhelp.py
index 21d4875a7..cdb51b2c6 100644
--- a/sphinx/builders/htmlhelp.py
+++ b/sphinx/builders/htmlhelp.py
@@ -18,6 +18,7 @@ from os import path
from docutils import nodes
from sphinx import addnodes
+from sphinx.util.osutil import make_filename
from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.util.pycompat import htmlescape
@@ -296,3 +297,10 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder):
for title, (refs, subitems, key_) in group:
write_index(title, refs, subitems)
f.write('\n')
+
+
+def setup(app):
+ app.setup_extension('sphinx.builders.html')
+ app.add_builder(HTMLHelpBuilder)
+
+ app.add_config_value('htmlhelp_basename', lambda self: make_filename(self.project), None)
diff --git a/sphinx/builders/latex.py b/sphinx/builders/latex.py
index f864a58c8..3bd1ebc06 100644
--- a/sphinx/builders/latex.py
+++ b/sphinx/builders/latex.py
@@ -21,12 +21,13 @@ from docutils.frontend import OptionParser
from sphinx import package_dir, addnodes, highlighting
from sphinx.util import texescape
+from sphinx.config import string_classes
from sphinx.errors import SphinxError
from sphinx.locale import _
from sphinx.builders import Builder
from sphinx.environment import NoUri
from sphinx.util.nodes import inline_all_toctrees
-from sphinx.util.osutil import SEP, copyfile
+from sphinx.util.osutil import SEP, copyfile, make_filename
from sphinx.util.console import bold, darkgreen
from sphinx.writers.latex import LaTeXWriter
@@ -233,3 +234,31 @@ class LaTeXBuilder(Builder):
elif not path.isfile(logotarget):
copyfile(path.join(self.confdir, self.config.latex_logo), logotarget)
self.info('done')
+
+
+def setup(app):
+ app.add_builder(LaTeXBuilder)
+
+ app.add_config_value('latex_documents',
+ lambda self: [(self.master_doc, make_filename(self.project) + '.tex',
+ self.project, '', 'manual')],
+ None)
+ app.add_config_value('latex_logo', None, None, string_classes)
+ app.add_config_value('latex_appendices', [], None)
+ app.add_config_value('latex_keep_old_macro_names', True, None)
+ # now deprecated - use latex_toplevel_sectioning
+ app.add_config_value('latex_use_parts', False, None)
+ app.add_config_value('latex_toplevel_sectioning', None, None, [str])
+ app.add_config_value('latex_use_modindex', True, None) # deprecated
+ app.add_config_value('latex_domain_indices', True, None, [list])
+ app.add_config_value('latex_show_urls', 'no', None)
+ app.add_config_value('latex_show_pagerefs', False, None)
+ # paper_size and font_size are still separate values
+ # so that you can give them easily on the command line
+ app.add_config_value('latex_paper_size', 'letter', None)
+ app.add_config_value('latex_font_size', '10pt', None)
+ app.add_config_value('latex_elements', {}, None)
+ app.add_config_value('latex_additional_files', [], None)
+ app.add_config_value('latex_docclass', {}, None)
+ # now deprecated - use latex_elements
+ app.add_config_value('latex_preamble', '', None)
diff --git a/sphinx/builders/linkcheck.py b/sphinx/builders/linkcheck.py
index 7c30597a8..4764f6947 100644
--- a/sphinx/builders/linkcheck.py
+++ b/sphinx/builders/linkcheck.py
@@ -300,3 +300,13 @@ class CheckExternalLinksBuilder(Builder):
def finish(self):
for worker in self.workers:
self.wqueue.put((None, None, None), False)
+
+
+def setup(app):
+ app.add_builder(CheckExternalLinksBuilder)
+
+ app.add_config_value('linkcheck_ignore', [], None)
+ app.add_config_value('linkcheck_retries', 1, None)
+ app.add_config_value('linkcheck_timeout', None, None, [int])
+ app.add_config_value('linkcheck_workers', 5, None)
+ app.add_config_value('linkcheck_anchors', True, None)
diff --git a/sphinx/builders/manpage.py b/sphinx/builders/manpage.py
index a2e75f9f7..248ed40b2 100644
--- a/sphinx/builders/manpage.py
+++ b/sphinx/builders/manpage.py
@@ -19,6 +19,7 @@ from sphinx import addnodes
from sphinx.builders import Builder
from sphinx.environment import NoUri
from sphinx.util.nodes import inline_all_toctrees
+from sphinx.util.osutil import make_filename
from sphinx.util.console import bold, darkgreen
from sphinx.writers.manpage import ManualPageWriter
@@ -88,3 +89,13 @@ class ManualPageBuilder(Builder):
def finish(self):
pass
+
+
+def setup(app):
+ app.add_builder(ManualPageBuilder)
+
+ app.add_config_value('man_pages',
+ lambda self: [(self.master_doc, make_filename(self.project).lower(),
+ '%s %s' % (self.project, self.release), [], 1)],
+ None)
+ app.add_config_value('man_show_urls', False, None)
diff --git a/sphinx/builders/qthelp.py b/sphinx/builders/qthelp.py
index 3ad74438b..d55ea3cc7 100644
--- a/sphinx/builders/qthelp.py
+++ b/sphinx/builders/qthelp.py
@@ -21,6 +21,7 @@ from docutils import nodes
from sphinx import addnodes
from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.util import force_decode
+from sphinx.util.osutil import make_filename
from sphinx.util.pycompat import htmlescape
@@ -291,3 +292,10 @@ class QtHelpBuilder(StandaloneHTMLBuilder):
keywords.extend(self.build_keywords(subitem[0], subitem[1], []))
return keywords
+
+
+def setup(app):
+ app.setup_extension('sphinx.builders.html')
+ app.add_builder(QtHelpBuilder)
+
+ app.add_config_value('qthelp_basename', lambda self: make_filename(self.project), None)
diff --git a/sphinx/builders/texinfo.py b/sphinx/builders/texinfo.py
index 8c4bd2419..f070840b6 100644
--- a/sphinx/builders/texinfo.py
+++ b/sphinx/builders/texinfo.py
@@ -22,7 +22,7 @@ from sphinx.locale import _
from sphinx.builders import Builder
from sphinx.environment import NoUri
from sphinx.util.nodes import inline_all_toctrees
-from sphinx.util.osutil import SEP, copyfile
+from sphinx.util.osutil import SEP, copyfile, make_filename
from sphinx.util.console import bold, darkgreen
from sphinx.writers.texinfo import TexinfoWriter
@@ -225,3 +225,20 @@ class TexinfoBuilder(Builder):
except (IOError, OSError) as err:
self.warn("error writing file %s: %s" % (fn, err))
self.info(' done')
+
+
+def setup(app):
+ app.add_builder(TexinfoBuilder)
+
+ app.add_config_value('texinfo_documents',
+ lambda self: [(self.master_doc, make_filename(self.project).lower(),
+ self.project, '', make_filename(self.project),
+ 'The %s reference manual.' %
+ make_filename(self.project),
+ 'Python')],
+ None)
+ app.add_config_value('texinfo_appendices', [], None)
+ app.add_config_value('texinfo_elements', {}, None)
+ app.add_config_value('texinfo_domain_indices', True, None, [list])
+ app.add_config_value('texinfo_show_urls', 'footnote', None)
+ app.add_config_value('texinfo_no_detailmenu', False, None)
diff --git a/sphinx/builders/text.py b/sphinx/builders/text.py
index 202ec20db..2daf8b043 100644
--- a/sphinx/builders/text.py
+++ b/sphinx/builders/text.py
@@ -67,3 +67,10 @@ class TextBuilder(Builder):
def finish(self):
pass
+
+
+def setup(app):
+ app.add_builder(TextBuilder)
+
+ app.add_config_value('text_sectionchars', '*=-~"+`', 'env')
+ app.add_config_value('text_newlines', 'unix', 'env')
diff --git a/sphinx/builders/websupport.py b/sphinx/builders/websupport.py
index 843b0899e..d8ff5ad8d 100644
--- a/sphinx/builders/websupport.py
+++ b/sphinx/builders/websupport.py
@@ -165,3 +165,7 @@ class WebSupportBuilder(PickleHTMLBuilder):
def dump_search_index(self):
self.indexer.finish_indexing()
+
+
+def setup(app):
+ app.add_builder(WebSupportBuilder)
diff --git a/sphinx/builders/xml.py b/sphinx/builders/xml.py
index 589e8a63a..e0e33312c 100644
--- a/sphinx/builders/xml.py
+++ b/sphinx/builders/xml.py
@@ -95,3 +95,10 @@ class PseudoXMLBuilder(XMLBuilder):
out_suffix = '.pseudoxml'
_writer_class = PseudoXMLWriter
+
+
+def setup(app):
+ app.add_builder(XMLBuilder)
+ app.add_builder(PseudoXMLBuilder)
+
+ app.add_config_value('xml_pretty', True, 'env')
diff --git a/sphinx/config.py b/sphinx/config.py
index 0954efeb2..b0acdedb8 100644
--- a/sphinx/config.py
+++ b/sphinx/config.py
@@ -10,14 +10,13 @@
"""
import re
-from os import path, environ, getenv
-import shlex
+from os import path, getenv
from six import PY2, PY3, iteritems, string_types, binary_type, text_type, integer_types
from sphinx.errors import ConfigError
from sphinx.locale import l_
-from sphinx.util.osutil import make_filename, cd
+from sphinx.util.osutil import cd
from sphinx.util.pycompat import execfile_, NoneType
from sphinx.util.i18n import format_date
@@ -94,183 +93,6 @@ class Config(object):
'table': l_('Table %s'),
'code-block': l_('Listing %s')},
'env'),
-
- # HTML options
- html_theme = ('alabaster', 'html'),
- html_theme_path = ([], 'html'),
- html_theme_options = ({}, 'html'),
- html_title = (lambda self: l_('%s %s documentation') %
- (self.project, self.release),
- 'html', string_classes),
- html_short_title = (lambda self: self.html_title, 'html'),
- html_style = (None, 'html', string_classes),
- html_logo = (None, 'html', string_classes),
- html_favicon = (None, 'html', string_classes),
- html_static_path = ([], 'html'),
- html_extra_path = ([], 'html'),
- # the real default is locale-dependent
- html_last_updated_fmt = (None, 'html', string_classes),
- html_use_smartypants = (True, 'html'),
- html_translator_class = (None, 'html', string_classes),
- html_sidebars = ({}, 'html'),
- html_additional_pages = ({}, 'html'),
- html_use_modindex = (True, 'html'), # deprecated
- html_domain_indices = (True, 'html', [list]),
- html_add_permalinks = (u'\u00B6', 'html'),
- html_use_index = (True, 'html'),
- html_split_index = (False, 'html'),
- html_copy_source = (True, 'html'),
- html_show_sourcelink = (True, 'html'),
- html_sourcelink_suffix = ('.txt', 'html'),
- html_use_opensearch = ('', 'html'),
- html_file_suffix = (None, 'html', string_classes),
- html_link_suffix = (None, 'html', string_classes),
- html_show_copyright = (True, 'html'),
- html_show_sphinx = (True, 'html'),
- html_context = ({}, 'html'),
- html_output_encoding = ('utf-8', 'html'),
- html_compact_lists = (True, 'html'),
- html_secnumber_suffix = ('. ', 'html'),
- html_search_language = (None, 'html', string_classes),
- html_search_options = ({}, 'html'),
- html_search_scorer = ('', None),
- html_scaled_image_link = (True, 'html'),
-
- # HTML help only options
- htmlhelp_basename = (lambda self: make_filename(self.project), None),
-
- # Qt help only options
- qthelp_basename = (lambda self: make_filename(self.project), None),
-
- # Devhelp only options
- devhelp_basename = (lambda self: make_filename(self.project), None),
-
- # Apple help options
- applehelp_bundle_name = (lambda self: make_filename(self.project),
- 'applehelp'),
- applehelp_bundle_id = (None, 'applehelp', string_classes),
- applehelp_dev_region = ('en-us', 'applehelp'),
- applehelp_bundle_version = ('1', 'applehelp'),
- applehelp_icon = (None, 'applehelp', string_classes),
- applehelp_kb_product = (lambda self: '%s-%s' %
- (make_filename(self.project), self.release),
- 'applehelp'),
- applehelp_kb_url = (None, 'applehelp', string_classes),
- applehelp_remote_url = (None, 'applehelp', string_classes),
- applehelp_index_anchors = (False, 'applehelp', string_classes),
- applehelp_min_term_length = (None, 'applehelp', string_classes),
- applehelp_stopwords = (lambda self: self.language or 'en', 'applehelp'),
- applehelp_locale = (lambda self: self.language or 'en', 'applehelp'),
- applehelp_title = (lambda self: self.project + ' Help', 'applehelp'),
- applehelp_codesign_identity = (lambda self:
- environ.get('CODE_SIGN_IDENTITY', None),
- 'applehelp'),
- applehelp_codesign_flags = (lambda self:
- shlex.split(
- environ.get('OTHER_CODE_SIGN_FLAGS',
- '')),
- 'applehelp'),
- applehelp_indexer_path = ('/usr/bin/hiutil', 'applehelp'),
- applehelp_codesign_path = ('/usr/bin/codesign', 'applehelp'),
- applehelp_disable_external_tools = (False, None),
-
- # Epub options
- epub_basename = (lambda self: make_filename(self.project), None),
- epub_theme = ('epub', 'html'),
- epub_theme_options = ({}, 'html'),
- epub_title = (lambda self: self.html_title, 'html'),
- epub3_description = ('', 'epub3', string_classes),
- epub_author = ('unknown', 'html'),
- epub3_contributor = ('unknown', 'epub3', string_classes),
- epub_language = (lambda self: self.language or 'en', 'html'),
- epub_publisher = ('unknown', 'html'),
- epub_copyright = (lambda self: self.copyright, 'html'),
- epub_identifier = ('unknown', 'html'),
- epub_scheme = ('unknown', 'html'),
- epub_uid = ('unknown', 'env'),
- epub_cover = ((), 'env'),
- epub_guide = ((), 'env'),
- epub_pre_files = ([], 'env'),
- epub_post_files = ([], 'env'),
- epub_exclude_files = ([], 'env'),
- epub_tocdepth = (3, 'env'),
- epub_tocdup = (True, 'env'),
- epub_tocscope = ('default', 'env'),
- epub_fix_images = (False, 'env'),
- epub_max_image_width = (0, 'env'),
- epub_show_urls = ('inline', 'html'),
- epub_use_index = (lambda self: self.html_use_index, 'html'),
- epub3_page_progression_direction = ('ltr', 'epub3', string_classes),
-
- # LaTeX options
- latex_documents = (lambda self: [(self.master_doc,
- make_filename(self.project) + '.tex',
- self.project,
- '', 'manual')],
- None),
- latex_logo = (None, None, string_classes),
- latex_appendices = ([], None),
- latex_keep_old_macro_names = (True, None),
- # now deprecated - use latex_toplevel_sectioning
- latex_use_parts = (False, None),
- latex_toplevel_sectioning = (None, None, [str]),
- latex_use_modindex = (True, None), # deprecated
- latex_domain_indices = (True, None, [list]),
- latex_show_urls = ('no', None),
- latex_show_pagerefs = (False, None),
- # paper_size and font_size are still separate values
- # so that you can give them easily on the command line
- latex_paper_size = ('letter', None),
- latex_font_size = ('10pt', None),
- latex_elements = ({}, None),
- latex_additional_files = ([], None),
- latex_docclass = ({}, None),
- # now deprecated - use latex_elements
- latex_preamble = ('', None),
-
- # text options
- text_sectionchars = ('*=-~"+`', 'env'),
- text_newlines = ('unix', 'env'),
-
- # manpage options
- man_pages = (lambda self: [(self.master_doc,
- make_filename(self.project).lower(),
- '%s %s' % (self.project, self.release),
- [], 1)],
- None),
- man_show_urls = (False, None),
-
- # Texinfo options
- texinfo_documents = (lambda self: [(self.master_doc,
- make_filename(self.project).lower(),
- self.project, '',
- make_filename(self.project),
- 'The %s reference manual.' %
- make_filename(self.project),
- 'Python')],
- None),
- texinfo_appendices = ([], None),
- texinfo_elements = ({}, None),
- texinfo_domain_indices = (True, None, [list]),
- texinfo_show_urls = ('footnote', None),
- texinfo_no_detailmenu = (False, None),
-
- # linkcheck options
- linkcheck_ignore = ([], None),
- linkcheck_retries = (1, None),
- linkcheck_timeout = (None, None, [int]),
- linkcheck_workers = (5, None),
- linkcheck_anchors = (True, None),
-
- # gettext options
- gettext_compact = (True, 'gettext'),
- gettext_location = (True, 'gettext'),
- gettext_uuid = (False, 'gettext'),
- gettext_auto_build = (True, 'env'),
- gettext_additional_targets = ([], 'env'),
-
- # XML options
- xml_pretty = (True, 'env'),
)
def __init__(self, dirname, filename, overrides, tags):
diff --git a/sphinx/domains/__init__.py b/sphinx/domains/__init__.py
index e4d397efe..c67abc207 100644
--- a/sphinx/domains/__init__.py
+++ b/sphinx/domains/__init__.py
@@ -273,20 +273,3 @@ class Domain(object):
if primary:
return type.lname
return _('%s %s') % (self.label, type.lname)
-
-
-from sphinx.domains.c import CDomain # noqa
-from sphinx.domains.cpp import CPPDomain # noqa
-from sphinx.domains.std import StandardDomain # noqa
-from sphinx.domains.python import PythonDomain # noqa
-from sphinx.domains.javascript import JavaScriptDomain # noqa
-from sphinx.domains.rst import ReSTDomain # noqa
-
-BUILTIN_DOMAINS = {
- 'std': StandardDomain,
- 'py': PythonDomain,
- 'c': CDomain,
- 'cpp': CPPDomain,
- 'js': JavaScriptDomain,
- 'rst': ReSTDomain,
-}
diff --git a/sphinx/domains/c.py b/sphinx/domains/c.py
index 8ba159d32..43e869dbc 100644
--- a/sphinx/domains/c.py
+++ b/sphinx/domains/c.py
@@ -302,3 +302,7 @@ class CDomain(Domain):
def get_objects(self):
for refname, (docname, type) in list(self.data['objects'].items()):
yield (refname, refname, type, docname, 'c.' + refname, 1)
+
+
+def setup(app):
+ app.add_domain(CDomain)
diff --git a/sphinx/domains/cpp.py b/sphinx/domains/cpp.py
index a2a2c562f..9a3d10a3f 100644
--- a/sphinx/domains/cpp.py
+++ b/sphinx/domains/cpp.py
@@ -4185,3 +4185,7 @@ class CPPDomain(Domain):
docname = symbol.docname
newestId = symbol.declaration.get_newest_id()
yield (name, name, objectType, docname, newestId, 1)
+
+
+def setup(app):
+ app.add_domain(CPPDomain)
diff --git a/sphinx/domains/javascript.py b/sphinx/domains/javascript.py
index b5f64022a..ade6e4224 100644
--- a/sphinx/domains/javascript.py
+++ b/sphinx/domains/javascript.py
@@ -234,3 +234,7 @@ class JavaScriptDomain(Domain):
for refname, (docname, type) in list(self.data['objects'].items()):
yield refname, refname, type, docname, \
refname.replace('$', '_S_'), 1
+
+
+def setup(app):
+ app.add_domain(JavaScriptDomain)
diff --git a/sphinx/domains/python.py b/sphinx/domains/python.py
index 1639d8288..9a9bcef16 100644
--- a/sphinx/domains/python.py
+++ b/sphinx/domains/python.py
@@ -771,3 +771,7 @@ class PythonDomain(Domain):
for refname, (docname, type) in iteritems(self.data['objects']):
if type != 'module': # modules are already handled
yield (refname, refname, type, docname, refname, 1)
+
+
+def setup(app):
+ app.add_domain(PythonDomain)
diff --git a/sphinx/domains/rst.py b/sphinx/domains/rst.py
index b11c9450b..526ae18a7 100644
--- a/sphinx/domains/rst.py
+++ b/sphinx/domains/rst.py
@@ -156,3 +156,7 @@ class ReSTDomain(Domain):
def get_objects(self):
for (typ, name), docname in iteritems(self.data['objects']):
yield name, name, typ, docname, typ + '-' + name, 1
+
+
+def setup(app):
+ app.add_domain(ReSTDomain)
diff --git a/sphinx/domains/std.py b/sphinx/domains/std.py
index e59b41a09..001d9f6d9 100644
--- a/sphinx/domains/std.py
+++ b/sphinx/domains/std.py
@@ -767,3 +767,7 @@ class StandardDomain(Domain):
else:
figtype, _ = self.enumerable_nodes.get(node.__class__, (None, None))
return figtype
+
+
+def setup(app):
+ app.add_domain(StandardDomain)
From 17cd06f237e78eab7e8201c9e98deab6a3ca9304 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 26 Jun 2016 22:22:25 +0900
Subject: [PATCH 194/217] Add sphinx.util.fileutil.copy_asset_file()
---
sphinx/builders/html.py | 1 +
sphinx/util/__init__.py | 14 ++-------
sphinx/util/fileutil.py | 39 +++++++++++++++++++++++++
tests/test_util_fileutil.py | 58 +++++++++++++++++++++++++++++++++++++
4 files changed, 101 insertions(+), 11 deletions(-)
create mode 100644 sphinx/util/fileutil.py
create mode 100644 tests/test_util_fileutil.py
diff --git a/sphinx/builders/html.py b/sphinx/builders/html.py
index 27e961bd9..1f1811778 100644
--- a/sphinx/builders/html.py
+++ b/sphinx/builders/html.py
@@ -1069,6 +1069,7 @@ class SerializingHTMLBuilder(StandaloneHTMLBuilder):
self.theme = None # no theme necessary
self.templates = None # no template bridge necessary
self.init_translator_class()
+ self.init_templates()
self.init_highlighter()
def get_target_uri(self, docname, typ=None):
diff --git a/sphinx/util/__init__.py b/sphinx/util/__init__.py
index 0c823fb1a..e1a65d950 100644
--- a/sphinx/util/__init__.py
+++ b/sphinx/util/__init__.py
@@ -18,7 +18,7 @@ import posixpath
import traceback
import unicodedata
from os import path
-from codecs import open, BOM_UTF8
+from codecs import BOM_UTF8
from collections import deque
from six import iteritems, text_type, binary_type
@@ -32,6 +32,7 @@ import jinja2
import sphinx
from sphinx.errors import PycodeError, SphinxParallelError, ExtensionError
from sphinx.util.console import strip_colors
+from sphinx.util.fileutil import copy_asset_file
from sphinx.util.osutil import fs_encoding
# import other utilities; partly for backwards compatibility, so don't
@@ -158,16 +159,7 @@ def copy_static_entry(source, targetdir, builder, context={},
if matcher(relpath):
return
if path.isfile(source):
- target = path.join(targetdir, path.basename(source))
- if source.lower().endswith('_t') and builder.templates:
- # templated!
- fsrc = open(source, 'r', encoding='utf-8')
- fdst = open(target[:-2], 'w', encoding='utf-8')
- fdst.write(builder.templates.render_string(fsrc.read(), context))
- fsrc.close()
- fdst.close()
- else:
- copyfile(source, target)
+ copy_asset_file(source, targetdir, context, builder.templates)
elif path.isdir(source):
if not path.isdir(targetdir):
os.mkdir(targetdir)
diff --git a/sphinx/util/fileutil.py b/sphinx/util/fileutil.py
new file mode 100644
index 000000000..df168b495
--- /dev/null
+++ b/sphinx/util/fileutil.py
@@ -0,0 +1,39 @@
+# -*- coding: utf-8 -*-
+"""
+ sphinx.util.fileutil
+ ~~~~~~~~~~~~~~~~~~~~
+
+ File utility functions for Sphinx.
+
+ :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+import os
+import codecs
+from sphinx.util.osutil import copyfile
+
+
+def copy_asset_file(source, destination, context={}, renderer=None):
+ """Copy an asset file to destination.
+
+ On copying, it expands the template variables if the asset is a template file.
+
+ :param source: The path to source file
+ :param destination: The path to destination file or directory
+ :param context: The template variables
+ :param renderer: The template engine
+ """
+ if os.path.exists(destination) and os.path.isdir(destination):
+ # Use source filename if destination points a directory
+ destination = os.path.join(destination, os.path.basename(source))
+
+ if source.lower().endswith('_t'):
+ if renderer is None:
+ msg = 'Template engine is not initialized. Failed to render %s' % source
+ raise RuntimeError(msg)
+
+ with codecs.open(source, 'r', encoding='utf-8') as fsrc:
+ with codecs.open(destination[:-2], 'w', encoding='utf-8') as fdst:
+ fdst.write(renderer.render_string(fsrc.read(), context))
+ else:
+ copyfile(source, destination)
diff --git a/tests/test_util_fileutil.py b/tests/test_util_fileutil.py
new file mode 100644
index 000000000..c5680c890
--- /dev/null
+++ b/tests/test_util_fileutil.py
@@ -0,0 +1,58 @@
+# -*- coding: utf-8 -*-
+"""
+ test_util_fileutil
+ ~~~~~~~~~~~~~~~~~~
+
+ Tests sphinx.util.fileutil functions.
+
+ :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+from sphinx.util.fileutil import copy_asset_file
+from sphinx.jinja2glue import BuiltinTemplateLoader
+
+from mock import Mock
+from util import with_tempdir
+
+
+class DummyTemplateLoader(BuiltinTemplateLoader):
+ def __init__(self):
+ BuiltinTemplateLoader.__init__(self)
+ builder = Mock()
+ builder.config.templates_path = []
+ builder.app.translater = None
+ self.init(builder)
+
+
+@with_tempdir
+def test_copy_asset_file(tmpdir):
+ renderer = DummyTemplateLoader()
+
+ # copy normal file
+ src = (tmpdir / 'asset.txt')
+ src.write_text('# test data')
+ dest = (tmpdir / 'output.txt')
+
+ copy_asset_file(src, dest)
+ assert dest.exists()
+ assert src.text() == dest.text()
+
+ # copy template file
+ src = (tmpdir / 'asset.txt_t')
+ src.write_text('# {{var1}} data')
+ dest = (tmpdir / 'output.txt_t')
+
+ copy_asset_file(src, dest, {'var1': 'template'}, renderer)
+ assert not dest.exists()
+ assert (tmpdir / 'output.txt').exists()
+ assert (tmpdir / 'output.txt').text() == '# template data'
+
+ # copy template file to subdir
+ src = (tmpdir / 'asset.txt_t')
+ src.write_text('# {{var1}} data')
+ subdir = (tmpdir / 'subdir')
+ subdir.makedirs()
+
+ copy_asset_file(src, subdir, {'var1': 'template'}, renderer)
+ assert (subdir / 'asset.txt').exists()
+ assert (subdir / 'asset.txt').text() == '# template data'
From 07ddff99335a34cad9e917b35a2ad81a4ceb4b2e Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Mon, 27 Jun 2016 11:54:42 +0900
Subject: [PATCH 195/217] Add sphinx.util.fileutil.copy_asset()
---
sphinx/util/fileutil.py | 35 ++++++++++++++++++++++++++-
tests/test_util_fileutil.py | 47 ++++++++++++++++++++++++++++++++++++-
2 files changed, 80 insertions(+), 2 deletions(-)
diff --git a/sphinx/util/fileutil.py b/sphinx/util/fileutil.py
index df168b495..1f6bede1a 100644
--- a/sphinx/util/fileutil.py
+++ b/sphinx/util/fileutil.py
@@ -10,7 +10,9 @@
"""
import os
import codecs
-from sphinx.util.osutil import copyfile
+import posixpath
+from docutils.utils import relative_path
+from sphinx.util.osutil import copyfile, ensuredir, walk
def copy_asset_file(source, destination, context={}, renderer=None):
@@ -37,3 +39,34 @@ def copy_asset_file(source, destination, context={}, renderer=None):
fdst.write(renderer.render_string(fsrc.read(), context))
else:
copyfile(source, destination)
+
+
+def copy_asset(source, destination, excluded=lambda path: False, context={}, renderer=None):
+ """Copy asset files to destination recursively.
+
+ On copying, it expands the template variables if the asset is a template file.
+
+ :param source: The path to source file or directory
+ :param destination: The path to destination directory
+ :param excluded: The matcher to determine the given path should be copied or not
+ :param context: The template variables
+ :param renderer: The template engine
+ """
+ ensuredir(destination)
+ if os.path.isfile(source):
+ copy_asset_file(source, destination, context, renderer)
+ return
+
+ for root, dirs, files in walk(source):
+ reldir = relative_path(source, root)
+ for dir in dirs[:]:
+ if excluded(posixpath.join(reldir, dir)):
+ dirs.remove(dir)
+ else:
+ ensuredir(posixpath.join(destination, reldir, dir))
+
+ for filename in files:
+ if not excluded(posixpath.join(reldir, filename)):
+ copy_asset_file(posixpath.join(root, filename),
+ posixpath.join(destination, reldir),
+ context, renderer)
diff --git a/tests/test_util_fileutil.py b/tests/test_util_fileutil.py
index c5680c890..5e13d79b2 100644
--- a/tests/test_util_fileutil.py
+++ b/tests/test_util_fileutil.py
@@ -8,7 +8,7 @@
:copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
-from sphinx.util.fileutil import copy_asset_file
+from sphinx.util.fileutil import copy_asset, copy_asset_file
from sphinx.jinja2glue import BuiltinTemplateLoader
from mock import Mock
@@ -56,3 +56,48 @@ def test_copy_asset_file(tmpdir):
copy_asset_file(src, subdir, {'var1': 'template'}, renderer)
assert (subdir / 'asset.txt').exists()
assert (subdir / 'asset.txt').text() == '# template data'
+
+
+@with_tempdir
+def test_copy_asset(tmpdir):
+ renderer = DummyTemplateLoader()
+
+ # prepare source files
+ source = (tmpdir / 'source')
+ source.makedirs()
+ (source / 'index.rst').write_text('index.rst')
+ (source / 'foo.rst_t').write_text('{{var1}}.rst')
+ (source / '_static').makedirs()
+ (source / '_static' / 'basic.css').write_text('basic.css')
+ (source / '_templates').makedirs()
+ (source / '_templates' / 'layout.html').write_text('layout.html')
+ (source / '_templates' / 'sidebar.html_t').write_text('sidebar: {{var2}}')
+
+ # copy a single file
+ assert not (tmpdir / 'test1').exists()
+ copy_asset(source / 'index.rst', tmpdir / 'test1')
+ assert (tmpdir / 'test1').exists()
+ assert (tmpdir / 'test1/index.rst').exists()
+
+ # copy directories
+ destdir = tmpdir / 'test2'
+ copy_asset(source, destdir, context=dict(var1='bar', var2='baz'), renderer=renderer)
+ assert (destdir / 'index.rst').exists()
+ assert (destdir / 'foo.rst').exists()
+ assert (destdir / 'foo.rst').text() == 'bar.rst'
+ assert (destdir / '_static' / 'basic.css').exists()
+ assert (destdir / '_templates' / 'layout.html').exists()
+ assert (destdir / '_templates' / 'sidebar.html').exists()
+ assert (destdir / '_templates' / 'sidebar.html').text() == 'sidebar: baz'
+
+ # copy with exclusion
+ def excluded(path):
+ return ('sidebar.html' in path or 'basic.css' in path)
+
+ destdir = tmpdir / 'test3'
+ copy_asset(source, destdir, excluded, renderer=renderer)
+ assert (destdir / 'index.rst').exists()
+ assert (destdir / 'foo.rst').exists()
+ assert not (destdir / '_static' / 'basic.css').exists()
+ assert (destdir / '_templates' / 'layout.html').exists()
+ assert not (destdir / '_templates' / 'sidebar.html').exists()
From db23797c57ac448a464da25f85e5b5bfd83eb188 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Mon, 27 Jun 2016 12:13:16 +0900
Subject: [PATCH 196/217] copy_asset_file() does not expand if context not
given
---
sphinx/util/fileutil.py | 16 +++++++++-------
tests/test_util_fileutil.py | 23 +++++++++++++++++------
2 files changed, 26 insertions(+), 13 deletions(-)
diff --git a/sphinx/util/fileutil.py b/sphinx/util/fileutil.py
index 1f6bede1a..8ab590472 100644
--- a/sphinx/util/fileutil.py
+++ b/sphinx/util/fileutil.py
@@ -15,21 +15,22 @@ from docutils.utils import relative_path
from sphinx.util.osutil import copyfile, ensuredir, walk
-def copy_asset_file(source, destination, context={}, renderer=None):
+def copy_asset_file(source, destination, context=None, renderer=None):
"""Copy an asset file to destination.
- On copying, it expands the template variables if the asset is a template file.
+ On copying, it expands the template variables if context argument is given and
+ the asset is a template file.
:param source: The path to source file
:param destination: The path to destination file or directory
- :param context: The template variables
+ :param context: The template variables. If not given, template files are simply copied
:param renderer: The template engine
"""
if os.path.exists(destination) and os.path.isdir(destination):
# Use source filename if destination points a directory
destination = os.path.join(destination, os.path.basename(source))
- if source.lower().endswith('_t'):
+ if source.lower().endswith('_t') and context:
if renderer is None:
msg = 'Template engine is not initialized. Failed to render %s' % source
raise RuntimeError(msg)
@@ -41,15 +42,16 @@ def copy_asset_file(source, destination, context={}, renderer=None):
copyfile(source, destination)
-def copy_asset(source, destination, excluded=lambda path: False, context={}, renderer=None):
+def copy_asset(source, destination, excluded=lambda path: False, context=None, renderer=None):
"""Copy asset files to destination recursively.
- On copying, it expands the template variables if the asset is a template file.
+ On copying, it expands the template variables if context argument is given and
+ the asset is a template file.
:param source: The path to source file or directory
:param destination: The path to destination directory
:param excluded: The matcher to determine the given path should be copied or not
- :param context: The template variables
+ :param context: The template variables. If not given, template files are simply copied
:param renderer: The template engine
"""
ensuredir(destination)
diff --git a/tests/test_util_fileutil.py b/tests/test_util_fileutil.py
index 5e13d79b2..a56543614 100644
--- a/tests/test_util_fileutil.py
+++ b/tests/test_util_fileutil.py
@@ -50,12 +50,22 @@ def test_copy_asset_file(tmpdir):
# copy template file to subdir
src = (tmpdir / 'asset.txt_t')
src.write_text('# {{var1}} data')
- subdir = (tmpdir / 'subdir')
- subdir.makedirs()
+ subdir1 = (tmpdir / 'subdir')
+ subdir1.makedirs()
- copy_asset_file(src, subdir, {'var1': 'template'}, renderer)
- assert (subdir / 'asset.txt').exists()
- assert (subdir / 'asset.txt').text() == '# template data'
+ copy_asset_file(src, subdir1, {'var1': 'template'}, renderer)
+ assert (subdir1 / 'asset.txt').exists()
+ assert (subdir1 / 'asset.txt').text() == '# template data'
+
+ # copy template file without context
+ src = (tmpdir / 'asset.txt_t')
+ subdir2 = (tmpdir / 'subdir2')
+ subdir2.makedirs()
+
+ copy_asset_file(src, subdir2)
+ assert not (subdir2 / 'asset.txt').exists()
+ assert (subdir2 / 'asset.txt_t').exists()
+ assert (subdir2 / 'asset.txt_t').text() == '# {{var1}} data'
@with_tempdir
@@ -95,7 +105,8 @@ def test_copy_asset(tmpdir):
return ('sidebar.html' in path or 'basic.css' in path)
destdir = tmpdir / 'test3'
- copy_asset(source, destdir, excluded, renderer=renderer)
+ copy_asset(source, destdir, excluded,
+ context=dict(var1='bar', var2='baz'), renderer=renderer)
assert (destdir / 'index.rst').exists()
assert (destdir / 'foo.rst').exists()
assert not (destdir / '_static' / 'basic.css').exists()
From 829b5631a34a7da67e6dee18853c82c12e1aa59d Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 3 Jul 2016 15:11:15 +0900
Subject: [PATCH 197/217] Add testcase for compile_matchers()
---
tests/test_util_matching.py | 83 +++++++++++++++++++++++++++++++++++++
1 file changed, 83 insertions(+)
create mode 100644 tests/test_util_matching.py
diff --git a/tests/test_util_matching.py b/tests/test_util_matching.py
new file mode 100644
index 000000000..fe86c3bbc
--- /dev/null
+++ b/tests/test_util_matching.py
@@ -0,0 +1,83 @@
+# -*- coding: utf-8 -*-
+"""
+ test_util_matching
+ ~~~~~~~~~~~~~~~~~~
+
+ Tests sphinx.util.matching functions.
+
+ :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+from sphinx.util.matching import compile_matchers
+
+
+def test_compile_matchers():
+ # exact matching
+ pat = compile_matchers(['hello.py']).pop()
+ assert pat('hello.py')
+ assert not pat('hello-py')
+ assert not pat('subdir/hello.py')
+
+ # wild card (*)
+ pat = compile_matchers(['hello.*']).pop()
+ assert pat('hello.py')
+ assert pat('hello.rst')
+
+ pat = compile_matchers(['*.py']).pop()
+ assert pat('hello.py')
+ assert pat('world.py')
+ assert not pat('subdir/hello.py')
+
+ # wild card (**)
+ pat = compile_matchers(['hello.**']).pop()
+ assert pat('hello.py')
+ assert pat('hello.rst')
+ assert pat('hello.py/world.py')
+
+ pat = compile_matchers(['**.py']).pop()
+ assert pat('hello.py')
+ assert pat('world.py')
+ assert pat('subdir/hello.py')
+
+ pat = compile_matchers(['**/hello.py']).pop()
+ assert not pat('hello.py')
+ assert pat('subdir/hello.py')
+ assert pat('subdir/subdir/hello.py')
+
+ # wild card (?)
+ pat = compile_matchers(['hello.?']).pop()
+ assert pat('hello.c')
+ assert not pat('hello.py')
+
+ # pattern ([...])
+ pat = compile_matchers(['hello[12\\].py']).pop()
+ assert pat('hello1.py')
+ assert pat('hello2.py')
+ assert pat('hello\\.py')
+ assert not pat('hello3.py')
+
+ pat = compile_matchers(['hello[^12].py']).pop() # "^" is not negative identifier
+ assert pat('hello1.py')
+ assert pat('hello2.py')
+ assert pat('hello^.py')
+ assert not pat('hello3.py')
+
+ # negative pattern ([!...])
+ pat = compile_matchers(['hello[!12].py']).pop()
+ assert not pat('hello1.py')
+ assert not pat('hello2.py')
+ assert not pat('hello/.py') # negative pattern does not match to "/"
+ assert pat('hello3.py')
+
+ # non patterns
+ pat = compile_matchers(['hello[.py']).pop()
+ assert pat('hello[.py')
+ assert not pat('hello.py')
+
+ pat = compile_matchers(['hello[].py']).pop()
+ assert pat('hello[].py')
+ assert not pat('hello.py')
+
+ pat = compile_matchers(['hello[!].py']).pop()
+ assert pat('hello[!].py')
+ assert not pat('hello.py')
From bb1e6f9044567fcd05a27bb1cc55f727c86fe2bd Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 3 Jul 2016 15:45:01 +0900
Subject: [PATCH 198/217] Refactor: Replace copy_extra_entry() with
copy_asset()
---
sphinx/builders/html.py | 16 +++++-----
sphinx/util/__init__.py | 31 -------------------
sphinx/util/matching.py | 18 +++++++++++
.../extra/subdir/.htaccess | 0
.../extra/subdir/.htpasswd | 0
tests/test_build_html.py | 2 ++
tests/test_util_matching.py | 10 +++++-
7 files changed, 38 insertions(+), 39 deletions(-)
create mode 100644 tests/roots/test-html_extra_path/extra/subdir/.htaccess
create mode 100644 tests/roots/test-html_extra_path/extra/subdir/.htpasswd
diff --git a/sphinx/builders/html.py b/sphinx/builders/html.py
index 1f1811778..25cdc04bd 100644
--- a/sphinx/builders/html.py
+++ b/sphinx/builders/html.py
@@ -27,12 +27,13 @@ from docutils.frontend import OptionParser
from docutils.readers.doctree import Reader as DoctreeReader
from sphinx import package_dir, __display_version__
-from sphinx.util import jsonimpl, copy_static_entry, copy_extra_entry
+from sphinx.util import jsonimpl, copy_static_entry
from sphinx.util.i18n import format_date
from sphinx.util.osutil import SEP, os_path, relative_uri, ensuredir, \
movefile, copyfile
from sphinx.util.nodes import inline_all_toctrees
-from sphinx.util.matching import patmatch, compile_matchers
+from sphinx.util.fileutil import copy_asset
+from sphinx.util.matching import patmatch, compile_matchers, Matcher
from sphinx.config import string_classes
from sphinx.locale import _, l_
from sphinx.search import js_index
@@ -650,14 +651,15 @@ class StandaloneHTMLBuilder(Builder):
def copy_extra_files(self):
# copy html_extra_path files
self.info(bold('copying extra files... '), nonl=True)
- extraentries = [path.join(self.confdir, epath)
- for epath in self.config.html_extra_path]
- matchers = compile_matchers(self.config.exclude_patterns)
- for entry in extraentries:
+ excluded = Matcher(self.config.exclude_patterns)
+
+ for extra_path in self.config.html_extra_path:
+ entry = path.join(self.confdir, extra_path)
if not path.exists(entry):
self.warn('html_extra_path entry %r does not exist' % entry)
continue
- copy_extra_entry(entry, self.outdir, matchers)
+
+ copy_asset(entry, self.outdir, excluded)
self.info('done')
def write_buildinfo(self):
diff --git a/sphinx/util/__init__.py b/sphinx/util/__init__.py
index e1a65d950..036e57ac0 100644
--- a/sphinx/util/__init__.py
+++ b/sphinx/util/__init__.py
@@ -173,37 +173,6 @@ def copy_static_entry(source, targetdir, builder, context={},
builder, context, level=level+1,
exclude_matchers=exclude_matchers)
-
-def copy_extra_entry(source, targetdir, exclude_matchers=()):
- """Copy a HTML builder extra_path entry from source to targetdir.
-
- Handles all possible cases of files, directories and subdirectories.
- """
- def excluded(path):
- relpath = relative_path(os.path.dirname(source), path)
- return any(matcher(relpath) for matcher in exclude_matchers)
-
- def copy_extra_file(source_, targetdir_):
- if not excluded(source_):
- target = path.join(targetdir_, os.path.basename(source_))
- copyfile(source_, target)
-
- if os.path.isfile(source):
- copy_extra_file(source, targetdir)
- return
-
- for root, dirs, files in os.walk(source):
- reltargetdir = os.path.join(targetdir, relative_path(source, root))
- for dir in dirs[:]:
- if excluded(os.path.join(root, dir)):
- dirs.remove(dir)
- else:
- target = os.path.join(reltargetdir, dir)
- if not path.exists(target):
- os.mkdir(target)
- for file in files:
- copy_extra_file(os.path.join(root, file), reltargetdir)
-
_DEBUG_HEADER = '''\
# Sphinx version: %s
# Python version: %s (%s)
diff --git a/sphinx/util/matching.py b/sphinx/util/matching.py
index 91fda6378..8f17980ca 100644
--- a/sphinx/util/matching.py
+++ b/sphinx/util/matching.py
@@ -62,6 +62,24 @@ def compile_matchers(patterns):
return [re.compile(_translate_pattern(pat)).match for pat in patterns]
+class Matcher(object):
+ """A pattern matcher for Multiple shell-style glob patterns.
+
+ Note: this modifies the patterns to work with copy_asset().
+ For example, "**/index.rst" matches with "index.rst"
+ """
+
+ def __init__(self, patterns):
+ expanded = [pat[3:] for pat in patterns if pat.startswith('**/')]
+ self.patterns = compile_matchers(patterns + expanded)
+
+ def __call__(self, string):
+ return self.match(string)
+
+ def match(self, string):
+ return any(pat(string) for pat in self.patterns)
+
+
_pat_cache = {}
diff --git a/tests/roots/test-html_extra_path/extra/subdir/.htaccess b/tests/roots/test-html_extra_path/extra/subdir/.htaccess
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/roots/test-html_extra_path/extra/subdir/.htpasswd b/tests/roots/test-html_extra_path/extra/subdir/.htpasswd
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/test_build_html.py b/tests/test_build_html.py
index 173ad6cf5..78ef1770c 100644
--- a/tests/test_build_html.py
+++ b/tests/test_build_html.py
@@ -987,6 +987,8 @@ def test_html_extra_path(app, status, warning):
assert (app.outdir / 'rimg.png').exists()
assert not (app.outdir / '_build/index.html').exists()
assert (app.outdir / 'background.png').exists()
+ assert (app.outdir / 'subdir' / '.htaccess').exists()
+ assert not (app.outdir / 'subdir' / '.htpasswd').exists()
@with_app(buildername='html', confoverrides={'html_sourcelink_suffix': ''})
diff --git a/tests/test_util_matching.py b/tests/test_util_matching.py
index fe86c3bbc..9e99a5322 100644
--- a/tests/test_util_matching.py
+++ b/tests/test_util_matching.py
@@ -8,7 +8,7 @@
:copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
-from sphinx.util.matching import compile_matchers
+from sphinx.util.matching import compile_matchers, Matcher
def test_compile_matchers():
@@ -81,3 +81,11 @@ def test_compile_matchers():
pat = compile_matchers(['hello[!].py']).pop()
assert pat('hello[!].py')
assert not pat('hello.py')
+
+
+def test_Matcher():
+ matcher = Matcher(['hello.py', '**/world.py'])
+ assert matcher('hello.py')
+ assert not matcher('subdir/hello.py')
+ assert matcher('world.py')
+ assert matcher('subdir/world.py')
From 02dbf860c2cf530adf85bd7a6325a90e9b3e3ca4 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 3 Jul 2016 16:43:18 +0900
Subject: [PATCH 199/217] Refactor: Use copy_asset() to copy html_static_path
---
sphinx/builders/html.py | 13 ++++++-------
.../conf.py | 3 +++
.../extra/.htaccess | 0
.../extra/.htpasswd | 0
tests/roots/test-html_assets/extra/API.html_t | 1 +
.../extra/css/style.css | 0
.../extra/rimg.png | Bin
.../extra/subdir/.htaccess | 0
.../extra/subdir/.htpasswd | 0
.../index.rst | 0
.../static/.htaccess} | 0
.../static/.htpasswd} | 0
tests/roots/test-html_assets/static/API.html_t | 1 +
.../test-html_assets/static/css/style.css | 0
.../static/rimg.png} | Bin
.../test-html_assets/static/subdir/.htaccess | 0
.../test-html_assets/static/subdir/.htpasswd | 0
.../test-html_assets/subdir/_build/index.html | 0
.../test-html_assets/subdir/background.png | Bin 0 -> 218 bytes
tests/test_build_html.py | 17 +++++++++++++++--
20 files changed, 26 insertions(+), 9 deletions(-)
rename tests/roots/{test-html_extra_path => test-html_assets}/conf.py (63%)
rename tests/roots/{test-html_extra_path => test-html_assets}/extra/.htaccess (100%)
rename tests/roots/{test-html_extra_path => test-html_assets}/extra/.htpasswd (100%)
create mode 100644 tests/roots/test-html_assets/extra/API.html_t
rename tests/roots/{test-html_extra_path => test-html_assets}/extra/css/style.css (100%)
rename tests/roots/{test-html_extra_path => test-html_assets}/extra/rimg.png (100%)
rename tests/roots/{test-html_extra_path => test-html_assets}/extra/subdir/.htaccess (100%)
rename tests/roots/{test-html_extra_path => test-html_assets}/extra/subdir/.htpasswd (100%)
rename tests/roots/{test-html_extra_path => test-html_assets}/index.rst (100%)
rename tests/roots/{test-html_extra_path/extra/API.html_t => test-html_assets/static/.htaccess} (100%)
rename tests/roots/{test-html_extra_path/subdir/_build/index.html => test-html_assets/static/.htpasswd} (100%)
create mode 100644 tests/roots/test-html_assets/static/API.html_t
create mode 100644 tests/roots/test-html_assets/static/css/style.css
rename tests/roots/{test-html_extra_path/subdir/background.png => test-html_assets/static/rimg.png} (100%)
create mode 100644 tests/roots/test-html_assets/static/subdir/.htaccess
create mode 100644 tests/roots/test-html_assets/static/subdir/.htpasswd
create mode 100644 tests/roots/test-html_assets/subdir/_build/index.html
create mode 100644 tests/roots/test-html_assets/subdir/background.png
diff --git a/sphinx/builders/html.py b/sphinx/builders/html.py
index 25cdc04bd..9e8600968 100644
--- a/sphinx/builders/html.py
+++ b/sphinx/builders/html.py
@@ -33,7 +33,7 @@ from sphinx.util.osutil import SEP, os_path, relative_uri, ensuredir, \
movefile, copyfile
from sphinx.util.nodes import inline_all_toctrees
from sphinx.util.fileutil import copy_asset
-from sphinx.util.matching import patmatch, compile_matchers, Matcher
+from sphinx.util.matching import patmatch, Matcher
from sphinx.config import string_classes
from sphinx.locale import _, l_
from sphinx.search import js_index
@@ -620,15 +620,14 @@ class StandaloneHTMLBuilder(Builder):
copy_static_entry(entry, path.join(self.outdir, '_static'),
self, ctx)
# then, copy over all user-supplied static files
- staticentries = [path.join(self.confdir, spath)
- for spath in self.config.html_static_path]
- matchers = compile_matchers(self.config.exclude_patterns)
- for entry in staticentries:
+ excluded = Matcher(self.config.exclude_patterns + ["**/.*"])
+ for static_path in self.config.html_static_path:
+ entry = path.join(self.confdir, static_path)
if not path.exists(entry):
self.warn('html_static_path entry %r does not exist' % entry)
continue
- copy_static_entry(entry, path.join(self.outdir, '_static'), self,
- ctx, exclude_matchers=matchers)
+ copy_asset(entry, path.join(self.outdir, '_static'), excluded,
+ context=ctx, renderer=self.templates)
# copy logo and favicon files if not already in static path
if self.config.html_logo:
logobase = path.basename(self.config.html_logo)
diff --git a/tests/roots/test-html_extra_path/conf.py b/tests/roots/test-html_assets/conf.py
similarity index 63%
rename from tests/roots/test-html_extra_path/conf.py
rename to tests/roots/test-html_assets/conf.py
index 53ee62197..a17e417a3 100644
--- a/tests/roots/test-html_extra_path/conf.py
+++ b/tests/roots/test-html_assets/conf.py
@@ -1,6 +1,9 @@
# -*- coding: utf-8 -*-
master_doc = 'index'
+project = 'Sphinx'
+version = '1.4.4'
+html_static_path = ['static', 'subdir']
html_extra_path = ['extra', 'subdir']
exclude_patterns = ['**/_build', '**/.htpasswd']
diff --git a/tests/roots/test-html_extra_path/extra/.htaccess b/tests/roots/test-html_assets/extra/.htaccess
similarity index 100%
rename from tests/roots/test-html_extra_path/extra/.htaccess
rename to tests/roots/test-html_assets/extra/.htaccess
diff --git a/tests/roots/test-html_extra_path/extra/.htpasswd b/tests/roots/test-html_assets/extra/.htpasswd
similarity index 100%
rename from tests/roots/test-html_extra_path/extra/.htpasswd
rename to tests/roots/test-html_assets/extra/.htpasswd
diff --git a/tests/roots/test-html_assets/extra/API.html_t b/tests/roots/test-html_assets/extra/API.html_t
new file mode 100644
index 000000000..34ecd9df1
--- /dev/null
+++ b/tests/roots/test-html_assets/extra/API.html_t
@@ -0,0 +1 @@
+{{ project }}-{{ version }}
diff --git a/tests/roots/test-html_extra_path/extra/css/style.css b/tests/roots/test-html_assets/extra/css/style.css
similarity index 100%
rename from tests/roots/test-html_extra_path/extra/css/style.css
rename to tests/roots/test-html_assets/extra/css/style.css
diff --git a/tests/roots/test-html_extra_path/extra/rimg.png b/tests/roots/test-html_assets/extra/rimg.png
similarity index 100%
rename from tests/roots/test-html_extra_path/extra/rimg.png
rename to tests/roots/test-html_assets/extra/rimg.png
diff --git a/tests/roots/test-html_extra_path/extra/subdir/.htaccess b/tests/roots/test-html_assets/extra/subdir/.htaccess
similarity index 100%
rename from tests/roots/test-html_extra_path/extra/subdir/.htaccess
rename to tests/roots/test-html_assets/extra/subdir/.htaccess
diff --git a/tests/roots/test-html_extra_path/extra/subdir/.htpasswd b/tests/roots/test-html_assets/extra/subdir/.htpasswd
similarity index 100%
rename from tests/roots/test-html_extra_path/extra/subdir/.htpasswd
rename to tests/roots/test-html_assets/extra/subdir/.htpasswd
diff --git a/tests/roots/test-html_extra_path/index.rst b/tests/roots/test-html_assets/index.rst
similarity index 100%
rename from tests/roots/test-html_extra_path/index.rst
rename to tests/roots/test-html_assets/index.rst
diff --git a/tests/roots/test-html_extra_path/extra/API.html_t b/tests/roots/test-html_assets/static/.htaccess
similarity index 100%
rename from tests/roots/test-html_extra_path/extra/API.html_t
rename to tests/roots/test-html_assets/static/.htaccess
diff --git a/tests/roots/test-html_extra_path/subdir/_build/index.html b/tests/roots/test-html_assets/static/.htpasswd
similarity index 100%
rename from tests/roots/test-html_extra_path/subdir/_build/index.html
rename to tests/roots/test-html_assets/static/.htpasswd
diff --git a/tests/roots/test-html_assets/static/API.html_t b/tests/roots/test-html_assets/static/API.html_t
new file mode 100644
index 000000000..34ecd9df1
--- /dev/null
+++ b/tests/roots/test-html_assets/static/API.html_t
@@ -0,0 +1 @@
+{{ project }}-{{ version }}
diff --git a/tests/roots/test-html_assets/static/css/style.css b/tests/roots/test-html_assets/static/css/style.css
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/roots/test-html_extra_path/subdir/background.png b/tests/roots/test-html_assets/static/rimg.png
similarity index 100%
rename from tests/roots/test-html_extra_path/subdir/background.png
rename to tests/roots/test-html_assets/static/rimg.png
diff --git a/tests/roots/test-html_assets/static/subdir/.htaccess b/tests/roots/test-html_assets/static/subdir/.htaccess
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/roots/test-html_assets/static/subdir/.htpasswd b/tests/roots/test-html_assets/static/subdir/.htpasswd
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/roots/test-html_assets/subdir/_build/index.html b/tests/roots/test-html_assets/subdir/_build/index.html
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/roots/test-html_assets/subdir/background.png b/tests/roots/test-html_assets/subdir/background.png
new file mode 100644
index 0000000000000000000000000000000000000000..1081dc1439fb984dfa7ef627afe3c7dc476fdbce
GIT binary patch
literal 218
zcmeAS@N?(olHy`uVBq!ia0vp^j6iI|!3HFkf4uMuBv2gW?!>U}oXkrghqJ&VvY3H^
zTNs2H8D`Cq01C2~c>21s-(chw7$R|bZ|_0D0|q>YSbqDzW^|HYIk%*-&O)*\na + 1 < b' in content
-@with_app(buildername='html', testroot='html_extra_path')
-def test_html_extra_path(app, status, warning):
+@with_app(buildername='html', testroot='html_assets')
+def test_html_assets(app, status, warning):
app.builder.build_all()
+ # html_static_path
+ assert not (app.outdir / '_static' / '.htaccess').exists()
+ assert not (app.outdir / '_static' / '.htpasswd').exists()
+ assert (app.outdir / '_static' / 'API.html').exists()
+ assert (app.outdir / '_static' / 'API.html').text() == 'Sphinx-1.4.4'
+ assert (app.outdir / '_static' / 'css/style.css').exists()
+ assert (app.outdir / '_static' / 'rimg.png').exists()
+ assert not (app.outdir / '_static' / '_build/index.html').exists()
+ assert (app.outdir / '_static' / 'background.png').exists()
+ assert not (app.outdir / '_static' / 'subdir' / '.htaccess').exists()
+ assert not (app.outdir / '_static' / 'subdir' / '.htpasswd').exists()
+
+ # html_extra_path
assert (app.outdir / '.htaccess').exists()
assert not (app.outdir / '.htpasswd').exists()
assert (app.outdir / 'API.html_t').exists()
From f8955b16d6c5b03b95d2a5ee85b739a1de307d2e Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 3 Jul 2016 17:16:28 +0900
Subject: [PATCH 200/217] Replace all copy_static_entry() with copy_asset()
At same time, copy_static_entry() is now deprecataed
---
CHANGES | 2 ++
sphinx/builders/applehelp.py | 14 ++++++--------
sphinx/builders/changes.py | 12 +++++-------
sphinx/builders/html.py | 13 ++++++-------
sphinx/util/__init__.py | 2 +-
sphinx/util/fileutil.py | 6 ++++++
sphinx/util/matching.py | 3 +++
7 files changed, 29 insertions(+), 23 deletions(-)
diff --git a/CHANGES b/CHANGES
index 1f007c479..c6812b714 100644
--- a/CHANGES
+++ b/CHANGES
@@ -21,6 +21,8 @@ Incompatible changes
* #2454: The filename of sourcelink is now changed. The value of
`html_sourcelink_suffix` will be appended to the original filename (like
``index.rst.txt``).
+* ``sphinx.util.copy_static_entry()`` is now deprecated.
+ Use ``sphinx.util.fileutil.copy_asset()`` instead.
Features added
diff --git a/sphinx/builders/applehelp.py b/sphinx/builders/applehelp.py
index 095457b80..e8a476f60 100644
--- a/sphinx/builders/applehelp.py
+++ b/sphinx/builders/applehelp.py
@@ -18,11 +18,11 @@ import shlex
from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.config import string_classes
-from sphinx.util import copy_static_entry
from sphinx.util.osutil import copyfile, ensuredir, make_filename
from sphinx.util.console import bold
+from sphinx.util.fileutil import copy_asset
from sphinx.util.pycompat import htmlescape
-from sphinx.util.matching import compile_matchers
+from sphinx.util.matching import Matcher
from sphinx.errors import SphinxError
import plistlib
@@ -107,17 +107,15 @@ class AppleHelpBuilder(StandaloneHTMLBuilder):
self.finish_tasks.add_task(self.build_helpbook)
def copy_localized_files(self):
- source_dir = path.join(self.confdir,
- self.config.applehelp_locale + '.lproj')
+ source_dir = path.join(self.confdir, self.config.applehelp_locale + '.lproj')
target_dir = self.outdir
if path.isdir(source_dir):
self.info(bold('copying localized files... '), nonl=True)
- ctx = self.globalcontext.copy()
- matchers = compile_matchers(self.config.exclude_patterns)
- copy_static_entry(source_dir, target_dir, self, ctx,
- exclude_matchers=matchers)
+ excluded = Matcher(self.config.exclude_patterns + ['**/.*'])
+ copy_asset(source_dir, target_dir, excluded,
+ context=self.globalcontext, renderer=self.templates)
self.info('done')
diff --git a/sphinx/builders/changes.py b/sphinx/builders/changes.py
index 18f94adca..1bccb67d9 100644
--- a/sphinx/builders/changes.py
+++ b/sphinx/builders/changes.py
@@ -15,12 +15,12 @@ from os import path
from six import iteritems
from sphinx import package_dir
-from sphinx.util import copy_static_entry
from sphinx.locale import _
from sphinx.theming import Theme
from sphinx.builders import Builder
from sphinx.util.osutil import ensuredir, os_path
from sphinx.util.console import bold
+from sphinx.util.fileutil import copy_asset_file
from sphinx.util.pycompat import htmlescape
@@ -138,12 +138,10 @@ class ChangesBuilder(Builder):
f.write(self.templates.render('changes/rstsource.html', ctx))
themectx = dict(('theme_' + key, val) for (key, val) in
iteritems(self.theme.get_options({})))
- copy_static_entry(path.join(package_dir, 'themes', 'default',
- 'static', 'default.css_t'),
- self.outdir, self, themectx)
- copy_static_entry(path.join(package_dir, 'themes', 'basic',
- 'static', 'basic.css'),
- self.outdir, self)
+ copy_asset_file(path.join(package_dir, 'themes', 'default', 'static', 'default.css_t'),
+ self.outdir, context=themectx, renderer=self.templates)
+ copy_asset_file(path.join(package_dir, 'themes', 'basic', 'static', 'basic.css'),
+ self.outdir)
def hl(self, text, version):
text = htmlescape(text)
diff --git a/sphinx/builders/html.py b/sphinx/builders/html.py
index 9e8600968..f670c1399 100644
--- a/sphinx/builders/html.py
+++ b/sphinx/builders/html.py
@@ -27,13 +27,13 @@ from docutils.frontend import OptionParser
from docutils.readers.doctree import Reader as DoctreeReader
from sphinx import package_dir, __display_version__
-from sphinx.util import jsonimpl, copy_static_entry
+from sphinx.util import jsonimpl
from sphinx.util.i18n import format_date
from sphinx.util.osutil import SEP, os_path, relative_uri, ensuredir, \
movefile, copyfile
from sphinx.util.nodes import inline_all_toctrees
from sphinx.util.fileutil import copy_asset
-from sphinx.util.matching import patmatch, Matcher
+from sphinx.util.matching import patmatch, Matcher, DOTFILES
from sphinx.config import string_classes
from sphinx.locale import _, l_
from sphinx.search import js_index
@@ -614,11 +614,10 @@ class StandaloneHTMLBuilder(Builder):
# then, copy over theme-supplied static files
if self.theme:
- themeentries = [path.join(themepath, 'static')
- for themepath in self.theme.get_dirchain()[::-1]]
- for entry in themeentries:
- copy_static_entry(entry, path.join(self.outdir, '_static'),
- self, ctx)
+ for theme_path in self.theme.get_dirchain()[::-1]:
+ entry = path.join(theme_path, 'static')
+ copy_asset(entry, path.join(self.outdir, '_static'), excluded=DOTFILES,
+ context=ctx, renderer=self.templates)
# then, copy over all user-supplied static files
excluded = Matcher(self.config.exclude_patterns + ["**/.*"])
for static_path in self.config.html_static_path:
diff --git a/sphinx/util/__init__.py b/sphinx/util/__init__.py
index 036e57ac0..a0dababc8 100644
--- a/sphinx/util/__init__.py
+++ b/sphinx/util/__init__.py
@@ -149,7 +149,7 @@ class FilenameUniqDict(dict):
def copy_static_entry(source, targetdir, builder, context={},
exclude_matchers=(), level=0):
- """Copy a HTML builder static_path entry from source to targetdir.
+ """[DEPRECATED] Copy a HTML builder static_path entry from source to targetdir.
Handles all possible cases of files, directories and subdirectories.
"""
diff --git a/sphinx/util/fileutil.py b/sphinx/util/fileutil.py
index 8ab590472..1d2797b9c 100644
--- a/sphinx/util/fileutil.py
+++ b/sphinx/util/fileutil.py
@@ -26,6 +26,9 @@ def copy_asset_file(source, destination, context=None, renderer=None):
:param context: The template variables. If not given, template files are simply copied
:param renderer: The template engine
"""
+ if not os.path.exists(source):
+ return
+
if os.path.exists(destination) and os.path.isdir(destination):
# Use source filename if destination points a directory
destination = os.path.join(destination, os.path.basename(source))
@@ -54,6 +57,9 @@ def copy_asset(source, destination, excluded=lambda path: False, context=None, r
:param context: The template variables. If not given, template files are simply copied
:param renderer: The template engine
"""
+ if not os.path.exists(source):
+ return
+
ensuredir(destination)
if os.path.isfile(source):
copy_asset_file(source, destination, context, renderer)
diff --git a/sphinx/util/matching.py b/sphinx/util/matching.py
index 8f17980ca..fc7750be9 100644
--- a/sphinx/util/matching.py
+++ b/sphinx/util/matching.py
@@ -80,6 +80,9 @@ class Matcher(object):
return any(pat(string) for pat in self.patterns)
+DOTFILES = Matcher(['**/.*'])
+
+
_pat_cache = {}
From d99c6c11fc01eea13a62f0a600bc1187b0345e42 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Thu, 7 Jul 2016 11:46:42 +0900
Subject: [PATCH 201/217] ``sphinx.util.osutil.filecopy()`` skips copying if
the file has not been changed (ref: #2510, #2753)
---
CHANGES | 2 ++
sphinx/util/osutil.py | 18 +++++++++++-------
2 files changed, 13 insertions(+), 7 deletions(-)
diff --git a/CHANGES b/CHANGES
index c6812b714..cc3a4b184 100644
--- a/CHANGES
+++ b/CHANGES
@@ -23,6 +23,8 @@ Incompatible changes
``index.rst.txt``).
* ``sphinx.util.copy_static_entry()`` is now deprecated.
Use ``sphinx.util.fileutil.copy_asset()`` instead.
+* ``sphinx.util.osutil.filecopy()`` skips copying if the file has not been changed
+ (ref: #2510, #2753)
Features added
diff --git a/sphinx/util/osutil.py b/sphinx/util/osutil.py
index 585dc6104..0de6d8472 100644
--- a/sphinx/util/osutil.py
+++ b/sphinx/util/osutil.py
@@ -17,6 +17,7 @@ import time
import errno
import locale
import shutil
+import filecmp
from os import path
import contextlib
@@ -141,13 +142,16 @@ def copytimes(source, dest):
def copyfile(source, dest):
- """Copy a file and its modification times, if possible."""
- shutil.copyfile(source, dest)
- try:
- # don't do full copystat because the source may be read-only
- copytimes(source, dest)
- except OSError:
- pass
+ """Copy a file and its modification times, if possible.
+
+ Note: ``copyfile`` skips copying if the file has not been changed"""
+ if not path.exists(dest) or not filecmp.cmp(source, dest):
+ shutil.copyfile(source, dest)
+ try:
+ # don't do full copystat because the source may be read-only
+ copytimes(source, dest)
+ except OSError:
+ pass
no_fn_re = re.compile(r'[^a-zA-Z0-9_-]')
From cc3e4fba75c20196bfb687190eb1f784b09222e0 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Wed, 6 Jul 2016 21:00:49 +0900
Subject: [PATCH 202/217] Jinja2-ize latex writer
---
sphinx/templates/latex/content.tex_t | 42 ++++++++++++++++++++
sphinx/util/template.py | 57 ++++++++++++++++++++++++++++
sphinx/writers/latex.py | 54 ++++----------------------
3 files changed, 106 insertions(+), 47 deletions(-)
create mode 100644 sphinx/templates/latex/content.tex_t
create mode 100644 sphinx/util/template.py
diff --git a/sphinx/templates/latex/content.tex_t b/sphinx/templates/latex/content.tex_t
new file mode 100644
index 000000000..fb5b1decd
--- /dev/null
+++ b/sphinx/templates/latex/content.tex_t
@@ -0,0 +1,42 @@
+%% Generated by Sphinx.
+\def\sphinxdocclass{<%= docclass %>}
+\newif\ifsphinxKeepOldNames <%= keepoldnames %>
+\documentclass[<%= papersize %>,<%= pointsize %><%= classoptions %>]{<%= wrapperclass %>}
+\ifdefined\pdfpxdimen
+ \let\sphinxpxdimen\pdfpxdimen\else\newdimen\sphinxpxdimen
+\fi \sphinxpxdimen=<%= pxunit %>\relax
+\usepackage{iftex}
+<%= passoptionstopackages %>
+<%= inputenc %>
+<%= utf8extra %>
+<%= cmappkg %>
+<%= fontenc %>
+<%= amsmath %>
+<%= babel %>
+<%= fontpkg %>
+<%= fncychap %>
+<%= longtable %>
+\usepackage{sphinx}
+\usepackage{multirow}
+\usepackage{eqparbox}
+<%= usepackages %>
+<%= contentsname %>
+<%= numfig_format %>
+<%= pageautorefname %>
+<%= tocdepth %>
+<%= secnumdepth %>
+<%= preamble %>
+
+\title{<%= title %>}
+\date{<%= date %>}
+\release{<%= release %>}
+\author{<%= author %>}
+\newcommand{\sphinxlogo}{<%= logo %>}
+\renewcommand{\releasename}{<%= releasename %>}
+<%= makeindex %>
+<%= body %>
+<%= footer %>
+<%= indices %>
+\renewcommand{\indexname}{<%= indexname %>}
+<%= printindex %>
+\end{document}
diff --git a/sphinx/util/template.py b/sphinx/util/template.py
new file mode 100644
index 000000000..b89a4c960
--- /dev/null
+++ b/sphinx/util/template.py
@@ -0,0 +1,57 @@
+# -*- coding: utf-8 -*-
+"""
+ sphinx.util.template
+ ~~~~~~~~~~~~~~~~~~~~
+
+ Templates utility functions for Sphinx.
+
+ :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+
+import os
+from jinja2.sandbox import SandboxedEnvironment
+
+from sphinx import package_dir
+from sphinx.jinja2glue import SphinxFileSystemLoader
+
+
+class BaseRenderer(object):
+ def __init__(self, loader=None):
+ self.env = SandboxedEnvironment(loader=loader)
+ self.env.filters['repr'] = repr
+
+ def render(self, template_name, context):
+ return self.env.get_template(template_name).render(context)
+
+ def render_string(self, source, context):
+ return self.env.from_string(source).render(context)
+
+
+class FileRenderer(BaseRenderer):
+ def __init__(self, search_path):
+ loader = SphinxFileSystemLoader(search_path)
+ super(FileRenderer, self).__init__(loader)
+
+ @classmethod
+ def render_from_file(cls, filename, context):
+ dirname = os.path.dirname(filename)
+ basename = os.path.basename(filename)
+ return cls(dirname).render(basename, context)
+
+
+class SphinxRenderer(FileRenderer):
+ def __init__(self):
+ super(SphinxRenderer, self).__init__(os.path.join(package_dir, 'templates'))
+
+
+class LaTeXRenderer(SphinxRenderer):
+ def __init__(self):
+ super(LaTeXRenderer, self).__init__()
+
+ # use JSP/eRuby like tagging instead because curly bracket; the default
+ # tagging of jinja2 is not good for LaTeX sources.
+ self.env.variable_start_string = '<%='
+ self.env.variable_end_string = '%>'
+ self.env.block_start_string = '<%'
+ self.env.block_end_string = '%>'
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index 528aca192..72050ad89 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -28,46 +28,10 @@ from sphinx.locale import admonitionlabels, _
from sphinx.util import split_into
from sphinx.util.i18n import format_date
from sphinx.util.nodes import clean_astext, traverse_parent
+from sphinx.util.template import LaTeXRenderer
from sphinx.util.texescape import tex_escape_map, tex_replace_map
from sphinx.util.smartypants import educate_quotes_latex
-HEADER = r'''%% Generated by Sphinx.
-\def\sphinxdocclass{%(docclass)s}
-\newif\ifsphinxKeepOldNames %(keepoldnames)s
-\documentclass[%(papersize)s,%(pointsize)s%(classoptions)s]{%(wrapperclass)s}
-\ifdefined\pdfpxdimen
- \let\sphinxpxdimen\pdfpxdimen\else\newdimen\sphinxpxdimen
-\fi \sphinxpxdimen=%(pxunit)s\relax
-\usepackage{iftex}
-%(passoptionstopackages)s
-%(inputenc)s
-%(utf8extra)s
-%(cmappkg)s
-%(fontenc)s
-%(amsmath)s
-%(babel)s
-%(fontpkg)s
-%(fncychap)s
-%(longtable)s
-\usepackage{sphinx}
-\usepackage{multirow}
-\usepackage{eqparbox}
-%(usepackages)s
-%(contentsname)s
-%(numfig_format)s
-%(pageautorefname)s
-%(tocdepth)s
-%(secnumdepth)s
-%(preamble)s
-
-\title{%(title)s}
-\date{%(date)s}
-\release{%(release)s}
-\author{%(author)s}
-\newcommand{\sphinxlogo}{%(logo)s}
-\renewcommand{\releasename}{%(releasename)s}
-%(makeindex)s
-'''
BEGIN_DOC = r'''
\begin{document}
@@ -76,12 +40,8 @@ BEGIN_DOC = r'''
%(tableofcontents)s
'''
-FOOTER = r'''
-\renewcommand{\indexname}{%(indexname)s}
-%(printindex)s
-\end{document}
-'''
+DEFAULT_TEMPLATE = 'latex/content.tex_t'
URI_SCHEMES = ('mailto:', 'http:', 'https:', 'ftp:')
SECNUMDEPTH = 3
@@ -543,11 +503,11 @@ class LaTeXTranslator(nodes.NodeVisitor):
return docclass
def astext(self):
- return (HEADER % self.elements +
- u''.join(self.body) +
- '\n' + self.elements['footer'] + '\n' +
- self.generate_indices() +
- FOOTER % self.elements)
+ self.elements.update({
+ 'body': u''.join(self.body),
+ 'indices': self.generate_indices()
+ })
+ return LaTeXRenderer().render(DEFAULT_TEMPLATE, self.elements)
def hypertarget(self, id, withdoc=True, anchor=True):
if withdoc:
From c06b21725d021902960a3eafb0f339aa0dd8862a Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Thu, 7 Jul 2016 22:22:01 +0900
Subject: [PATCH 203/217] Fix invalid variable name was used
---
sphinx/builders/latex.py | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/sphinx/builders/latex.py b/sphinx/builders/latex.py
index 3bd1ebc06..d3b9d97a8 100644
--- a/sphinx/builders/latex.py
+++ b/sphinx/builders/latex.py
@@ -50,8 +50,8 @@ class LaTeXBuilder(Builder):
def check_options(self):
if self.config.latex_toplevel_sectioning not in (None, 'part', 'chapter', 'section'):
self.warn('invalid latex_toplevel_sectioning, ignored: %s' %
- self.config.latex_top_sectionlevel)
- self.config.latex_top_sectionlevel = None
+ self.config.latex_toplevel_sectioning)
+ self.config.latex_toplevel_sectioning = None
if self.config.latex_use_parts:
warnings.warn('latex_use_parts will be removed at Sphinx-1.5. '
From 27fe1cfed5d6db163aba9b82e00517adbdc9afc1 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Thu, 7 Jul 2016 22:23:35 +0900
Subject: [PATCH 204/217] latex: validate config values on builder-inited event
---
sphinx/builders/latex.py | 31 ++++++++++++++++---------------
1 file changed, 16 insertions(+), 15 deletions(-)
diff --git a/sphinx/builders/latex.py b/sphinx/builders/latex.py
index d3b9d97a8..19af4768e 100644
--- a/sphinx/builders/latex.py
+++ b/sphinx/builders/latex.py
@@ -45,21 +45,6 @@ class LaTeXBuilder(Builder):
self.docnames = []
self.document_data = []
texescape.init()
- self.check_options()
-
- def check_options(self):
- if self.config.latex_toplevel_sectioning not in (None, 'part', 'chapter', 'section'):
- self.warn('invalid latex_toplevel_sectioning, ignored: %s' %
- self.config.latex_toplevel_sectioning)
- self.config.latex_toplevel_sectioning = None
-
- if self.config.latex_use_parts:
- warnings.warn('latex_use_parts will be removed at Sphinx-1.5. '
- 'Use latex_toplevel_sectioning instead.',
- DeprecationWarning)
-
- if self.config.latex_toplevel_sectioning:
- self.warn('latex_use_parts conflicts with latex_toplevel_sectioning, ignored.')
def get_outdated_docs(self):
return 'all documents' # for now
@@ -236,8 +221,24 @@ class LaTeXBuilder(Builder):
self.info('done')
+def validate_config_values(app):
+ if app.config.latex_toplevel_sectioning not in (None, 'part', 'chapter', 'section'):
+ app.warn('invalid latex_toplevel_sectioning, ignored: %s' %
+ app.config.latex_toplevel_sectioning)
+ app.config.latex_toplevel_sectioning = None
+
+ if app.config.latex_use_parts:
+ warnings.warn('latex_use_parts will be removed at Sphinx-1.5. '
+ 'Use latex_toplevel_sectioning instead.',
+ DeprecationWarning)
+
+ if app.config.latex_toplevel_sectioning:
+ app.warn('latex_use_parts conflicts with latex_toplevel_sectioning, ignored.')
+
+
def setup(app):
app.add_builder(LaTeXBuilder)
+ app.connect('builder-inited', validate_config_values)
app.add_config_value('latex_documents',
lambda self: [(self.master_doc, make_filename(self.project) + '.tex',
From 77f9bbd9cc67d591a95b50310f26a8ec6721b763 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ville=20Skytt=C3=A4?=
Date: Thu, 7 Jul 2016 16:21:18 +0300
Subject: [PATCH 205/217] Travis: Run style-check with Python 3.5
Doing this with 3.5 only, because the PEP 484 annotation examples in
docs won't compile with old Python versions, causing failures.
---
.travis.yml | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/.travis.yml b/.travis.yml
index 91ad798e7..45bf4bb40 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -31,6 +31,5 @@ install:
- pip install -r test-reqs.txt
before_script: flake8
script:
-
- - if [[ $TRAVIS_PYTHON_VERSION == '3.5' ]]; then make test-async; fi
+ - if [[ $TRAVIS_PYTHON_VERSION == '3.5' ]]; then make style-check test-async; fi
- if [[ $TRAVIS_PYTHON_VERSION != '3.5' ]]; then make test; fi
From 7cfbc2a70267422986c816f254f6abf2f323e748 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ville=20Skytt=C3=A4?=
Date: Thu, 7 Jul 2016 16:36:44 +0300
Subject: [PATCH 206/217] Fix style checks
---
doc/ext/doctest.rst | 2 +-
doc/ext/inheritance.rst | 2 +-
tests/test_directive_code.py | 3 ++-
3 files changed, 4 insertions(+), 3 deletions(-)
diff --git a/doc/ext/doctest.rst b/doc/ext/doctest.rst
index 3d4f66a9a..818b86007 100644
--- a/doc/ext/doctest.rst
+++ b/doc/ext/doctest.rst
@@ -182,7 +182,7 @@ The doctest extension uses the following configuration values:
.. confval:: doctest_default_flags
By default, these options are enabled:
-
+
- ``ELLIPSIS``, allowing you to put ellipses in the expected output that
match anything in the actual output;
- ``IGNORE_EXCEPTION_DETAIL``, causing everything following the leftmost
diff --git a/doc/ext/inheritance.rst b/doc/ext/inheritance.rst
index dd8d5aa99..bd287aa49 100644
--- a/doc/ext/inheritance.rst
+++ b/doc/ext/inheritance.rst
@@ -40,7 +40,7 @@ It adds this directive:
included.
.. versionchanged:: 1.5
- Added ``caption`` option
+ Added ``caption`` option
New config values are:
diff --git a/tests/test_directive_code.py b/tests/test_directive_code.py
index f4abab935..175e1881e 100644
--- a/tests/test_directive_code.py
+++ b/tests/test_directive_code.py
@@ -228,7 +228,8 @@ def test_literalinclude_file_whole_of_emptyline(app, status, warning):
app.builder.build_all()
latex = (app.outdir / 'Python.tex').text(encoding='utf-8').replace('\r\n', '\n')
includes = (
- '\\begin{sphinxVerbatim}[commandchars=\\\\\\{\\},numbers=left,firstnumber=1,stepnumber=1]\n'
+ '\\begin{sphinxVerbatim}'
+ '[commandchars=\\\\\\{\\},numbers=left,firstnumber=1,stepnumber=1]\n'
'\n'
'\n'
'\n'
From 2e83592ae76f78f27c3a45402af4dc7c2729095d Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Thu, 7 Jul 2016 23:15:51 +0900
Subject: [PATCH 207/217] Show warnings if deprecated latex options are used
---
CHANGES | 1 +
sphinx/builders/latex.py | 33 +++++++++++++++++++++++++++++----
sphinx/writers/latex.py | 12 +-----------
3 files changed, 31 insertions(+), 15 deletions(-)
diff --git a/CHANGES b/CHANGES
index c6812b714..772a33199 100644
--- a/CHANGES
+++ b/CHANGES
@@ -61,6 +61,7 @@ Features added
* #2650: Add ``--pdb`` option to setup.py command
* latex, make the use of ``\small`` for code listings customizable (ref #2721)
* #2663: Add ``--warning-is-error`` option to setup.py command
+* Show warnings if deprecated latex options are used
Bugs fixed
diff --git a/sphinx/builders/latex.py b/sphinx/builders/latex.py
index 19af4768e..9f45aa2a4 100644
--- a/sphinx/builders/latex.py
+++ b/sphinx/builders/latex.py
@@ -228,12 +228,37 @@ def validate_config_values(app):
app.config.latex_toplevel_sectioning = None
if app.config.latex_use_parts:
- warnings.warn('latex_use_parts will be removed at Sphinx-1.5. '
- 'Use latex_toplevel_sectioning instead.',
- DeprecationWarning)
-
if app.config.latex_toplevel_sectioning:
app.warn('latex_use_parts conflicts with latex_toplevel_sectioning, ignored.')
+ else:
+ app.warn('latex_use_parts is deprecated. Use latex_toplevel_sectioning instead.')
+ app.config.latex_toplevel_sectioning = 'parts'
+
+ if app.config.latex_use_modindex is not True: # changed by user
+ app.warn('latex_use_modeindex is deprecated. Use latex_domain_indices instead.')
+
+ if app.config.latex_preamble:
+ if app.config.latex_elements.get('preamble'):
+ app.warn("latex_preamble conflicts with latex_elements['preamble'], ignored.")
+ else:
+ app.warn("latex_preamble is deprecated. Use latex_elements['preamble'] instead.")
+ app.config.latex_elements['preamble'] = app.config.latex_preamble
+
+ if app.config.latex_paper_size != 'letter':
+ if app.config.latex_elements.get('papersize'):
+ app.warn("latex_paper_size conflicts with latex_elements['papersize'], ignored.")
+ else:
+ app.warn("latex_paper_size is deprecated. "
+ "Use latex_elements['papersize'] instead.")
+ if app.config.latex_paper_size:
+ app.config.latex_elements['papersize'] = app.config.latex_paper_size + 'paper'
+
+ if app.config.latex_font_size != '10pt':
+ if app.config.latex_elements.get('pointsize'):
+ app.warn("latex_font_size conflicts with latex_elements['pointsize'], ignored.")
+ else:
+ app.warn("latex_font_size is deprecated. Use latex_elements['pointsize'] instead.")
+ app.config.latex_elements['pointsize'] = app.config.latex_font_size
def setup(app):
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index 72050ad89..7685405c7 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -335,27 +335,17 @@ class LaTeXTranslator(nodes.NodeVisitor):
if document.settings.docclass == 'howto':
self.top_sectionlevel = 2
else:
- if builder.config.latex_use_parts:
- self.top_sectionlevel = 0
- else:
- self.top_sectionlevel = 1
+ self.top_sectionlevel = 1
# sort out some elements
- papersize = builder.config.latex_paper_size + 'paper'
- if papersize == 'paper': # e.g. command line "-D latex_paper_size="
- papersize = 'letterpaper'
-
self.elements = self.default_elements.copy()
self.elements.update({
'wrapperclass': self.format_docclass(document.settings.docclass),
- 'papersize': papersize,
- 'pointsize': builder.config.latex_font_size,
# if empty, the title is set to the first section title
'title': document.settings.title,
'release': builder.config.release,
'author': document.settings.author,
'releasename': _('Release'),
- 'preamble': builder.config.latex_preamble,
'indexname': _('Index'),
})
# set-up boolean for sphinx.sty
From d984852908b130474b4a7e70836244f56776df05 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Thu, 7 Jul 2016 23:41:13 +0900
Subject: [PATCH 208/217] Fix flake8 violation
---
sphinx/builders/latex.py | 1 -
1 file changed, 1 deletion(-)
diff --git a/sphinx/builders/latex.py b/sphinx/builders/latex.py
index 9f45aa2a4..f82e7ade0 100644
--- a/sphinx/builders/latex.py
+++ b/sphinx/builders/latex.py
@@ -11,7 +11,6 @@
import os
from os import path
-import warnings
from six import iteritems
from docutils import nodes
From 5991bbe4ac8513c018def7042c06ae64cd33cabd Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Sun, 3 Jul 2016 23:55:15 +0900
Subject: [PATCH 209/217] Add sphinx.config.ENUM to check the config values is
in candidates
---
CHANGES | 1 +
sphinx/config.py | 42 ++++++++++++++++++++++++---------
tests/roots/test-config/conf.py | 3 ++-
tests/test_config.py | 12 ++++++++++
4 files changed, 46 insertions(+), 12 deletions(-)
diff --git a/CHANGES b/CHANGES
index d7397684b..c87c71afa 100644
--- a/CHANGES
+++ b/CHANGES
@@ -64,6 +64,7 @@ Features added
* latex, make the use of ``\small`` for code listings customizable (ref #2721)
* #2663: Add ``--warning-is-error`` option to setup.py command
* Show warnings if deprecated latex options are used
+* Add sphinx.config.ENUM to check the config values is in candidates
Bugs fixed
diff --git a/sphinx/config.py b/sphinx/config.py
index b0acdedb8..13921aac8 100644
--- a/sphinx/config.py
+++ b/sphinx/config.py
@@ -28,10 +28,25 @@ if PY3:
CONFIG_SYNTAX_ERROR += "\nDid you change the syntax from 2.x to 3.x?"
CONFIG_EXIT_ERROR = "The configuration file (or one of the modules it imports) " \
"called sys.exit()"
+CONFIG_ENUM_WARNING = "The config value `{name}` has to be a one of {candidates}, " \
+ "but `{current}` is given."
CONFIG_TYPE_WARNING = "The config value `{name}' has type `{current.__name__}', " \
"defaults to `{default.__name__}.'"
+class ENUM:
+ """represents the config value should be a one of candidates.
+
+ Example:
+ app.add_config_value('latex_show_urls', 'no', ENUM('no', 'footnote', 'inline'))
+ """
+ def __init__(self, *candidates):
+ self.candidates = candidates
+
+ def match(self, value):
+ return value in self.candidates
+
+
string_classes = [text_type]
if PY2:
string_classes.append(binary_type) # => [str, unicode]
@@ -150,19 +165,24 @@ class Config(object):
if default is None and not permitted:
continue # neither inferrable nor expliclitly permitted types
current = self[name]
- if type(current) is type(default):
- continue
- if type(current) in permitted:
- continue
+ if isinstance(permitted, ENUM):
+ if not permitted.match(current):
+ warn(CONFIG_ENUM_WARNING.format(
+ name=name, current=current, candidates=permitted.candidates))
+ else:
+ if type(current) is type(default):
+ continue
+ if type(current) in permitted:
+ continue
- common_bases = (set(type(current).__bases__ + (type(current),)) &
- set(type(default).__bases__))
- common_bases.discard(object)
- if common_bases:
- continue # at least we share a non-trivial base class
+ common_bases = (set(type(current).__bases__ + (type(current),)) &
+ set(type(default).__bases__))
+ common_bases.discard(object)
+ if common_bases:
+ continue # at least we share a non-trivial base class
- warn(CONFIG_TYPE_WARNING.format(
- name=name, current=type(current), default=type(default)))
+ warn(CONFIG_TYPE_WARNING.format(
+ name=name, current=type(current), default=type(default)))
def check_unicode(self, warn):
# check all string values for non-ASCII characters in bytestrings,
diff --git a/tests/roots/test-config/conf.py b/tests/roots/test-config/conf.py
index b6075e5cb..1e583d1e0 100644
--- a/tests/roots/test-config/conf.py
+++ b/tests/roots/test-config/conf.py
@@ -1,4 +1,4 @@
-from sphinx.config import string_classes
+from sphinx.config import string_classes, ENUM
value1 = 123 # wrong type
value2 = 123 # lambda with wrong type
@@ -45,3 +45,4 @@ def setup(app):
app.add_config_value('value14', None, False, string_classes)
app.add_config_value('value15', u'unicode', False)
app.add_config_value('value16', u'unicode', False)
+ app.add_config_value('value17', 'default', False, ENUM('default', 'one', 'two'))
diff --git a/tests/test_config.py b/tests/test_config.py
index 79bcb3504..b10711732 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -206,3 +206,15 @@ def test_gen_check_types(app, status, warning):
'override on "%s" should%s raise a type warning' %
(key, '' if should else ' NOT')
)
+
+
+@with_app(testroot='config')
+def test_check_enum(app, status, warning):
+ assert "The config value `value17` has to be a one of ('default', 'one', 'two'), " \
+ not in warning.getvalue()
+
+
+@with_app(testroot='config', confoverrides={'value17': 'invalid'})
+def test_check_enum_failed(app, status, warning):
+ assert "The config value `value17` has to be a one of ('default', 'one', 'two'), " \
+ "but `invalid` is given." in warning.getvalue()
From 3c756e76883e908af3bdb32accb7bcbcf815d0d3 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Thu, 7 Jul 2016 23:48:39 +0900
Subject: [PATCH 210/217] Use SphinxRenderer as a default renderer of
copy_asset()
---
sphinx/util/fileutil.py | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/sphinx/util/fileutil.py b/sphinx/util/fileutil.py
index 1d2797b9c..f2d37775a 100644
--- a/sphinx/util/fileutil.py
+++ b/sphinx/util/fileutil.py
@@ -13,6 +13,7 @@ import codecs
import posixpath
from docutils.utils import relative_path
from sphinx.util.osutil import copyfile, ensuredir, walk
+from sphinx.util.temlate import SphinxRenderer
def copy_asset_file(source, destination, context=None, renderer=None):
@@ -23,8 +24,8 @@ def copy_asset_file(source, destination, context=None, renderer=None):
:param source: The path to source file
:param destination: The path to destination file or directory
- :param context: The template variables. If not given, template files are simply copied
- :param renderer: The template engine
+ :param context: The template variables. If not given, template files are simply copied
+ :param renderer: The template engine. If not given, SphinxRenderer is used by default
"""
if not os.path.exists(source):
return
@@ -35,8 +36,7 @@ def copy_asset_file(source, destination, context=None, renderer=None):
if source.lower().endswith('_t') and context:
if renderer is None:
- msg = 'Template engine is not initialized. Failed to render %s' % source
- raise RuntimeError(msg)
+ renderer = SphinxRenderer()
with codecs.open(source, 'r', encoding='utf-8') as fsrc:
with codecs.open(destination[:-2], 'w', encoding='utf-8') as fdst:
@@ -54,8 +54,8 @@ def copy_asset(source, destination, excluded=lambda path: False, context=None, r
:param source: The path to source file or directory
:param destination: The path to destination directory
:param excluded: The matcher to determine the given path should be copied or not
- :param context: The template variables. If not given, template files are simply copied
- :param renderer: The template engine
+ :param context: The template variables. If not given, template files are simply copied
+ :param renderer: The template engine. If not given, SphinxRenderer is used by default
"""
if not os.path.exists(source):
return
From a37106599c55cd4c51a19213deb2986fe4fdbf9a Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Fri, 8 Jul 2016 00:12:44 +0900
Subject: [PATCH 211/217] Fix typo
---
sphinx/util/fileutil.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/sphinx/util/fileutil.py b/sphinx/util/fileutil.py
index f2d37775a..fd7ebe05b 100644
--- a/sphinx/util/fileutil.py
+++ b/sphinx/util/fileutil.py
@@ -13,7 +13,7 @@ import codecs
import posixpath
from docutils.utils import relative_path
from sphinx.util.osutil import copyfile, ensuredir, walk
-from sphinx.util.temlate import SphinxRenderer
+from sphinx.util.template import SphinxRenderer
def copy_asset_file(source, destination, context=None, renderer=None):
From 593708a39cda458386b6c7352bebb62df6191af7 Mon Sep 17 00:00:00 2001
From: Takeshi KOMIYA
Date: Fri, 8 Jul 2016 00:14:13 +0900
Subject: [PATCH 212/217] Fix importing error
---
sphinx/util/fileutil.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/sphinx/util/fileutil.py b/sphinx/util/fileutil.py
index fd7ebe05b..d11ae9f1b 100644
--- a/sphinx/util/fileutil.py
+++ b/sphinx/util/fileutil.py
@@ -13,7 +13,6 @@ import codecs
import posixpath
from docutils.utils import relative_path
from sphinx.util.osutil import copyfile, ensuredir, walk
-from sphinx.util.template import SphinxRenderer
def copy_asset_file(source, destination, context=None, renderer=None):
@@ -36,6 +35,7 @@ def copy_asset_file(source, destination, context=None, renderer=None):
if source.lower().endswith('_t') and context:
if renderer is None:
+ from sphinx.util.template import SphinxRenderer
renderer = SphinxRenderer()
with codecs.open(source, 'r', encoding='utf-8') as fsrc:
From f1316a0bb336b7810f68cb45968ca86281a4f7bd Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ville=20Skytt=C3=A4?=
Date: Thu, 7 Jul 2016 15:48:38 +0300
Subject: [PATCH 213/217] Run *.jpg through jpegoptim -s
Before: 28408 bytes
After: 25206 bytes
---
doc/installpython.jpg | Bin 28408 -> 25206 bytes
1 file changed, 0 insertions(+), 0 deletions(-)
diff --git a/doc/installpython.jpg b/doc/installpython.jpg
index b0e458e40dd69a8bc26f29ec68e0a572a757f04a..fff4630ae0147514a5bded17851bb13ed41b31eb 100644
GIT binary patch
literal 25206
zcmd?Q1yCH_)-F6)f<*A(fx$JwodjnF_n-+dGq^h;K#(wKU~qRCU`WE?mIMhl_~4S@
z!Gi`(esbRPo$tN(es$}7|E*i~SN(fd@9M5zYwu@v_g=mB)2n|^|NaIb1*?Em05~`}
zfEPDE!0$PLA^;Z$=a2le;1S^cDYx+P@d$3;x_$f4Mo2_LL`X6Z-U1DOAJ2&Mv
z(Y^b3@7(*d|EG~Z=6|ei@V3lDzJ
z0`B15Sd-zA0iFQhse6w!x=d7!QpfL~faC0x-t=K>l9oXrT8NTznkqwha$bn&oTDvq
zDZ8*iXH+s+R>)cN%&FU3I2rD!?~#x!Nz0`-XKIkt7oahoX;7R&yX~UgSlgn0OJJa6
zgFe!%0WxRdkXe!?t3Dw*EeK&cj*Tl6V|1%~Kzj|WTz~TlfNpRIB6*+7uJicwRv<`
z_MM2=rMTL@1x4Skf8o=ex!RmZ&_M)yKiB(elAIltH`~<9+fgBzwL(Q$y$z!pO{vui
zcL`^T*iEnj+E$z#qU1B@OZ+46?x{z|++qW@c}w$3MR(Ch#d3b<_ggF&&I+o+f%*X6
z56Sb^Q2tHDFX+YcF*|w%*_G)d!52MAKGa=KVv@B!;*yPM2tUA9QZ>ceO<3DMAG-&8@!6TT@Ij&)|yT7n#m7gg>Jvm3+?4esUcAJp4cddhrle
z_l4)KN|=s{J9v#&wOO=3`fEq*6tTolC0~xnDu%DkV@!i%(o;%@FD>m}{>SJRJ(;`J
z+c8bReo~320g(*46yn7(9xwq5i
zG~M3xcyB4gLsZ$Ce{#W4g*w+T>)>(nQpXB_s6IMKh3U&97KP&izf&
z9}B4j5zEDT+NrTcliDl1%qPTvm>-h1uzy$?=#EOI5HzfFlPnhwORdG&c}5$cc>jx$
z6|-cpHm?$&o+4+iKK6N~uolFgCEt+vd@KEfP3ut-CzdX%RV1JqM(ToA1yK
zV{1k;PkF_J-qzi7+`hNzb7e1DTA@Q__GYW3wSs>4ebb%%;df-9@r4GmNN=D*oNeM-
zMNWyIMln(PC4;ny8{oFD4T-thrF42osgAkbUA3x1V;9P`IArGEJEioQ)&T+=;RHzG;5>S`52}
zauH6HNAh#PJ=89p9ln*0ZNI8-uIl6URj>1^DWRd2@uJLOP
zx+6J`VKAw#aQ3i-8JV)wh(~U1OGsYJqfcm#yjw6Fen-WM(WoyaMNRpDJBr-i!ehmB
z3WF`T0`RP#MkO~kaOd|D?Nugc!ph1ds_g#@xb*vX?P!#v{A|%{OzkmRA!QcLbj@pw
z%8iD?elyPfwgyO*ls(N(kgHM7xIZ^X>5=Z8hWld5pOHEadaILFvkP)FuWdx#3^UtS
zsDL>fg-5%SlzL-_rh2pL5a)VzVN49$JDImV(m_?5LhFN1U#hYBvT{w`c`VO%r}#Fs
zgl;`&q>a2mz#4-0h^(0O$-Kv_ge^$5QxUs^{7B))e@(Lgyq#;zDG3G44Fx{50WHXc
zA1X^J_K7rc2uc*%caxQHs1%bMrXn`hSwP#~drPsWchJC2C!<>3Ph`3pzcjm}x+Cw=
zFWl|n5|Q-c%bWQE3Lf-&{*T!lTYWMbcr%*?Z5r}ePb&^?qkdj*wJKD9Vj|Qtx*ySR
zq`$Mm+x9;zyPEA^PWXjQUj90Oc9e*@Z#;j;g*xEmrvni96;k&=A*9~uS!
zf)Z=?SJ(fv5Ci;B_&))w_rC=TX}LdxlL66rSNB9|ANwe(Xr8X0hjtmEzP(dkAImXQv&@@g?}OW
zAFwj-_-0B_{J(}8`e6(#^c$cu`cYFhPsIA#%5(8rNkaCiyJm*H&~W2ZzI_ol0`h}_y%5PcD@72x;NWj!Z5~=m*fItieb4G3M5xv+a
z)+Kqb#(TDMxQCtFxxwj^XfeX19212Z01nH2D_uQDVo?~1`X#+$9)8oJ0E1DY4!;Z$
zS?sZgLS058Cp#?@45B>5kvfuQ2t-Ft)k*_f?0dSy^^>+cN~mhPm3??fZMnax8VINMX18$H5#}HiZ`SGUwi9-&
z<;JY9^-wLpBr6?Tue-n$uvRQlT~L}RA4V**ORn;fyBAGy|$)Wlzl2-Z4`)b<2PVsB82fZG6!up
z=c_eTw_y>_XUFFm2SBoN=TlN0LQHus7q*3ZTJO@HlA7R7%WD
zB~4KYb`oq-IVe|ZROzro%PM#h=hQ3hp}Se8F|xe!v@r8k6-6i6zIX8yJc6*knr~_u
zx40GJkLsqY`QMQ6Wr2{dD*QZ2(`Ax|=zN&!)X>+5+SiBSZx<^sECtK=RVt~gN?IO&
zQUAn2sd}riv$DM}U*dyNEgnyOzd4eqNku98EQ|&}WJ|1!yYDh(?d4TgM{ZN|r~R(~p+
zF7JTW@KCGIeOWuwoWH&=XjH*M>0^zb%ntXqR_-|2G<@3fO)d0anx5`)eU07cS32sc
z$eIXN{~{rE7$xbxvP5xu-MWY`z}qhR$dQC%cqMr3u;D{p{8v2WqG{Adq>UqE`)&Q!
zI*MVYGWr9^99UA6>1(?X3FZwJ$;@&6wO4sC*-SR7#CXlyFt8;QJ7{~re6=@su
zMZ4;C$<$rlp}sP2sd>dpyJ`tY1d8^%Zkc~#rZq@b<^0wiNRla5gTvaBHCMq
zrZ%rbvxB!xPlagRB5%X@(_^tN`$^iZEB7P(;sX;eRWg19wqzd-{Ago7pN^ju|MqA9
zn)$St;N!OP%b$%5s)5~RwcU$XLyymlqZi=2ML~FDS0C?>-L{st`xxg^NHwZ{0Lovh5hzZv2Ee~$3~XB(E2?4zpn7=dn6BTRk+j_{wzynKdp
zQrJ#Ee~-1@+9#vsYsQy{#D@>>NlKo^pix>i*!N$uj6%Amcu0Rf2z;j1?T;0iTlhfN
z2QoFW71HyghbE>v3>}Fl9nqHw*?HcYER@>=b{#8D{Gh8ocy3}A5X4^QI3tv3qg2XC
ztyEbKpeoi81_<+)_!gN_Q^rb*_0^WL$VZy<-*=|hGq*R&8PneTD9cdRBDDMlPX|Se
zy0q6vN#WU9+>7pV=rm+cqp_8Ij?v79KlhW-?jZXTQ22`TxSPNx0D6&_KC5QS!BD8&G
z&k<5-6Vk+{j(aV$EYt~NXwhhuJ3%jJc*K@{EBlH$^R9e+^XMs
zWbGB*@1*99{`OF?b%6el!M&Qmb{2$p!>1tTZP$=1Md~TTanomCP2`@FZu>-Lto3vW
z#n+$R?~=%QjJbXXn9?_W_IZ?Wpsb7EyF3b>#CM2+B~2@dX<&L|9k(ZI=Dj3P5G8~#
zrrVCKan-;&WHiM-*3#e5$t+*Nm7UI#9eVNPfTDRc3QG;42
zDfkmPW>NF@wHN6|F(T0KOuA?}6}&M}_kE9quC1C!mp4=uLh~DtBKq)7Ou8G}s!6UA
zPa#_rT28hBbQ~%$NU%gbd*PM!yzG=Dy?&lyHz;pfW;`!6IIE&qZqrQZ-fWLcp!(;W
zDuD_!!)Pe*OT$)bju2(<51R?(=zMv5crUD81L;{Hv1MQ%U!y=Lt3g{nXq$aNN9WCp
zcYt<`360_yDKeLcgLao`R$(oQT*214
z@s@94#mQ;IS~V%smxSUmD@XreV;Zxh37jmEpi}dqzE?(LFd@nzoJ>p;vti
zDrLQcj2PLU5jPW)EnVmoo%$M3n10ta+xwXAp{J4Mf}JosZ;p~}#(|(K(n&L{j?l{p
zYSos!>KH&702Qqpr(NiZVKkk#;vV3ib68H!!#^g?mSc(_rYhaH)FC-tE?iN{qU)$<
zD6ujODzR(PtF*8sw_g8JA}U^?OM#@Gi`{={Pe*jU3{OTeh~yf+me&93EeF035HS~P
z<&8fvq8IfmjZ;cqZvOStbe#V#>mj~V^TnmbEWKBj=xUNLP`Gww54bb_+V7`nxuwwr
zQOo*U>J*QmY@_o&U!Lsog04gqmymv?S6q@D4_G1>w9G~j7H(8c_3V4yZvS1LC|7n8
z1?~?t>bi&sYA}eok=$b`(XCe=3xGT=%w_Uu7muciiNu=nM-PITIL%4zC$GMHFDFjX
zStD!M3@QfeQ-$?OZB;zTkA%RnBYU+4cI@`oNs`uk^U~ANo$r=WHP^!iu94TVS`F)aPiDV?s;?O(%#k!kbjrENA7~;Ehnr*l|_EmcY`VhK%N=lr3
zh=DiZbP4A7K`?WCceH}erp^YXq>&&DrCe0!vXn%fqds+=q-fqeR^g=Y=vL{GIv)GJ
zDYKb6*@{{YO}=QM{s&A7qay|_
zDgsdn8?O7_Yr#V=w1hdHpyI*QTk_1$zEa6Adr@DFO2XmipctY}bE+pw1=T&I+#635
zyd`G$3j(I1aSAf-FFA+nTPb$X9o1t3>PA&~#vOB=Rej*tI(h_y0e+{VYc+6AYs+jv
zA=@cA7Skt*_tMMSlKIf+tKUA|=b~qI23ALDIY=huPlg6^{YawBw48B9DNPblgsG71
zl30$)B$~}u{1q}}+N?I>qe?(u{yQ>3s^-}A65==7?MK85b#m&_V6Xbw<^m#j7_`#Q
zek(
z7s-wbUEo!nlmxlPkYmu?hfeekO#udvGYg`E0{$}Us5?BC_0aWcZ52zy@8*QW2?KW6=Rbl4VqB#Ce)IR-(
zk6EXbrd$lJXp&?1TbD28iX}o=>JfuehuhhcGeCjSM|ls3Bpo&>HJyUP2WQZz<7uO)
z(K2m^N*=*aPGiUQh-7gV)zp_=?A&0(T!?a_8(H^#1sxQ3R4Y>J*-MS_ooQ;iYI?Q(
zei!-)muGc`A{Cm}j(3|=4QYENm4OBRFhss;3px)yYhsjyqO
zIVr)+AbjuzLZf#gZNHa|8S&9c39<6Y{QXZ`C%KMjtmI^Ok@HB|c>WV`^f8TQ&8pv9
zkfiJ5BoIuqT0W}+X;jB%hC1L@A&E_EN6xeg8JWo8~Z>#-Z_`M(X=vH
znYH`O)8507Dt$l536xrvicR5^FX3?SjXjpoq8xvx-MO3WMAE*WZXhl8)jV>~EIR*9
zROy00NWmiYpct(;$R$r#BP;~+y~PsNLObK<3ZL%wtwcK3xKDcddnbdU$5@-l(jyql
zOJ~&*mI+fY;v7M!mq+Z}O37rJQ5n5pDmp=WS0~GkK)+&aiEepah4&NN*?6GQZoOk9
zQ?3Va5UR>fu0`AIQXyx@@lz?(tci9t=Ue|?&@+PZ)p;tgB@+;uXV(T3G*07b!%hG#
z`gIMyEc4hj&V~0w>#C+$S~00gCS-KQB~PGE!X+IN?mID7^;%)TNwJFv^iT@R;Pwx{
zw0#njE&U+uaK4w;^gi*HF}u|JUk^>Su$%mf)@%{_W}@%m!COcH2F$9d@M#9M2}FTr
zrkOm#E|zT#j9eBFHcP#_lC(}zX#POA+UZ9nw#S4-AiX@&(TMVEjZk%gLb{J@-USW=
z;4#yok1kg)zTDw!&xncq$=-VHvgE+v2*fyK>y;YA*iU%!Pvq6LoSxc;xr%4$iO^Ix#_mE?IV(@41;zPO@6CS=|-w^5*u{UK5#fHJ}RzDqjIInlZ<9i
zn0a(p(E3_=+{1)=7q;rc@>E$%L#bNN22q#9woyM?SwEg@l4?zpWg1eXQ0dscod-QdM7EM@Etg|!+w0t8v={#
zSI7Li#?uG`A%6q<9XO6N;aF?ySPJ6$7oDy5P-^8frxs1l!znZcO~5>YJB?1{CrL^W
zbNY!M5X9uzjdnV$mlKE&z~PBL{5k=Cne*f02E*GHn%fo0Kc$y~ha?~RJZ9V|xAh{up-EDUT5c82K
zMV??*==ig4tdiXX(2*Osv3tZqJrn7L)GQUpol6S>iWQef`EShAJ*4@dc|LSfky#WF
z*lh>aze31;@7eMz({JA*&~7MtBKq^b)-n8;bxn}@RA+kB%Y>^@;K>kY6QVa;TRbEt
zKYVmWJ_!n{tmS?oA18Kk=QZq-?3>k6N@kQN{ndr3H*JQy%vna<273x!9l53jtuJn7
zhfS@$0*DI)Q6ltruFM~hW1pvi*i}a#{