TextDocument: do not swallow KeyError raised by substitution method
With safe_substitute=True, a KeyError raised by the substitution method were silently ignored.
This still supports python2, once we finally drop python2, this code
can be simplified a lot with raise from and raise e.__cause__
Edited by Jérome Perrin