Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sphinx references to other sections containing section number and section title

I am using Sphinx to write a document with lots of references:

.. _human-factor:

The Human Factor
================

...

(see :ref:`human-factor` for details)

The compiled document contains something like this:

(see The Human Factor for details)

Instead I would like to have it formatted like this:

(see 5.1 The Human Factor for details)

I tried to google the solution and I found out that the latex hyperref package can do this but I have no idea how to add this to the Sphinx build.

like image 337
moin moin Avatar asked Dec 12 '12 20:12

moin moin


1 Answers

I resolved it by basically using numsec.py from here: https://github.com/jterrace/sphinxtr

I had to replace the doctree_resolved function with this one to get section number + title (e.g. "5.1 The Human Factor").

def doctree_resolved(app, doctree, docname):
    secnums = app.builder.env.toc_secnumbers
    for node in doctree.traverse(nodes.reference):
        if 'refdocname' in node:
            refdocname = node['refdocname']
            if refdocname in secnums:
                secnum = secnums[refdocname]
                emphnode = node.children[0]
                textnode = emphnode.children[0]

                toclist = app.builder.env.tocs[refdocname]
                anchorname = None
                for refnode in toclist.traverse(nodes.reference):
                    if refnode.astext() == textnode.astext():
                        anchorname = refnode['anchorname']
                if anchorname is None:
                    continue
                linktext = '.'.join(map(str, secnum[anchorname]))
                node.replace(emphnode, nodes.Text(linktext
                    + ' ' + textnode))

To make it work one needs to include the numsec extension in conf.py and also to add :numbered: in the toctree like so:

.. toctree::
   :maxdepth: 1
   :numbered:
like image 69
moin moin Avatar answered Sep 20 '22 06:09

moin moin