Question: :noindex: prevents cross-referencing If a flag is to a directive, it can't be cross-referenced, and no permalink to it is generated. The following ReST: generates the following HTML: I would expect only to result in no index entry, not to prevent cross-referencing or permalinking. The HTML generated for the two class directives should be the same, i.e. the HTML for the Unindexed class should be OS: Linux Mint 19.1 (based on Ubuntu 18.04) Python version: 3.8.1 Sphinx version: 3.0.0 (HEAD) but also occurs with Sphinx 2.x, 1.x

from docutils import nodes from docutils.nodes import Element, Node, TextElement, system_message<ins>from docutils.parsers.rst import directives</ins>  from sphinx import addnodes from sphinx.addnodes import pending_xref


Question: :noindex: prevents cross-referencing If a flag is to a directive, it can't be cross-referenced, and no permalink to it is generated. The following ReST: generates the following HTML: I would expect only to result in no index entry, not to prevent cross-referencing or permalinking. The HTML generated for the two class directives should be the same, i.e. the HTML for the Unindexed class should be OS: Linux Mint 19.1 (based on Ubuntu 18.04) Python version: 3.8.1 Sphinx version: 3.0.0 (HEAD) but also occurs with Sphinx 2.x, 1.x

]      option_spec = {        # have a dummy option to ensure proper errors on options,        # otherwise the option is taken as a continuation of the        # argument        'dummy': None        'noindexentry': directives.flag,     }      def _add_enumerator_to_parent(self, ast: ASTDeclaration) -> None:


Question: :noindex: prevents cross-referencing If a flag is to a directive, it can't be cross-referenced, and no permalink to it is generated. The following ReST: generates the following HTML: I would expect only to result in no index entry, not to prevent cross-referencing or permalinking. The HTML generated for the two class directives should be the same, i.e. the HTML for the Unindexed class should be OS: Linux Mint 19.1 (based on Ubuntu 18.04) Python version: 3.8.1 Sphinx version: 3.0.0 (HEAD) but also occurs with Sphinx 2.x, 1.x

if name not in domain.objects:                 domain.objects[name] = (domain.env.docname, newestId, self.objtype)         indexText = self.get_index_text(name)        self.indexnode['entries'].append(('single', indexText, newestId, '', None))        if 'noindexentry' not in self.options:            indexText = self.get_index_text(name)            self.indexnode['entries'].append(('single', indexText, newestId, '', None))      @property     def object_type(self) -> str:diff --git a/sphinx/domains/cpp.py b/sphinx/domains/cpp.py-- a/sphinx/domains/cpp.py++ b/sphinx/domains/cpp.py


Question: :noindex: prevents cross-referencing If a flag is to a directive, it can't be cross-referenced, and no permalink to it is generated. The following ReST: generates the following HTML: I would expect only to result in no index entry, not to prevent cross-referencing or permalinking. The HTML generated for the two class directives should be the same, i.e. the HTML for the Unindexed class should be OS: Linux Mint 19.1 (based on Ubuntu 18.04) Python version: 3.8.1 Sphinx version: 3.0.0 (HEAD) but also occurs with Sphinx 2.x, 1.x

]      option_spec = {<ins>        'noindexentry': directives.flag,</ins>         'tparam-line-spec': directives.flag,     }


Question: :noindex: prevents cross-referencing If a flag is to a directive, it can't be cross-referenced, and no permalink to it is generated. The following ReST: generates the following HTML: I would expect only to result in no index entry, not to prevent cross-referencing or permalinking. The HTML generated for the two class directives should be the same, i.e. the HTML for the Unindexed class should be OS: Linux Mint 19.1 (based on Ubuntu 18.04) Python version: 3.8.1 Sphinx version: 3.0.0 (HEAD) but also occurs with Sphinx 2.x, 1.x

if decl.objectType == 'concept':                 isInConcept = True                 break        if not isInConcept:        if not isInConcept and 'noindexentry' not in self.options:             strippedName = name             for prefix in self.env.config.cpp_index_common_prefix:                 if name.startswith(prefix):diff --git a/sphinx/domains/javascript.py b/sphinx/domains/javascript.py-- a/sphinx/domains/javascript.py++ b/sphinx/domains/javascript.py


Question: :noindex: prevents cross-referencing If a flag is to a directive, it can't be cross-referenced, and no permalink to it is generated. The following ReST: generates the following HTML: I would expect only to result in no index entry, not to prevent cross-referencing or permalinking. The HTML generated for the two class directives should be the same, i.e. the HTML for the Unindexed class should be OS: Linux Mint 19.1 (based on Ubuntu 18.04) Python version: 3.8.1 Sphinx version: 3.0.0 (HEAD) but also occurs with Sphinx 2.x, 1.x

#: based on directive nesting     allow_nesting = False <ins>    option_spec = {        'noindex': directives.flag,        'noindexentry': directives.flag,    }</ins>     def handle_signature(self, sig: str, signode: desc_signature) -> Tuple[str, str]:         """Breaks down construct signatures


Question: :noindex: prevents cross-referencing If a flag is to a directive, it can't be cross-referenced, and no permalink to it is generated. The following ReST: generates the following HTML: I would expect only to result in no index entry, not to prevent cross-referencing or permalinking. The HTML generated for the two class directives should be the same, i.e. the HTML for the Unindexed class should be OS: Linux Mint 19.1 (based on Ubuntu 18.04) Python version: 3.8.1 Sphinx version: 3.0.0 (HEAD) but also occurs with Sphinx 2.x, 1.x

domain = cast(JavaScriptDomain, self.env.get_domain('js'))         domain.note_object(fullname, self.objtype, node_id, location=signode)         indextext = self.get_index_text(mod_name, name_obj)        if indextext:            self.indexnode['entries'].append(('single', indextext, node_id, '', None))        if 'noindexentry' not in self.options:            indextext = self.get_index_text(mod_name, name_obj)            if indextext:                self.indexnode['entries'].append(('single', indextext, node_id, '', None))      def get_index_text(self, objectname: str, name_obj: Tuple[str, str]) -> str:         name, obj = name_objdiff --git a/sphinx/domains/python.py b/sphinx/domains/python.py-- a/sphinx/domains/python.py++ b/sphinx/domains/python.py


Question: :noindex: prevents cross-referencing If a flag is to a directive, it can't be cross-referenced, and no permalink to it is generated. The following ReST: generates the following HTML: I would expect only to result in no index entry, not to prevent cross-referencing or permalinking. The HTML generated for the two class directives should be the same, i.e. the HTML for the Unindexed class should be OS: Linux Mint 19.1 (based on Ubuntu 18.04) Python version: 3.8.1 Sphinx version: 3.0.0 (HEAD) but also occurs with Sphinx 2.x, 1.x

"""     option_spec = {         'noindex': directives.flag,<ins>        'noindexentry': directives.flag,</ins>         'module': directives.unchanged,         'annotation': directives.unchanged,     }


Question: :noindex: prevents cross-referencing If a flag is to a directive, it can't be cross-referenced, and no permalink to it is generated. The following ReST: generates the following HTML: I would expect only to result in no index entry, not to prevent cross-referencing or permalinking. The HTML generated for the two class directives should be the same, i.e. the HTML for the Unindexed class should be OS: Linux Mint 19.1 (based on Ubuntu 18.04) Python version: 3.8.1 Sphinx version: 3.0.0 (HEAD) but also occurs with Sphinx 2.x, 1.x

domain = cast(PythonDomain, self.env.get_domain('py'))         domain.note_object(fullname, self.objtype, node_id, location=signode)         indextext = self.get_index_text(modname, name_cls)        if indextext:            self.indexnode['entries'].append(('single', indextext, node_id, '', None))        if 'noindexentry' not in self.options:            indextext = self.get_index_text(modname, name_cls)            if indextext:                self.indexnode['entries'].append(('single', indextext, node_id, '', None))      def before_content(self) -> None:         """Handle object nesting before content


Question: :noindex: prevents cross-referencing If a flag is to a directive, it can't be cross-referenced, and no permalink to it is generated. The following ReST: generates the following HTML: I would expect only to result in no index entry, not to prevent cross-referencing or permalinking. The HTML generated for the two class directives should be the same, i.e. the HTML for the Unindexed class should be OS: Linux Mint 19.1 (based on Ubuntu 18.04) Python version: 3.8.1 Sphinx version: 3.0.0 (HEAD) but also occurs with Sphinx 2.x, 1.x

def add_target_and_index(self, name_cls: Tuple[str, str], sig: str,                              signode: desc_signature) -> None:         super().add_target_and_index(name_cls, sig, signode)        modname = self.options.get('module', self.env.ref_context.get('py:module'))        node_id = signode['ids'][0]        if 'noindexentry' not in self.options:            modname = self.options.get('module', self.env.ref_context.get('py:module'))            node_id = signode['ids'][0]         name, cls = name_cls        if modname:            text = _('%s() (in module %s)') % (name, modname)            self.indexnode['entries'].append(('single', text, node_id, '', None))        else:            text = '%s; %s()' % (pairindextypes['builtin'], name)            self.indexnode['entries'].append(('pair', text, node_id, '', None))            name, cls = name_cls            if modname:                text = _('%s() (in module %s)') % (name, modname)                self.indexnode['entries'].append(('single', text, node_id, '', None))            else:                text = '%s; %s()' % (pairindextypes['builtin'], name)                self.indexnode['entries'].append(('pair', text, node_id, '', None))      def get_index_text(self, modname: str, name_cls: Tuple[str, str]) -> str:         # add index in own add_target_and_index() instead.


Question: Decorated init doesn't show up in docs Subject: Decorated init won't be documented. I'm working on I have , so will be documented. But if I decorate the method, it will not show up in docs. I decorate it with , so the decorated object still has the same . I've found that the bug is due to this commit: I've printed the relevant variables in that function: And the root cause of the issue is in this line of code: Because now is not the method itself, but a decorated method, its does not contain the class anymore. This makes sphinx think it's not a method, i.e. . OS: <Unix/Linux/Mac/Win/other with version: ArchLinux Python version: 3.6 Sphinx version:1.6.5

from sphinx import __display_version__ as __version__ from sphinx.application import Sphinx from sphinx.ext.napoleon.docstring import GoogleDocstring, NumpyDocstring<ins>from sphinx.util import inspect</ins>   class Config:


Question: Decorated init doesn't show up in docs Subject: Decorated init won't be documented. I'm working on I have , so will be documented. But if I decorate the method, it will not show up in docs. I decorate it with , so the decorated object still has the same . I've found that the bug is due to this commit: I've printed the relevant variables in that function: And the root cause of the issue is in this line of code: Because now is not the method itself, but a decorated method, its does not contain the class anymore. This makes sphinx think it's not a method, i.e. . OS: <Unix/Linux/Mac/Win/other with version: ArchLinux Python version: 3.6 Sphinx version:1.6.5

mod_path = cls_path.split('.')                         cls = functools.reduce(getattr, mod_path, mod)                     else:                        cls = obj.__globals__[cls_path]                        cls = inspect.unwrap(obj).__globals__[cls_path]                 except Exception:                     cls_is_owner = False                 else:


Question: Bad refs in pot files, when using rst_epilog To Reproduce produces with bad string numbers and "\<generated\" refs:

def append_epilog(content: StringList, epilog: str) -> None:     """Append a string to content body as epilog."""     if epilog:        content.append('', '<generated>', 0)        if 0 < len(content):            source, lineno = content.info(-1)        else:            source = '<generated>'            lineno = 0        content.append('', source, lineno + 1)         for lineno, line in enumerate(epilog.splitlines()):             content.append(line, '<rst_epilog>', lineno)


Question: Regression: autodoc Dataclass variables reference target not found Describe the bug When I use and with my code which includes a dataclass with a variable of a custom type, I get a warning. To Reproduce Open the attached project . Install Sphinx. Run . Expected behavior I expect there to be no warning, or a clear message saying how I can avoid this warning. Your project Environment info macOS latest Python 3.7.7 Sphinx 3.1.2 (reproducible also with 3.1.0 but not 3.0.4)

('deprecated', bool)])  def type_to_xref(text: str) -> addnodes.pending_xref:def type_to_xref(text: str, env: BuildEnvironment = None) -> addnodes.pending_xref:     """Convert a type string to a cross reference node."""     if text == 'None':         reftype = 'obj'     else:         reftype = 'class'     if env:        kwargs = {'py:module': env.ref_context.get('py:module'),                  'py:class': env.ref_context.get('py:class')}    else:        kwargs = {}     return pending_xref('', nodes.Text(text),                        refdomain='py', reftype=reftype, reftarget=text)                        refdomain='py', reftype=reftype, reftarget=text, **kwargs)  def _parse_annotation(annotation: str) -> List[Node]:def _parse_annotation(annotation: str, env: BuildEnvironment = None) -> List[Node]:     """Parse type annotation."""     def unparse(node: ast.AST) -> List[Node]:         if isinstance(node, ast.Attribute):


Question: Regression: autodoc Dataclass variables reference target not found Describe the bug When I use and with my code which includes a dataclass with a variable of a custom type, I get a warning. To Reproduce Open the attached project . Install Sphinx. Run . Expected behavior I expect there to be no warning, or a clear message saying how I can avoid this warning. Your project Environment info macOS latest Python 3.7.7 Sphinx 3.1.2 (reproducible also with 3.1.0 but not 3.0.4)

else:             raise SyntaxError  # unsupported syntax     if env is None:        warnings.warn("The env parameter for _parse_annotation becomes required now.",                      RemovedInSphinx50Warning, stacklevel=2)     try:         tree = ast_parse(annotation)         result = unparse(tree)         for i, node in enumerate(result):             if isinstance(node, nodes.Text):                result[i] = type_to_xref(str(node))                result[i] = type_to_xref(str(node), env)         return result     except SyntaxError:        return [type_to_xref(annotation)]        return [type_to_xref(annotation, env)]  def _parse_arglist(arglist: str) -> addnodes.desc_parameterlist:def _parse_arglist(arglist: str, env: BuildEnvironment = None) -> addnodes.desc_parameterlist:     """Parse a list of arguments using AST parser"""     params = addnodes.desc_parameterlist(arglist)     sig = signature_from_str('(%s)' % arglist)


Question: Regression: autodoc Dataclass variables reference target not found Describe the bug When I use and with my code which includes a dataclass with a variable of a custom type, I get a warning. To Reproduce Open the attached project . Install Sphinx. Run . Expected behavior I expect there to be no warning, or a clear message saying how I can avoid this warning. Your project Environment info macOS latest Python 3.7.7 Sphinx 3.1.2 (reproducible also with 3.1.0 but not 3.0.4)

node += addnodes.desc_sig_name('', param.name)          if param.annotation is not param.empty:            children = _parse_annotation(param.annotation)            children = _parse_annotation(param.annotation, env)             node += addnodes.desc_sig_punctuation('', ':')             node += nodes.Text(' ')             node += addnodes.desc_sig_name('', '', *children)  # type: ignore


Question: Regression: autodoc Dataclass variables reference target not found Describe the bug When I use and with my code which includes a dataclass with a variable of a custom type, I get a warning. To Reproduce Open the attached project . Install Sphinx. Run . Expected behavior I expect there to be no warning, or a clear message saying how I can avoid this warning. Your project Environment info macOS latest Python 3.7.7 Sphinx 3.1.2 (reproducible also with 3.1.0 but not 3.0.4)

signode += addnodes.desc_name(name, name)         if arglist:             try:                signode += _parse_arglist(arglist)                signode += _parse_arglist(arglist, self.env)             except SyntaxError:                 # fallback to parse arglist original parser.                 # it supports to represent optional arguments (ex. "func(foo [, bar])")


Question: Regression: autodoc Dataclass variables reference target not found Describe the bug When I use and with my code which includes a dataclass with a variable of a custom type, I get a warning. To Reproduce Open the attached project . Install Sphinx. Run . Expected behavior I expect there to be no warning, or a clear message saying how I can avoid this warning. Your project Environment info macOS latest Python 3.7.7 Sphinx 3.1.2 (reproducible also with 3.1.0 but not 3.0.4)

signode += addnodes.desc_parameterlist()          if retann:            children = _parse_annotation(retann)            children = _parse_annotation(retann, self.env)             signode += addnodes.desc_returns(retann, '', *children)          anno = self.options.get('annotation')


Question: Regression: autodoc Dataclass variables reference target not found Describe the bug When I use and with my code which includes a dataclass with a variable of a custom type, I get a warning. To Reproduce Open the attached project . Install Sphinx. Run . Expected behavior I expect there to be no warning, or a clear message saying how I can avoid this warning. Your project Environment info macOS latest Python 3.7.7 Sphinx 3.1.2 (reproducible also with 3.1.0 but not 3.0.4)

typ = self.options.get('type')         if typ:            annotations = _parse_annotation(typ)            annotations = _parse_annotation(typ, self.env)             signode += addnodes.desc_annotation(typ, '', nodes.Text(': '), *annotations)          value = self.options.get('value')


Question: Regression: autodoc Dataclass variables reference target not found Describe the bug When I use and with my code which includes a dataclass with a variable of a custom type, I get a warning. To Reproduce Open the attached project . Install Sphinx. Run . Expected behavior I expect there to be no warning, or a clear message saying how I can avoid this warning. Your project Environment info macOS latest Python 3.7.7 Sphinx 3.1.2 (reproducible also with 3.1.0 but not 3.0.4)


Question: Support mathjax 3.0 , and has a number of improvements - most notably on the speed of loading (something like an 80% decrease in load time). It would be great to get this into the Sphinx MathJax extension. The suggest that it will not be trivial to upgrade, but it may be worth it given the performance and modularity improvements. What do folks think?

# more information for mathjax secure url is here:     # https://docs.mathjax.org/en/latest/start.html#secure-access-to-the-cdn     app.add_config_value('mathjax_path',                         'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?'                         'config=TeX-AMS-MML_HTMLorMML', 'html')                         'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js',                         'html')     app.add_config_value('mathjax_options', {}, 'html')     app.add_config_value('mathjax_inline', [r'\(', r'\)'], 'html')     app.add_config_value('mathjax_display', [r'\[', r'\]'], 'html')


Question: Two sections called Symbols in index When using index entries with the following leading characters: £, and ← I get two sections called Symbols in the HTML output, the first containing all @ entries before ”normal” words and the second containing £ and ← entries after the ”normal” words. Both have the same anchor in HTML so the links at the top of the index page contain two Symbols links, one before the letters and one after, but both lead to the first section.

for subentry in indexentry[1].values():                 subentry[0].sort(key=keyfunc0)  # type: ignore         # sort the index entries; put all symbols at the front, even those        # following the letters in ASCII, this is where the chr(127) comes from        def keyfunc(entry: Tuple[str, List]) -> Tuple[str, str]:        # sort the index entries        def keyfunc(entry: Tuple[str, List]) -> Tuple[Tuple[int, str], str]:             key, (void, void, category_key) = entry             if category_key:                 # using specified category key to sort


Question: Two sections called Symbols in index When using index entries with the following leading characters: £, and ← I get two sections called Symbols in the HTML output, the first containing all @ entries before ”normal” words and the second containing £ and ← entries after the ”normal” words. Both have the same anchor in HTML so the links at the top of the index page contain two Symbols links, one before the letters and one after, but both lead to the first section.

lckey = unicodedata.normalize('NFD', key.lower())             if lckey.startswith('\N{RIGHT-TO-LEFT MARK}'):                 lckey = lckey[1:]             if lckey[0:1].isalpha() or lckey.startswith('_'):                lckey = chr(127) + lckey                # put non-symbol characters at the folloing group (1)                sortkey = (1, lckey)            else:                # put symbols at the front of the index (0)                sortkey = (0, lckey)             # ensure a determinstic order *within* letters by also sorting on             # the entry itself            return (lckey, entry[0])            return (sortkey, entry[0])         newlist = sorted(new.items(), key=keyfunc)          if group_entries:


Question: linkcheck could also check local (internal) links Subject: linkcheck currently doesn't check local (internal) links, but this would be useful. <!-- Important: This is a list of issues for Sphinx, not a forum. If you'd like to post a question, please move to sphinx-users group. !forum/sphinx-users Thanks, --See above. Create a template project with sphinx-quickstart, put the following in Run Also a check for the local link. N/A OS: Arch Linux Python version: 3.6 Sphinx version: 1.7.6

logger = logging.getLogger(__name__) <ins>uri_re = re.compile('[a-z]+://')</ins>  DEFAULT_REQUEST_HEADERS = {     'Accept': 'text/html,application/xhtml+xml;q=0.9,*/*;q=0.8',


Question: linkcheck could also check local (internal) links Subject: linkcheck currently doesn't check local (internal) links, but this would be useful. <!-- Important: This is a list of issues for Sphinx, not a forum. If you'd like to post a question, please move to sphinx-users group. !forum/sphinx-users Thanks, --See above. Create a template project with sphinx-quickstart, put the following in Run Also a check for the local link. N/A OS: Arch Linux Python version: 3.6 Sphinx version: 1.7.6

def check() -> Tuple[str, str, int]:             # check for various conditions without bothering the network            if len(uri) == 0 or uri.startswith(('#', 'mailto:', 'ftp:')):            if len(uri) == 0 or uri.startswith(('#', 'mailto:')):                 return 'unchecked', '', 0             elif not uri.startswith(('http:', 'https:')):                return 'local', '', 0                if uri_re.match(uri):                    # non supported URI schemes (ex. ftp)                    return 'unchecked', '', 0                else:                    if path.exists(path.join(self.srcdir, uri)):                        return 'working', '', 0                    else:                        for rex in self.to_ignore:                            if rex.match(uri):                                return 'ignored', '', 0                        else:                            return 'broken', '', 0             elif uri in self.good:                 return 'working', 'old', 0             elif uri in self.broken:


Question: 2 introduces WARNING: py:class reference target not found: Callable[[...], Awaitable[None]] Describe the bug My project, including the above function definition, builds cleanly with Sphinx 3.1.1 but with 3.1.2 I get the following warning. Note that the resulting parameter documentation does properly hyperlink and but does not get a link. https://qtrio-- To Reproduce Steps to reproduce the behavior: Expected behavior The error doesn't happen in either case and , , and all get properly hyperlinked. Your project Screenshots ! Environment info OS: Linux - Ubuntu 20.04 Python version: 3.8.3 Sphinx version: 3.1.2 Sphinx extensions: sphinxautodoctypehints sphinxqtdocumentation sphinxcontrib_trio Additional context

import builtins import inspect import re<ins>import sys</ins> import typing import warnings from inspect import Parameter


Question: 2 introduces WARNING: py:class reference target not found: Callable[[...], Awaitable[None]] Describe the bug My project, including the above function definition, builds cleanly with Sphinx 3.1.1 but with 3.1.2 I get the following warning. Note that the resulting parameter documentation does properly hyperlink and but does not get a link. https://qtrio-- To Reproduce Steps to reproduce the behavior: Expected behavior The error doesn't happen in either case and , , and all get properly hyperlinked. Your project Screenshots ! Environment info OS: Linux - Ubuntu 20.04 Python version: 3.8.3 Sphinx version: 3.1.2 Sphinx extensions: sphinxautodoctypehints sphinxqtdocumentation sphinxcontrib_trio Additional context

return result         else:<ins>            if sys.version_info >= (3, 6):                if isinstance(node, ast.Constant):                    if node.value is Ellipsis:                        return [addnodes.desc_sig_punctuation('', "...")]                    else:                        return [nodes.Text(node.value)]            if sys.version_info < (3, 8):                if isinstance(node, ast.Ellipsis):                    return [addnodes.desc_sig_punctuation('', "...")]                elif isinstance(node, ast.NameConstant):                    return [nodes.Text(node.value)]</ins>             raise SyntaxError  # unsupported syntax      if env is None:


Question: More customization options for figurelanguagefilename for localized images Is your feature request related to a problem? Please describe. I'm working on the localization of the , and we use a to hold the massive PO files that we use for Weblate and Sphinx. I'm now working on image localization () and I find that even though  seems to provide some customization option, it's impossible to host the localized images in the separate repository. Indeed, both the and substitution tokens resolve to absolute paths from the host system (e.g. ), and since I can't do post-processing of the subsituted string, I can't strip the base path to attempt using something like . Describe the solution you'd like I'd like the addition of one or more new path substitution tokens that can be used to customize the path to localized images more freely. For example, for this structure: and referencing , I could imagine two useful substitution tokens: Alternatively (and possible as a better solution), and could be changed to actually be relative to the Sphinx project's root folder, i.e. the in my example above, i.e.: (While the documentation currently states that these would be and , which is wrong in my tests on Linux with Sphinx 1.8.5). I don't specifically need access to the file-relative path in my use case, but I imagine that some projects may benefit from it. Describe alternatives you've considered I don't see any alternative option that would enable the workflow I want to use with localized images not being either in the original image's folder, or in one of its subfolders. Edit: We came up with ~two~ three hacks that we could use to workaround the currently limited substitution tokens offered by : Passing a class that redefines with our custom post-processing: Symlinking all localized images from the out-of-tree location to the in-tree location where Sphinx wants it: Overriding since apparently Python lets us do that, so we can do the post-processing we want: I did not test with latest Sphinx as it's not properly supported on ReadTheDocs yet, but the relevant code seems to be unchanged from 1.8.5: Additional context

dirname = path.dirname(d['root'])     if dirname and not dirname.endswith(path.sep):         dirname += path.sep    docpath = path.dirname(env.docname)    if docpath and not docpath.endswith(path.sep):        docpath += path.sep     d['path'] = dirname     d['basename'] = path.basename(d['root'])    d['docpath'] = docpath     d['language'] = env.config.language     try:         return filename_format.format(**d)


Question: Instance attributes are omitted with autosummary This issue is a followup of . Sorry, I forgot to open it. Is your feature request related to a problem? Please describe. Instance attributes are omitted when using the autosummary, as they cannot be imported. Consider the following class via will document the attribute, but via won't. Describe the solution you'd like Instance attributes should be documented, too Describe alternatives you've considered it did work before , i.e. for (although the documentation was omitted). Additional context files to reproduce the issue (including page build) Screenshot of !

from sphinx.deprecation import RemovedInSphinx40Warning, RemovedInSphinx50Warning from sphinx.environment import BuildEnvironment from sphinx.environment.adapters.toctree import TocTreefrom sphinx.ext.autodoc import Documenterfrom sphinx.ext.autodoc import Documenter, INSTANCEATTR from sphinx.ext.autodoc.directive import DocumenterBridge, Options from sphinx.ext.autodoc.importer import import_module from sphinx.ext.autodoc.mock import mock


Question: Instance attributes are omitted with autosummary This issue is a followup of . Sorry, I forgot to open it. Is your feature request related to a problem? Please describe. Instance attributes are omitted when using the autosummary, as they cannot be imported. Consider the following class via will document the attribute, but via won't. Describe the solution you'd like Instance attributes should be documented, too Describe alternatives you've considered it did work before , i.e. for (although the documentation was omitted). Additional context files to reproduce the issue (including page build) Screenshot of !

return nodes <ins>    def import_by_name(self, name: str, prefixes: List[str]) -> Tuple[str, Any, Any, str]:        with mock(self.config.autosummary_mock_imports):            try:                return import_by_name(name, prefixes)            except ImportError as exc:                # check existence of instance attribute                try:                    return import_ivar_by_name(name, prefixes)                except ImportError:                    pass                raise exc  # re-raise ImportError if instance attribute not found</ins>     def get_items(self, names: List[str]) -> List[Tuple[str, str, str, str]]:         """Try to import the given names, and return a list of         ``[(name, signature, summary_string, real_name), ...]``.


Question: Instance attributes are omitted with autosummary This issue is a followup of . Sorry, I forgot to open it. Is your feature request related to a problem? Please describe. Instance attributes are omitted when using the autosummary, as they cannot be imported. Consider the following class via will document the attribute, but via won't. Describe the solution you'd like Instance attributes should be documented, too Describe alternatives you've considered it did work before , i.e. for (although the documentation was omitted). Additional context files to reproduce the issue (including page build) Screenshot of !

display_name = name.split('.')[-1]              try:                with mock(self.config.autosummary_mock_imports):                    real_name, obj, parent, modname = import_by_name(name, prefixes=prefixes)                real_name, obj, parent, modname = self.import_by_name(name, prefixes=prefixes)             except ImportError:                 logger.warning(__('autosummary: failed to import %s'), name,                                location=self.get_source_info())


Question: Instance attributes are omitted with autosummary This issue is a followup of . Sorry, I forgot to open it. Is your feature request related to a problem? Please describe. Instance attributes are omitted when using the autosummary, as they cannot be imported. Consider the following class via will document the attribute, but via won't. Describe the solution you'd like Instance attributes should be documented, too Describe alternatives you've considered it did work before , i.e. for (although the documentation was omitted). Additional context files to reproduce the issue (including page build) Screenshot of !

raise ImportError(*e.args) from e  def import_ivar_by_name(name: str, prefixes: List[str] = [None]) -> Tuple[str, Any, Any, str]:    """Import an instance variable that has the given *name*, under one of the    *prefixes*.  The first name that succeeds is used.    """    try:        name, attr = name.rsplit(".", 1)        real_name, obj, parent, modname = import_by_name(name, prefixes)        qualname = real_name.replace(modname + ".", "")        analyzer = ModuleAnalyzer.for_module(modname)        if (qualname, attr) in analyzer.find_attr_docs():            return real_name + "." + attr, INSTANCEATTR, obj, modname    except (ImportError, ValueError):        pass    raise ImportError # -- :autolink: (smart default role) -------------------------------------------  def autolink_role(typ: str, rawtext: str, etext: str, lineno: int, inliner: Inliner,diff --git a/sphinx/ext/autosummary/generate.py b/sphinx/ext/autosummary/generate.py-- a/sphinx/ext/autosummary/generate.py++ b/sphinx/ext/autosummary/generate.py


Question: Instance attributes are omitted with autosummary This issue is a followup of . Sorry, I forgot to open it. Is your feature request related to a problem? Please describe. Instance attributes are omitted when using the autosummary, as they cannot be imported. Consider the following class via will document the attribute, but via won't. Describe the solution you'd like Instance attributes should be documented, too Describe alternatives you've considered it did work before , i.e. for (although the documentation was omitted). Additional context files to reproduce the issue (including page build) Screenshot of !

from sphinx.config import Config from sphinx.deprecation import RemovedInSphinx40Warning, RemovedInSphinx50Warning from sphinx.ext.autodoc import Documenterfrom sphinx.ext.autosummary import import_by_name, get_documenterfrom sphinx.ext.autosummary import import_by_name, import_ivar_by_name, get_documenter from sphinx.locale import __ from sphinx.pycode import ModuleAnalyzer, PycodeError from sphinx.registry import SphinxComponentRegistry


Question: Instance attributes are omitted with autosummary This issue is a followup of . Sorry, I forgot to open it. Is your feature request related to a problem? Please describe. Instance attributes are omitted when using the autosummary, as they cannot be imported. Consider the following class via will document the attribute, but via won't. Describe the solution you'd like Instance attributes should be documented, too Describe alternatives you've considered it did work before , i.e. for (although the documentation was omitted). Additional context files to reproduce the issue (including page build) Screenshot of !

name, obj, parent, modname = import_by_name(entry.name)             qualname = name.replace(modname + ".", "")         except ImportError as e:            _warn(__('[autosummary] failed to import %r: %s') % (entry.name, e))            continue            try:                # try to importl as an instance attribute                name, obj, parent, modname = import_ivar_by_name(entry.name)                qualname = name.replace(modname + ".", "")            except ImportError:                _warn(__('[autosummary] failed to import %r: %s') % (entry.name, e))                continue          context = {}         if app:


Question: Support defining specific for autodoc Is your feature request related to a problem? Please describe. Currently, if I'm using autodoc, the option does not allow specification of which private members to document. The current behavior is to document all private members, but what if I would only like to document 1 or 2? Describe the solution you'd like For to take arguments, similarly to how currently works Describe alternatives you've considered The current best way to do this is to explicitly list each class in a module and use Some prior discussion:

def merge_special_members_option(options: Dict) -> None:     """Merge :special-members: option to :members: option."""<ins>    warnings.warn("merge_special_members_option() is deprecated.",                  RemovedInSphinx50Warning, stacklevel=2)</ins>     if 'special-members' in options and options['special-members'] is not ALL:         if options.get('members') is ALL:             pass


Question: Support defining specific for autodoc Is your feature request related to a problem? Please describe. Currently, if I'm using autodoc, the option does not allow specification of which private members to document. The current behavior is to document all private members, but what if I would only like to document 1 or 2? Describe the solution you'd like For to take arguments, similarly to how currently works Describe alternatives you've considered The current best way to do this is to explicitly list each class in a module and use Some prior discussion:

options['members'] = options['special-members']  <ins>def merge_members_option(options: Dict) -> None:    """Merge :*-members: option to the :members: option."""    if options.get('members') is ALL:        # merging is not needed when members: ALL        return    members = options.setdefault('members', [])    for key in {'private-members', 'special-members'}:        if key in options and options[key] is not ALL:            for member in options[key]:                if member not in members:                    members.append(member)</ins> # Some useful event listener factories for autodoc-process-docstring.  def cut_lines(pre: int, post: int = 0, what: str = None) -> Callable:


Question: Support defining specific for autodoc Is your feature request related to a problem? Please describe. Currently, if I'm using autodoc, the option does not allow specification of which private members to document. The current behavior is to document all private members, but what if I would only like to document 1 or 2? Describe the solution you'd like For to take arguments, similarly to how currently works Describe alternatives you've considered The current best way to do this is to explicitly list each class in a module and use Some prior discussion:

keep = has_doc or self.options.undoc_members             elif (namespace, membername) in attr_docs:                 if want_all and isprivate:                    # ignore members whose name starts with _ by default                    keep = self.options.private_members                    if self.options.private_members is None:                        keep = False                    elif self.options.private_members is ALL:                        keep = True                    else:                        keep = membername in self.options.private_members                 else:                     # keep documented attributes                     keep = True                 isattr = True             elif want_all and isprivate:                # ignore members whose name starts with _ by default                keep = self.options.private_members and \                    (has_doc or self.options.undoc_members)                if has_doc or self.options.undoc_members:                    if self.options.private_members is None:                        keep = False                    elif self.options.private_members is ALL:                        keep = True                    elif is_filtered_inherited_member(membername):                        keep = False                    else:                        keep = membername in self.options.private_members                else:                    keep = False             else:                 if self.options.members is ALL and is_filtered_inherited_member(membername):                     keep = False


Question: Support defining specific for autodoc Is your feature request related to a problem? Please describe. Currently, if I'm using autodoc, the option does not allow specification of which private members to document. The current behavior is to document all private members, but what if I would only like to document 1 or 2? Describe the solution you'd like For to take arguments, similarly to how currently works Describe alternatives you've considered The current best way to do this is to explicitly list each class in a module and use Some prior discussion:

'show-inheritance': bool_option, 'synopsis': identity,         'platform': identity, 'deprecated': bool_option,         'member-order': member_order_option, 'exclude-members': members_set_option,        'private-members': bool_option, 'special-members': members_option,        'private-members': members_option, 'special-members': members_option,         'imported-members': bool_option, 'ignore-module-all': bool_option     }  # type: Dict[str, Callable]      def __init__(self, *args: Any) -> None:         super().__init__(*args)        merge_special_members_option(self.options)        merge_members_option(self.options)         self.__all__ = None      @classmethod


Question: Support defining specific for autodoc Is your feature request related to a problem? Please describe. Currently, if I'm using autodoc, the option does not allow specification of which private members to document. The current behavior is to document all private members, but what if I would only like to document 1 or 2? Describe the solution you'd like For to take arguments, similarly to how currently works Describe alternatives you've considered The current best way to do this is to explicitly list each class in a module and use Some prior discussion:

'noindex': bool_option, 'inherited-members': inherited_members_option,         'show-inheritance': bool_option, 'member-order': member_order_option,         'exclude-members': members_set_option,        'private-members': bool_option, 'special-members': members_option,        'private-members': members_option, 'special-members': members_option,     }  # type: Dict[str, Callable]      _signature_class = None  # type: Any


Question: Support defining specific for autodoc Is your feature request related to a problem? Please describe. Currently, if I'm using autodoc, the option does not allow specification of which private members to document. The current behavior is to document all private members, but what if I would only like to document 1 or 2? Describe the solution you'd like For to take arguments, similarly to how currently works Describe alternatives you've considered The current best way to do this is to explicitly list each class in a module and use Some prior discussion:

def __init__(self, *args: Any) -> None:         super().__init__(*args)        merge_special_members_option(self.options)        merge_members_option(self.options)      @classmethod     def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: Any


Question: Error in template parameter list. Describe the bug I appear to have some valid C++14 syntax which causes Sphinx's C++ parser to choke. Here is the full error trace: To Reproduce Steps to reproduce the behavior: Expected behavior Build should succeed

# ==========================================================================     def _parse_template_parameter_list(self) -> ASTTemplateParams:        # only: '<' parameter-list '>'        # we assume that 'template' has just been parsed        templateParams = []  # type: List[ASTTemplateParam]        self.skip_ws()        if not self.skip_string("<"):            self.fail("Expected '<' after 'template'")        prevErrors = []        while 1:            self.skip_ws()            if self.skip_word('template'):                # declare a tenplate template parameter                nestedParams = self._parse_template_parameter_list()            else:                nestedParams = None            self.skip_ws()    def _parse_template_paramter(self) -> ASTTemplateParam:        if self.skip_word('template'):            # declare a tenplate template parameter            nestedParams = self._parse_template_parameter_list()        else:            nestedParams = None        pos = self.pos        try:            # Unconstrained type parameter or template type parameter             key = None            self.skip_ws()             if self.skip_word_and_ws('typename'):                 key = 'typename'             elif self.skip_word_and_ws('class'):


Question: Error in template parameter list. Describe the bug I appear to have some valid C++14 syntax which causes Sphinx's C++ parser to choke. Here is the full error trace: To Reproduce Steps to reproduce the behavior: Expected behavior Build should succeed

elif nestedParams:                 self.fail("Expected 'typename' or 'class' after "                           "template template parameter list.")            if key:                # declare a type or template type parameter                self.skip_ws()                parameterPack = self.skip_string('...')                self.skip_ws()                if self.match(identifier_re):                    identifier = ASTIdentifier(self.matched_text)                else:                    identifier = None                self.skip_ws()                if not parameterPack and self.skip_string('='):                    default = self._parse_type(named=False, outer=None)                else:                    default = None                data = ASTTemplateKeyParamPackIdDefault(key, identifier,                                                        parameterPack, default)                if nestedParams:                    # template type                    templateParams.append(                        ASTTemplateParamTemplateType(nestedParams, data))                else:                    # type                    templateParams.append(ASTTemplateParamType(data))             else:                # declare a non-type parameter, or constrained type parameter                pos = self.pos                try:                    param = self._parse_type_with_init('maybe', 'templateParam')                    templateParams.append(ASTTemplateParamNonType(param))                except DefinitionError as e:                    msg = "If non-type template parameter or constrained template parameter"                    prevErrors.append((e, msg))                    self.pos = pos                self.fail("Expected 'typename' or 'class' in tbe "                          "beginning of template type parameter.")            self.skip_ws()            parameterPack = self.skip_string('...')            self.skip_ws()            if self.match(identifier_re):                identifier = ASTIdentifier(self.matched_text)            else:                identifier = None            self.skip_ws()            if not parameterPack and self.skip_string('='):                default = self._parse_type(named=False, outer=None)            else:                default = None                if self.current_char not in ',>':                    self.fail('Expected "," or ">" after (template) type parameter.')            data = ASTTemplateKeyParamPackIdDefault(key, identifier,                                                    parameterPack, default)            if nestedParams:                return ASTTemplateParamTemplateType(nestedParams, data)            else:                return ASTTemplateParamType(data)        except DefinitionError as eType:            if nestedParams:                raise            try:                # non-type parameter or constrained type parameter                self.pos = pos                param = self._parse_type_with_init('maybe', 'templateParam')                return ASTTemplateParamNonType(param)            except DefinitionError as eNonType:                self.pos = pos                header = "Error when parsing template parameter."                errs = []                errs.append(                    (eType, "If unconstrained type parameter or template type parameter"))                errs.append(                    (eNonType, "If constrained type parameter or non-type parameter"))                raise self._make_multi_error(errs, header)    def _parse_template_parameter_list(self) -> ASTTemplateParams:        # only: '<' parameter-list '>'        # we assume that 'template' has just been parsed        templateParams = []  # type: List[ASTTemplateParam]        self.skip_ws()        if not self.skip_string("<"):            self.fail("Expected '<' after 'template'")        while 1:            pos = self.pos            err = None            try:                param = self._parse_template_paramter()                templateParams.append(param)            except DefinitionError as eParam:                self.pos = pos                err = eParam             self.skip_ws()             if self.skip_string('>'):                 return ASTTemplateParams(templateParams)             elif self.skip_string(','):                prevErrors = []                 continue             else:                 header = "Error in template parameter list."                errs = []                if err:                    errs.append((err, "If parameter"))                 try:                    self.fail('Expected "=", ",", or ">".')                    self.fail('Expected "," or ">".')                 except DefinitionError as e:                    prevErrors.append((e, ""))                raise self._make_multi_error(prevErrors, header)                    errs.append((e, "If no parameter"))                print(errs)                raise self._make_multi_error(errs, header)      def _parse_template_introduction(self) -> ASTTemplateIntroduction:         pos = self.pos


Question: Render error when combining multiple input parameters in docstring Describe the bug & Reproduce My team is writing a function in Python, which contains 3 inputs that are similar, so we want to put them in the same line in the docstring. As described in 4. Parameters in , this is possible if you write something like this: However, this produces: <img width="406" alt="" src="https://user-"Even worse, when "optional", the rendered HTML stays the same as the screenshot above, so there is no way to tell whether it is optional: Expected behavior Something like x1, x2 (arraylike, optional_) - Input arrays, description of x1, x2. Environment info OS: macOS 10.15.5 (19F101) Python version: 3.7.7 Sphinx version: 3.0.3. Extra tools: browser: Firefox 79.0a1 or Safari 13.1.1 Sphinx extensions:

_descs = self.__class__(_descs, self._config).lines()         return _name, _type, _descs     def _consume_fields(self, parse_type: bool = True, prefer_type: bool = False                        ) -> List[Tuple[str, str, List[str]]]:    def _consume_fields(self, parse_type: bool = True, prefer_type: bool = False,                        multiple: bool = False) -> List[Tuple[str, str, List[str]]]:         self._consume_empty()         fields = []         while not self._is_section_break():             _name, _type, _desc = self._consume_field(parse_type, prefer_type)            if _name or _type or _desc:            if multiple and _name:                for name in _name.split(","):                    fields.append((name.strip(), _type, _desc))            elif _name or _type or _desc:                 fields.append((_name, _type, _desc,))         return fields


Question: Render error when combining multiple input parameters in docstring Describe the bug & Reproduce My team is writing a function in Python, which contains 3 inputs that are similar, so we want to put them in the same line in the docstring. As described in 4. Parameters in , this is possible if you write something like this: However, this produces: <img width="406" alt="" src="https://user-"Even worse, when "optional", the rendered HTML stays the same as the screenshot above, so there is no way to tell whether it is optional: Expected behavior Something like x1, x2 (arraylike, optional_) - Input arrays, description of x1, x2. Environment info OS: macOS 10.15.5 (19F101) Python version: 3.7.7 Sphinx version: 3.0.3. Extra tools: browser: Firefox 79.0a1 or Safari 13.1.1 Sphinx extensions:

return self._format_fields(_('Other Parameters'), self._consume_fields())      def _parse_parameters_section(self, section: str) -> List[str]:        fields = self._consume_fields()         if self._config.napoleon_use_param:            # Allow to declare multiple parameters at once (ex: x, y: int)            fields = self._consume_fields(multiple=True)             return self._format_docutils_params(fields)         else:            fields = self._consume_fields()             return self._format_fields(_('Parameters'), fields)      def _parse_raises_section(self, section: str) -> List[str]:


Question: Allow more compaction in gettext builder The OKFN people manually merge all generated message catalogs into a single file for upload. {{{gettext_compact}}} should support that use case too. Bitbucket: Originally reported by: Robert Lehmann Originally created at: 2011-10-11T16:43:20.007

def setup(app: Sphinx) -> Dict[str, Any]:     app.add_builder(MessageCatalogBuilder)     app.add_config_value('gettext_compact', True, 'gettext')    app.add_config_value('gettext_compact', True, 'gettext', Any)     app.add_config_value('gettext_location', True, 'gettext')     app.add_config_value('gettext_uuid', False, 'gettext')     app.add_config_value('gettext_auto_build', True, 'env')diff --git a/sphinx/util/i18n.py b/sphinx/util/i18n.py-- a/sphinx/util/i18n.py++ b/sphinx/util/i18n.py


Question: Allow more compaction in gettext builder The OKFN people manually merge all generated message catalogs into a single file for upload. {{{gettext_compact}}} should support that use case too. Bitbucket: Originally reported by: Robert Lehmann Originally created at: 2011-10-11T16:43:20.007

from collections import namedtuple from datetime import datetime, timezone from os import pathfrom typing import Callable, Generator, List, Set, Tuplefrom typing import Callable, Generator, List, Set, Tuple, Union  import babel.dates from babel.messages.mofile import write_mo


Question: Allow more compaction in gettext builder The OKFN people manually merge all generated message catalogs into a single file for upload. {{{gettext_compact}}} should support that use case too. Bitbucket: Originally reported by: Robert Lehmann Originally created at: 2011-10-11T16:43:20.007

return ret  def docname_to_domain(docname: str, compation: bool) -> str:def docname_to_domain(docname: str, compation: Union[bool, str]) -> str:     """Convert docname to domain for catalogs."""    if isinstance(compation, str):        return compation     if compation:         return docname.split(SEP, 1)[0]     else:


Question: References to figures without captions: errors in both HTML and LaTeX Describe the bug Using figures without captions causes errors in both HTML (though these are properly reported when source is processed) and in LaTeX (they are not reported until LaTeX says there were undefined references). This was the test document, compiled with sphinx 2.2.2 from pypi; was to , the project was otherwise generated with sphinx-build with no other changes. It is attached here: and these are the results: warning: WARNING: undefined label: fig-sample-nocaption (if the link has no caption the label must precede a section header) is HTML output (the error highlighted corresponds to the warning mentioned above): ! is LaTeX (pdflatex) output: ! Expected behavior I expect to produce valid LaTeX input without undefined references; figures to be referencable in LaTeX (this could be an optional setting perhaps causing uncaptioned figured to produce only "Figure 4.1." caption); about figure not being captioned to be more meaningful -- I understand that non-numbered figure cannot be referenced via :ref: (as the label will not resolve to any text) but the warning is not pointing to how to fix the issue. Environment info OS: Ubuntu 18.04 LTS Python version: 3.6.8 Sphinx version: 2.2.2 Sphinx extensions: none Extra tools: pdflatex TeXLive

dangling_warnings = {         'term': 'term not in glossary: %(target)s',<del>        'ref':  'undefined label: %(target)s (if the link has no caption '                'the label must precede a section header)',</del>         'numref':  'undefined label: %(target)s',         'keyword': 'unknown keyword: %(target)s',         'doc': 'unknown document: %(target)s',


Question: References to figures without captions: errors in both HTML and LaTeX Describe the bug Using figures without captions causes errors in both HTML (though these are properly reported when source is processed) and in LaTeX (they are not reported until LaTeX says there were undefined references). This was the test document, compiled with sphinx 2.2.2 from pypi; was to , the project was otherwise generated with sphinx-build with no other changes. It is attached here: and these are the results: warning: WARNING: undefined label: fig-sample-nocaption (if the link has no caption the label must precede a section header) is HTML output (the error highlighted corresponds to the warning mentioned above): ! is LaTeX (pdflatex) output: ! Expected behavior I expect to produce valid LaTeX input without undefined references; figures to be referencable in LaTeX (this could be an optional setting perhaps causing uncaptioned figured to produce only "Figure 4.1." caption); about figure not being captioned to be more meaningful -- I understand that non-numbered figure cannot be referenced via :ref: (as the label will not resolve to any text) but the warning is not pointing to how to fix the issue. Environment info OS: Ubuntu 18.04 LTS Python version: 3.6.8 Sphinx version: 2.2.2 Sphinx extensions: none Extra tools: pdflatex TeXLive

RemovedInSphinx40Warning, stacklevel=2)  def warn_missing_reference(app: "Sphinx", domain: Domain, node: pending_xref) -> bool:    if domain.name != 'std' or node['reftype'] != 'ref':        return None    else:        target = node['reftarget']        if target not in domain.anonlabels:  # type: ignore            msg = __('undefined label: %s')        else:            msg = __('Failed to create a cross reference. A title or caption not found: %s')        logger.warning(msg % target, location=node, type='ref', subtype=node['reftype'])        return True def setup(app: "Sphinx") -> Dict[str, Any]:     app.add_domain(StandardDomain)    app.connect('warn-missing-reference', warn_missing_reference)      return {         'version': 'builtin',diff --git a/sphinx/events.py b/sphinx/events.py-- a/sphinx/events.py++ b/sphinx/events.py


Question: References to figures without captions: errors in both HTML and LaTeX Describe the bug Using figures without captions causes errors in both HTML (though these are properly reported when source is processed) and in LaTeX (they are not reported until LaTeX says there were undefined references). This was the test document, compiled with sphinx 2.2.2 from pypi; was to , the project was otherwise generated with sphinx-build with no other changes. It is attached here: and these are the results: warning: WARNING: undefined label: fig-sample-nocaption (if the link has no caption the label must precede a section header) is HTML output (the error highlighted corresponds to the warning mentioned above): ! is LaTeX (pdflatex) output: ! Expected behavior I expect to produce valid LaTeX input without undefined references; figures to be referencable in LaTeX (this could be an optional setting perhaps causing uncaptioned figured to produce only "Figure 4.1." caption); about figure not being captioned to be more meaningful -- I understand that non-numbered figure cannot be referenced via :ref: (as the label will not resolve to any text) but the warning is not pointing to how to fix the issue. Environment info OS: Ubuntu 18.04 LTS Python version: 3.6.8 Sphinx version: 2.2.2 Sphinx extensions: none Extra tools: pdflatex TeXLive

'doctree-read': 'the doctree before being pickled',     'env-merge-info': 'env, read docnames, other env instance',     'missing-reference': 'env, node, contnode',    'warn-missing-reference': 'domain, node',     'doctree-resolved': 'doctree, docname',     'env-updated': 'env',     'html-collect-pages': 'builder',diff --git a/sphinx/transforms/post_transforms/__init__.py b/sphinx/transforms/post_transforms/__init__.py-- a/sphinx/transforms/post_transforms/__init__.py++ b/sphinx/transforms/post_transforms/__init__.py


Question: References to figures without captions: errors in both HTML and LaTeX Describe the bug Using figures without captions causes errors in both HTML (though these are properly reported when source is processed) and in LaTeX (they are not reported until LaTeX says there were undefined references). This was the test document, compiled with sphinx 2.2.2 from pypi; was to , the project was otherwise generated with sphinx-build with no other changes. It is attached here: and these are the results: warning: WARNING: undefined label: fig-sample-nocaption (if the link has no caption the label must precede a section header) is HTML output (the error highlighted corresponds to the warning mentioned above): ! is LaTeX (pdflatex) output: ! Expected behavior I expect to produce valid LaTeX input without undefined references; figures to be referencable in LaTeX (this could be an optional setting perhaps causing uncaptioned figured to produce only "Figure 4.1." caption); about figure not being captioned to be more meaningful -- I understand that non-numbered figure cannot be referenced via :ref: (as the label will not resolve to any text) but the warning is not pointing to how to fix the issue. Environment info OS: Ubuntu 18.04 LTS Python version: 3.6.8 Sphinx version: 2.2.2 Sphinx extensions: none Extra tools: pdflatex TeXLive

warn = False         if not warn:             return        if domain and typ in domain.dangling_warnings:        if self.app.emit_firstresult('warn-missing-reference', domain, node):            return        elif domain and typ in domain.dangling_warnings:             msg = domain.dangling_warnings[typ]         elif node.get('refdomain', 'std') not in ('', 'std'):             msg = (__('%s:%s reference target not found: %%(target)s') %


Question: Warning: Inline literal start-string without end-string in Numpy style Parameters section Describe the bug The following docstring generates a warning on the line of the timeout parameter. Removing the quote around cause the warning to go away. To Reproduce Steps to reproduce the behavior: Expected behavior I do not expect to see a warning there and was not seeing any before 3.2 Your project The project is build under the Documentation build action. Environment info OS: Mac Os and Linux Python version: 3.8.2 and 3.8.5 Sphinx version: 3.2.0 Sphinx extensions: "", "","", "", "", "", ""

napoleon_use_param = True         napoleon_use_rtype = True         napoleon_use_keyword = True<ins>        napoleon_preprocess_types = False</ins>         napoleon_type_aliases = None         napoleon_custom_sections = None


Question: Warning: Inline literal start-string without end-string in Numpy style Parameters section Describe the bug The following docstring generates a warning on the line of the timeout parameter. Removing the quote around cause the warning to go away. To Reproduce Steps to reproduce the behavior: Expected behavior I do not expect to see a warning there and was not seeing any before 3.2 Your project The project is build under the Documentation build action. Environment info OS: Mac Os and Linux Python version: 3.8.2 and 3.8.5 Sphinx version: 3.2.0 Sphinx extensions: "", "","", "", "", "", ""

:returns: *bool* -- True if successful, False otherwise     napoleon_preprocess_types : :obj:`bool` (Defaults to False)        Enable the type preprocessor for numpy style docstrings.     napoleon_type_aliases : :obj:`dict` (Defaults to None)         Add a mapping of strings to string, translating types in numpy        style docstrings.        style docstrings. Only works if ``napoleon_preprocess_types = True``.      napoleon_custom_sections : :obj:`list` (Defaults to None)         Add a list of custom sections to include, expanding the list of parsed sections.


Question: Warning: Inline literal start-string without end-string in Numpy style Parameters section Describe the bug The following docstring generates a warning on the line of the timeout parameter. Removing the quote around cause the warning to go away. To Reproduce Steps to reproduce the behavior: Expected behavior I do not expect to see a warning there and was not seeing any before 3.2 Your project The project is build under the Documentation build action. Environment info OS: Mac Os and Linux Python version: 3.8.2 and 3.8.5 Sphinx version: 3.2.0 Sphinx extensions: "", "","", "", "", "", ""

'napoleon_use_param': (True, 'env'),         'napoleon_use_rtype': (True, 'env'),         'napoleon_use_keyword': (True, 'env'),        'napoleon_preprocess_types': (False, 'env'),         'napoleon_type_aliases': (None, 'env'),         'napoleon_custom_sections': (None, 'env')     }diff --git a/sphinx/ext/napoleon/docstring.py b/sphinx/ext/napoleon/docstring.py-- a/sphinx/ext/napoleon/docstring.py++ b/sphinx/ext/napoleon/docstring.py


Question: Warning: Inline literal start-string without end-string in Numpy style Parameters section Describe the bug The following docstring generates a warning on the line of the timeout parameter. Removing the quote around cause the warning to go away. To Reproduce Steps to reproduce the behavior: Expected behavior I do not expect to see a warning there and was not seeing any before 3.2 Your project The project is build under the Documentation build action. Environment info OS: Mac Os and Linux Python version: 3.8.2 and 3.8.5 Sphinx version: 3.2.0 Sphinx extensions: "", "","", "", "", "", ""

_name, _type = line, ''         _name, _type = _name.strip(), _type.strip()         _name = self._escape_args_and_kwargs(_name)        _type = _convert_numpy_type_spec(            _type,            location=self._get_location(),            translations=self._config.napoleon_type_aliases or {},        )        if self._config.napoleon_preprocess_types:            _type = _convert_numpy_type_spec(                _type,                location=self._get_location(),                translations=self._config.napoleon_type_aliases or {},            )          if prefer_type and not _type:             _type, _name = _name, _type


Question: locale/ translation ignored Describe the bug I read [1] as it should be possible to add a file ) and through that change translations or add additional translation to <language. When I add. [1] [2] To Reproduce Steps to reproduce the behavior: Notice that . Expected behavior The caption label for the figure (again for the sake of testing). Your project Screenshots ! Environment info OS: Arch Linux Python version: 3.7.3 Sphinx version: 2.1.2 Sphinx extensions: none Extra tools: none

from collections import deque from io import StringIO from os import pathfrom typing import Any, Callable, Dict, IO, List, Tuple, Unionfrom typing import Any, Callable, Dict, IO, List, Optional, Tuple, Union  from docutils import nodes from docutils.nodes import Element, TextElement


Question: locale/ translation ignored Describe the bug I read [1] as it should be possible to add a file ) and through that change translations or add additional translation to <language. When I add. [1] [2] To Reproduce Steps to reproduce the behavior: Notice that . Expected behavior The caption label for the figure (again for the sake of testing). Your project Screenshots ! Environment info OS: Arch Linux Python version: 3.7.3 Sphinx version: 2.1.2 Sphinx extensions: none Extra tools: none

if catalog.domain == 'sphinx' and catalog.is_outdated():                     catalog.write_mo(self.config.language)             locale_dirs = [None, path.join(package_dir, 'locale')] + list(repo.locale_dirs)            locale_dirs = [None]  # type: List[Optional[str]]            locale_dirs += list(repo.locale_dirs)            locale_dirs += [path.join(package_dir, 'locale')]             self.translator, has_translation = locale.init(locale_dirs, self.config.language)             if has_translation or self.config.language == 'en':                 # "en" never needs to be translateddiff --git a/sphinx/locale/__init__.py b/sphinx/locale/__init__.py-- a/sphinx/locale/__init__.py++ b/sphinx/locale/__init__.py


Question: locale/ translation ignored Describe the bug I read [1] as it should be possible to add a file ) and through that change translations or add additional translation to <language. When I add. [1] [2] To Reproduce Steps to reproduce the behavior: Notice that . Expected behavior The caption label for the figure (again for the sake of testing). Your project Screenshots ! Environment info OS: Arch Linux Python version: 3.7.3 Sphinx version: 2.1.2 Sphinx extensions: none Extra tools: none

translators = defaultdict(NullTranslations)  # type: Dict[Tuple[str, str], NullTranslations]  def init(locale_dirs: List[str], language: str,def init(locale_dirs: List[Optional[str]], language: str,          catalog: str = 'sphinx', namespace: str = 'general') -> Tuple[NullTranslations, bool]:     """Look for message catalogs in `locale_dirs` and *ensure* that there is at     least a NullTranslations catalog set in `translators`. If called multiple


Question: All identifiers should be passed to autodoc-skip-member, even if not in all Is your feature request related to a problem? Please describe. I have a Python project for which I've generated docs. It did well. Almost everything was doc'ed. I knew about the default of excluding anything starting with '_' so I created an autodoc-skip-member function that would include those. It works. I see a bunch of private methods and functions included. But...I have a module, let's call it XYZ that has both private and public functions. Sphinx is only doc'ing the public functions of XYZ, but not its private functions. I have other modules that have private functions, and it's doc'ing those .I a print() to the autodoc-skip-member function and it doesn't even print out the of those private functions so it seems it's not even seeing it. I figured it out. The module had certain identifiers listed in , and was not passing anything else in that module to autodoc-skip-member. Describe the solution you'd like Sphinx should pass through all members, not just the ones in . Maybe add something to the object that is passed to autodoc-skip-members that indicates it would have been excluded by the designator, or some such. Describe alternatives you've considered I simply removed the from the file.

return None  <ins>class ObjectMember(tuple):    """A member of object.    This is used for the result of `Documenter.get_object_members()` to    represent each member of the object.    .. Note::       An instance of this class behaves as a tuple of (name, object)       for compatibility to old Sphinx.  The behavior will be dropped       in the future.  Therefore extensions should not use the tuple       interface.    """    def __new__(cls, name: str, obj: Any, **kwargs: Any) -> Any:        return super().__new__(cls, (name, obj))  # type: ignore    def __init__(self, name: str, obj: Any, skipped: bool = False) -> None:        self.__name__ = name        self.object = obj        self.skipped = skippedObjectMembers = Union[List[ObjectMember], List[Tuple[str, Any]]]</ins> class Documenter:     """     A Documenter knows how to autodocument a single object type.  When


Question: All identifiers should be passed to autodoc-skip-member, even if not in all Is your feature request related to a problem? Please describe. I have a Python project for which I've generated docs. It did well. Almost everything was doc'ed. I knew about the default of excluding anything starting with '_' so I created an autodoc-skip-member function that would include those. It works. I see a bunch of private methods and functions included. But...I have a module, let's call it XYZ that has both private and public functions. Sphinx is only doc'ing the public functions of XYZ, but not its private functions. I have other modules that have private functions, and it's doc'ing those .I a print() to the autodoc-skip-member function and it doesn't even print out the of those private functions so it seems it's not even seeing it. I figured it out. The module had certain identifiers listed in , and was not passing anything else in that module to autodoc-skip-member. Describe the solution you'd like Sphinx should pass through all members, not just the ones in . Maybe add something to the object that is passed to autodoc-skip-members that indicates it would have been excluded by the designator, or some such. Describe alternatives you've considered I simply removed the from the file.

for line, src in zip(more_content.data, more_content.items):                 self.add_line(line, src[0], src[1])     def get_object_members(self, want_all: bool) -> Tuple[bool, List[Tuple[str, Any]]]:    def get_object_members(self, want_all: bool) -> Tuple[bool, ObjectMembers]:         """Return `(members_check_module, members)` where `members` is a         list of `(membername, member)` pairs of the members of *self.object*.


Question: All identifiers should be passed to autodoc-skip-member, even if not in all Is your feature request related to a problem? Please describe. I have a Python project for which I've generated docs. It did well. Almost everything was doc'ed. I knew about the default of excluding anything starting with '_' so I created an autodoc-skip-member function that would include those. It works. I see a bunch of private methods and functions included. But...I have a module, let's call it XYZ that has both private and public functions. Sphinx is only doc'ing the public functions of XYZ, but not its private functions. I have other modules that have private functions, and it's doc'ing those .I a print() to the autodoc-skip-member function and it doesn't even print out the of those private functions so it seems it's not even seeing it. I figured it out. The module had certain identifiers listed in , and was not passing anything else in that module to autodoc-skip-member. Describe the solution you'd like Sphinx should pass through all members, not just the ones in . Maybe add something to the object that is passed to autodoc-skip-members that indicates it would have been excluded by the designator, or some such. Describe alternatives you've considered I simply removed the from the file.

members = get_object_members(self.object, self.objpath, self.get_attr, self.analyzer)         if not want_all:             if not self.options.members:                return False, []                return False, []  # type: ignore             # specific members given             selected = []            for name in self.options.members:            for name in self.options.members:  # type: str                 if name in members:                     selected.append((name, members[name].value))                 else:


Question: All identifiers should be passed to autodoc-skip-member, even if not in all Is your feature request related to a problem? Please describe. I have a Python project for which I've generated docs. It did well. Almost everything was doc'ed. I knew about the default of excluding anything starting with '_' so I created an autodoc-skip-member function that would include those. It works. I see a bunch of private methods and functions included. But...I have a module, let's call it XYZ that has both private and public functions. Sphinx is only doc'ing the public functions of XYZ, but not its private functions. I have other modules that have private functions, and it's doc'ing those .I a print() to the autodoc-skip-member function and it doesn't even print out the of those private functions so it seems it's not even seeing it. I figured it out. The module had certain identifiers listed in , and was not passing anything else in that module to autodoc-skip-member. Describe the solution you'd like Sphinx should pass through all members, not just the ones in . Maybe add something to the object that is passed to autodoc-skip-members that indicates it would have been excluded by the designator, or some such. Describe alternatives you've considered I simply removed the from the file.

return False, [(m.name, m.value) for m in members.values()                            if m.directly_defined]     def filter_members(self, members: List[Tuple[str, Any]], want_all: bool    def filter_members(self, members: ObjectMembers, want_all: bool                        ) -> List[Tuple[str, Any, bool]]:         """Filter the given member list.


Question: All identifiers should be passed to autodoc-skip-member, even if not in all Is your feature request related to a problem? Please describe. I have a Python project for which I've generated docs. It did well. Almost everything was doc'ed. I knew about the default of excluding anything starting with '_' so I created an autodoc-skip-member function that would include those. It works. I see a bunch of private methods and functions included. But...I have a module, let's call it XYZ that has both private and public functions. Sphinx is only doc'ing the public functions of XYZ, but not its private functions. I have other modules that have private functions, and it's doc'ing those .I a print() to the autodoc-skip-member function and it doesn't even print out the of those private functions so it seems it's not even seeing it. I figured it out. The module had certain identifiers listed in , and was not passing anything else in that module to autodoc-skip-member. Describe the solution you'd like Sphinx should pass through all members, not just the ones in . Maybe add something to the object that is passed to autodoc-skip-members that indicates it would have been excluded by the designator, or some such. Describe alternatives you've considered I simply removed the from the file.

attr_docs = {}          # process members and determine which to skip        for (membername, member) in members:        for obj in members:            membername, member = obj             # if isattr is True, the member is documented as an attribute             if member is INSTANCEATTR:                 isattr = True


Question: All identifiers should be passed to autodoc-skip-member, even if not in all Is your feature request related to a problem? Please describe. I have a Python project for which I've generated docs. It did well. Almost everything was doc'ed. I knew about the default of excluding anything starting with '_' so I created an autodoc-skip-member function that would include those. It works. I see a bunch of private methods and functions included. But...I have a module, let's call it XYZ that has both private and public functions. Sphinx is only doc'ing the public functions of XYZ, but not its private functions. I have other modules that have private functions, and it's doc'ing those .I a print() to the autodoc-skip-member function and it doesn't even print out the of those private functions so it seems it's not even seeing it. I figured it out. The module had certain identifiers listed in , and was not passing anything else in that module to autodoc-skip-member. Describe the solution you'd like Sphinx should pass through all members, not just the ones in . Maybe add something to the object that is passed to autodoc-skip-members that indicates it would have been excluded by the designator, or some such. Describe alternatives you've considered I simply removed the from the file.

# ignore undocumented members if :undoc-members: is not given                     keep = has_doc or self.options.undoc_members <ins>            if isinstance(obj, ObjectMember) and obj.skipped:                # forcedly skipped member (ex. a module attribute not defined in __all__)                keep = False</ins>             # give the user a chance to decide whether this member             # should be skipped             if self.env.app:


Question: All identifiers should be passed to autodoc-skip-member, even if not in all Is your feature request related to a problem? Please describe. I have a Python project for which I've generated docs. It did well. Almost everything was doc'ed. I knew about the default of excluding anything starting with '_' so I created an autodoc-skip-member function that would include those. It works. I see a bunch of private methods and functions included. But...I have a module, let's call it XYZ that has both private and public functions. Sphinx is only doc'ing the public functions of XYZ, but not its private functions. I have other modules that have private functions, and it's doc'ing those .I a print() to the autodoc-skip-member function and it doesn't even print out the of those private functions so it seems it's not even seeing it. I figured it out. The module had certain identifiers listed in , and was not passing anything else in that module to autodoc-skip-member. Describe the solution you'd like Sphinx should pass through all members, not just the ones in . Maybe add something to the object that is passed to autodoc-skip-members that indicates it would have been excluded by the designator, or some such. Describe alternatives you've considered I simply removed the from the file.

if self.options.deprecated:             self.add_line('   :deprecated:', sourcename)     def get_object_members(self, want_all: bool) -> Tuple[bool, List[Tuple[str, Any]]]:    def get_object_members(self, want_all: bool) -> Tuple[bool, ObjectMembers]:         if want_all:            if self.__all__:                memberlist = self.__all__            else:            members = get_module_members(self.object)            if not self.__all__:                 # for implicit module members, check __module__ to avoid                 # documenting imported objects                return True, get_module_members(self.object)                return True, members            else:                ret = []                for name, value in members:                    if name in self.__all__:                        ret.append(ObjectMember(name, value))                    else:                        ret.append(ObjectMember(name, value, skipped=True))                return False, ret         else:             memberlist = self.options.members or []        ret = []        for mname in memberlist:            try:                ret.append((mname, safe_getattr(self.object, mname)))            except AttributeError:                logger.warning(                    __('missing attribute mentioned in :members: or __all__: '                       'module %s, attribute %s') %                    (safe_getattr(self.object, '__name__', '???'), mname),                    type='autodoc'                )        return False, ret            ret = []            for name in memberlist:                try:                    value = safe_getattr(self.object, name)                    ret.append(ObjectMember(name, value))                except AttributeError:                    logger.warning(__('missing attribute mentioned in :members: option: '                                      'module %s, attribute %s') %                                   (safe_getattr(self.object, '__name__', '???'), name),                                   type='autodoc')            return False, ret      def sort_members(self, documenters: List[Tuple["Documenter", bool]],                      order: str) -> List[Tuple["Documenter", bool]]:


Question: Problems with doc comments using Generic class and extending it Describe the bug This is a very specific bug (I think), when we have a class with doc comment for an attribute and I extend it. If the child class has the method (using typed parameters) and I try to reassign the attribute from class I got the following error: To Reproduce Steps to reproduce the behavior: Code example: Python script rst If you try to modify something in the script maybe the error will not appear, it's a very specific corner case! Expected behavior The warning should not appear! Your project Environment info OS: Linux 5.7.9-1-MANJARO Python version: 3.8.3 Sphinx version: 3.1.1 Sphinx extensions: related issue

self.env.app.emit('autodoc-process-docstring',                                   self.objtype, self.fullname, self.object,                                   self.options, docstringlines)<ins>                if docstringlines and docstringlines[-1] != '':                    # append a blank line to the end of the docstring                    docstringlines.append('')</ins>             yield from docstringlines      def get_sourcename(self) -> str:


Question: TypeError: 'type' object is not iterable Hi All, this is the first time I try to create a documentation using Sphinx. venv is a virutal environment created with miniconda. Using the Miniconda3 prompt, I activated the environment and tried to create the documentation. As suggested in the error, please find below the error log. Thanks a lot for your help! PS: for privacy, I hide my absolute path calling it PATH.

return repr(annotation)      if getattr(annotation, '__args__', None):        if qualname == 'Union':        if not isinstance(annotation.__args__, (list, tuple)):            # broken __args__ found            pass        elif qualname == 'Union':             if len(annotation.__args__) > 1 and annotation.__args__[-1] is NoneType:                 if len(annotation.__args__) > 2:                     args = ', '.join(stringify(a) for a in annotation.__args__[:-1])


Question: docstring default arg is broken Describe the bug docstring default arg is broken in html. Python class method is rendered as To Reproduce Steps to reproduce the behavior (Dockerfile): Expected behavior A clear and concise description of what you expected to happen. Python class method is rendered as Your project Link to your sphinx project, or attach zipped small project sample. Screenshots If applicable, add screenshots to help explain your problem. ! Environment info OS: [e.g. Unix/Linux/Mac/Win/other with version] Linux Python version: [e.g. 3.7.1] 3.7 Sphinx version: [e.g. 1.8.2] sphinx-build 3.1.1 Sphinx extensions: [e.g. , recommonmark] Extra tools: [e.g. Browser, tex or something else] None Additional context Add any other context about the problem here. [e.g. URL or Ticket] None

return "{" + ", ".join(self.visit(e) for e in node.elts) + "}"      def visit_Subscript(self, node: ast.Subscript) -> str:        return "%s[%s]" % (self.visit(node.value), self.visit(node.slice))        def is_simple_tuple(value: ast.AST) -> bool:            return (                isinstance(value, ast.Tuple) and                bool(value.elts) and                not any(isinstance(elt, ast.Starred) for elt in value.elts)            )        if is_simple_tuple(node.slice):            elts = ", ".join(self.visit(e) for e in node.slice.elts)  # type: ignore            return "%s[%s]" % (self.visit(node.value), elts)        elif isinstance(node.slice, ast.Index) and is_simple_tuple(node.slice.value):            elts = ", ".join(self.visit(e) for e in node.slice.value.elts)  # type: ignore            return "%s[%s]" % (self.visit(node.value), elts)        else:            return "%s[%s]" % (self.visit(node.value), self.visit(node.slice))      def visit_UnaryOp(self, node: ast.UnaryOp) -> str:         return "%s %s" % (self.visit(node.op), self.visit(node.operand))      def visit_Tuple(self, node: ast.Tuple) -> str:         if node.elts:            return ", ".join(self.visit(e) for e in node.elts)            return "(" + ", ".join(self.visit(e) for e in node.elts) + ")"         else:             return "()"


Question: Linkcheck should report HTTP errors instead of Anchor not found Describe the bug The command always reports that it was unable to find the anchor when  is , even when the server replied with an error status code (e.g. 404, 500). While it is indeed unable to find the anchor, the real issue is that the server encountered an error. To Reproduce Expected behavior Actual Expected output Same as when . Environment info OS: Linux 5.8.12.a-1-hardened Python version: 3.8.5 Sphinx version: 3.2.1

# Read the whole document and see if #anchor exists                     response = requests.get(req_url, stream=True, config=self.app.config,                                             auth=auth_info, **kwargs)<ins>                    response.raise_for_status()</ins>                     found = check_anchor(response, unquote(anchor))                      if not found:


Question: Generate man page section directories Current man page generation does not conform to search functionality Currently, all generated man pages are placed in to a single-level directory: . Unfortunately, this cannot be used in combination with the unix environment variable. The program explicitly looks for man pages in section directories (such as , etc.). Describe the solution you'd like It would be great if sphinx would automatically create the section directories (e.g., , , etc.) and place each generated man page within appropriate section. Describe alternatives you've considered This problem can be over come within our project’s build system, ensuring the built man pages are installed in a correct location, but it would be nice if the build directory had the proper layout. I’m happy to take a crack at implementing a fix, though this change in behavior may break some people who expect everything to appear in a directory.

from sphinx.util import progress_message from sphinx.util.console import darkgreen  # type: ignore from sphinx.util.nodes import inline_all_toctreesfrom sphinx.util.osutil import make_filename_from_projectfrom sphinx.util.osutil import ensuredir, make_filename_from_project from sphinx.writers.manpage import ManualPageWriter, ManualPageTranslator


Question: Generate man page section directories Current man page generation does not conform to search functionality Currently, all generated man pages are placed in to a single-level directory: . Unfortunately, this cannot be used in combination with the unix environment variable. The program explicitly looks for man pages in section directories (such as , etc.). Describe the solution you'd like It would be great if sphinx would automatically create the section directories (e.g., , , etc.) and place each generated man page within appropriate section. Describe alternatives you've considered This problem can be over come within our project’s build system, ensuring the built man pages are installed in a correct location, but it would be nice if the build directory had the proper layout. I’m happy to take a crack at implementing a fix, though this change in behavior may break some people who expect everything to appear in a directory.

docsettings.authors = authors             docsettings.section = section             targetname = '%s.%s' % (name, section)            if self.config.man_make_section_directory:                ensuredir(path.join(self.outdir, str(section)))                targetname = '%s/%s.%s' % (section, name, section)            else:                targetname = '%s.%s' % (name, section)             logger.info(darkgreen(targetname) + ' { ', nonl=True)             destination = FileOutput(                 destination_path=path.join(self.outdir, targetname),


Question: Generate man page section directories Current man page generation does not conform to search functionality Currently, all generated man pages are placed in to a single-level directory: . Unfortunately, this cannot be used in combination with the unix environment variable. The program explicitly looks for man pages in section directories (such as , etc.). Describe the solution you'd like It would be great if sphinx would automatically create the section directories (e.g., , , etc.) and place each generated man page within appropriate section. Describe alternatives you've considered This problem can be over come within our project’s build system, ensuring the built man pages are installed in a correct location, but it would be nice if the build directory had the proper layout. I’m happy to take a crack at implementing a fix, though this change in behavior may break some people who expect everything to appear in a directory.

app.add_config_value('man_pages', default_man_pages, None)     app.add_config_value('man_show_urls', False, None)<ins>    app.add_config_value('man_make_section_directory', False, None)</ins>      return {         'version': 'builtin',


Question: Sphinx changes number system from hexadecimal to decimal for function default arguments Describe the bug When documenting a function, which requires a default argument specified in hexadecimal: Sphinx 3.2.1 will render HTML documentation where the hexadecimal value is in a different number system, than what was specified by the user (decimal), as seen in the following output from the above input: ! Expected behavior The expected behaviour would be to present the default argument in the same radix/number system as the user typed in, thus in this case the documentation would also display the value in hexadecimal. In the above example of with colors, it is unintuitive what the color might refer to, but it's easy read RGB colors in hexadecimal format - e.g. 0xffffff is white, thus which number system is used can make a huge difference. The same for example goes for e.g. specifying access rights for files () Screenshots ! Environment info OS: Mac OS X 10.14.6 Python version: 3.8.5 Sphinx version: 3.2.1 Sphinx extensions: None Extra tools: None

return ast.parse(code, mode=mode)  def unparse(node: Optional[ast.AST]) -> Optional[str]:def unparse(node: Optional[ast.AST], code: str = '') -> Optional[str]:     """Unparse an AST to string."""     if node is None:         return None     elif isinstance(node, str):         return node    return _UnparseVisitor().visit(node)    return _UnparseVisitor(code).visit(node)   # a greatly cut-down version of `ast._Unparser` class _UnparseVisitor(ast.NodeVisitor):    def __init__(self, code: str = '') -> None:        self.code = code      def _visit_op(self, node: ast.AST) -> str:         return OPERATORS[node.__class__]


Question: Sphinx changes number system from hexadecimal to decimal for function default arguments Describe the bug When documenting a function, which requires a default argument specified in hexadecimal: Sphinx 3.2.1 will render HTML documentation where the hexadecimal value is in a different number system, than what was specified by the user (decimal), as seen in the following output from the above input: ! Expected behavior The expected behaviour would be to present the default argument in the same radix/number system as the user typed in, thus in this case the documentation would also display the value in hexadecimal. In the above example of with colors, it is unintuitive what the color might refer to, but it's easy read RGB colors in hexadecimal format - e.g. 0xffffff is white, thus which number system is used can make a huge difference. The same for example goes for e.g. specifying access rights for files () Screenshots ! Environment info OS: Mac OS X 10.14.6 Python version: 3.8.5 Sphinx version: 3.2.1 Sphinx extensions: None Extra tools: None

def visit_Constant(self, node: ast.Constant) -> str:             if node.value is Ellipsis:                 return "..."            elif isinstance(node.value, (int, float, complex)):                if self.code and sys.version_info > (3, 8):                    return ast.get_source_segment(self.code, node)                else:                    return repr(node.value)             else:                 return repr(node.value) diff --git a/sphinx/util/inspect.py b/sphinx/util/inspect.py-- a/sphinx/util/inspect.py++ b/sphinx/util/inspect.py


Question: Sphinx changes number system from hexadecimal to decimal for function default arguments Describe the bug When documenting a function, which requires a default argument specified in hexadecimal: Sphinx 3.2.1 will render HTML documentation where the hexadecimal value is in a different number system, than what was specified by the user (decimal), as seen in the following output from the above input: ! Expected behavior The expected behaviour would be to present the default argument in the same radix/number system as the user typed in, thus in this case the documentation would also display the value in hexadecimal. In the above example of with colors, it is unintuitive what the color might refer to, but it's easy read RGB colors in hexadecimal format - e.g. 0xffffff is white, thus which number system is used can make a huge difference. The same for example goes for e.g. specifying access rights for files () Screenshots ! Environment info OS: Mac OS X 10.14.6 Python version: 3.8.5 Sphinx version: 3.2.1 Sphinx extensions: None Extra tools: None

def signature_from_str(signature: str) -> inspect.Signature:     """Create a Signature object from string."""    module = ast.parse('def func' + signature + ': pass')    code = 'def func' + signature + ': pass'    module = ast.parse(code)     function = cast(ast.FunctionDef, module.body[0])  # type: ignore     return signature_from_ast(function)    return signature_from_ast(function, code)  def signature_from_ast(node: ast.FunctionDef) -> inspect.Signature:def signature_from_ast(node: ast.FunctionDef, code: str = '') -> inspect.Signature:     """Create a Signature object from AST *node*."""     args = node.args     defaults = list(args.defaults)