Refactor common code between onkeydown and onkeypress; add some comments to explain how character input and character deletion works with respect to the current selection