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

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!

1 Like