pythonrestructuredtextdocutils

Specifying anchor names in reST


I'm creating HTML from reST using the rst2html tool which comes with docutils. It seems that the code already assigns id attributes to the individual sections, which can be used as fragment identifiers in a URL, i.e. as anchors to jump to a specific part of the page. Those id values are based on the text of the section headline. When I change the wording of that headline, the identifier will change as well, rendering old URLs invalid.

Is there a way to specify the name to use as an identifier for a given section, so that I can edit the headline without invalidating links? Would there be a way if I were to call the docutils publisher myself, from my own script?


Solution

  • I don't think you can set an explicit id in reST sections, but I could be mistaken.

    If you'd rather have numbered ids, which will depend on the ordering of the sections in the document tree, rather than their titles, you can do it with a small change to document.set_id() method in docutils/nodes.py (at line 997 on my version.)

    Here is the patch:

     def set_id(self, node, msgnode=None):
         for id in node['ids']:
             if id in self.ids and self.ids[id] is not node:
                 msg = self.reporter.severe('Duplicate ID: "%s".' % id)
                 if msgnode != None:
                     msgnode += msg
         if not node['ids']:
    -        for name in node['names']:
    -            id = self.settings.id_prefix + make_id(name)
    -            if id and id not in self.ids:
    -                break
    -        else:
    +        if True: #forcing numeric ids
                 id = ''
                 while not id or id in self.ids:
                     id = (self.settings.id_prefix +
                           self.settings.auto_id_prefix + str(self.id_start))
                     self.id_start += 1
             node['ids'].append(id)
         self.ids[id] = node
         return id
    

    I just tested it and it generates the section ids as id1, id2...

    If you don't want to change this system-wide file, you can probably monkey-patch it from a custom rst2html command.