more generalized which allows this to work for Emacs mode or for pastes. Code inspired and adapted by eshell.