Fixed cursor movement when inserting new lines
Refactor event handling