Footnotes in ReST

Peter Otten __peter__ at web.de
Sun Oct 4 05:50:24 EDT 2015


Blake Garretson wrote:

> On Oct 3, 2015 7:40 AM, "Steven D'Aprano" <steve at pearwood.info> wrote:
>> I need to add a footnote between [2] and [3], but I don't want to have to
>> renumber the following 997 footnotes by hand. Is there something I can
>> do, within the syntax of ReST itself, to help?
> 
> I would use a regular expression to find and replace all the numbers with
> the auto-numbering feature.  So something like "\[\d+\]_" should be
> replaced with "\[#\]_".

With labeled autonumbers:

>>> text = """\
...     blah blah blah [1]_ and blah blah blah [2]_.
...     blah blah [3]_ blah ... blah blah
...     blah blah [999]_.
... 
...     .. [1] fe
...     .. [2] fi
...     .. [3] fo
...        ...
...     .. [999] fum
... """
>>> print(re.compile(r"\[(\d+)\]").sub(r"[#n\1]", text))
    blah blah blah [#n1]_ and blah blah blah [#n2]_.
    blah blah [#n3]_ blah ... blah blah
    blah blah [#n999]_.

    .. [#n1] fe
    .. [#n2] fi
    .. [#n3] fo
       ...
    .. [#n999] fum

Changing numbers to make room for a new footnote is not much harder (but 
less convenient as you have to repeat it for every new footnote):

>>> def replace(match, n=2):
...     index = int(match.group(1))
...     if index >= n:
...         index += 1
...     return "[{}]".format(index)
... 
>>> print(re.compile(r"\[(\d+)\]").sub(replace, text))
    blah blah blah [1]_ and blah blah blah [3]_.
    blah blah [4]_ blah ... blah blah
    blah blah [1000]_.

    .. [1] fe
    .. [3] fi
    .. [4] fo
       ...
    .. [1000] fum






More information about the Python-list mailing list