summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTakeshi KOMIYA <i.tkomiya@gmail.com>2018-04-13 00:21:33 +0900
committerGitHub <noreply@github.com>2018-04-13 00:21:33 +0900
commitc35eb6fade7a3b4a6de4183d1dd4196f04a5edaf (patch)
treeca24458cbf1fa537af0c74818b843e59a1606918
parentc12d616be90466d2b7f385a69665ef6a9c6fd74c (diff)
parentbd2967f1d2e95bcbf06894d4a83814b701f2ab0c (diff)
downloadsphinx-git-c35eb6fade7a3b4a6de4183d1dd4196f04a5edaf.tar.gz
Merge pull request #4815 from tk0miya/refine_add_css_file
Refine adding CSS files
-rw-r--r--CHANGES3
-rw-r--r--doc/config.rst27
-rw-r--r--doc/extdev/index.rst5
-rw-r--r--sphinx/application.py52
-rw-r--r--sphinx/builders/epub3.py1
-rw-r--r--sphinx/builders/html.py62
-rw-r--r--sphinx/deprecation.py4
-rw-r--r--sphinx/registry.py6
-rw-r--r--sphinx/themes/basic/layout.html4
-rw-r--r--tests/roots/test-html_assets/conf.py2
-rw-r--r--tests/roots/test-html_assets/static/js/custom.js0
-rw-r--r--tests/test_build_epub.py28
-rw-r--r--tests/test_build_html.py13
13 files changed, 182 insertions, 25 deletions
diff --git a/CHANGES b/CHANGES
index 184365670..d3c7f9c1b 100644
--- a/CHANGES
+++ b/CHANGES
@@ -35,6 +35,7 @@ Deprecated
* #2157: helper function ``warn()`` for HTML themes is deprecated
* ``env._nitpick_ignore`` is deprecated
* ``app.override_domain()`` is deprecated
+* ``app.add_stylesheet()`` is deprecated
For more details, see `deprecation APIs list
<http://www.sphinx-doc.org/en/master/extdev/index.html#deprecated-apis>`_
@@ -58,6 +59,8 @@ Features added
* LaTeX: new key ``'fvset'`` for :confval:`latex_elements`. For
XeLaTeX/LuaLaTeX its default sets ``fanvyvrb`` to use normal, not small,
fontsize in code-blocks (refs: #4793)
+* Add :confval:`html_css_files` and :confval:`epub_css_files` for adding CSS
+ files from configuration
Bugs fixed
----------
diff --git a/doc/config.rst b/doc/config.rst
index 04f3c2d7c..46958cde6 100644
--- a/doc/config.rst
+++ b/doc/config.rst
@@ -59,9 +59,6 @@ Important points to note:
Note that the current builder tag is not available in ``conf.py``, as it is
created *after* the builder is initialized.
-.. seealso:: Additional configurations, such as adding stylesheets,
- javascripts, builders, etc. can be made through the :doc:`/extdev/appapi`.
-
General configuration
---------------------
@@ -846,6 +843,22 @@ that use Sphinx's HTMLWriter class.
The image file will be copied to the ``_static`` directory of the output
HTML, but only if the file does not already exist there.
+.. confval:: html_css_files
+
+ A list of CSS files. The entry must be a *filename* string or a tuple
+ containing the *filename* string and the *attributes* dictionary. The
+ *filename* must be relative to the :confval:`html_static_path`, or a full URI
+ with scheme like ``http://example.org/style.css``. The *attributes* is used
+ for attributes of ``<link>`` tag. It defaults to an empty list.
+
+ Example::
+
+ html_css_files = ['custom.css'
+ 'https://example.com/css/custom.css',
+ ('print.css', {'media': 'print'})]
+
+ .. versionadded:: 1.8
+
.. confval:: html_static_path
A list of paths that contain custom static files (such as style
@@ -1511,6 +1524,14 @@ the `Dublin Core metadata <http://dublincore.org/>`_.
.. versionadded:: 1.1
+.. confval:: epub_css_files
+
+ A list of CSS files. The entry must be a *filename* string or a tuple
+ containing the *filename* string and the *attributes* dictionary. For more
+ information, see :confval:`html_css_files`.
+
+ .. versionadded:: 1.8
+
.. confval:: epub_guide
Meta data for the guide element of :file:`content.opf`. This is a
diff --git a/doc/extdev/index.rst b/doc/extdev/index.rst
index 2dba7a430..94a23aaea 100644
--- a/doc/extdev/index.rst
+++ b/doc/extdev/index.rst
@@ -114,6 +114,11 @@ The following is a list of deprecated interface.
- (will be) Removed
- Alternatives
+ * - :meth:`~sphinx.application.Sphinx.add_stylesheet()`
+ - 1.8
+ - 4.0
+ - :meth:`~sphinx.application.Sphinx.add_css_file()`
+
* - ``sphinx.application.Sphinx.override_domain()``
- 1.8
- 3.0
diff --git a/sphinx/application.py b/sphinx/application.py
index c8e06245c..71358ca5d 100644
--- a/sphinx/application.py
+++ b/sphinx/application.py
@@ -27,7 +27,9 @@ from six.moves import cStringIO
import sphinx
from sphinx import package_dir, locale
from sphinx.config import Config
-from sphinx.deprecation import RemovedInSphinx20Warning, RemovedInSphinx30Warning
+from sphinx.deprecation import (
+ RemovedInSphinx20Warning, RemovedInSphinx30Warning, RemovedInSphinx40Warning
+)
from sphinx.environment import BuildEnvironment
from sphinx.errors import (
ApplicationError, ConfigError, ExtensionError, VersionRequirementError
@@ -1001,13 +1003,27 @@ class Sphinx(object):
StandaloneHTMLBuilder.script_files.append(
posixpath.join('_static', filename))
- def add_stylesheet(self, filename, alternate=False, title=None):
- # type: (unicode, bool, unicode) -> None
+ def add_css_file(self, filename, **kwargs):
+ # type: (unicode, **unicode) -> None
"""Register a stylesheet to include in the HTML output.
Add *filename* to the list of CSS files that the default HTML template
- will include. Like for :meth:`add_javascript`, the filename must be
- relative to the HTML static path, or a full URI with scheme.
+ will include. The filename must be relative to the HTML static path,
+ or a full URI with scheme. The keyword arguments are also accepted for
+ attributes of ``<link>`` tag.
+
+ Example::
+
+ app.add_css_file('custom.css')
+ # => <link rel="stylesheet" href="_static/custom.css" type="text/css" />
+
+ app.add_css_file('print.css', media='print')
+ # => <link rel="stylesheet" href="_static/print.css"
+ # type="text/css" media="print" />
+
+ app.add_css_file('fancy.css', rel='alternate stylesheet', title='fancy')
+ # => <link rel="alternate stylesheet" href="_static/fancy.css"
+ # type="text/css" title="fancy" />
.. versionadded:: 1.0
@@ -1017,17 +1033,33 @@ class Sphinx(object):
arguments. The default is no title and *alternate* = ``False``. For
more information, refer to the `documentation
<https://mdn.io/Web/CSS/Alternative_style_sheets>`__.
+
+ .. versionchanged:: 1.8
+ Renamed from ``app.add_stylesheet()``.
+ And it allows keyword arguments as attributes of link tag.
"""
logger.debug('[app] adding stylesheet: %r', filename)
- from sphinx.builders.html import StandaloneHTMLBuilder, Stylesheet
if '://' not in filename:
filename = posixpath.join('_static', filename)
+ self.registry.add_css_files(filename, **kwargs)
+
+ def add_stylesheet(self, filename, alternate=False, title=None):
+ # type: (unicode, bool, unicode) -> None
+ """An alias of :meth:`add_css_file`."""
+ warnings.warn('The app.add_stylesheet() is deprecated. '
+ 'Please use app.add_css_file() instead.',
+ RemovedInSphinx40Warning)
+
+ attributes = {} # type: Dict[unicode, unicode]
if alternate:
- rel = u'alternate stylesheet'
+ attributes['rel'] = 'alternate stylesheet'
else:
- rel = u'stylesheet'
- css = Stylesheet(filename, title, rel) # type: ignore
- StandaloneHTMLBuilder.css_files.append(css)
+ attributes['rel'] = 'stylesheet'
+
+ if title:
+ attributes['title'] = title
+
+ self.add_css_file(filename, **attributes)
def add_latex_package(self, packagename, options=None):
# type: (unicode, unicode) -> None
diff --git a/sphinx/builders/epub3.py b/sphinx/builders/epub3.py
index 752a3990d..895d2f5f5 100644
--- a/sphinx/builders/epub3.py
+++ b/sphinx/builders/epub3.py
@@ -247,6 +247,7 @@ def setup(app):
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_css_files', lambda config: config.html_css_files, 'epub')
app.add_config_value('epub_exclude_files', [], 'env')
app.add_config_value('epub_tocdepth', 3, 'env')
app.add_config_value('epub_tocdup', True, 'env')
diff --git a/sphinx/builders/html.py b/sphinx/builders/html.py
index 257b35353..25538ac17 100644
--- a/sphinx/builders/html.py
+++ b/sphinx/builders/html.py
@@ -50,6 +50,7 @@ from sphinx.util.matching import patmatch, Matcher, DOTFILES
from sphinx.util.nodes import inline_all_toctrees
from sphinx.util.osutil import SEP, os_path, relative_uri, ensuredir, \
movefile, copyfile
+from sphinx.util.pycompat import htmlescape
from sphinx.writers.html import HTMLWriter, HTMLTranslator
if False:
@@ -101,7 +102,7 @@ class CSSContainer(list):
if isinstance(obj, Stylesheet):
super(CSSContainer, self).append(obj)
else:
- super(CSSContainer, self).append(Stylesheet(obj, None, 'stylesheet')) # type: ignore # NOQA
+ super(CSSContainer, self).append(Stylesheet(obj))
def insert(self, index, obj):
# type: (int, Union[unicode, Stylesheet]) -> None
@@ -111,7 +112,7 @@ class CSSContainer(list):
if isinstance(obj, Stylesheet):
super(CSSContainer, self).insert(index, obj)
else:
- super(CSSContainer, self).insert(index, Stylesheet(obj, None, 'stylesheet')) # type: ignore # NOQA
+ super(CSSContainer, self).insert(index, Stylesheet(obj))
def extend(self, other): # type: ignore
# type: (List[Union[unicode, Stylesheet]]) -> None
@@ -144,12 +145,19 @@ class Stylesheet(text_type):
its filename (str).
"""
- def __new__(cls, filename, title, rel):
+ attributes = None # type: Dict[unicode, unicode]
+ filename = None # type: unicode
+
+ def __new__(cls, filename, *args, **attributes):
# type: (unicode, unicode, unicode) -> None
self = text_type.__new__(cls, filename) # type: ignore
self.filename = filename
- self.title = title
- self.rel = rel
+ self.attributes = attributes
+ self.attributes.setdefault('rel', 'stylesheet')
+ self.attributes.setdefault('type', 'text/css')
+ if args: # old style arguments (rel, title)
+ self.attributes['rel'] = args[0]
+ self.attributes['title'] = args[1]
return self
@@ -241,8 +249,6 @@ class StandaloneHTMLBuilder(Builder):
# This is a class attribute because it is mutated by Sphinx.add_javascript.
script_files = ['_static/jquery.js', '_static/underscore.js',
'_static/doctools.js'] # type: List[unicode]
- # Ditto for this one (Sphinx.add_stylesheet).
- css_files = CSSContainer() # type: List[Dict[unicode, unicode]]
imgpath = None # type: unicode
domain_indices = [] # type: List[Tuple[unicode, Type[Index], List[Tuple[unicode, List[List[Union[unicode, int]]]]], bool]] # NOQA
@@ -250,6 +256,13 @@ class StandaloneHTMLBuilder(Builder):
# cached publisher object for snippets
_publisher = None
+ def __init__(self, app):
+ # type: (Sphinx) -> None
+ super(StandaloneHTMLBuilder, self).__init__(app)
+
+ # CSS files
+ self.css_files = CSSContainer() # type: List[Dict[unicode, unicode]]
+
def init(self):
# type: () -> None
self.build_info = self.create_build_info()
@@ -262,6 +275,7 @@ class StandaloneHTMLBuilder(Builder):
self.init_templates()
self.init_highlighter()
+ self.init_css_files()
if self.config.html_file_suffix is not None:
self.out_suffix = self.config.html_file_suffix
@@ -324,6 +338,27 @@ class StandaloneHTMLBuilder(Builder):
self.highlighter = PygmentsBridge('html', style,
self.config.trim_doctest_flags)
+ def init_css_files(self):
+ # type: () -> None
+ for filename, attrs in self.app.registry.css_files:
+ self.css_files.append(Stylesheet(filename, **attrs)) # type: ignore
+
+ for entry in self.get_builder_config('css_files', 'html'):
+ if isinstance(entry, string_types):
+ filename = entry
+ attrs = {}
+ else:
+ try:
+ filename, attrs = entry
+ except (TypeError, ValueError):
+ logger.warning('invalid css_file: %r', entry)
+ continue
+
+ if '://' not in filename:
+ filename = path.join('_static', filename)
+
+ self.css_files.append(Stylesheet(filename, **attrs)) # type: ignore
+
@property
def default_translator_class(self):
# type: () -> nodes.NodeVisitor
@@ -988,6 +1023,17 @@ class StandaloneHTMLBuilder(Builder):
return uri
ctx['pathto'] = pathto
+ def css_tag(css):
+ # type: (Stylesheet) -> unicode
+ attrs = []
+ for key in sorted(css.attributes):
+ value = css.attributes[key]
+ if value is not None:
+ attrs.append('%s="%s"' % (key, htmlescape(value, True)))
+ attrs.append('href="%s"' % pathto(css.filename, resource=True))
+ return '<link %s />' % ' '.join(attrs)
+ ctx['css_tag'] = css_tag
+
def hasdoc(name):
# type: (unicode) -> bool
if name in self.env.all_docs:
@@ -1316,6 +1362,7 @@ class SerializingHTMLBuilder(StandaloneHTMLBuilder):
self.templates = None # no template bridge necessary
self.init_templates()
self.init_highlighter()
+ self.init_css_files()
self.use_index = self.get_builder_config('use_index', 'html')
def get_target_uri(self, docname, typ=None):
@@ -1440,6 +1487,7 @@ def setup(app):
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_css_files', [], 'html')
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)
diff --git a/sphinx/deprecation.py b/sphinx/deprecation.py
index 1b0e862f0..d4067055a 100644
--- a/sphinx/deprecation.py
+++ b/sphinx/deprecation.py
@@ -33,6 +33,10 @@ class RemovedInSphinx30Warning(PendingDeprecationWarning):
pass
+class RemovedInSphinx40Warning(PendingDeprecationWarning):
+ pass
+
+
RemovedInNextVersionWarning = RemovedInSphinx18Warning
diff --git a/sphinx/registry.py b/sphinx/registry.py
index ab4cfce70..dc42219ae 100644
--- a/sphinx/registry.py
+++ b/sphinx/registry.py
@@ -65,6 +65,9 @@ class SphinxComponentRegistry(object):
#: autodoc documenters; a dict of documenter name -> documenter class
self.documenters = {} # type: Dict[unicode, Type[Documenter]]
+ #: css_files; a list of tuple of filename and attributes
+ self.css_files = [] # type: List[Tuple[unicode, Dict[unicode, unicode]]]
+
#: domains; a dict of domain name -> domain class
self.domains = {} # type: Dict[unicode, Type[Domain]]
@@ -412,6 +415,9 @@ class SphinxComponentRegistry(object):
# type: (Type, Callable[[Any, unicode, Any], Any]) -> None
self.autodoc_attrgettrs[typ] = attrgetter
+ def add_css_files(self, filename, **attributes):
+ self.css_files.append((filename, attributes))
+
def add_latex_package(self, name, options):
# type: (unicode, unicode) -> None
logger.debug('[app] adding latex package: %r', name)
diff --git a/sphinx/themes/basic/layout.html b/sphinx/themes/basic/layout.html
index 68c7d9e51..a25a18b90 100644
--- a/sphinx/themes/basic/layout.html
+++ b/sphinx/themes/basic/layout.html
@@ -97,8 +97,8 @@
<link rel="stylesheet" href="{{ pathto('_static/' + style, 1) }}" type="text/css" />
<link rel="stylesheet" href="{{ pathto('_static/pygments.css', 1) }}" type="text/css" />
{%- for css in css_files %}
- {%- if css|attr("rel") %}
- <link rel="{{ css.rel }}" href="{{ pathto(css.filename, 1) }}" type="text/css"{% if css.title is not none %} title="{{ css.title }}"{% endif %} />
+ {%- if css|attr("filename") %}
+ {{ css_tag(css) }}
{%- else %}
<link rel="stylesheet" href="{{ pathto(css, 1) }}" type="text/css" />
{%- endif %}
diff --git a/tests/roots/test-html_assets/conf.py b/tests/roots/test-html_assets/conf.py
index a17e417a3..c61f0b42c 100644
--- a/tests/roots/test-html_assets/conf.py
+++ b/tests/roots/test-html_assets/conf.py
@@ -6,4 +6,6 @@ version = '1.4.4'
html_static_path = ['static', 'subdir']
html_extra_path = ['extra', 'subdir']
+html_css_files = ['css/style.css',
+ ('https://example.com/custom.css', {'title': 'title', 'media': 'print'})]
exclude_patterns = ['**/_build', '**/.htpasswd']
diff --git a/tests/roots/test-html_assets/static/js/custom.js b/tests/roots/test-html_assets/static/js/custom.js
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/roots/test-html_assets/static/js/custom.js
diff --git a/tests/test_build_epub.py b/tests/test_build_epub.py
index 2f09f6d5a..24450089b 100644
--- a/tests/test_build_epub.py
+++ b/tests/test_build_epub.py
@@ -317,6 +317,34 @@ def test_epub_writing_mode(app):
assert 'writing-mode: vertical-rl;' in css
+@pytest.mark.sphinx('epub', testroot='html_assets')
+def test_epub_assets(app):
+ app.builder.build_all()
+
+ # epub_sytlesheets (same as html_css_files)
+ content = (app.outdir / 'index.xhtml').text()
+ assert ('<link rel="stylesheet" type="text/css" href="_static/css/style.css" />'
+ in content)
+ assert ('<link media="print" rel="stylesheet" title="title" type="text/css" '
+ 'href="https://example.com/custom.css" />' in content)
+
+
+@pytest.mark.sphinx('epub', testroot='html_assets',
+ confoverrides={'epub_css_files': ['css/epub.css']})
+def test_epub_css_files(app):
+ app.builder.build_all()
+
+ # epub_css_files
+ content = (app.outdir / 'index.xhtml').text()
+ assert '<link rel="stylesheet" type="text/css" href="_static/css/epub.css" />' in content
+
+ # files in html_css_files are not outputed
+ assert ('<link rel="stylesheet" type="text/css" href="_static/css/style.css" />'
+ not in content)
+ assert ('<link media="print" rel="stylesheet" title="title" type="text/css" '
+ 'href="https://example.com/custom.css" />' not in content)
+
+
@pytest.mark.sphinx('epub')
def test_run_epubcheck(app):
app.build()
diff --git a/tests/test_build_html.py b/tests/test_build_html.py
index 1ee5eb473..655feec03 100644
--- a/tests/test_build_html.py
+++ b/tests/test_build_html.py
@@ -1094,9 +1094,10 @@ def test_html_assets(app):
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' / 'css' / 'style.css').exists()
+ assert (app.outdir / '_static' / 'js' / 'custom.js').exists()
assert (app.outdir / '_static' / 'rimg.png').exists()
- assert not (app.outdir / '_static' / '_build/index.html').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()
@@ -1107,11 +1108,17 @@ def test_html_assets(app):
assert (app.outdir / 'API.html_t').exists()
assert (app.outdir / 'css/style.css').exists()
assert (app.outdir / 'rimg.png').exists()
- assert not (app.outdir / '_build/index.html').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()
+ # html_css_files
+ content = (app.outdir / 'index.html').text()
+ assert '<link rel="stylesheet" type="text/css" href="_static/css/style.css" />' in content
+ assert ('<link media="print" rel="stylesheet" title="title" type="text/css" '
+ 'href="https://example.com/custom.css" />' in content)
+
@pytest.mark.sphinx('html', testroot='basic', confoverrides={'html_copy_source': False})
def test_html_copy_source(app):