Stop cursor correctly at document boundaries