cleanup logic moved upstream

cf https://github.com/ipython/ipython/pull/7172/files

closes #37
Merge pull request #46 from Carreau/cleanup-sort

cleanup logic moved upstream