Selection refactor range

In this PR, I have focused on range selection code. There where some places where code that extended the selection was copied. I have isolated and moved the code to a new function.