Codemirror 6: Move cursor to specific line and mark its text

Is there a way to programatically move cursor to a given line on editor and then highlight text of this line?

1 Like

Yes, there is, but this is not really a place where people do your work for you — I wrote a lot of docs, and to use this software you’ll have to read some of them.

I’m currently reading the docs, but coudn’t find something that can help me with this yet. Just thought the forum would be a good place to ask for help.
Anyways, thanks for your reply.

1 Like

This is something I needed to look into as well, found this thread without any info, then had to spend time digging through the various different docs trying to find what I needed.

Assuming “highlight” is referring to the selection, then there are two pieces to this puzzle:

  1. You have to get the position information based on a line number
  2. You need to send through a transaction to select that range and scroll it into view.

In the interest of helping future users:

  // Get line info from current state.
  const line = editor.state.doc.line(3);
  
  editor.dispatch({
    // Set selection to that entire line.
    selection: { head: line.from, anchor: line.to },
    // Ensure the selection is shown in viewport
    scrollIntoView: true
  });

CodeMirror Try

References:

Hope that saves other folks some time!