Refactor query and caretPos