waylan/Python-Markdown — Issue #51: Footnote extension crashes (stack recursion depth) when there are many footnotes
Author: Mekk
Created: 2011-11-03 19:01:38+00:00
State: open

## The problem

Current footnotes implementation allows no more than about 1000 footnotes per document. A bit more and you get
very long traceback ending with:

```
(… the line below repeated many many times …)
File "/usr/lib/pymodules/python2.6/markdown/extensions/footnotes.py", line 177, in _handleFootnoteDefinitions
more_plain = self._handleFootnoteDefinitions(theRest)
File "/usr/lib/pymodules/python2.6/markdown/extensions/footnotes.py", line 176, in _handleFootnoteDefinitions
+ "\n".join(detabbed))
File "/usr/lib/pymodules/python2.6/markdown/extensions/footnotes.py", line 98, in setFootnote
self.footnotes[id] = text
File "/usr/lib/pymodules/python2.6/markdown/odict.py", line 31, in __setitem__
super(OrderedDict, self).__setitem__(key, value)
RuntimeError: maximum recursion depth exceeded while calling a Python object
```

## Simple demo

Save the script below as foot_demo.py:

```python
COUNT = 990 # On my machine this is the smallest value which breaks, your values may change
for i in xrange(1, COUNT):
print "Something[^%d]\n" % i
for i in xrange(1, COUNT):
print "[^%d]: Another thing\n" % i
```

then run:

```
python foot_demo.py > foot_demo.txt
markdown -x footnotes foot_demo.txt
```

## The reason

The [_handleFootnoteDefinitions method](https://github.com/waylan/Python-Markdown/blob/master/markdown/extensions/footnotes.py#L159) finds first footnote definition, then
calls itself recursively on the remaining text. This obviously calls
for very deep stack when there are many footnotes, it is also fairly
inefficient.

## The solution

Just rewrite the method so it loops instead of recursing.

PS If original author has no time to work on the code, I can try
working on the patch – but I am not sure whether I understand all
ideas in the code properly.