Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #97389

Re: Footnotes in ReST

From Peter Otten <__peter__@web.de>
Subject Re: Footnotes in ReST
Date 2015-10-04 12:14 +0200
Organization None
References <560fbe70$0$1586$c3e8da3$5496439d@news.astraweb.com> <CA+wXuVnA4aPsDzaWNQWtP53Z3Dt-3w9k40uJ-BYx9kBwKi7J6g@mail.gmail.com> <muqsp0$81q$1@ger.gmane.org>
Newsgroups comp.lang.python
Message-ID <mailman.376.1443953667.28679.python-list@python.org> (permalink)

Show all headers | View raw


Peter Otten wrote:

> 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

Those who remember the old basic dialects might [1]_ like

$ cat insert_footnote_basic.py
#!/usr/bin/env python3
import re
import sys


def step(start, delta):
    n = start
    while True:
        yield n
        n += delta


def insert_footnote(text):
    lookup = {}
    steps = step(10, 10)

    def replace(match):
        index = int(match.group(1))
        try:
            new_index = lookup[index]
        except KeyError:
            new_index = lookup[index] = next(steps)

        return "[{}]".format(new_index)

    return re.compile(r"\[(\d+)\]").sub(replace, text)


if __name__ == "__main__":
    sys.stdout.write(
        insert_footnote(sys.stdin.read())
    )
$ cat sample.rst
blah blah blah [10]_ and blah blah blah [20]_.
[21] this is new
blah blah [30]_ blah ... blah blah
blah blah [9990]_.

.. [10] fe
.. [20] fi
.. [21] yes it is
.. [30] fo
   ...
.. [9990] fum

$ ./insert_footnote_basic.py < sample.rst
blah blah blah [10]_ and blah blah blah [20]_.
[30] this is new
blah blah [40]_ blah ... blah blah
blah blah [50]_.

.. [10] fe
.. [20] fi
.. [30] yes it is
.. [40] fo
   ...
.. [50] fum

$

.. [1] or run away screaming ;)


Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

Footnotes in ReST Steven D'Aprano <steve@pearwood.info> - 2015-10-03 21:39 +1000
  Re: Footnotes in ReST Chris Angelico <rosuav@gmail.com> - 2015-10-03 21:57 +1000
  Re: Footnotes in ReST Laura Creighton <lac@openend.se> - 2015-10-03 14:21 +0200
    Re: Footnotes in ReST Steven D'Aprano <steve@pearwood.info> - 2015-10-04 00:22 +1000
  Re: Footnotes in ReST Peter Otten <__peter__@web.de> - 2015-10-04 11:50 +0200
  Re: Footnotes in ReST Peter Otten <__peter__@web.de> - 2015-10-04 12:14 +0200

csiph-web