Fix range error when reaching end of the line