summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--sphinx/application.py22
-rw-r--r--sphinx/builders/__init__.py60
-rw-r--r--sphinx/builders/_epub_base.py21
-rw-r--r--sphinx/builders/applehelp.py55
-rw-r--r--sphinx/builders/changes.py10
-rw-r--r--sphinx/builders/devhelp.py11
-rw-r--r--sphinx/builders/dummy.py3
-rw-r--r--sphinx/builders/epub3.py31
-rw-r--r--sphinx/builders/gettext.py11
-rw-r--r--sphinx/builders/html.py82
-rw-r--r--sphinx/builders/htmlhelp.py13
-rw-r--r--sphinx/builders/latex.py44
-rw-r--r--sphinx/builders/linkcheck.py9
-rw-r--r--sphinx/builders/manpage.py9
-rw-r--r--sphinx/builders/qthelp.py15
-rw-r--r--sphinx/builders/texinfo.py36
-rw-r--r--sphinx/builders/text.py5
-rw-r--r--sphinx/builders/xml.py7
-rw-r--r--sphinx/config.py28
-rw-r--r--sphinx/directives/code.py6
-rw-r--r--sphinx/domains/cpp.py10
-rw-r--r--sphinx/domains/python.py4
-rw-r--r--sphinx/domains/std.py26
-rw-r--r--sphinx/environment/__init__.py25
-rw-r--r--sphinx/environment/adapters/indexentries.py4
-rw-r--r--sphinx/environment/adapters/toctree.py11
-rw-r--r--sphinx/environment/collectors/asset.py7
-rw-r--r--sphinx/environment/collectors/toctree.py5
-rw-r--r--sphinx/ext/autodoc/__init__.py28
-rw-r--r--sphinx/ext/autosectionlabel.py5
-rw-r--r--sphinx/ext/autosummary/__init__.py5
-rw-r--r--sphinx/ext/coverage.py11
-rw-r--r--sphinx/ext/doctest.py18
-rw-r--r--sphinx/ext/graphviz.py6
-rw-r--r--sphinx/ext/imgmath.py14
-rw-r--r--sphinx/ext/intersphinx.py8
-rw-r--r--sphinx/ext/mathbase.py4
-rw-r--r--sphinx/ext/todo.py4
-rw-r--r--sphinx/highlighting.py7
-rw-r--r--sphinx/io.py3
-rw-r--r--sphinx/theming.py2
-rw-r--r--sphinx/transforms/__init__.py10
-rw-r--r--sphinx/transforms/i18n.py22
-rw-r--r--sphinx/transforms/post_transforms/images.py7
-rw-r--r--sphinx/util/i18n.py9
-rw-r--r--sphinx/util/nodes.py5
-rw-r--r--sphinx/util/rst.py3
-rw-r--r--sphinx/writers/html.py14
-rw-r--r--sphinx/writers/html5.py14
-rw-r--r--sphinx/writers/latex.py26
-rw-r--r--sphinx/writers/manpage.py8
-rw-r--r--sphinx/writers/texinfo.py18
-rw-r--r--sphinx/writers/text.py8
53 files changed, 427 insertions, 402 deletions
diff --git a/sphinx/application.py b/sphinx/application.py
index b39996106..32d6384ed 100644
--- a/sphinx/application.py
+++ b/sphinx/application.py
@@ -145,16 +145,16 @@ class Sphinx(object):
if self.confdir: # confdir is optional
self.confdir = abspath(self.confdir)
if not path.isfile(path.join(self.confdir, 'conf.py')):
- raise ApplicationError("config directory doesn't contain a "
- "conf.py file (%s)" % confdir)
+ raise ApplicationError(__("config directory doesn't contain a "
+ "conf.py file (%s)") % confdir)
if not path.isdir(self.srcdir):
- raise ApplicationError('Cannot find source directory (%s)' %
+ raise ApplicationError(__('Cannot find source directory (%s)') %
self.srcdir)
if self.srcdir == self.outdir:
- raise ApplicationError('Source directory and destination '
- 'directory cannot be identical')
+ raise ApplicationError(__('Source directory and destination '
+ 'directory cannot be identical'))
self.parallel = parallel
@@ -180,7 +180,7 @@ class Sphinx(object):
self.messagelog = deque(maxlen=10) # type: deque
# say hello to the world
- logger.info(bold('Running Sphinx v%s' % sphinx.__display_version__))
+ logger.info(bold(__('Running Sphinx v%s') % sphinx.__display_version__))
# status code for command-line application
self.statuscode = 0
@@ -222,7 +222,7 @@ class Sphinx(object):
self.preload_builder(buildername)
if not path.isdir(outdir):
- logger.info('making output directory...')
+ logger.info(__('making output directory...'))
ensuredir(outdir)
# the config file itself can be an extension
@@ -261,7 +261,7 @@ class Sphinx(object):
the configuration.
"""
if self.config.language is not None:
- logger.info(bold('loading translations [%s]... ' % self.config.language),
+ logger.info(bold(__('loading translations [%s]... ') % self.config.language),
nonl=True)
user_locale_dirs = [
path.join(self.srcdir, x) for x in self.config.locale_dirs]
@@ -279,7 +279,7 @@ class Sphinx(object):
# "en" never needs to be translated
logger.info(__('done'))
else:
- logger.info('not available for built-in messages')
+ logger.info(__('not available for built-in messages'))
def _init_env(self, freshenv):
# type: (bool) -> None
@@ -343,7 +343,7 @@ class Sphinx(object):
__('succeeded') or __('finished with problems'))
if self._warncount:
logger.info(bold(__('build %s, %s warning.',
- 'build %s, %s warnings.', self._warncount) %
+ 'build %s, %s warnings.', self._warncount) %
(status, self._warncount)))
else:
logger.info(bold(__('build %s.') % status))
@@ -1152,7 +1152,7 @@ class Sphinx(object):
allowed = getattr(ext, attrname, None)
if allowed is None:
logger.warning(message, ext.name)
- logger.warning('doing serial %s', typ)
+ logger.warning(__('doing serial %s'), typ)
return False
elif not allowed:
return False
diff --git a/sphinx/builders/__init__.py b/sphinx/builders/__init__.py
index 71825b2c7..3dcc117ea 100644
--- a/sphinx/builders/__init__.py
+++ b/sphinx/builders/__init__.py
@@ -19,6 +19,7 @@ from sphinx.deprecation import RemovedInSphinx20Warning
from sphinx.environment import BuildEnvironment
from sphinx.environment.adapters.asset import ImageAdapter
from sphinx.errors import SphinxError
+from sphinx.locale import __
from sphinx.util import i18n, import_object, logging, status_iterator
from sphinx.util.build_phase import BuildPhase
from sphinx.util.console import bold # type: ignore
@@ -214,7 +215,7 @@ class Builder(object):
if candidate:
break
else:
- logger.warning('no matching candidate for image URI %r',
+ logger.warning(__('no matching candidate for image URI %r'),
images.get_original_image_uri(node['uri']),
location=node)
continue
@@ -237,8 +238,8 @@ class Builder(object):
# type: (CatalogInfo) -> unicode
return path.relpath(cat.mo_path, self.env.srcdir).replace(path.sep, SEP)
- logger.info(bold('building [mo]: ') + message)
- for catalog in status_iterator(catalogs, 'writing output... ', "darkgreen",
+ logger.info(bold(__('building [mo]: ')) + message)
+ for catalog in status_iterator(catalogs, __('writing output... '), "darkgreen",
len(catalogs), self.app.verbosity,
stringify_func=cat2relpath):
catalog.write_mo(self.config.language)
@@ -251,7 +252,7 @@ class Builder(object):
charset=self.config.source_encoding,
gettext_compact=self.config.gettext_compact,
force_all=True)
- message = 'all of %d po files' % len(catalogs)
+ message = __('all of %d po files') % len(catalogs)
self.compile_catalogs(catalogs, message)
def compile_specific_catalogs(self, specified_files):
@@ -272,7 +273,7 @@ class Builder(object):
domains=list(specified_domains),
charset=self.config.source_encoding,
gettext_compact=self.config.gettext_compact)
- message = 'targets for %d po files that are specified' % len(catalogs)
+ message = __('targets for %d po files that are specified') % len(catalogs)
self.compile_catalogs(catalogs, message)
def compile_update_catalogs(self):
@@ -282,7 +283,7 @@ class Builder(object):
self.config.language,
charset=self.config.source_encoding,
gettext_compact=self.config.gettext_compact)
- message = 'targets for %d po files that are out of date' % len(catalogs)
+ message = __('targets for %d po files that are out of date') % len(catalogs)
self.compile_catalogs(catalogs, message)
# build methods
@@ -290,7 +291,7 @@ class Builder(object):
def build_all(self):
# type: () -> None
"""Build all source files."""
- self.build(None, summary='all source files', method='all')
+ self.build(None, summary=__('all source files'), method='all')
def build_specific(self, filenames):
# type: (List[unicode]) -> None
@@ -304,13 +305,13 @@ class Builder(object):
for filename in filenames:
filename = path.normpath(path.abspath(filename))
if not filename.startswith(self.srcdir):
- logger.warning('file %r given on command line is not under the '
- 'source directory, ignoring', filename)
+ logger.warning(__('file %r given on command line is not under the '
+ 'source directory, ignoring'), filename)
continue
if not (path.isfile(filename) or
any(path.isfile(filename + suffix) for suffix in suffixes)):
- logger.warning('file %r given on command line does not exist, '
- 'ignoring', filename)
+ logger.warning(__('file %r given on command line does not exist, '
+ 'ignoring'), filename)
continue
filename = filename[dirlen:]
for suffix in suffixes:
@@ -320,8 +321,7 @@ class Builder(object):
filename = filename.replace(path.sep, SEP)
to_write.append(filename)
self.build(to_write, method='specific',
- summary='%d source files given on command '
- 'line' % len(to_write))
+ summary=__('%d source files given on command line') % len(to_write))
def build_update(self):
# type: () -> None
@@ -332,8 +332,8 @@ class Builder(object):
else:
to_build = list(to_build)
self.build(to_build,
- summary='targets for %d source files that are '
- 'out of date' % len(to_build))
+ summary=__('targets for %d source files that are out of date') %
+ len(to_build))
def build(self, docnames, summary=None, method='update'):
# type: (Iterable[unicode], unicode, unicode) -> None
@@ -342,37 +342,37 @@ class Builder(object):
First updates the environment, and then calls :meth:`write`.
"""
if summary:
- logger.info(bold('building [%s]' % self.name) + ': ' + summary)
+ logger.info(bold(__('building [%s]') % self.name) + ': ' + summary)
# while reading, collect all warnings from docutils
with logging.pending_warnings():
updated_docnames = set(self.read())
doccount = len(updated_docnames)
- logger.info(bold('looking for now-outdated files... '), nonl=1)
+ logger.info(bold(__('looking for now-outdated files... ')), nonl=1)
for docname in self.env.check_dependents(self.app, updated_docnames):
updated_docnames.add(docname)
outdated = len(updated_docnames) - doccount
if outdated:
- logger.info('%d found', outdated)
+ logger.info(__('%d found'), outdated)
else:
- logger.info('none found')
+ logger.info(__('none found'))
if updated_docnames:
# save the environment
from sphinx.application import ENV_PICKLE_FILENAME
- logger.info(bold('pickling environment... '), nonl=True)
+ logger.info(bold(__('pickling environment... ')), nonl=True)
self.env.topickle(path.join(self.doctreedir, ENV_PICKLE_FILENAME))
- logger.info('done')
+ logger.info(__('done'))
# global actions
self.app.phase = BuildPhase.CONSISTENCY_CHECK
- logger.info(bold('checking consistency... '), nonl=True)
+ logger.info(bold(__('checking consistency... ')), nonl=True)
self.env.check_consistency()
- logger.info('done')
+ logger.info(__('done'))
else:
if method == 'update' and not docnames:
- logger.info(bold('no targets are out of date.'))
+ logger.info(bold(__('no targets are out of date.')))
return
self.app.phase = BuildPhase.RESOLVING
@@ -515,7 +515,7 @@ class Builder(object):
docnames = set(build_docnames) | set(updated_docnames)
else:
docnames = set(build_docnames)
- logger.debug('docnames to write: %s', ', '.join(sorted(docnames)))
+ logger.debug(__('docnames to write: %s'), ', '.join(sorted(docnames)))
# add all toctree-containing files that may have changed
for docname in list(docnames):
@@ -524,9 +524,9 @@ class Builder(object):
docnames.add(tocdocname)
docnames.add(self.config.master_doc)
- logger.info(bold('preparing documents... '), nonl=True)
+ logger.info(bold(__('preparing documents... ')), nonl=True)
self.prepare_writing(docnames)
- logger.info('done')
+ logger.info(__('done'))
if self.parallel_ok:
# number of subprocesses is parallel-1 because the main process
@@ -539,7 +539,7 @@ class Builder(object):
def _write_serial(self, docnames):
# type: (Sequence[unicode]) -> None
with logging.pending_warnings():
- for docname in status_iterator(docnames, 'writing output... ', "darkgreen",
+ for docname in status_iterator(docnames, __('writing output... '), "darkgreen",
len(docnames), self.app.verbosity):
self.app.phase = BuildPhase.RESOLVING
doctree = self.env.get_and_resolve_doctree(docname, self)
@@ -567,7 +567,7 @@ class Builder(object):
chunks = make_chunks(docnames, nproc)
self.app.phase = BuildPhase.RESOLVING
- for chunk in status_iterator(chunks, 'writing output... ', "darkgreen",
+ for chunk in status_iterator(chunks, __('writing output... '), "darkgreen",
len(chunks), self.app.verbosity):
arg = []
for i, docname in enumerate(chunk):
@@ -577,7 +577,7 @@ class Builder(object):
tasks.add_task(write_process, arg)
# make sure all threads have finished
- logger.info(bold('waiting for workers...'))
+ logger.info(bold(__('waiting for workers...')))
tasks.join()
def prepare_writing(self, docnames):
diff --git a/sphinx/builders/_epub_base.py b/sphinx/builders/_epub_base.py
index 880326100..39c288cf5 100644
--- a/sphinx/builders/_epub_base.py
+++ b/sphinx/builders/_epub_base.py
@@ -21,6 +21,7 @@ from docutils.utils import smartquotes
from sphinx import addnodes
from sphinx.builders.html import BuildInfo, StandaloneHTMLBuilder
+from sphinx.locale import __
from sphinx.util import logging
from sphinx.util import status_iterator
from sphinx.util.fileutil import copy_asset_file
@@ -401,13 +402,13 @@ class EpubBuilder(StandaloneHTMLBuilder):
img = Image.open(path.join(self.srcdir, src))
except IOError:
if not self.is_vector_graphics(src):
- logger.warning('cannot read image file %r: copying it instead',
+ logger.warning(__('cannot read image file %r: copying it instead'),
path.join(self.srcdir, src))
try:
copyfile(path.join(self.srcdir, src),
path.join(self.outdir, self.imagedir, dest))
except (IOError, OSError) as err:
- logger.warning('cannot copy image file %r: %s',
+ logger.warning(__('cannot copy image file %r: %s'),
path.join(self.srcdir, src), err)
continue
if self.config.epub_fix_images:
@@ -423,7 +424,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
try:
img.save(path.join(self.outdir, self.imagedir, dest))
except (IOError, OSError) as err:
- logger.warning('cannot write image file %r: %s',
+ logger.warning(__('cannot write image file %r: %s'),
path.join(self.srcdir, src), err)
def copy_image_files(self):
@@ -434,7 +435,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
if self.images:
if self.config.epub_fix_images or self.config.epub_max_image_width:
if not Image:
- logger.warning('PIL not found - copying image files')
+ logger.warning(__('PIL not found - copying image files'))
super(EpubBuilder, self).copy_image_files()
else:
self.copy_image_files_pil()
@@ -464,14 +465,14 @@ class EpubBuilder(StandaloneHTMLBuilder):
def build_mimetype(self, outdir, outname):
# type: (unicode, unicode) -> None
"""Write the metainfo file mimetype."""
- logger.info('writing %s file...', outname)
+ logger.info(__('writing %s file...'), outname)
copy_asset_file(path.join(self.template_dir, 'mimetype'),
path.join(outdir, outname))
def build_container(self, outdir, outname):
# type: (unicode, unicode) -> None
"""Write the metainfo file META-INF/container.xml."""
- logger.info('writing %s file...', outname)
+ logger.info(__('writing %s file...'), outname)
filename = path.join(outdir, outname)
ensuredir(path.dirname(filename))
copy_asset_file(path.join(self.template_dir, 'container.xml'), filename)
@@ -501,7 +502,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
"""Write the metainfo file content.opf It contains bibliographic data,
a file list and the spine (the reading order).
"""
- logger.info('writing %s file...', outname)
+ logger.info(__('writing %s file...'), outname)
metadata = self.content_metadata()
# files
@@ -527,7 +528,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
# we always have JS and potentially OpenSearch files, don't
# always warn about them
if ext not in ('.js', '.xml'):
- logger.warning('unknown mimetype for %s, ignoring', filename,
+ logger.warning(__('unknown mimetype for %s, ignoring'), filename,
type='epub', subtype='unknown_project_files')
continue
filename = filename.replace(os.sep, '/')
@@ -680,7 +681,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
def build_toc(self, outdir, outname):
# type: (unicode, unicode) -> None
"""Write the metainfo file toc.ncx."""
- logger.info('writing %s file...', outname)
+ logger.info(__('writing %s file...'), outname)
if self.config.epub_tocscope == 'default':
doctree = self.env.get_and_resolve_doctree(self.config.master_doc,
@@ -705,7 +706,7 @@ class EpubBuilder(StandaloneHTMLBuilder):
It is a zip file with the mimetype file stored uncompressed as the first
entry.
"""
- logger.info('writing %s file...', outname)
+ logger.info(__('writing %s file...'), outname)
epub_filename = path.join(outdir, outname)
with ZipFile(epub_filename, 'w', ZIP_DEFLATED) as epub: # type: ignore
epub.write(path.join(outdir, 'mimetype'), 'mimetype', ZIP_STORED) # type: ignore
diff --git a/sphinx/builders/applehelp.py b/sphinx/builders/applehelp.py
index d850581a8..3e289effc 100644
--- a/sphinx/builders/applehelp.py
+++ b/sphinx/builders/applehelp.py
@@ -21,6 +21,7 @@ from typing import TYPE_CHECKING
from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.config import string_classes
from sphinx.errors import SphinxError
+from sphinx.locale import __
from sphinx.util import logging
from sphinx.util.console import bold # type: ignore
from sphinx.util.fileutil import copy_asset
@@ -60,11 +61,11 @@ access_page_template = '''\
class AppleHelpIndexerFailed(SphinxError):
- category = 'Help indexer failed'
+ category = __('Help indexer failed')
class AppleHelpCodeSigningFailed(SphinxError):
- category = 'Code signing failed'
+ category = __('Code signing failed')
class AppleHelpBuilder(StandaloneHTMLBuilder):
@@ -73,10 +74,10 @@ class AppleHelpBuilder(StandaloneHTMLBuilder):
on the ``hiutil`` command line tool.
"""
name = 'applehelp'
- epilog = ('The help book is in %(outdir)s.\n'
- 'Note that won\'t be able to view it unless you put it in '
- '~/Library/Documentation/Help or install it in your application '
- 'bundle.')
+ epilog = __('The help book is in %(outdir)s.\n'
+ 'Note that won\'t be able to view it unless you put it in '
+ '~/Library/Documentation/Help or install it in your application '
+ 'bundle.')
# don't copy the reST source
copysource = False
@@ -100,8 +101,8 @@ class AppleHelpBuilder(StandaloneHTMLBuilder):
self.link_suffix = '.html'
if self.config.applehelp_bundle_id is None:
- raise SphinxError('You must set applehelp_bundle_id before '
- 'building Apple Help output')
+ raise SphinxError(__('You must set applehelp_bundle_id before '
+ 'building Apple Help output'))
self.bundle_path = path.join(self.outdir,
self.config.applehelp_bundle_name +
@@ -124,13 +125,13 @@ class AppleHelpBuilder(StandaloneHTMLBuilder):
target_dir = self.outdir
if path.isdir(source_dir):
- logger.info(bold('copying localized files... '), nonl=True)
+ logger.info(bold(__('copying localized files... ')), nonl=True)
excluded = Matcher(self.config.exclude_patterns + ['**/.*'])
copy_asset(source_dir, target_dir, excluded,
context=self.globalcontext, renderer=self.templates)
- logger.info('done')
+ logger.info(__('done'))
def build_helpbook(self):
# type: () -> None
@@ -171,36 +172,36 @@ class AppleHelpBuilder(StandaloneHTMLBuilder):
if self.config.applehelp_remote_url is not None:
info_plist['HPDBookRemoteURL'] = self.config.applehelp_remote_url
- logger.info(bold('writing Info.plist... '), nonl=True)
+ logger.info(bold(__('writing Info.plist... ')), nonl=True)
with open(path.join(contents_dir, 'Info.plist'), 'wb') as f:
write_plist(info_plist, f)
- logger.info('done')
+ logger.info(__('done'))
# Copy the icon, if one is supplied
if self.config.applehelp_icon:
- logger.info(bold('copying icon... '), nonl=True)
+ logger.info(bold(__('copying icon... ')), nonl=True)
try:
copyfile(path.join(self.srcdir, self.config.applehelp_icon),
path.join(resources_dir, info_plist['HPDBookIconPath']))
- logger.info('done')
+ logger.info(__('done'))
except Exception as err:
- logger.warning('cannot copy icon file %r: %s',
+ logger.warning(__('cannot copy icon file %r: %s'),
path.join(self.srcdir, self.config.applehelp_icon), err)
del info_plist['HPDBookIconPath']
# Build the access page
- logger.info(bold('building access page...'), nonl=True)
+ logger.info(bold(__('building access page...')), nonl=True)
with codecs.open(path.join(language_dir, '_access.html'), 'w') as f: # type: ignore
f.write(access_page_template % {
'toc': htmlescape(toc, quote=True),
'title': htmlescape(self.config.applehelp_title)
})
- logger.info('done')
+ logger.info(__('done'))
# Generate the help index
- logger.info(bold('generating help index... '), nonl=True)
+ logger.info(bold(__('generating help index... ')), nonl=True)
args = [
self.config.applehelp_indexer_path,
@@ -222,9 +223,9 @@ class AppleHelpBuilder(StandaloneHTMLBuilder):
args += ['-l', self.config.applehelp_locale]
if self.config.applehelp_disable_external_tools:
- logger.info('skipping')
+ logger.info(__('skipping'))
- logger.warning('you will need to index this help book with:\n %s',
+ logger.warning(__('you will need to index this help book with:\n %s'),
' '.join([pipes.quote(arg) for arg in args]))
else:
try:
@@ -237,13 +238,13 @@ class AppleHelpBuilder(StandaloneHTMLBuilder):
if p.returncode != 0:
raise AppleHelpIndexerFailed(output)
else:
- logger.info('done')
+ logger.info(__('done'))
except OSError:
- raise AppleHelpIndexerFailed('Command not found: %s' % args[0])
+ raise AppleHelpIndexerFailed(__('Command not found: %s') % args[0])
# If we've been asked to, sign the bundle
if self.config.applehelp_codesign_identity:
- logger.info(bold('signing help book... '), nonl=True)
+ logger.info(bold(__('signing help book... ')), nonl=True)
args = [
self.config.applehelp_codesign_path,
@@ -256,8 +257,8 @@ class AppleHelpBuilder(StandaloneHTMLBuilder):
args.append(self.bundle_path)
if self.config.applehelp_disable_external_tools:
- logger.info('skipping')
- logger.warning('you will need to sign this help book with:\n %s',
+ logger.info(__('skipping'))
+ logger.warning(__('you will need to sign this help book with:\n %s'),
' '.join([pipes.quote(arg) for arg in args]))
else:
try:
@@ -270,9 +271,9 @@ class AppleHelpBuilder(StandaloneHTMLBuilder):
if p.returncode != 0:
raise AppleHelpCodeSigningFailed(output)
else:
- logger.info('done')
+ logger.info(__('done'))
except OSError:
- raise AppleHelpCodeSigningFailed('Command not found: %s' % args[0])
+ raise AppleHelpCodeSigningFailed(__('Command not found: %s') % args[0])
def setup(app):
diff --git a/sphinx/builders/changes.py b/sphinx/builders/changes.py
index eb7bb1554..fe88b5aaf 100644
--- a/sphinx/builders/changes.py
+++ b/sphinx/builders/changes.py
@@ -17,7 +17,7 @@ from six import iteritems
from sphinx import package_dir
from sphinx.builders import Builder
-from sphinx.locale import _
+from sphinx.locale import _, __
from sphinx.theming import HTMLThemeFactory
from sphinx.util import logging
from sphinx.util.console import bold # type: ignore
@@ -38,7 +38,7 @@ class ChangesBuilder(Builder):
Write a summary with all versionadded/changed directives.
"""
name = 'changes'
- epilog = 'The overview file is in %(outdir)s.'
+ epilog = __('The overview file is in %(outdir)s.')
def init(self):
# type: () -> None
@@ -64,7 +64,7 @@ class ChangesBuilder(Builder):
apichanges = [] # type: List[Tuple[unicode, unicode, int]]
otherchanges = {} # type: Dict[Tuple[unicode, unicode], List[Tuple[unicode, unicode, int]]] # NOQA
if version not in self.env.versionchanges:
- logger.info(bold('no changes in version %s.' % version))
+ logger.info(bold(__('no changes in version %s.') % version))
return
logger.info(bold('writing summary file...'))
for type, docname, lineno, module, descname, content in \
@@ -129,14 +129,14 @@ class ChangesBuilder(Builder):
break
return line
- logger.info(bold('copying source files...'))
+ logger.info(bold(__('copying source files...')))
for docname in self.env.all_docs:
with codecs.open(self.env.doc2path(docname), 'r', # type: ignore
self.env.config.source_encoding) as f:
try:
lines = f.readlines()
except UnicodeDecodeError:
- logger.warning('could not read %r for changelog creation', docname)
+ logger.warning(__('could not read %r for changelog creation'), docname)
continue
targetfn = path.join(self.outdir, 'rst', os_path(docname)) + '.html'
ensuredir(path.dirname(targetfn))
diff --git a/sphinx/builders/devhelp.py b/sphinx/builders/devhelp.py
index 4e204eabb..f1511b564 100644
--- a/sphinx/builders/devhelp.py
+++ b/sphinx/builders/devhelp.py
@@ -22,6 +22,7 @@ from docutils import nodes
from sphinx import addnodes
from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.environment.adapters.indexentries import IndexEntries
+from sphinx.locale import __
from sphinx.util import logging
from sphinx.util.osutil import make_filename
@@ -43,10 +44,10 @@ class DevhelpBuilder(StandaloneHTMLBuilder):
Builder that also outputs GNOME Devhelp file.
"""
name = 'devhelp'
- epilog = ('To view the help file:\n'
- '$ mkdir -p $HOME/.local/share/devhelp/%(project)s\n'
- '$ ln -s %(outdir)s $HOME/.local/share/devhelp/%(project)s\n'
- '$ devhelp')
+ epilog = __('To view the help file:\n'
+ '$ mkdir -p $HOME/.local/share/devhelp/%(project)s\n'
+ '$ ln -s %(outdir)s $HOME/.local/share/devhelp/%(project)s\n'
+ '$ devhelp')
# don't copy the reST source
copysource = False
@@ -69,7 +70,7 @@ class DevhelpBuilder(StandaloneHTMLBuilder):
def build_devhelp(self, outdir, outname):
# type: (unicode, unicode) -> None
- logger.info('dumping devhelp index...')
+ logger.info(__('dumping devhelp index...'))
# Basic info
root = etree.Element('book',
diff --git a/sphinx/builders/dummy.py b/sphinx/builders/dummy.py
index e0f2a3dab..cc23c6e2b 100644
--- a/sphinx/builders/dummy.py
+++ b/sphinx/builders/dummy.py
@@ -12,6 +12,7 @@
from typing import TYPE_CHECKING
from sphinx.builders import Builder
+from sphinx.locale import __
if TYPE_CHECKING:
from typing import Any, Dict, Set # NOQA
@@ -21,7 +22,7 @@ if TYPE_CHECKING:
class DummyBuilder(Builder):
name = 'dummy'
- epilog = 'The dummy builder generates no files.'
+ epilog = __('The dummy builder generates no files.')
allow_parallel = True
diff --git a/sphinx/builders/epub3.py b/sphinx/builders/epub3.py
index 53deb0ee5..995f5a6dc 100644
--- a/sphinx/builders/epub3.py
+++ b/sphinx/builders/epub3.py
@@ -17,6 +17,7 @@ from typing import TYPE_CHECKING
from sphinx import package_dir
from sphinx.builders import _epub_base
from sphinx.config import string_classes, ENUM
+from sphinx.locale import __
from sphinx.util import logging, xmlname_checker
from sphinx.util.fileutil import copy_asset_file
from sphinx.util.i18n import format_date
@@ -63,7 +64,7 @@ class Epub3Builder(_epub_base.EpubBuilder):
an epub file.
"""
name = 'epub'
- epilog = 'The ePub file is in %(outdir)s.'
+ epilog = __('The ePub file is in %(outdir)s.')
supported_remote_images = False
template_dir = path.join(package_dir, 'templates', 'epub3')
@@ -88,37 +89,37 @@ class Epub3Builder(_epub_base.EpubBuilder):
# type: () -> None
# <package> lang attribute, dc:language
if not self.app.config.epub_language:
- logger.warning('conf value "epub_language" (or "language") '
- 'should not be empty for EPUB3')
+ logger.warning(__('conf value "epub_language" (or "language") '
+ 'should not be empty for EPUB3'))
# <package> unique-identifier attribute
if not xmlname_checker().match(self.app.config.epub_uid):
- logger.warning('conf value "epub_uid" should be XML NAME for EPUB3')
+ logger.warning(__('conf value "epub_uid" should be XML NAME for EPUB3'))
# dc:title
if not self.app.config.epub_title:
- logger.warning('conf value "epub_title" (or "html_title") '
- 'should not be empty for EPUB3')
+ logger.warning(__('conf value "epub_title" (or "html_title") '
+ 'should not be empty for EPUB3'))
# dc:creator
if not self.app.config.epub_author:
- logger.warning('conf value "epub_author" should not be empty for EPUB3')
+ logger.warning(__('conf value "epub_author" should not be empty for EPUB3'))
# dc:contributor
if not self.app.config.epub_contributor:
- logger.warning('conf value "epub_contributor" should not be empty for EPUB3')
+ logger.warning(__('conf value "epub_contributor" should not be empty for EPUB3'))
# dc:description
if not self.app.config.epub_description:
- logger.warning('conf value "epub_description" should not be empty for EPUB3')
+ logger.warning(__('conf value "epub_description" should not be empty for EPUB3'))
# dc:publisher
if not self.app.config.epub_publisher:
- logger.warning('conf value "epub_publisher" should not be empty for EPUB3')
+ logger.warning(__('conf value "epub_publisher" should not be empty for EPUB3'))
# dc:rights
if not self.app.config.epub_copyright:
- logger.warning('conf value "epub_copyright" (or "copyright")'
- 'should not be empty for EPUB3')
+ logger.warning(__('conf value "epub_copyright" (or "copyright")'
+ 'should not be empty for EPUB3'))
# dc:identifier
if not self.app.config.epub_identifier:
- logger.warning('conf value "epub_identifier" should not be empty for EPUB3')
+ logger.warning(__('conf value "epub_identifier" should not be empty for EPUB3'))
# meta ibooks:version
if not self.app.config.version:
- logger.warning('conf value "version" should not be empty for EPUB3')
+ logger.warning(__('conf value "version" should not be empty for EPUB3'))
def content_metadata(self):
# type: () -> Dict
@@ -204,7 +205,7 @@ class Epub3Builder(_epub_base.EpubBuilder):
def build_navigation_doc(self, outdir, outname):
# type: (unicode, unicode) -> None
"""Write the metainfo file nav.xhtml."""
- logger.info('writing %s file...', outname)
+ logger.info(__('writing %s file...'), outname)
if self.config.epub_tocscope == 'default':
doctree = self.env.get_and_resolve_doctree(
diff --git a/sphinx/builders/gettext.py b/sphinx/builders/gettext.py
index f7a2c988f..584463b4f 100644
--- a/sphinx/builders/gettext.py
+++ b/sphinx/builders/gettext.py
@@ -23,6 +23,7 @@ from six import iteritems, StringIO
from sphinx.builders import Builder
from sphinx.domains.python import pairindextypes
+from sphinx.locale import __
from sphinx.util import split_index_msg, logging, status_iterator
from sphinx.util.console import bold # type: ignore
from sphinx.util.i18n import find_catalog
@@ -215,7 +216,7 @@ class MessageCatalogBuilder(I18nBuilder):
Builds gettext-style message catalogs (.pot files).
"""
name = 'gettext'
- epilog = 'The message catalogs are in %(outdir)s.'
+ epilog = __('The message catalogs are in %(outdir)s.')
def init(self):
# type: () -> None
@@ -239,12 +240,12 @@ class MessageCatalogBuilder(I18nBuilder):
# type: () -> None
files = list(self._collect_templates())
files.sort()
- logger.info(bold('building [%s]: ' % self.name), nonl=1)
- logger.info('targets for %d template files', len(files))
+ logger.info(bold(__('building [%s]: ') % self.name), nonl=1)
+ logger.info(__('targets for %d template files'), len(files))
extract_translations = self.templates.environment.extract_translations
- for template in status_iterator(files, 'reading templates... ', "purple", # type: ignore # NOQA
+ for template in status_iterator(files, __('reading templates... '), "purple", # type: ignore # NOQA
len(files), self.app.verbosity):
with open(template, 'r', encoding='utf-8') as f: # type: ignore
context = f.read()
@@ -268,7 +269,7 @@ class MessageCatalogBuilder(I18nBuilder):
timestamp, ltz).strftime('%Y-%m-%d %H:%M%z'),
)
for textdomain, catalog in status_iterator(iteritems(self.catalogs), # type: ignore
- "writing message catalogs... ",
+ __("writing message catalogs... "),
"darkgreen", len(self.catalogs),
self.app.verbosity,
lambda textdomain__: textdomain__[0]):
diff --git a/sphinx/builders/html.py b/sphinx/builders/html.py
index b8c43d08c..017f58620 100644
--- a/sphinx/builders/html.py
+++ b/sphinx/builders/html.py
@@ -37,7 +37,7 @@ from sphinx.environment.adapters.asset import ImageAdapter
from sphinx.environment.adapters.indexentries import IndexEntries
from sphinx.environment.adapters.toctree import TocTree
from sphinx.highlighting import PygmentsBridge
-from sphinx.locale import _
+from sphinx.locale import _, __
from sphinx.search import js_index
from sphinx.theming import HTMLThemeFactory
from sphinx.util import jsonimpl, logging, status_iterator
@@ -174,7 +174,7 @@ class BuildInfo(object):
build_info.tags_hash = lines[3].split()[1].strip()
return build_info
except Exception as exc:
- raise ValueError('build info file is broken: %r' % exc)
+ raise ValueError(__('build info file is broken: %r') % exc)
def __init__(self, config=None, tags=None, config_categories=[]):
# type: (Config, Tags, List[unicode]) -> None
@@ -213,7 +213,7 @@ class StandaloneHTMLBuilder(Builder):
"""
name = 'html'
format = 'html'
- epilog = 'The HTML pages are in %(outdir)s.'
+ epilog = __('The HTML pages are in %(outdir)s.')
copysource = True
allow_parallel = True
@@ -346,7 +346,7 @@ class StandaloneHTMLBuilder(Builder):
yield docname
return
except ValueError as exc:
- logger.warning('Failed to read build info file: %r', exc)
+ logger.warning(__('Failed to read build info file: %r'), exc)
except IOError:
# ignore errors on reading
pass
@@ -458,7 +458,7 @@ class StandaloneHTMLBuilder(Builder):
path.basename(self.config.html_favicon) or ''
if not isinstance(self.config.html_use_opensearch, string_types):
- logger.warning('html_use_opensearch config value must now be a string')
+ logger.warning(__('html_use_opensearch config value must now be a string'))
self.relations = self.env.collect_relations()
@@ -635,7 +635,7 @@ class StandaloneHTMLBuilder(Builder):
def gen_indices(self):
# type: () -> None
- logger.info(bold('generating indices...'), nonl=1)
+ logger.info(bold(__('generating indices...')), nonl=1)
# the global general index
if self.use_index:
@@ -653,7 +653,7 @@ class StandaloneHTMLBuilder(Builder):
for pagename, context, template in pagelist:
self.handle_page(pagename, context, template)
- logger.info(bold('writing additional pages...'), nonl=1)
+ logger.info(bold(__('writing additional pages...')), nonl=1)
# additional pages from conf.py
for pagename, template in self.config.html_additional_pages.items():
@@ -719,7 +719,7 @@ class StandaloneHTMLBuilder(Builder):
if self.images:
stringify_func = ImageAdapter(self.app.env).get_original_image_uri
ensuredir(path.join(self.outdir, self.imagedir))
- for src in status_iterator(self.images, 'copying images... ', "brown",
+ for src in status_iterator(self.images, __('copying images... '), "brown",
len(self.images), self.app.verbosity,
stringify_func=stringify_func):
dest = self.images[src]
@@ -727,7 +727,7 @@ class StandaloneHTMLBuilder(Builder):
copyfile(path.join(self.srcdir, src),
path.join(self.outdir, self.imagedir, dest))
except Exception as err:
- logger.warning('cannot copy image file %r: %s',
+ logger.warning(__('cannot copy image file %r: %s'),
path.join(self.srcdir, src), err)
def copy_download_files(self):
@@ -738,7 +738,7 @@ class StandaloneHTMLBuilder(Builder):
# copy downloadable files
if self.env.dlfiles:
ensuredir(path.join(self.outdir, '_downloads'))
- for src in status_iterator(self.env.dlfiles, 'copying downloadable files... ',
+ for src in status_iterator(self.env.dlfiles, __('copying downloadable files... '),
"brown", len(self.env.dlfiles), self.app.verbosity,
stringify_func=to_relpath):
dest = self.env.dlfiles[src][1]
@@ -746,13 +746,13 @@ class StandaloneHTMLBuilder(Builder):
copyfile(path.join(self.srcdir, src),
path.join(self.outdir, '_downloads', dest))
except Exception as err:
- logger.warning('cannot copy downloadable file %r: %s',
+ logger.warning(__('cannot copy downloadable file %r: %s'),
path.join(self.srcdir, src), err)
def copy_static_files(self):
# type: () -> None
# copy static files
- logger.info(bold('copying static files... '), nonl=True)
+ logger.info(bold(__('copying static files... ')), nonl=True)
ensuredir(path.join(self.outdir, '_static'))
# first, create pygments style file
with open(path.join(self.outdir, '_static', 'pygments.css'), 'w') as f:
@@ -787,7 +787,7 @@ class StandaloneHTMLBuilder(Builder):
for static_path in self.config.html_static_path:
entry = path.join(self.confdir, static_path)
if not path.exists(entry):
- logger.warning('html_static_path entry %r does not exist', entry)
+ logger.warning(__('html_static_path entry %r does not exist'), entry)
continue
copy_asset(entry, path.join(self.outdir, '_static'), excluded,
context=ctx, renderer=self.templates)
@@ -796,7 +796,7 @@ class StandaloneHTMLBuilder(Builder):
logobase = path.basename(self.config.html_logo)
logotarget = path.join(self.outdir, '_static', logobase)
if not path.isfile(path.join(self.confdir, self.config.html_logo)):
- logger.warning('logo file %r does not exist', self.config.html_logo)
+ logger.warning(__('logo file %r does not exist'), self.config.html_logo)
elif not path.isfile(logotarget):
copyfile(path.join(self.confdir, self.config.html_logo),
logotarget)
@@ -804,7 +804,7 @@ class StandaloneHTMLBuilder(Builder):
iconbase = path.basename(self.config.html_favicon)
icontarget = path.join(self.outdir, '_static', iconbase)
if not path.isfile(path.join(self.confdir, self.config.html_favicon)):
- logger.warning('favicon file %r does not exist', self.config.html_favicon)
+ logger.warning(__('favicon file %r does not exist'), self.config.html_favicon)
elif not path.isfile(icontarget):
copyfile(path.join(self.confdir, self.config.html_favicon),
icontarget)
@@ -813,17 +813,17 @@ class StandaloneHTMLBuilder(Builder):
def copy_extra_files(self):
# type: () -> None
# copy html_extra_path files
- logger.info(bold('copying extra files... '), nonl=True)
+ logger.info(bold(__('copying extra files... ')), nonl=True)
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):
- logger.warning('html_extra_path entry %r does not exist', entry)
+ logger.warning(__('html_extra_path entry %r does not exist'), entry)
continue
copy_asset(entry, self.outdir, excluded)
- logger.info('done')
+ logger.info(__('done'))
def write_buildinfo(self):
# type: () -> None
@@ -831,7 +831,7 @@ class StandaloneHTMLBuilder(Builder):
with open(path.join(self.outdir, '.buildinfo'), 'w') as fp:
self.build_info.dump(fp)
except IOError as exc:
- logger.warning('Failed to write build info file: %r', exc)
+ logger.warning(__('Failed to write build info file: %r'), exc)
def cleanup(self):
# type: () -> None
@@ -878,9 +878,9 @@ class StandaloneHTMLBuilder(Builder):
self.indexer.load(f, self.indexer_format)
except (IOError, OSError, ValueError):
if keep:
- logger.warning('search index couldn\'t be loaded, but not all '
- 'documents will be built: the index will be '
- 'incomplete.')
+ logger.warning(__('search index couldn\'t be loaded, but not all '
+ 'documents will be built: the index will be '
+ 'incomplete.'))
# delete all entries for files that will be rebuilt
self.indexer.prune(keep)
@@ -932,8 +932,8 @@ class StandaloneHTMLBuilder(Builder):
if has_wildcard(pattern):
# warn if both patterns contain wildcards
if has_wildcard(matched):
- logger.warning('page %s matches two patterns in '
- 'html_sidebars: %r and %r',
+ logger.warning(__('page %s matches two patterns in '
+ 'html_sidebars: %r and %r'),
pagename, matched, pattern)
# else the already matched pattern is more specific
# than the present one, because it contains no wildcard
@@ -1018,9 +1018,9 @@ class StandaloneHTMLBuilder(Builder):
try:
output = self.templates.render(templatename, ctx)
except UnicodeError:
- logger.warning("a Unicode error occurred when rendering the page %s. "
- "Please make sure all config values that contain "
- "non-ASCII content are Unicode strings.", pagename)
+ logger.warning(__("a Unicode error occurred when rendering the page %s. "
+ "Please make sure all config values that contain "
+ "non-ASCII content are Unicode strings."), pagename)
return
if not outfilename:
@@ -1031,7 +1031,7 @@ class StandaloneHTMLBuilder(Builder):
with codecs.open(outfilename, 'w', ctx['encoding'], 'xmlcharrefreplace') as f: # type: ignore # NOQA
f.write(output)
except (IOError, OSError) as err:
- logger.warning("error writing file %s: %s", outfilename, err)
+ logger.warning(__("error writing file %s: %s"), outfilename, err)
if self.copysource and ctx.get('sourcename'):
# copy the source file for the "show source" link
source_name = path.join(self.outdir, '_sources',
@@ -1051,14 +1051,14 @@ class StandaloneHTMLBuilder(Builder):
def dump_inventory(self):
# type: () -> None
- logger.info(bold('dumping object inventory... '), nonl=True)
+ logger.info(bold(__('dumping object inventory... ')), nonl=True)
InventoryFile.dump(path.join(self.outdir, INVENTORY_FILENAME), self.env, self)
- logger.info('done')
+ logger.info(__('done'))
def dump_search_index(self):
# type: () -> None
logger.info(
- bold('dumping search index in %s ... ' % self.indexer.label()),
+ bold(__('dumping search index in %s ... ') % self.indexer.label()),
nonl=True)
self.indexer.prune(self.env.all_docs)
searchindexfn = path.join(self.outdir, self.searchindex_filename)
@@ -1071,7 +1071,7 @@ class StandaloneHTMLBuilder(Builder):
with f:
self.indexer.dump(f, self.indexer_format)
movefile(searchindexfn + '.tmp', searchindexfn)
- logger.info('done')
+ logger.info(__('done'))
class DirectoryHTMLBuilder(StandaloneHTMLBuilder):
@@ -1113,7 +1113,7 @@ class SingleFileHTMLBuilder(StandaloneHTMLBuilder):
HTML page.
"""
name = 'singlehtml'
- epilog = 'The HTML page is in %(outdir)s.'
+ epilog = __('The HTML page is in %(outdir)s.')
copysource = False
@@ -1243,24 +1243,24 @@ class SingleFileHTMLBuilder(StandaloneHTMLBuilder):
# type: (Any) -> None
docnames = self.env.all_docs
- logger.info(bold('preparing documents... '), nonl=True)
+ logger.info(bold(__('preparing documents... ')), nonl=True)
self.prepare_writing(docnames)
- logger.info('done')
+ logger.info(__('done'))
- logger.info(bold('assembling single document... '), nonl=True)
+ logger.info(bold(__('assembling single document... ')), nonl=True)
doctree = self.assemble_doctree()
self.env.toc_secnumbers = self.assemble_toc_secnumbers()
self.env.toc_fignumbers = self.assemble_toc_fignumbers()
logger.info('')
- logger.info(bold('writing... '), nonl=True)
+ logger.info(bold(__('writing... ')), nonl=True)
self.write_doc_serialized(self.config.master_doc, doctree)
self.write_doc(self.config.master_doc, doctree)
- logger.info('done')
+ logger.info(__('done'))
def finish(self):
# type: () -> None
# no indices or search pages are supported
- logger.info(bold('writing additional files...'), nonl=1)
+ logger.info(bold(__('writing additional files...')), nonl=1)
# additional pages from conf.py
for pagename, template in self.config.html_additional_pages.items():
@@ -1377,7 +1377,7 @@ class PickleHTMLBuilder(SerializingHTMLBuilder):
A Builder that dumps the generated HTML into pickle files.
"""
name = 'pickle'
- epilog = 'You can now process the pickle files in %(outdir)s.'
+ epilog = __('You can now process the pickle files in %(outdir)s.')
implementation = pickle
implementation_dumps_unicode = False
@@ -1398,7 +1398,7 @@ class JSONHTMLBuilder(SerializingHTMLBuilder):
A builder that dumps the generated HTML into JSON files.
"""
name = 'json'
- epilog = 'You can now process the JSON files in %(outdir)s.'
+ epilog = __('You can now process the JSON files in %(outdir)s.')
implementation = jsonimpl
implementation_dumps_unicode = True
diff --git a/sphinx/builders/htmlhelp.py b/sphinx/builders/htmlhelp.py
index a518582b4..8f7cd7734 100644
--- a/sphinx/builders/htmlhelp.py
+++ b/sphinx/builders/htmlhelp.py
@@ -21,6 +21,7 @@ from docutils import nodes
from sphinx import addnodes
from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.environment.adapters.indexentries import IndexEntries
+from sphinx.locale import __
from sphinx.util import logging
from sphinx.util.osutil import make_filename
from sphinx.util.pycompat import htmlescape
@@ -174,8 +175,8 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder):
index files. Adapted from the original Doc/tools/prechm.py.
"""
name = 'htmlhelp'
- epilog = ('You can now run HTML Help Workshop with the .htp file in '
- '%(outdir)s.')
+ epilog = __('You can now run HTML Help Workshop with the .htp file in '
+ '%(outdir)s.')
# don't copy the reST source
copysource = False
@@ -228,12 +229,12 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder):
def build_hhx(self, outdir, outname):
# type: (unicode, unicode) -> None
- logger.info('dumping stopword list...')
+ logger.info(__('dumping stopword list...'))
with self.open_file(outdir, outname + '.stp') as f:
for word in sorted(stopwords):
print(word, file=f)
- logger.info('writing project file...')
+ logger.info(__('writing project file...'))
with self.open_file(outdir, outname + '.hhp') as f:
f.write(project_template % {
'outname': outname,
@@ -254,7 +255,7 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder):
print(path.join(root, fn)[olen:].replace(os.sep, '\\'),
file=f)
- logger.info('writing TOC file...')
+ logger.info(__('writing TOC file...'))
with self.open_file(outdir, outname + '.hhc') as f:
f.write(contents_header)
# special books
@@ -296,7 +297,7 @@ class HTMLHelpBuilder(StandaloneHTMLBuilder):
write_toc(node)
f.write(contents_footer)
- logger.info('writing index file...')
+ logger.info(__('writing index file...'))
index = IndexEntries(self.env).create_index(self)
with self.open_file(outdir, outname + '.hhk') as f:
f.write('<UL>\n')
diff --git a/sphinx/builders/latex.py b/sphinx/builders/latex.py
index 7c5d40a9e..0be57f013 100644
--- a/sphinx/builders/latex.py
+++ b/sphinx/builders/latex.py
@@ -24,7 +24,7 @@ from sphinx.config import string_classes, ENUM
from sphinx.environment import NoUri
from sphinx.environment.adapters.asset import ImageAdapter
from sphinx.errors import SphinxError, ConfigError
-from sphinx.locale import _
+from sphinx.locale import _, __
from sphinx.util import texescape, logging, status_iterator
from sphinx.util.console import bold, darkgreen # type: ignore
from sphinx.util.docutils import new_document
@@ -48,11 +48,11 @@ class LaTeXBuilder(Builder):
"""
name = 'latex'
format = 'latex'
- epilog = 'The LaTeX files are in %(outdir)s.'
+ epilog = __('The LaTeX files are in %(outdir)s.')
if os.name == 'posix':
- epilog += ("\nRun 'make' in that directory to run these through "
- "(pdf)latex\n"
- "(use `make latexpdf' here to do that automatically).")
+ epilog += __("\nRun 'make' in that directory to run these through "
+ "(pdf)latex\n"
+ "(use `make latexpdf' here to do that automatically).")
supported_image_types = ['application/pdf', 'image/png', 'image/jpeg']
supported_remote_images = False
@@ -85,16 +85,16 @@ class LaTeXBuilder(Builder):
# type: () -> None
preliminary_document_data = [list(x) for x in self.config.latex_documents]
if not preliminary_document_data:
- logger.warning('no "latex_documents" config value found; no documents '
- 'will be written')
+ logger.warning(__('no "latex_documents" config value found; no documents '
+ 'will be written'))
return
# assign subdirs to titles
self.titles = [] # type: List[Tuple[unicode, unicode]]
for entry in preliminary_document_data:
docname = entry[0]
if docname not in self.env.all_docs:
- logger.warning('"latex_documents" config value references unknown '
- 'document %s', docname)
+ logger.warning(__('"latex_documents" config value references unknown '
+ 'document %s'), docname)
continue
self.document_data.append(entry) # type: ignore
if docname.endswith(SEP + 'index'):
@@ -131,7 +131,7 @@ class LaTeXBuilder(Builder):
destination = FileOutput(
destination_path=path.join(self.outdir, targetname),
encoding='utf-8')
- logger.info("processing %s...", targetname, nonl=1)
+ logger.info(__("processing %s..."), targetname, nonl=1)
toctrees = self.env.get_doctree(docname).traverse(addnodes.toctree)
if toctrees:
if toctrees[0].get('maxdepth') > 0:
@@ -145,7 +145,7 @@ class LaTeXBuilder(Builder):
appendices=((docclass != 'howto') and self.config.latex_appendices or []))
doctree['tocdepth'] = tocdepth
self.post_process_images(doctree)
- logger.info("writing... ", nonl=1)
+ logger.info(__("writing... "), nonl=1)
doctree.settings = docsettings
doctree.settings.author = author
doctree.settings.title = title
@@ -191,7 +191,7 @@ class LaTeXBuilder(Builder):
appendix['docname'] = docname
largetree.append(appendix)
logger.info('')
- logger.info("resolving references...")
+ logger.info(__("resolving references..."))
self.env.resolve_references(largetree, indexfile, self)
# resolve :ref:s to distant tex files -- we can't add a cross-reference,
# but append the document name
@@ -216,7 +216,7 @@ class LaTeXBuilder(Builder):
# copy TeX support files from texinputs
context = {'latex_engine': self.config.latex_engine}
- logger.info(bold('copying TeX support files...'))
+ logger.info(bold(__('copying TeX support files...')))
staticdirname = path.join(package_dir, 'texinputs')
for filename in os.listdir(staticdirname):
if not filename.startswith('.'):
@@ -231,7 +231,7 @@ class LaTeXBuilder(Builder):
# copy additional files
if self.config.latex_additional_files:
- logger.info(bold('copying additional files...'), nonl=1)
+ logger.info(bold(__('copying additional files...')), nonl=1)
for filename in self.config.latex_additional_files:
logger.info(' ' + filename, nonl=1)
copy_asset_file(path.join(self.confdir, filename), self.outdir)
@@ -240,16 +240,16 @@ class LaTeXBuilder(Builder):
# the logo is handled differently
if self.config.latex_logo:
if not path.isfile(path.join(self.confdir, self.config.latex_logo)):
- raise SphinxError('logo file %r does not exist' % self.config.latex_logo)
+ raise SphinxError(__('logo file %r does not exist') % self.config.latex_logo)
else:
copy_asset_file(path.join(self.confdir, self.config.latex_logo), self.outdir)
- logger.info('done')
+ logger.info(__('done'))
def copy_image_files(self):
# type: () -> None
if self.images:
stringify_func = ImageAdapter(self.app.env).get_original_image_uri
- for src in status_iterator(self.images, 'copying images... ', "brown",
+ for src in status_iterator(self.images, __('copying images... '), "brown",
len(self.images), self.app.verbosity,
stringify_func=stringify_func):
dest = self.images[src]
@@ -257,7 +257,7 @@ class LaTeXBuilder(Builder):
copy_asset_file(path.join(self.srcdir, src),
path.join(self.outdir, dest))
except Exception as err:
- logger.warning('cannot copy image file %r: %s',
+ logger.warning(__('cannot copy image file %r: %s'),
path.join(self.srcdir, src), err)
@@ -268,16 +268,16 @@ def validate_config_values(app, config):
text_type(document[2])
except UnicodeDecodeError:
raise ConfigError(
- 'Invalid latex_documents.title found (might contain non-ASCII chars. '
- 'Please use u"..." notation instead): %r' % (document,)
+ __('Invalid latex_documents.title found (might contain non-ASCII chars. '
+ 'Please use u"..." notation instead): %r') % (document,)
)
try:
text_type(document[3])
except UnicodeDecodeError:
raise ConfigError(
- 'Invalid latex_documents.author found (might contain non-ASCII chars. '
- 'Please use u"..." notation instead): %r' % (document,)
+ __('Invalid latex_documents.author found (might contain non-ASCII chars. '
+ 'Please use u"..." notation instead): %r') % (document,)
)
diff --git a/sphinx/builders/linkcheck.py b/sphinx/builders/linkcheck.py
index 24bf13edc..50768c5b9 100644
--- a/sphinx/builders/linkcheck.py
+++ b/sphinx/builders/linkcheck.py
@@ -32,6 +32,7 @@ except ImportError:
pass
from sphinx.builders import Builder
+from sphinx.locale import __
from sphinx.util import encode_uri, requests, logging
from sphinx.util.console import ( # type: ignore
purple, red, darkgreen, darkgray, darkred, turquoise
@@ -91,8 +92,8 @@ class CheckExternalLinksBuilder(Builder):
Checks for broken external links.
"""
name = 'linkcheck'
- epilog = ('Look for any errors in the above output or in '
- '%(outdir)s/output.txt')
+ epilog = __('Look for any errors in the above output or in '
+ '%(outdir)s/output.txt')
def init(self):
# type: () -> None
@@ -152,7 +153,7 @@ class CheckExternalLinksBuilder(Builder):
found = check_anchor(response, unquote(anchor))
if not found:
- raise Exception("Anchor '%s' not found" % anchor)
+ raise Exception(__("Anchor '%s' not found") % anchor)
else:
try:
# try a HEAD request first, which should be easier on
@@ -250,7 +251,7 @@ class CheckExternalLinksBuilder(Builder):
elif status == 'broken':
self.write_entry('broken', docname, lineno, uri + ': ' + info)
if self.app.quiet or self.app.warningiserror:
- logger.warning('broken link: %s (%s)', uri, info,
+ logger.warning(__('broken link: %s (%s)'), uri, info,
location=(self.env.doc2path(docname), lineno))
else:
logger.info(red('broken ') + uri + red(' - ' + info))
diff --git a/sphinx/builders/manpage.py b/sphinx/builders/manpage.py
index fb7c15ac5..e1bbcffa8 100644
--- a/sphinx/builders/manpage.py
+++ b/sphinx/builders/manpage.py
@@ -19,6 +19,7 @@ from six import string_types
from sphinx import addnodes
from sphinx.builders import Builder
from sphinx.environment import NoUri
+from sphinx.locale import __
from sphinx.util import logging
from sphinx.util.console import bold, darkgreen # type: ignore
from sphinx.util.nodes import inline_all_toctrees
@@ -39,7 +40,7 @@ class ManualPageBuilder(Builder):
"""
name = 'man'
format = 'man'
- epilog = 'The manual pages are in %(outdir)s.'
+ epilog = __('The manual pages are in %(outdir)s.')
default_translator_class = ManualPageTranslator
supported_image_types = [] # type: List[unicode]
@@ -47,8 +48,8 @@ class ManualPageBuilder(Builder):
def init(self):
# type: () -> None
if not self.config.man_pages:
- logger.warning('no "man_pages" config value found; no manual pages '
- 'will be written')
+ logger.warning(__('no "man_pages" config value found; no manual pages '
+ 'will be written'))
def get_outdated_docs(self):
# type: () -> Union[unicode, List[unicode]]
@@ -68,7 +69,7 @@ class ManualPageBuilder(Builder):
components=(docwriter,),
read_config_files=True).get_default_values()
- logger.info(bold('writing... '), nonl=True)
+ logger.info(bold(__('writing... ')), nonl=True)
for info in self.config.man_pages:
docname, name, description, authors, section = info
diff --git a/sphinx/builders/qthelp.py b/sphinx/builders/qthelp.py
index 089470cb6..a5b320c9e 100644
--- a/sphinx/builders/qthelp.py
+++ b/sphinx/builders/qthelp.py
@@ -23,6 +23,7 @@ from sphinx import addnodes
from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.config import string_classes
from sphinx.environment.adapters.indexentries import IndexEntries
+from sphinx.locale import __
from sphinx.util import force_decode, logging
from sphinx.util.osutil import make_filename
from sphinx.util.pycompat import htmlescape
@@ -107,11 +108,11 @@ class QtHelpBuilder(StandaloneHTMLBuilder):
Builder that also outputs Qt help project, contents and index files.
"""
name = 'qthelp'
- epilog = ('You can now run "qcollectiongenerator" with the .qhcp '
- 'project file in %(outdir)s, like this:\n'
- '$ qcollectiongenerator %(outdir)s/%(project)s.qhcp\n'
- 'To view the help file:\n'
- '$ assistant -collectionFile %(outdir)s/%(project)s.qhc')
+ epilog = __('You can now run "qcollectiongenerator" with the .qhcp '
+ 'project file in %(outdir)s, like this:\n'
+ '$ qcollectiongenerator %(outdir)s/%(project)s.qhcp\n'
+ 'To view the help file:\n'
+ '$ assistant -collectionFile %(outdir)s/%(project)s.qhc')
# don't copy the reST source
copysource = False
@@ -147,7 +148,7 @@ class QtHelpBuilder(StandaloneHTMLBuilder):
def build_qhp(self, outdir, outname):
# type: (unicode, unicode) -> None
- logger.info('writing project file...')
+ logger.info(__('writing project file...'))
# sections
tocdoc = self.env.get_and_resolve_doctree(self.config.master_doc, self,
@@ -230,7 +231,7 @@ class QtHelpBuilder(StandaloneHTMLBuilder):
nspace, 'doc', self.get_target_uri(self.config.master_doc))
startpage = 'qthelp://' + posixpath.join(nspace, 'doc', 'index.html')
- logger.info('writing collection project file...')
+ logger.info(__('writing collection project file...'))
with codecs.open(path.join(outdir, outname + '.qhcp'), 'w', 'utf-8') as f: # type: ignore # NOQA
f.write(collection_template % {
'outname': htmlescape(outname),
diff --git a/sphinx/builders/texinfo.py b/sphinx/builders/texinfo.py
index 282689cef..f43ff9ec0 100644
--- a/sphinx/builders/texinfo.py
+++ b/sphinx/builders/texinfo.py
@@ -21,7 +21,7 @@ from sphinx import addnodes
from sphinx.builders import Builder
from sphinx.environment import NoUri
from sphinx.environment.adapters.asset import ImageAdapter
-from sphinx.locale import _
+from sphinx.locale import _, __
from sphinx.util import logging
from sphinx.util import status_iterator
from sphinx.util.console import bold, darkgreen # type: ignore
@@ -98,11 +98,11 @@ class TexinfoBuilder(Builder):
"""
name = 'texinfo'
format = 'texinfo'
- epilog = 'The Texinfo files are in %(outdir)s.'
+ epilog = __('The Texinfo files are in %(outdir)s.')
if os.name == 'posix':
- epilog += ("\nRun 'make' in that directory to run these through "
- "makeinfo\n"
- "(use 'make info' here to do that automatically).")
+ epilog += __("\nRun 'make' in that directory to run these through "
+ "makeinfo\n"
+ "(use 'make info' here to do that automatically).")
supported_image_types = ['image/png', 'image/jpeg',
'image/gif']
@@ -133,16 +133,16 @@ class TexinfoBuilder(Builder):
# type: () -> None
preliminary_document_data = [list(x) for x in self.config.texinfo_documents]
if not preliminary_document_data:
- logger.warning('no "texinfo_documents" config value found; no documents '
- 'will be written')
+ logger.warning(__('no "texinfo_documents" config value found; no documents '
+ 'will be written'))
return
# assign subdirs to titles
self.titles = [] # type: List[Tuple[unicode, unicode]]
for entry in preliminary_document_data:
docname = entry[0]
if docname not in self.env.all_docs:
- logger.warning('"texinfo_documents" config value references unknown '
- 'document %s', docname)
+ logger.warning(__('"texinfo_documents" config value references unknown '
+ 'document %s'), docname)
continue
self.document_data.append(entry) # type: ignore
if docname.endswith(SEP + 'index'):
@@ -164,11 +164,11 @@ class TexinfoBuilder(Builder):
destination = FileOutput(
destination_path=path.join(self.outdir, targetname),
encoding='utf-8')
- logger.info("processing " + targetname + "... ", nonl=1)
+ logger.info(__("processing %s..."), targetname, nonl=1)
doctree = self.assemble_doctree(
docname, toctree_only,
appendices=(self.config.texinfo_appendices or []))
- logger.info("writing... ", nonl=1)
+ logger.info(__("writing... "), nonl=1)
self.post_process_images(doctree)
docwriter = TexinfoWriter(self)
settings = OptionParser(
@@ -185,7 +185,7 @@ class TexinfoBuilder(Builder):
settings.docname = docname
doctree.settings = settings
docwriter.write(doctree, destination)
- logger.info("done")
+ logger.info(__("done"))
def assemble_doctree(self, indexfile, toctree_only, appendices):
# type: (unicode, bool, List[unicode]) -> nodes.Node
@@ -212,7 +212,7 @@ class TexinfoBuilder(Builder):
appendix['docname'] = docname
largetree.append(appendix)
logger.info('')
- logger.info("resolving references...")
+ logger.info(__("resolving references..."))
self.env.resolve_references(largetree, indexfile, self)
# TODO: add support for external :ref:s
for pendingnode in largetree.traverse(addnodes.pending_xref):
@@ -234,7 +234,7 @@ class TexinfoBuilder(Builder):
# type: () -> None
self.copy_image_files()
- logger.info(bold('copying Texinfo support files... '), nonl=True)
+ logger.info(bold(__('copying Texinfo support files... ')), nonl=True)
# copy Makefile
fn = path.join(self.outdir, 'Makefile')
logger.info(fn, nonl=1)
@@ -242,14 +242,14 @@ class TexinfoBuilder(Builder):
with open(fn, 'w') as mkfile:
mkfile.write(TEXINFO_MAKEFILE)
except (IOError, OSError) as err:
- logger.warning("error writing file %s: %s", fn, err)
- logger.info(' done')
+ logger.warning(__("error writing file %s: %s"), fn, err)
+ logger.info(__(' done'))
def copy_image_files(self):
# type: () -> None
if self.images:
stringify_func = ImageAdapter(self.app.env).get_original_image_uri
- for src in status_iterator(self.images, 'copying images... ', "brown",
+ for src in status_iterator(self.images, __('copying images... '), "brown",
len(self.images), self.app.verbosity,
stringify_func=stringify_func):
dest = self.images[src]
@@ -257,7 +257,7 @@ class TexinfoBuilder(Builder):
copy_asset_file(path.join(self.srcdir, src),
path.join(self.outdir, dest))
except Exception as err:
- logger.warning('cannot copy image file %r: %s',
+ logger.warning(__('cannot copy image file %r: %s'),
path.join(self.srcdir, src), err)
diff --git a/sphinx/builders/text.py b/sphinx/builders/text.py
index be33c0f9e..0be9f3795 100644
--- a/sphinx/builders/text.py
+++ b/sphinx/builders/text.py
@@ -16,6 +16,7 @@ from typing import TYPE_CHECKING
from docutils.io import StringOutput
from sphinx.builders import Builder
+from sphinx.locale import __
from sphinx.util import logging
from sphinx.util.osutil import ensuredir, os_path
from sphinx.writers.text import TextWriter, TextTranslator
@@ -31,7 +32,7 @@ logger = logging.getLogger(__name__)
class TextBuilder(Builder):
name = 'text'
format = 'text'
- epilog = 'The text files are in %(outdir)s.'
+ epilog = __('The text files are in %(outdir)s.')
out_suffix = '.txt'
allow_parallel = True
@@ -84,7 +85,7 @@ class TextBuilder(Builder):
with codecs.open(outfilename, 'w', 'utf-8') as f: # type: ignore
f.write(self.writer.output)
except (IOError, OSError) as err:
- logger.warning("error writing file %s: %s", outfilename, err)
+ logger.warning(__("error writing file %s: %s"), outfilename, err)
def finish(self):
# type: () -> None
diff --git a/sphinx/builders/xml.py b/sphinx/builders/xml.py
index 47a9f47d5..933e86374 100644
--- a/sphinx/builders/xml.py
+++ b/sphinx/builders/xml.py
@@ -18,6 +18,7 @@ from docutils.io import StringOutput
from docutils.writers.docutils_xml import XMLTranslator
from sphinx.builders import Builder
+from sphinx.locale import __
from sphinx.util import logging
from sphinx.util.osutil import ensuredir, os_path
from sphinx.writers.xml import XMLWriter, PseudoXMLWriter
@@ -35,7 +36,7 @@ class XMLBuilder(Builder):
"""
name = 'xml'
format = 'xml'
- epilog = 'The XML files are in %(outdir)s.'
+ epilog = __('The XML files are in %(outdir)s.')
out_suffix = '.xml'
allow_parallel = True
@@ -97,7 +98,7 @@ class XMLBuilder(Builder):
with codecs.open(outfilename, 'w', 'utf-8') as f: # type: ignore
f.write(self.writer.output)
except (IOError, OSError) as err:
- logger.warning("error writing file %s: %s", outfilename, err)
+ logger.warning(__("error writing file %s: %s"), outfilename, err)
def finish(self):
# type: () -> None
@@ -110,7 +111,7 @@ class PseudoXMLBuilder(XMLBuilder):
"""
name = 'pseudoxml'
format = 'pseudoxml'
- epilog = 'The pseudo-XML files are in %(outdir)s.'
+ epilog = __('The pseudo-XML files are in %(outdir)s.')
out_suffix = '.pseudoxml'
diff --git a/sphinx/config.py b/sphinx/config.py
index 5c7e2bb73..46487619b 100644
--- a/sphinx/config.py
+++ b/sphinx/config.py
@@ -34,18 +34,18 @@ logger = logging.getLogger(__name__)
nonascii_re = re.compile(br'[\x80-\xff]')
copyright_year_re = re.compile(r'^((\d{4}-)?)(\d{4})(?=[ ,])')
-CONFIG_SYNTAX_ERROR = "There is a syntax error in your configuration file: %s"
+CONFIG_SYNTAX_ERROR = __("There is a syntax error in your configuration file: %s")
if PY3:
- CONFIG_SYNTAX_ERROR += "\nDid you change the syntax from 2.x to 3.x?"
-CONFIG_ERROR = "There is a programable error in your configuration file:\n\n%s"
-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_PERMITTED_TYPE_WARNING = "The config value `{name}' has type `{current.__name__}', " \
- "expected to {permitted}."
-CONFIG_TYPE_WARNING = "The config value `{name}' has type `{current.__name__}', " \
- "defaults to `{default.__name__}'."
+ CONFIG_SYNTAX_ERROR += __("\nDid you change the syntax from 2.x to 3.x?")
+CONFIG_ERROR = __("There is a programable error in your configuration file:\n\n%s")
+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_PERMITTED_TYPE_WARNING = __("The config value `{name}' has type `{current.__name__}', "
+ "expected to {permitted}.")
+CONFIG_TYPE_WARNING = __("The config value `{name}' has type `{current.__name__}', "
+ "defaults to `{default.__name__}'.")
if PY3:
unicode = str # special alias for static typing...
@@ -251,9 +251,9 @@ class Config(object):
# since that can result in UnicodeErrors all over the place
for name, value in iteritems(self._raw_config):
if isinstance(value, binary_type) and nonascii_re.search(value):
- logger.warning('the config value %r is set to a string with non-ASCII '
- 'characters; this can lead to Unicode errors occurring. '
- 'Please use Unicode strings, e.g. %r.', name, u'Content')
+ logger.warning(__('the config value %r is set to a string with non-ASCII '
+ 'characters; this can lead to Unicode errors occurring. '
+ 'Please use Unicode strings, e.g. %r.'), name, u'Content')
def convert_overrides(self, name, value):
# type: (unicode, Any) -> Any
diff --git a/sphinx/directives/code.py b/sphinx/directives/code.py
index 51abc252b..17e77327d 100644
--- a/sphinx/directives/code.py
+++ b/sphinx/directives/code.py
@@ -126,7 +126,7 @@ class CodeBlock(Directive):
nlines = len(self.content)
hl_lines = parselinenos(linespec, nlines)
if any(i >= nlines for i in hl_lines):
- logger.warning('line number spec is out of range(1-%d): %r' %
+ logger.warning(__('line number spec is out of range(1-%d): %r') %
(nlines, self.options['emphasize-lines']),
location=location)
@@ -268,7 +268,7 @@ class LiteralIncludeReader(object):
if linespec:
linelist = parselinenos(linespec, len(lines))
if any(i >= len(lines) for i in linelist):
- logger.warning('line number spec is out of range(1-%d): %r' %
+ logger.warning(__('line number spec is out of range(1-%d): %r') %
(len(lines), linespec), location=location)
if 'lineno-match' in self.options:
@@ -440,7 +440,7 @@ class LiteralInclude(Directive):
if 'emphasize-lines' in self.options:
hl_lines = parselinenos(self.options['emphasize-lines'], lines)
if any(i >= lines for i in hl_lines):
- logger.warning('line number spec is out of range(1-%d): %r' %
+ logger.warning(__('line number spec is out of range(1-%d): %r') %
(lines, self.options['emphasize-lines']),
location=location)
extra_args['hl_lines'] = [x + 1 for x in hl_lines if x < lines]
diff --git a/sphinx/domains/cpp.py b/sphinx/domains/cpp.py
index dfad97a6c..cbf3bb39c 100644
--- a/sphinx/domains/cpp.py
+++ b/sphinx/domains/cpp.py
@@ -21,7 +21,7 @@ from sphinx import addnodes
from sphinx.directives import ObjectDescription
from sphinx.domains import Domain, ObjType
from sphinx.environment import NoUri
-from sphinx.locale import _
+from sphinx.locale import _, __
from sphinx.roles import XRefRole
from sphinx.util import logging
from sphinx.util.docfields import Field, GroupedField
@@ -3656,8 +3656,8 @@ class Symbol(object):
ourChild._fill_empty(otherChild.declaration, otherChild.docname)
elif ourChild.docname != otherChild.docname:
name = text_type(ourChild.declaration)
- msg = "Duplicate declaration, also defined in '%s'.\n"
- msg += "Declaration is '%s'."
+ msg = __("Duplicate declaration, also defined in '%s'.\n"
+ "Declaration is '%s'.")
msg = msg % (ourChild.docname, name)
logger.warning(msg, location=otherChild.docname)
else:
@@ -6053,8 +6053,8 @@ class CPPDomain(Domain):
for name, docname in otherdata['names'].items():
if docname in docnames:
if name in ourNames:
- msg = "Duplicate declaration, also defined in '%s'.\n"
- msg += "Name of declaration is '%s'."
+ msg = __("Duplicate declaration, also defined in '%s'.\n"
+ "Name of declaration is '%s'.")
msg = msg % (ourNames[name], name)
logger.warning(msg, docname)
else:
diff --git a/sphinx/domains/python.py b/sphinx/domains/python.py
index 95c10d4fd..d63e5c747 100644
--- a/sphinx/domains/python.py
+++ b/sphinx/domains/python.py
@@ -20,7 +20,7 @@ from sphinx import addnodes, locale
from sphinx.deprecation import DeprecatedDict, RemovedInSphinx30Warning
from sphinx.directives import ObjectDescription
from sphinx.domains import Domain, ObjType, Index
-from sphinx.locale import _
+from sphinx.locale import _, __
from sphinx.roles import XRefRole
from sphinx.util import logging
from sphinx.util.docfields import Field, GroupedField, TypedField
@@ -859,7 +859,7 @@ class PythonDomain(Domain):
if not matches:
return None
elif len(matches) > 1:
- logger.warning('more than one target found for cross-reference %r: %s',
+ logger.warning(__('more than one target found for cross-reference %r: %s'),
target, ', '.join(match[0] for match in matches),
type='ref', subtype='python', location=node)
name, obj = matches[0]
diff --git a/sphinx/domains/std.py b/sphinx/domains/std.py
index 54d0e5de5..8a334f7e5 100644
--- a/sphinx/domains/std.py
+++ b/sphinx/domains/std.py
@@ -22,7 +22,7 @@ from six import iteritems
from sphinx import addnodes
from sphinx.directives import ObjectDescription
from sphinx.domains import Domain, ObjType
-from sphinx.locale import _
+from sphinx.locale import _, __
from sphinx.roles import XRefRole
from sphinx.util import ws_re, logging, docname_join
from sphinx.util.nodes import clean_astext, make_refnode
@@ -158,9 +158,9 @@ class Cmdoption(ObjectDescription):
potential_option = potential_option.strip()
m = option_desc_re.match(potential_option) # type: ignore
if not m:
- logger.warning('Malformed option description %r, should '
- 'look like "opt", "-opt args", "--opt args", '
- '"/opt args" or "+opt args"', potential_option,
+ logger.warning(__('Malformed option description %r, should '
+ 'look like "opt", "-opt args", "--opt args", '
+ '"/opt args" or "+opt args"'), potential_option,
location=(self.env.docname, self.lineno))
continue
optname, args = m.groups()
@@ -591,7 +591,7 @@ class StandardDomain(Domain):
label = node[0].astext()
if label in self.data['citations']:
path = env.doc2path(self.data['citations'][label][0])
- logger.warning('duplicate citation %s, other instance in %s', label, path,
+ logger.warning(__('duplicate citation %s, other instance in %s'), label, path,
location=node, type='ref', subtype='citation')
self.data['citations'][label] = (docname, node['ids'][0], node.line)
@@ -623,8 +623,8 @@ class StandardDomain(Domain):
# link and object descriptions
continue
if name in labels:
- logger.warning('duplicate label %s, ' % name + 'other instance '
- 'in ' + env.doc2path(labels[name][0]),
+ logger.warning(__('duplicate label %s, other instance in %s'),
+ name, env.doc2path(labels[name][0]),
location=node)
anonlabels[name] = docname, labelid
if node.tagname in ('section', 'rubric'):
@@ -648,7 +648,7 @@ class StandardDomain(Domain):
# type: () -> None
for name, (docname, labelid, lineno) in iteritems(self.data['citations']):
if name not in self.data['citation_refs']:
- logger.warning('Citation [%s] is not referenced.', name,
+ logger.warning(__('Citation [%s] is not referenced.'), name,
type='ref', subtype='citation',
location=(docname, lineno))
@@ -726,7 +726,7 @@ class StandardDomain(Domain):
return None
if env.config.numfig is False:
- logger.warning('numfig is disabled. :numref: is ignored.', location=node)
+ logger.warning(__('numfig is disabled. :numref: is ignored.'), location=node)
return contnode
target_node = env.get_doctree(docname).ids.get(labelid)
@@ -739,7 +739,7 @@ class StandardDomain(Domain):
if fignumber is None:
return contnode
except ValueError:
- logger.warning("no number is assigned for %s: %s", figtype, labelid,
+ logger.warning(__("no number is assigned for %s: %s"), figtype, labelid,
location=node)
return contnode
@@ -750,7 +750,7 @@ class StandardDomain(Domain):
title = env.config.numfig_format.get(figtype, '')
if figname is None and '{name}' in title:
- logger.warning('the link has no caption: %s', title, location=node)
+ logger.warning(__('the link has no caption: %s'), title, location=node)
return contnode
else:
fignum = '.'.join(map(str, fignumber))
@@ -764,10 +764,10 @@ class StandardDomain(Domain):
# old style format (cf. "Fig.%s")
newtitle = title % fignum
except KeyError as exc:
- logger.warning('invalid numfig_format: %s (%r)', title, exc, location=node)
+ logger.warning(__('invalid numfig_format: %s (%r)'), title, exc, location=node)
return contnode
except TypeError:
- logger.warning('invalid numfig_format: %s', title, location=node)
+ logger.warning(__('invalid numfig_format: %s'), title, location=node)
return contnode
return self.build_reference_node(fromdocname, builder,
diff --git a/sphinx/environment/__init__.py b/sphinx/environment/__init__.py
index 7ef7dec53..136953616 100644
--- a/sphinx/environment/__init__.py
+++ b/sphinx/environment/__init__.py
@@ -31,6 +31,7 @@ from sphinx.environment.adapters.indexentries import IndexEntries
from sphinx.environment.adapters.toctree import TocTree
from sphinx.errors import SphinxError, ExtensionError
from sphinx.io import read_doc
+from sphinx.locale import __
from sphinx.transforms import SphinxTransformer
from sphinx.util import get_matching_docs, FilenameUniqDict
from sphinx.util import logging, rst
@@ -277,9 +278,9 @@ class BuildEnvironment(object):
raise ValueError('invalid versioning method: %r' % method)
condition = versioning_conditions[method]
if self.versioning_condition not in (None, condition):
- raise SphinxError('This environment is incompatible with the '
- 'selected builder, please choose another '
- 'doctree directory.')
+ raise SphinxError(__('This environment is incompatible with the '
+ 'selected builder, please choose another '
+ 'doctree directory.'))
self.versioning_condition = condition
self.versioning_compare = compare
@@ -305,9 +306,9 @@ class BuildEnvironment(object):
If needed, this method returns the reason for refresh.
"""
if self.version != app.registry.get_envversion(app):
- return True, 'build environment version not current'
+ return True, __('build environment version not current')
elif self.srcdir != app.srcdir:
- return True, 'source directory has changed'
+ return True, __('source directory has changed')
else:
return False, None
@@ -426,7 +427,7 @@ class BuildEnvironment(object):
if os.access(self.doc2path(docname), os.R_OK):
self.found_docs.add(docname)
else:
- logger.warning("document not readable. Ignored.", location=docname)
+ logger.warning(__("document not readable. Ignored."), location=docname)
# Current implementation is applying translated messages in the reading
# phase.Therefore, in order to apply the updated message catalog, it is
@@ -511,19 +512,19 @@ class BuildEnvironment(object):
"""Update configurations by new one."""
changed_reason = ''
if self.config is None:
- changed_reason = 'new config'
+ changed_reason = __('new config')
else:
# check if a config value was changed that affects how
# doctrees are read
for confval in config.filter('env'):
if self.config[confval.name] != confval.value:
- changed_reason = 'config changed'
+ changed_reason = __('config changed')
break
# this value is not covered by the above loop because it is handled
# specially by the config class
if self.config.extensions != config.extensions:
- changed_reason = 'extensions changed'
+ changed_reason = __('extensions changed')
# the source and doctree directories may have been relocated
self.srcdir = srcdir
@@ -686,7 +687,7 @@ class BuildEnvironment(object):
try:
return self.domains[domainname]
except KeyError:
- raise ExtensionError('Domain %r is not registered' % domainname)
+ raise ExtensionError(__('Domain %r is not registered') % domainname)
# --------- RESOLVING REFERENCES AND TOCTREES ------------------------------
@@ -796,7 +797,7 @@ class BuildEnvironment(object):
def traverse_toctree(parent, docname):
# type: (unicode, unicode) -> Iterator[Tuple[unicode, unicode]]
if parent == docname:
- logger.warning('self referenced toctree found. Ignored.', location=docname)
+ logger.warning(__('self referenced toctree found. Ignored.'), location=docname)
return
# traverse toctree by pre-order
@@ -836,7 +837,7 @@ class BuildEnvironment(object):
continue
if 'orphan' in self.metadata[docname]:
continue
- logger.warning('document isn\'t included in any toctree',
+ logger.warning(__('document isn\'t included in any toctree'),
location=docname)
# call check-consistency for all extensions
diff --git a/sphinx/environment/adapters/indexentries.py b/sphinx/environment/adapters/indexentries.py
index db33a76a7..3e1f47c6e 100644
--- a/sphinx/environment/adapters/indexentries.py
+++ b/sphinx/environment/adapters/indexentries.py
@@ -16,7 +16,7 @@ from typing import TYPE_CHECKING
from six import text_type, iteritems
-from sphinx.locale import _
+from sphinx.locale import _, __
from sphinx.util import split_into, logging
if TYPE_CHECKING:
@@ -89,7 +89,7 @@ class IndexEntries(object):
add_entry(first, _('see also %s') % second, None,
link=False, key=index_key)
else:
- logger.warning('unknown index entry type %r', type, location=fn)
+ logger.warning(__('unknown index entry type %r'), type, location=fn)
except ValueError as err:
logger.warning(str(err), location=fn)
diff --git a/sphinx/environment/adapters/toctree.py b/sphinx/environment/adapters/toctree.py
index aeba0cc08..920c4b502 100644
--- a/sphinx/environment/adapters/toctree.py
+++ b/sphinx/environment/adapters/toctree.py
@@ -15,6 +15,7 @@ from docutils import nodes
from six import iteritems
from sphinx import addnodes
+from sphinx.locale import __
from sphinx.util import url_re, logging
from sphinx.util.nodes import clean_astext, process_only_nodes
@@ -148,8 +149,8 @@ class TocTree(object):
toc = nodes.bullet_list('', item)
else:
if ref in parents:
- logger.warning('circular toctree references '
- 'detected, ignoring: %s <- %s',
+ logger.warning(__('circular toctree references '
+ 'detected, ignoring: %s <- %s'),
ref, ' <- '.join(parents),
location=ref)
continue
@@ -167,12 +168,12 @@ class TocTree(object):
refnode.children = [nodes.Text(title)]
if not toc.children:
# empty toc means: no titles will show up in the toctree
- logger.warning('toctree contains reference to document %r that '
- 'doesn\'t have a title: no link will be generated',
+ logger.warning(__('toctree contains reference to document %r that '
+ 'doesn\'t have a title: no link will be generated'),
ref, location=toctreenode)
except KeyError:
# this is raised if the included file does not exist
- logger.warning('toctree contains reference to nonexisting document %r',
+ logger.warning(__('toctree contains reference to nonexisting document %r'),
ref, location=toctreenode)
else:
# if titles_only is given, only keep the main title and
diff --git a/sphinx/environment/collectors/asset.py b/sphinx/environment/collectors/asset.py
index d33d8f665..06af528c1 100644
--- a/sphinx/environment/collectors/asset.py
+++ b/sphinx/environment/collectors/asset.py
@@ -20,6 +20,7 @@ from six import iteritems, itervalues
from sphinx import addnodes
from sphinx.environment.collectors import EnvironmentCollector
+from sphinx.locale import __
from sphinx.util import logging
from sphinx.util.i18n import get_image_filename_for_language, search_image_for_language
from sphinx.util.images import guess_mimetype
@@ -89,7 +90,7 @@ class ImageCollector(EnvironmentCollector):
for imgpath in itervalues(candidates):
app.env.dependencies[docname].add(imgpath)
if not os.access(path.join(app.srcdir, imgpath), os.R_OK):
- logger.warning('image file not readable: %s' % imgpath,
+ logger.warning(__('image file not readable: %s') % imgpath,
location=node, type='image', subtype='not_readable')
continue
app.env.images.add_file(docname, imgpath)
@@ -105,7 +106,7 @@ class ImageCollector(EnvironmentCollector):
if mimetype not in candidates:
globbed.setdefault(mimetype, []).append(new_imgpath)
except (OSError, IOError) as err:
- logger.warning('image file %s not readable: %s' % (filename, err),
+ logger.warning(__('image file %s not readable: %s') % (filename, err),
location=node, type='image', subtype='not_readable')
for key, files in iteritems(globbed):
candidates[key] = sorted(files, key=len)[0] # select by similarity
@@ -130,7 +131,7 @@ class DownloadFileCollector(EnvironmentCollector):
rel_filename, filename = app.env.relfn2path(targetname, app.env.docname)
app.env.dependencies[app.env.docname].add(rel_filename)
if not os.access(filename, os.R_OK):
- logger.warning('download file not readable: %s' % filename,
+ logger.warning(__('download file not readable: %s') % filename,
location=node, type='download', subtype='not_readable')
continue
node['filename'] = app.env.dlfiles.add_file(app.env.docname, filename)
diff --git a/sphinx/environment/collectors/toctree.py b/sphinx/environment/collectors/toctree.py
index 27fca5540..5ff03da39 100644
--- a/sphinx/environment/collectors/toctree.py
+++ b/sphinx/environment/collectors/toctree.py
@@ -17,6 +17,7 @@ from six import iteritems
from sphinx import addnodes
from sphinx.environment.adapters.toctree import TocTree
from sphinx.environment.collectors import EnvironmentCollector
+from sphinx.locale import __
from sphinx.transforms import SphinxContentsFilter
from sphinx.util import url_re, logging
@@ -189,8 +190,8 @@ class TocTreeCollector(EnvironmentCollector):
# don't mess with those
continue
elif ref in assigned:
- logger.warning('%s is already assigned section numbers '
- '(nested numbered toctree?)', ref,
+ logger.warning(__('%s is already assigned section numbers '
+ '(nested numbered toctree?)'), ref,
location=toctreenode, type='toc', subtype='secnum')
elif ref in env.tocs:
secnums = env.toc_secnumbers[ref] = {}
diff --git a/sphinx/ext/autodoc/__init__.py b/sphinx/ext/autodoc/__init__.py
index a37a76167..b5fef0df6 100644
--- a/sphinx/ext/autodoc/__init__.py
+++ b/sphinx/ext/autodoc/__init__.py
@@ -26,7 +26,7 @@ from sphinx.deprecation import RemovedInSphinx20Warning
from sphinx.ext.autodoc.importer import mock, import_object, get_object_members
from sphinx.ext.autodoc.importer import _MockImporter # to keep compatibility # NOQA
from sphinx.ext.autodoc.inspector import format_annotation, formatargspec # to keep compatibility # NOQA
-from sphinx.locale import _
+from sphinx.locale import _, __
from sphinx.pycode import ModuleAnalyzer, PycodeError
from sphinx.util import logging
from sphinx.util import rpartition, force_decode
@@ -340,7 +340,7 @@ class Documenter(object):
explicit_modname, path, base, args, retann = \
py_ext_sig_re.match(self.name).groups() # type: ignore
except AttributeError:
- logger.warning('invalid signature for auto%s (%r)' % (self.objtype, self.name))
+ logger.warning(__('invalid signature for auto%s (%r)') % (self.objtype, self.name))
return False
# support explicit module and class name separation via ::
@@ -437,7 +437,7 @@ class Documenter(object):
try:
args = self.format_args()
except Exception as err:
- logger.warning('error while formatting arguments for %s: %s' %
+ logger.warning(__('error while formatting arguments for %s: %s') %
(self.fullname, err))
args = None
@@ -560,7 +560,7 @@ class Documenter(object):
if name in members:
selected.append((name, members[name].value))
else:
- logger.warning('missing attribute %s in object %s' %
+ logger.warning(__('missing attribute %s in object %s') %
(name, self.fullname))
return False, sorted(selected)
elif self.options.inherited_members:
@@ -731,9 +731,9 @@ class Documenter(object):
if not self.parse_name():
# need a module to import
logger.warning(
- 'don\'t know which module to import for autodocumenting '
- '%r (try placing a "module" or "currentmodule" directive '
- 'in the document, or giving an explicit module name)' %
+ __('don\'t know which module to import for autodocumenting '
+ '%r (try placing a "module" or "currentmodule" directive '
+ 'in the document, or giving an explicit module name)') %
self.name)
return
@@ -820,15 +820,15 @@ class ModuleDocumenter(Documenter):
def resolve_name(self, modname, parents, path, base):
# type: (str, Any, str, Any) -> Tuple[str, List[unicode]]
if modname is not None:
- logger.warning('"::" in automodule name doesn\'t make sense')
+ logger.warning(__('"::" in automodule name doesn\'t make sense'))
return (path or '') + base, []
def parse_name(self):
# type: () -> bool
ret = Documenter.parse_name(self)
if self.args or self.retann:
- logger.warning('signature arguments or return annotation '
- 'given for automodule %s' % self.fullname)
+ logger.warning(__('signature arguments or return annotation '
+ 'given for automodule %s') % self.fullname)
return ret
def add_directive_header(self, sig):
@@ -861,8 +861,8 @@ class ModuleDocumenter(Documenter):
if not isinstance(memberlist, (list, tuple)) or not \
all(isinstance(entry, string_types) for entry in memberlist):
logger.warning(
- '__all__ should be a list of strings, not %r '
- '(in module %s) -- ignoring __all__' %
+ __('__all__ should be a list of strings, not %r '
+ '(in module %s) -- ignoring __all__') %
(memberlist, self.fullname))
# fall back to all members
return True, safe_getmembers(self.object)
@@ -874,8 +874,8 @@ class ModuleDocumenter(Documenter):
ret.append((mname, safe_getattr(self.object, mname)))
except AttributeError:
logger.warning(
- 'missing attribute mentioned in :members: or __all__: '
- 'module %s, attribute %s' %
+ __('missing attribute mentioned in :members: or __all__: '
+ 'module %s, attribute %s') %
(safe_getattr(self.object, '__name__', '???'), mname))
return False, ret
diff --git a/sphinx/ext/autosectionlabel.py b/sphinx/ext/autosectionlabel.py
index 80ca92711..ad039483f 100644
--- a/sphinx/ext/autosectionlabel.py
+++ b/sphinx/ext/autosectionlabel.py
@@ -13,6 +13,7 @@ from typing import TYPE_CHECKING
from docutils import nodes
+from sphinx.locale import __
from sphinx.util import logging
from sphinx.util.nodes import clean_astext
@@ -44,8 +45,8 @@ def register_sections_as_label(app, document):
sectname = clean_astext(node[0])
if name in labels:
- logger.warning('duplicate label %s, ' % name + 'other instance '
- 'in ' + app.env.doc2path(labels[name][0]),
+ logger.warning(__('duplicate label %s, other instance in %s'),
+ name, app.env.doc2path(labels[name][0]),
location=node)
anonlabels[name] = docname, labelid
diff --git a/sphinx/ext/autosummary/__init__.py b/sphinx/ext/autosummary/__init__.py
index c7f38377d..a942c0aac 100644
--- a/sphinx/ext/autosummary/__init__.py
+++ b/sphinx/ext/autosummary/__init__.py
@@ -76,6 +76,7 @@ from sphinx.environment.adapters.toctree import TocTree
from sphinx.ext.autodoc import get_documenters
from sphinx.ext.autodoc.directive import DocumenterBridge, Options
from sphinx.ext.autodoc.importer import import_module
+from sphinx.locale import __
from sphinx.pycode import ModuleAnalyzer, PycodeError
from sphinx.util import import_object, rst, logging
from sphinx.util.docutils import NullReporter, new_document
@@ -660,8 +661,8 @@ def process_generate_options(app):
suffix = get_rst_suffix(app)
if suffix is None:
- logger.warning('autosummary generats .rst files internally. '
- 'But your source_suffix does not contain .rst. Skipped.')
+ logger.warning(__('autosummary generats .rst files internally. '
+ 'But your source_suffix does not contain .rst. Skipped.'))
return
generate_autosummary_docs(genfiles, builder=app.builder,
diff --git a/sphinx/ext/coverage.py b/sphinx/ext/coverage.py
index 73bd8d68e..f473a607e 100644
--- a/sphinx/ext/coverage.py
+++ b/sphinx/ext/coverage.py
@@ -21,6 +21,7 @@ from six.moves import cPickle as pickle
import sphinx
from sphinx.builders import Builder
+from sphinx.locale import __
from sphinx.util import logging
from sphinx.util.inspect import safe_getattr
@@ -45,7 +46,7 @@ def compile_regex_list(name, exps):
try:
lst.append(re.compile(exp))
except Exception:
- logger.warning('invalid regex %r in %s', exp, name)
+ logger.warning(__('invalid regex %r in %s'), exp, name)
return lst
@@ -54,8 +55,8 @@ class CoverageBuilder(Builder):
Evaluates coverage of code in the documentation.
"""
name = 'coverage'
- epilog = ('Testing of coverage in the sources finished, look at the '
- 'results in %(outdir)s/python.txt.')
+ epilog = __('Testing of coverage in the sources finished, look at the '
+ 'results in %(outdir)s/python.txt.')
def init(self):
# type: () -> None
@@ -69,7 +70,7 @@ class CoverageBuilder(Builder):
try:
self.c_regexes.append((name, re.compile(exp)))
except Exception:
- logger.warning('invalid regex %r in coverage_c_regexes', exp)
+ logger.warning(__('invalid regex %r in coverage_c_regexes'), exp)
self.c_ignorexps = {} # type: Dict[unicode, List[Pattern]]
for (name, exps) in iteritems(self.config.coverage_ignore_c_items):
@@ -151,7 +152,7 @@ class CoverageBuilder(Builder):
try:
mod = __import__(mod_name, fromlist=['foo'])
except ImportError as err:
- logger.warning('module %s could not be imported: %s', mod_name, err)
+ logger.warning(__('module %s could not be imported: %s'), mod_name, err)
self.py_undoc[mod_name] = {'error': err}
continue
diff --git a/sphinx/ext/doctest.py b/sphinx/ext/doctest.py
index b5123204d..3b57c3469 100644
--- a/sphinx/ext/doctest.py
+++ b/sphinx/ext/doctest.py
@@ -27,7 +27,7 @@ from six import itervalues, StringIO, binary_type, text_type, PY2
import sphinx
from sphinx.builders import Builder
-from sphinx.locale import _
+from sphinx.locale import __
from sphinx.util import force_decode, logging
from sphinx.util.console import bold # type: ignore
from sphinx.util.nodes import set_source_info
@@ -129,12 +129,12 @@ class TestDirective(Directive):
prefix, option_name = option[0], option[1:]
if prefix not in '+-':
self.state.document.reporter.warning(
- _("missing '+' or '-' in '%s' option.") % option,
+ __("missing '+' or '-' in '%s' option.") % option,
line=self.lineno)
continue
if option_name not in doctest.OPTIONFLAGS_BY_NAME:
self.state.document.reporter.warning(
- _("'%s' is not a valid option.") % option_name,
+ __("'%s' is not a valid option.") % option_name,
line=self.lineno)
continue
flag = doctest.OPTIONFLAGS_BY_NAME[option[1:]]
@@ -148,7 +148,7 @@ class TestDirective(Directive):
node['options'][flag] = True # Skip the test
except InvalidSpecifier:
self.state.document.reporter.warning(
- _("'%s' is not a valid pyversion option") % spec,
+ __("'%s' is not a valid pyversion option") % spec,
line=self.lineno)
return [node]
@@ -214,7 +214,7 @@ class TestGroup(object):
if self.tests and len(self.tests[-1]) == 2:
self.tests[-1][1] = code
else:
- raise RuntimeError('invalid TestCode type')
+ raise RuntimeError(__('invalid TestCode type'))
def __repr__(self): # type: ignore
# type: () -> unicode
@@ -275,8 +275,8 @@ class DocTestBuilder(Builder):
Runs test snippets in the documentation.
"""
name = 'doctest'
- epilog = ('Testing of doctests in the sources finished, look at the '
- 'results in %(outdir)s/output.txt.')
+ epilog = __('Testing of doctests in the sources finished, look at the '
+ 'results in %(outdir)s/output.txt.')
def init(self):
# type: () -> None
@@ -427,7 +427,7 @@ Doctest summary
filename = self.get_filename_for_node(node, docname)
line_number = self.get_line_number(node)
if not source:
- logger.warning('no code/output in %s block at %s:%s',
+ logger.warning(__('no code/output in %s block at %s:%s'),
node.get('testnodetype', 'doctest'),
filename, line_number)
code = TestCode(source, type=node.get('testnodetype', 'doctest'),
@@ -518,7 +518,7 @@ Doctest summary
doctest_encode(code[0].code, self.env.config.source_encoding), {}, # type: ignore # NOQA
group.name, code[0].filename, code[0].lineno)
except Exception:
- logger.warning('ignoring invalid doctest code: %r', code[0].code,
+ logger.warning(__('ignoring invalid doctest code: %r'), code[0].code,
location=(code[0].filename, code[0].lineno))
continue
if not test.examples:
diff --git a/sphinx/ext/graphviz.py b/sphinx/ext/graphviz.py
index a061ae885..3acb8e3f5 100644
--- a/sphinx/ext/graphviz.py
+++ b/sphinx/ext/graphviz.py
@@ -277,7 +277,7 @@ def render_dot_html(self, node, code, options, prefix='graphviz',
"'svg', but is %r") % format)
fname, outfn = render_dot(self, code, options, format, prefix)
except GraphvizError as exc:
- logger.warning('dot code %r: ' % code + str(exc))
+ logger.warning(__('dot code %r: ') % code + str(exc))
raise nodes.SkipNode
if fname is None:
@@ -321,7 +321,7 @@ def render_dot_latex(self, node, code, options, prefix='graphviz'):
try:
fname, outfn = render_dot(self, code, options, 'pdf', prefix)
except GraphvizError as exc:
- logger.warning('dot code %r: ' % code + str(exc))
+ logger.warning(__('dot code %r: ') % code + str(exc))
raise nodes.SkipNode
is_inline = self.is_inline(node)
@@ -359,7 +359,7 @@ def render_dot_texinfo(self, node, code, options, prefix='graphviz'):
try:
fname, outfn = render_dot(self, code, options, 'png', prefix)
except GraphvizError as exc:
- logger.warning('dot code %r: ' % code + str(exc))
+ logger.warning(__('dot code %r: ') % code + str(exc))
raise nodes.SkipNode
if fname is not None:
self.body.append('@image{%s,,,[graphviz],png}\n' % fname[:-4])
diff --git a/sphinx/ext/imgmath.py b/sphinx/ext/imgmath.py
index c35ac293a..463fdda88 100644
--- a/sphinx/ext/imgmath.py
+++ b/sphinx/ext/imgmath.py
@@ -26,7 +26,7 @@ import sphinx
from sphinx.errors import SphinxError, ExtensionError
from sphinx.ext.mathbase import get_node_equation_number
from sphinx.ext.mathbase import setup_math as mathbase_setup, wrap_displaymath
-from sphinx.locale import _
+from sphinx.locale import _, __
from sphinx.util import logging
from sphinx.util.osutil import ensuredir, ENOENT, cd
from sphinx.util.png import read_png_depth, write_png_depth
@@ -141,8 +141,8 @@ def compile_math(latex, builder):
except OSError as err:
if err.errno != ENOENT: # No such file or directory
raise
- logger.warning('LaTeX command %r cannot be run (needed for math '
- 'display), check the imgmath_latex setting',
+ logger.warning(__('LaTeX command %r cannot be run (needed for math '
+ 'display), check the imgmath_latex setting'),
builder.config.imgmath_latex)
raise InvokeError
@@ -161,8 +161,8 @@ def convert_dvi_to_image(command, name):
except OSError as err:
if err.errno != ENOENT: # No such file or directory
raise
- logger.warning('%s command %r cannot be run (needed for math '
- 'display), check the imgmath_%s setting',
+ logger.warning(__('%s command %r cannot be run (needed for math '
+ 'display), check the imgmath_%s setting'),
name, command[0], name)
raise InvokeError
@@ -300,7 +300,7 @@ def html_visit_math(self, node):
sm = nodes.system_message(msg, type='WARNING', level=2,
backrefs=[], source=node['latex'])
sm.walkabout(self)
- logger.warning('display latex %r: %s', node['latex'], msg)
+ logger.warning(__('display latex %r: %s'), node['latex'], msg)
raise nodes.SkipNode
if fname is None:
# something failed -- use text-only as a bad substitute
@@ -328,7 +328,7 @@ def html_visit_displaymath(self, node):
sm = nodes.system_message(msg, type='WARNING', level=2,
backrefs=[], source=node['latex'])
sm.walkabout(self)
- logger.warning('inline latex %r: %s', node['latex'], msg)
+ logger.warning(__('inline latex %r: %s'), node['latex'], msg)
raise nodes.SkipNode
self.body.append(self.starttag(node, 'div', CLASS='math'))
self.body.append('<p>')
diff --git a/sphinx/ext/intersphinx.py b/sphinx/ext/intersphinx.py
index d8362a48d..c9878e3ef 100644
--- a/sphinx/ext/intersphinx.py
+++ b/sphinx/ext/intersphinx.py
@@ -42,7 +42,7 @@ from six.moves.urllib.parse import urlsplit, urlunsplit
import sphinx
from sphinx.builders.html import INVENTORY_FILENAME
from sphinx.deprecation import RemovedInSphinx20Warning
-from sphinx.locale import _
+from sphinx.locale import _, __
from sphinx.util import requests, logging
from sphinx.util.inventory import InventoryFile
@@ -223,7 +223,7 @@ def load_mappings(app):
# new format
name, (uri, inv) = key, value
if not isinstance(name, string_types):
- logger.warning('intersphinx identifier %r is not string. Ignored', name)
+ logger.warning(__('intersphinx identifier %r is not string. Ignored'), name)
continue
else:
# old format, no name
@@ -265,8 +265,8 @@ def load_mappings(app):
for fail in failures:
logger.info(*fail)
else:
- logger.warning("failed to reach any of the inventories "
- "with the following issues:")
+ logger.warning(__("failed to reach any of the inventories "
+ "with the following issues:"))
for fail in failures:
logger.warning(*fail)
diff --git a/sphinx/ext/mathbase.py b/sphinx/ext/mathbase.py
index b742469ef..54c300d67 100644
--- a/sphinx/ext/mathbase.py
+++ b/sphinx/ext/mathbase.py
@@ -98,7 +98,7 @@ class MathDomain(Domain):
eqref_format = env.config.math_eqref_format or "({number})"
title = nodes.Text(eqref_format.format(number=number))
except KeyError as exc:
- logger.warning('Invalid math_eqref_format: %r', exc,
+ logger.warning(__('Invalid math_eqref_format: %r'), exc,
location=node)
title = nodes.Text("(%d)" % number)
title = nodes.Text("(%d)" % number)
@@ -309,7 +309,7 @@ def latex_visit_eqref(self, node):
ref = '\\ref{%s}' % label
self.body.append(eqref_format.format(number=ref))
except KeyError as exc:
- logger.warning('Invalid math_eqref_format: %r', exc,
+ logger.warning(__('Invalid math_eqref_format: %r'), exc,
location=node)
self.body.append('\\eqref{%s}' % label)
else:
diff --git a/sphinx/ext/todo.py b/sphinx/ext/todo.py
index c9a94b358..1f3bc71da 100644
--- a/sphinx/ext/todo.py
+++ b/sphinx/ext/todo.py
@@ -21,7 +21,7 @@ from docutils.parsers.rst.directives.admonitions import BaseAdmonition
import sphinx
from sphinx.environment import NoUri
-from sphinx.locale import _
+from sphinx.locale import _, __
from sphinx.util import logging
from sphinx.util.nodes import set_source_info
from sphinx.util.texescape import tex_escape_map
@@ -104,7 +104,7 @@ def process_todos(app, doctree):
})
if env.config.todo_emit_warnings:
- logger.warning("TODO entry found: %s", node[1].astext(),
+ logger.warning(__("TODO entry found: %s"), node[1].astext(),
location=node)
diff --git a/sphinx/highlighting.py b/sphinx/highlighting.py
index a14efd510..372ab7c43 100644
--- a/sphinx/highlighting.py
+++ b/sphinx/highlighting.py
@@ -23,6 +23,7 @@ from pygments.util import ClassNotFound
from six import text_type
from sphinx.ext import doctest
+from sphinx.locale import __
from sphinx.pygments_styles import SphinxStyle, NoneStyle
from sphinx.util import logging
from sphinx.util.pycompat import htmlescape
@@ -132,7 +133,7 @@ class PygmentsBridge(object):
try:
lexer = lexers[lang] = get_lexer_by_name(lang, **(opts or {}))
except ClassNotFound:
- logger.warning('Pygments lexer name %r is not known', lang,
+ logger.warning(__('Pygments lexer name %r is not known'), lang,
location=location)
lexer = lexers['none']
else:
@@ -153,8 +154,8 @@ class PygmentsBridge(object):
if lang == 'default':
pass # automatic highlighting failed.
else:
- logger.warning('Could not lex literal_block as "%s". '
- 'Highlighting skipped.', lang,
+ logger.warning(__('Could not lex literal_block as "%s". '
+ 'Highlighting skipped.'), lang,
type='misc', subtype='highlighting_failure',
location=location)
hlsource = highlight(source, lexers['none'], formatter)
diff --git a/sphinx/io.py b/sphinx/io.py
index f37220f8e..b7b70ef9b 100644
--- a/sphinx/io.py
+++ b/sphinx/io.py
@@ -20,6 +20,7 @@ from docutils.writers import UnfilteredWriter
from six import text_type, iteritems
from typing import Any, Union # NOQA
+from sphinx.locale import __
from sphinx.transforms import (
ApplySourceWorkaround, ExtraTranslatableNodes, CitationReferences,
DefaultSubstitutions, MoveModuleTargets, HandleCodeBlocks, SortIds,
@@ -199,7 +200,7 @@ class SphinxBaseFileInput(FileInput):
if lineend == -1:
lineend = len(error.object)
lineno = error.object.count(b'\n', 0, error.start) + 1
- logger.warning('undecodable source characters, replacing with "?": %r',
+ logger.warning(__('undecodable source characters, replacing with "?": %r'),
(error.object[linestart + 1:error.start] + b'>>>' +
error.object[error.start:error.end] + b'<<<' +
error.object[error.end:lineend]),
diff --git a/sphinx/theming.py b/sphinx/theming.py
index bfd7e68ae..5944a3751 100644
--- a/sphinx/theming.py
+++ b/sphinx/theming.py
@@ -133,7 +133,7 @@ class Theme(object):
for option, value in iteritems(overrides):
if option not in options:
- logger.warning('unsupported theme option %r given' % option)
+ logger.warning(__('unsupported theme option %r given') % option)
else:
options[option] = value
diff --git a/sphinx/transforms/__init__.py b/sphinx/transforms/__init__.py
index 8367dcde5..fcce60feb 100644
--- a/sphinx/transforms/__init__.py
+++ b/sphinx/transforms/__init__.py
@@ -20,7 +20,7 @@ from docutils.utils import normalize_language_tag
from docutils.utils.smartquotes import smartchars
from sphinx import addnodes
-from sphinx.locale import _
+from sphinx.locale import _, __
from sphinx.util import logging
from sphinx.util.docutils import new_document
from sphinx.util.i18n import format_date
@@ -262,8 +262,8 @@ class AutoIndexUpgrader(SphinxTransform):
# type: () -> None
for node in self.document.traverse(addnodes.index):
if 'entries' in node and any(len(entry) == 4 for entry in node['entries']):
- msg = ('4 column based index found. '
- 'It might be a bug of extensions you use: %r' % node['entries'])
+ msg = __('4 column based index found. '
+ 'It might be a bug of extensions you use: %r') % node['entries']
logger.warning(msg, location=node)
for i, entry in enumerate(node['entries']):
if len(entry) == 4:
@@ -304,13 +304,13 @@ class UnreferencedFootnotesDetector(SphinxTransform):
# footnote having duplicated number. It is already warned at parser.
pass
elif node['names'][0] not in self.document.footnote_refs:
- logger.warning('Footnote [%s] is not referenced.', node['names'][0],
+ logger.warning(__('Footnote [%s] is not referenced.'), node['names'][0],
type='ref', subtype='footnote',
location=node)
for node in self.document.autofootnotes:
if not any(ref['auto'] == node['auto'] for ref in self.document.autofootnote_refs):
- logger.warning('Footnote [#] is not referenced.',
+ logger.warning(__('Footnote [#] is not referenced.'),
type='ref', subtype='footnote',
location=node)
diff --git a/sphinx/transforms/i18n.py b/sphinx/transforms/i18n.py
index 9dddce343..386c5ae39 100644
--- a/sphinx/transforms/i18n.py
+++ b/sphinx/transforms/i18n.py
@@ -18,7 +18,7 @@ from docutils.utils import relative_path
from sphinx import addnodes
from sphinx.domains.std import make_glossary_term, split_term_classifiers
-from sphinx.locale import init as init_locale
+from sphinx.locale import __, init as init_locale
from sphinx.transforms import SphinxTransform
from sphinx.util import split_index_msg, logging
from sphinx.util.i18n import find_catalog
@@ -274,8 +274,8 @@ class Locale(SphinxTransform):
if len(old_foot_refs) != len(new_foot_refs):
old_foot_ref_rawsources = [ref.rawsource for ref in old_foot_refs]
new_foot_ref_rawsources = [ref.rawsource for ref in new_foot_refs]
- logger.warning('inconsistent footnote references in translated message.' +
- ' original: {0}, translated: {1}'
+ logger.warning(__('inconsistent footnote references in translated message.' +
+ ' original: {0}, translated: {1}')
.format(old_foot_ref_rawsources, new_foot_ref_rawsources),
location=node)
old_foot_namerefs = {} # type: Dict[unicode, List[nodes.footnote_reference]]
@@ -314,8 +314,8 @@ class Locale(SphinxTransform):
if len(old_refs) != len(new_refs):
old_ref_rawsources = [ref.rawsource for ref in old_refs]
new_ref_rawsources = [ref.rawsource for ref in new_refs]
- logger.warning('inconsistent references in translated message.' +
- ' original: {0}, translated: {1}'
+ logger.warning(__('inconsistent references in translated message.' +
+ ' original: {0}, translated: {1}')
.format(old_ref_rawsources, new_ref_rawsources),
location=node)
old_ref_names = [r['refname'] for r in old_refs]
@@ -345,8 +345,8 @@ class Locale(SphinxTransform):
if len(old_foot_refs) != len(new_foot_refs):
old_foot_ref_rawsources = [ref.rawsource for ref in old_foot_refs]
new_foot_ref_rawsources = [ref.rawsource for ref in new_foot_refs]
- logger.warning('inconsistent footnote references in translated message.' +
- ' original: {0}, translated: {1}'
+ logger.warning(__('inconsistent footnote references in translated message.' +
+ ' original: {0}, translated: {1}')
.format(old_foot_ref_rawsources, new_foot_ref_rawsources),
location=node)
for old in old_foot_refs:
@@ -367,8 +367,8 @@ class Locale(SphinxTransform):
if len(old_cite_refs) != len(new_cite_refs):
old_cite_ref_rawsources = [ref.rawsource for ref in old_cite_refs]
new_cite_ref_rawsources = [ref.rawsource for ref in new_cite_refs]
- logger.warning('inconsistent citation references in translated message.' +
- ' original: {0}, translated: {1}'
+ logger.warning(__('inconsistent citation references in translated message.' +
+ ' original: {0}, translated: {1}')
.format(old_cite_ref_rawsources, new_cite_ref_rawsources),
location=node)
for old in old_cite_refs:
@@ -387,8 +387,8 @@ class Locale(SphinxTransform):
if len(old_refs) != len(new_refs):
old_ref_rawsources = [ref.rawsource for ref in old_refs]
new_ref_rawsources = [ref.rawsource for ref in new_refs]
- logger.warning('inconsistent term references in translated message.' +
- ' original: {0}, translated: {1}'
+ logger.warning(__('inconsistent term references in translated message.' +
+ ' original: {0}, translated: {1}')
.format(old_ref_rawsources, new_ref_rawsources),
location=node)
diff --git a/sphinx/transforms/post_transforms/images.py b/sphinx/transforms/post_transforms/images.py
index ac0f2d37c..0e29fdead 100644
--- a/sphinx/transforms/post_transforms/images.py
+++ b/sphinx/transforms/post_transforms/images.py
@@ -17,6 +17,7 @@ from typing import TYPE_CHECKING
from docutils import nodes
from six import text_type
+from sphinx.locale import __
from sphinx.transforms import SphinxTransform
from sphinx.util import epoch_to_rfc1123, rfc1123_to_epoch
from sphinx.util import logging, requests
@@ -83,7 +84,7 @@ class ImageDownloader(BaseImageConverter):
r = requests.get(node['uri'], headers=headers)
if r.status_code >= 400:
- logger.warning('Could not fetch remote image: %s [%d]' %
+ logger.warning(__('Could not fetch remote image: %s [%d]') %
(node['uri'], r.status_code))
else:
self.app.env.original_image_uri[path] = node['uri']
@@ -111,7 +112,7 @@ class ImageDownloader(BaseImageConverter):
node['uri'] = path
self.app.env.images.add_file(self.env.docname, path)
except Exception as exc:
- logger.warning('Could not fetch remote image: %s [%s]' %
+ logger.warning(__('Could not fetch remote image: %s [%s]') %
(node['uri'], text_type(exc)))
@@ -132,7 +133,7 @@ class DataURIExtractor(BaseImageConverter):
image = parse_data_uri(node['uri'])
ext = get_image_extension(image.mimetype)
if ext is None:
- logger.warning('Unknown image format: %s...', node['uri'][:32],
+ logger.warning(__('Unknown image format: %s...'), node['uri'][:32],
location=node)
return
diff --git a/sphinx/util/i18n.py b/sphinx/util/i18n.py
index c11f59381..0ed25818d 100644
--- a/sphinx/util/i18n.py
+++ b/sphinx/util/i18n.py
@@ -24,6 +24,7 @@ from babel.messages.mofile import write_mo
from babel.messages.pofile import read_po
from sphinx.errors import SphinxError
+from sphinx.locale import __
from sphinx.util import logging
from sphinx.util.osutil import SEP, walk
@@ -70,14 +71,14 @@ class CatalogInfo(LocaleFileInfoBase):
try:
po = read_po(file_po, locale)
except Exception as exc:
- logger.warning('reading error: %s, %s', self.po_path, exc)
+ logger.warning(__('reading error: %s, %s'), self.po_path, exc)
return
with io.open(self.mo_path, 'wb') as file_mo:
try:
write_mo(file_mo, po)
except Exception as exc:
- logger.warning('writing error: %s, %s', self.mo_path, exc)
+ logger.warning(__('writing error: %s, %s'), self.mo_path, exc)
def find_catalog(docname, compaction):
@@ -210,8 +211,8 @@ def babel_format_date(date, format, locale, formatter=babel.dates.format_date):
# fallback to English
return formatter(date, format, locale='en')
except AttributeError:
- logger.warning('Invalid date format. Quote the string by single quote '
- 'if you want to output it directly: %s', format)
+ logger.warning(__('Invalid date format. Quote the string by single quote '
+ 'if you want to output it directly: %s'), format)
return format
diff --git a/sphinx/util/nodes.py b/sphinx/util/nodes.py
index c17edce2f..ef0872c64 100644
--- a/sphinx/util/nodes.py
+++ b/sphinx/util/nodes.py
@@ -17,6 +17,7 @@ from docutils import nodes
from six import text_type
from sphinx import addnodes
+from sphinx.locale import __
from sphinx.util import logging
if TYPE_CHECKING:
@@ -296,7 +297,7 @@ def inline_all_toctrees(builder, docnameset, docname, tree, colorfunc, traversed
colorfunc, traversed)
docnameset.add(includefile)
except Exception:
- logger.warning('toctree contains ref to nonexisting file %r',
+ logger.warning(__('toctree contains ref to nonexisting file %r'),
includefile, location=docname)
else:
sof = addnodes.start_of_file(docname=includefile)
@@ -369,7 +370,7 @@ def process_only_nodes(document, tags):
try:
ret = tags.eval_condition(node['expr'])
except Exception as err:
- logger.warning('exception while evaluating only directive expression: %s', err,
+ logger.warning(__('exception while evaluating only directive expression: %s'), err,
location=node)
node.replace_self(node.children or nodes.comment())
else:
diff --git a/sphinx/util/rst.py b/sphinx/util/rst.py
index e2e68f6d0..40f26c888 100644
--- a/sphinx/util/rst.py
+++ b/sphinx/util/rst.py
@@ -18,6 +18,7 @@ from docutils.parsers.rst import roles
from docutils.parsers.rst.languages import en as english
from docutils.utils import Reporter
+from sphinx.locale import __
from sphinx.util import logging
if TYPE_CHECKING:
@@ -43,7 +44,7 @@ def default_role(docname, name):
if role_fn:
roles._roles[''] = role_fn
else:
- logger.warning('default role %s not found', name, location=docname)
+ logger.warning(__('default role %s not found'), name, location=docname)
yield
diff --git a/sphinx/writers/html.py b/sphinx/writers/html.py
index 722e595ac..26abdcd12 100644
--- a/sphinx/writers/html.py
+++ b/sphinx/writers/html.py
@@ -20,7 +20,7 @@ from docutils.writers.html4css1 import Writer, HTMLTranslator as BaseTranslator
from six import string_types
from sphinx import addnodes
-from sphinx.locale import admonitionlabels, _
+from sphinx.locale import admonitionlabels, _, __
from sphinx.util import logging
from sphinx.util.images import get_image_size
@@ -335,7 +335,7 @@ class HTMLTranslator(BaseTranslator):
self.body.append('<span class="caption-number">')
prefix = self.builder.config.numfig_format.get(figtype)
if prefix is None:
- msg = 'numfig_format is not defined for %s' % figtype
+ msg = __('numfig_format is not defined for %s') % figtype
logger.warning(msg)
else:
numbers = self.builder.fignumbers[key][figure_id]
@@ -345,7 +345,7 @@ class HTMLTranslator(BaseTranslator):
figtype = self.builder.env.domains['std'].get_figtype(node) # type: ignore
if figtype:
if len(node['ids']) == 0:
- msg = 'Any IDs not assigned for %s node' % node.tagname
+ msg = __('Any IDs not assigned for %s node') % node.tagname
logger.warning(msg, location=node)
else:
append_fignumber(figtype, node['ids'][0])
@@ -625,7 +625,7 @@ class HTMLTranslator(BaseTranslator):
if not ('width' in node and 'height' in node):
size = get_image_size(os.path.join(self.builder.srcdir, olduri))
if size is None:
- logger.warning('Could not obtain image size. :scale: option is ignored.',
+ logger.warning(__('Could not obtain image size. :scale: option is ignored.'), # NOQA
location=node)
else:
if 'width' not in node:
@@ -874,9 +874,9 @@ class HTMLTranslator(BaseTranslator):
def visit_math(self, node, math_env=''):
# type: (nodes.Node, unicode) -> None
- logger.warning('using "math" markup without a Sphinx math extension '
- 'active, please use one of the math extensions '
- 'described at http://sphinx-doc.org/ext/math.html',
+ logger.warning(__('using "math" markup without a Sphinx math extension '
+ 'active, please use one of the math extensions '
+ 'described at http://sphinx-doc.org/ext/math.html'),
location=(self.builder.current_docname, node.line))
raise nodes.SkipNode
diff --git a/sphinx/writers/html5.py b/sphinx/writers/html5.py
index 4a265594e..b2acf8570 100644
--- a/sphinx/writers/html5.py
+++ b/sphinx/writers/html5.py
@@ -19,7 +19,7 @@ from docutils.writers.html5_polyglot import HTMLTranslator as BaseTranslator
from six import string_types
from sphinx import addnodes
-from sphinx.locale import admonitionlabels, _
+from sphinx.locale import admonitionlabels, _, __
from sphinx.util import logging
from sphinx.util.images import get_image_size
@@ -303,7 +303,7 @@ class HTML5Translator(BaseTranslator):
self.body.append('<span class="caption-number">')
prefix = self.builder.config.numfig_format.get(figtype)
if prefix is None:
- msg = 'numfig_format is not defined for %s' % figtype
+ msg = __('numfig_format is not defined for %s') % figtype
logger.warning(msg)
else:
numbers = self.builder.fignumbers[key][figure_id]
@@ -313,7 +313,7 @@ class HTML5Translator(BaseTranslator):
figtype = self.builder.env.domains['std'].get_figtype(node) # type: ignore
if figtype:
if len(node['ids']) == 0:
- msg = 'Any IDs not assigned for %s node' % node.tagname
+ msg = __('Any IDs not assigned for %s node') % node.tagname
logger.warning(msg, location=node)
else:
append_fignumber(figtype, node['ids'][0])
@@ -571,7 +571,7 @@ class HTML5Translator(BaseTranslator):
if not ('width' in node and 'height' in node):
size = get_image_size(os.path.join(self.builder.srcdir, olduri))
if size is None:
- logger.warning('Could not obtain image size. :scale: option is ignored.',
+ logger.warning(__('Could not obtain image size. :scale: option is ignored.'), # NOQA
location=node)
else:
if 'width' not in node:
@@ -825,9 +825,9 @@ class HTML5Translator(BaseTranslator):
def visit_math(self, node, math_env=''):
# type: (nodes.Node, unicode) -> None
- logger.warning('using "math" markup without a Sphinx math extension '
- 'active, please use one of the math extensions '
- 'described at http://sphinx-doc.org/ext/math.html',
+ logger.warning(__('using "math" markup without a Sphinx math extension '
+ 'active, please use one of the math extensions '
+ 'described at http://sphinx-doc.org/ext/math.html'),
location=(self.builder.current_docname, node.line))
raise nodes.SkipNode
diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py
index 8112a16b1..3cd5022b9 100644
--- a/sphinx/writers/latex.py
+++ b/sphinx/writers/latex.py
@@ -25,7 +25,7 @@ from six import itervalues, text_type
from sphinx import addnodes
from sphinx import highlighting
from sphinx.errors import SphinxError
-from sphinx.locale import admonitionlabels, _
+from sphinx.locale import admonitionlabels, _, __
from sphinx.transforms import SphinxTransform
from sphinx.util import split_into, logging
from sphinx.util.i18n import format_date
@@ -574,7 +574,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
self.top_sectionlevel = \
self.sectionnames.index(builder.config.latex_toplevel_sectioning)
except ValueError:
- logger.warning('unknown %r toplevel_sectioning for class %r' %
+ logger.warning(__('unknown %r toplevel_sectioning for class %r') %
(builder.config.latex_toplevel_sectioning, docclass))
if builder.config.today:
@@ -621,7 +621,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
if builder.config.language and not self.babel.is_supported_language():
# emit warning if specified language is invalid
# (only emitting, nothing changed to processing)
- logger.warning('no Babel option known for language %r',
+ logger.warning(__('no Babel option known for language %r'),
builder.config.language)
# simply use babel.get_language() always, as get_language() returns
@@ -677,7 +677,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
self.top_sectionlevel > 0:
tocdepth += 1 # because top_sectionlevel is shifted by -1
if tocdepth > len(LATEXSECTIONNAMES) - 2: # default is 5 <-> subparagraph
- logger.warning('too large :maxdepth:, ignored.')
+ logger.warning(__('too large :maxdepth:, ignored.'))
tocdepth = len(LATEXSECTIONNAMES) - 2
self.elements['tocdepth'] = '\\setcounter{tocdepth}{%d}' % tocdepth
@@ -765,7 +765,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
# type: () -> None
for key in self.builder.config.latex_elements:
if key not in self.elements:
- msg = _("Unknown configure key: latex_elements[%r] is ignored.")
+ msg = __("Unknown configure key: latex_elements[%r] is ignored.")
logger.warning(msg % key)
def restrict_footnote(self, node):
@@ -1091,7 +1091,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
if self.this_is_the_title:
if len(node.children) != 1 and not isinstance(node.children[0],
nodes.Text):
- logger.warning('document title is not a single Text node',
+ logger.warning(__('document title is not a single Text node'),
location=(self.curfilestack[-1], node.line))
if not self.elements['title']:
# text needs to be escaped since it is inserted into
@@ -1131,8 +1131,8 @@ class LaTeXTranslator(nodes.NodeVisitor):
self.pushbody([])
self.restrict_footnote(node)
else:
- logger.warning('encountered title node not in section, topic, table, '
- 'admonition or sidebar',
+ logger.warning(__('encountered title node not in section, topic, table, '
+ 'admonition or sidebar'),
location=(self.curfilestack[-1], node.line or ''))
self.body.append('\\sphinxstyleothertitle{')
self.context.append('}\n')
@@ -1741,7 +1741,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
try:
return rstdim_to_latexdim(width_str)
except ValueError:
- logger.warning('dimension unit %s is invalid. Ignored.', width_str)
+ logger.warning(__('dimension unit %s is invalid. Ignored.'), width_str)
return None
def is_inline(self, node):
@@ -2052,7 +2052,7 @@ class LaTeXTranslator(nodes.NodeVisitor):
p1, p2 = [self.encode(x) for x in split_into(2, 'seealso', string)]
self.body.append(r'\index{%s|see{%s}}' % (p1, p2))
else:
- logger.warning('unknown index entry type %s found', type)
+ logger.warning(__('unknown index entry type %s found'), type)
except ValueError as err:
logger.warning(str(err))
if not node.get('inline', True):
@@ -2624,9 +2624,9 @@ class LaTeXTranslator(nodes.NodeVisitor):
def visit_math(self, node):
# type: (nodes.Node) -> None
- logger.warning('using "math" markup without a Sphinx math extension '
- 'active, please use one of the math extensions '
- 'described at http://sphinx-doc.org/ext/math.html',
+ logger.warning(__('using "math" markup without a Sphinx math extension '
+ 'active, please use one of the math extensions '
+ 'described at http://sphinx-doc.org/ext/math.html'),
location=(self.curfilestack[-1], node.line))
raise nodes.SkipNode
diff --git a/sphinx/writers/manpage.py b/sphinx/writers/manpage.py
index df2f74c02..f4431a3d6 100644
--- a/sphinx/writers/manpage.py
+++ b/sphinx/writers/manpage.py
@@ -20,7 +20,7 @@ from docutils.writers.manpage import (
import sphinx.util.docutils
from sphinx import addnodes
-from sphinx.locale import admonitionlabels, _
+from sphinx.locale import admonitionlabels, _, __
from sphinx.util import logging
from sphinx.util.i18n import format_date
@@ -514,9 +514,9 @@ class ManualPageTranslator(BaseTranslator):
def visit_math(self, node):
# type: (nodes.Node) -> None
- logger.warning('using "math" markup without a Sphinx math extension '
- 'active, please use one of the math extensions '
- 'described at http://sphinx-doc.org/ext/math.html')
+ logger.warning(__('using "math" markup without a Sphinx math extension '
+ 'active, please use one of the math extensions '
+ 'described at http://sphinx-doc.org/ext/math.html'))
raise nodes.SkipNode
visit_math_block = visit_math
diff --git a/sphinx/writers/texinfo.py b/sphinx/writers/texinfo.py
index d17566429..a69c7bd27 100644
--- a/sphinx/writers/texinfo.py
+++ b/sphinx/writers/texinfo.py
@@ -20,7 +20,7 @@ from six.moves import range
from sphinx import addnodes, __display_version__
from sphinx.errors import ExtensionError
-from sphinx.locale import admonitionlabels, _
+from sphinx.locale import admonitionlabels, _, __
from sphinx.util import logging
from sphinx.util.i18n import format_date
from sphinx.writers.latex import collected_footnote
@@ -648,8 +648,8 @@ class TexinfoTranslator(nodes.NodeVisitor):
if isinstance(parent, (nodes.Admonition, nodes.sidebar, nodes.topic)):
raise nodes.SkipNode
elif not isinstance(parent, nodes.section):
- logger.warning('encountered title node not in section, topic, table, '
- 'admonition or sidebar',
+ logger.warning(__('encountered title node not in section, topic, table, '
+ 'admonition or sidebar'),
location=(self.curfilestack[-1], node.line))
self.visit_rubric(node)
else:
@@ -1318,7 +1318,7 @@ class TexinfoTranslator(nodes.NodeVisitor):
node.parent.get('literal_block'))):
self.body.append('\n@caption{')
else:
- logger.warning('caption not inside a figure.',
+ logger.warning(__('caption not inside a figure.'),
location=(self.curfilestack[-1], node.line))
def depart_caption(self, node):
@@ -1421,12 +1421,12 @@ class TexinfoTranslator(nodes.NodeVisitor):
def unimplemented_visit(self, node):
# type: (nodes.Node) -> None
- logger.warning("unimplemented node type: %r", node,
+ logger.warning(__("unimplemented node type: %r"), node,
location=(self.curfilestack[-1], node.line))
def unknown_visit(self, node):
# type: (nodes.Node) -> None
- logger.warning("unknown node type: %r", node,
+ logger.warning(__("unknown node type: %r"), node,
location=(self.curfilestack[-1], node.line))
def unknown_departure(self, node):
@@ -1743,9 +1743,9 @@ class TexinfoTranslator(nodes.NodeVisitor):
def visit_math(self, node):
# type: (nodes.Node) -> None
- logger.warning('using "math" markup without a Sphinx math extension '
- 'active, please use one of the math extensions '
- 'described at http://sphinx-doc.org/ext/math.html')
+ logger.warning(__('using "math" markup without a Sphinx math extension '
+ 'active, please use one of the math extensions '
+ 'described at http://sphinx-doc.org/ext/math.html'))
raise nodes.SkipNode
visit_math_block = visit_math
diff --git a/sphinx/writers/text.py b/sphinx/writers/text.py
index 12103042f..73a8f05b6 100644
--- a/sphinx/writers/text.py
+++ b/sphinx/writers/text.py
@@ -19,7 +19,7 @@ from docutils.utils import column_width
from six.moves import zip_longest
from sphinx import addnodes
-from sphinx.locale import admonitionlabels, _
+from sphinx.locale import admonitionlabels, _, __
from sphinx.util import logging
if TYPE_CHECKING:
@@ -1183,9 +1183,9 @@ class TextTranslator(nodes.NodeVisitor):
def visit_math(self, node):
# type: (nodes.Node) -> None
- logger.warning('using "math" markup without a Sphinx math extension '
- 'active, please use one of the math extensions '
- 'described at http://sphinx-doc.org/ext/math.html',
+ logger.warning(__('using "math" markup without a Sphinx math extension '
+ 'active, please use one of the math extensions '
+ 'described at http://sphinx-doc.org/ext/math.html'),
location=(self.builder.current_docname, node.line))
raise nodes.SkipNode