1import { EditorSelection } from '@codemirror/state'; 2import { SearchCursor } from '@codemirror/search'; 3 4export function jumpToCharacter(view, character, direction = 1) { 5 const { state, dispatch } = view; 6 const pos = state.selection.main.head; 7 const cursor = new SearchCursor(state.doc, character); 8 9 let characterPositions = []; 10 let jumpPos; 11 while (!cursor.next().done) { 12 characterPositions.push(cursor.value.to); 13 } 14 if (!characterPositions.length) { 15 return false; 16 } 17 if (direction > 0) { 18 jumpPos = characterPositions.find((x) => x > pos + 1) ?? characterPositions.at(0); // Loop back around for convenience 19 } else { 20 jumpPos = characterPositions.reverse().find((x) => x < pos + 1) ?? characterPositions.at(0); 21 } 22 23 if (jumpPos == null) { 24 return false; 25 } 26 dispatch({ 27 selection: EditorSelection.cursor(jumpPos - 1), 28 scrollIntoView: true, 29 }); 30 return true; 31}