pulled from the official mercurial commit (issue #329 with IPython)