Search code examples
codemirrortext-cursor

codemirror - get the current word under the cursor


Is there a way to get the current text under the cursor? I don't mean the text of the entire line, but just the single word.. For example, if the cursor is actually in the middle of the word "orange" --> ora|nge, I need to get the word "orange".

Any way to solve this is much appreciated, thanks in advance


Solution

  • Thanks to Marijn for help, findWordAt is what I was looking for:

    editor.on('cursorActivity', function() {
        var A1 = editor.getCursor().line;
        var A2 = editor.getCursor().ch;
    
        var B1 = editor.findWordAt({line: A1, ch: A2}).anchor.ch;
        var B2 = editor.findWordAt({line: A1, ch: A2}).head.ch;
    
        console.log(editor.getRange({line: A1,ch: B1}, {line: A1,ch: B2}));
    });