mechanical-turk
mechanical-turk

Reputation: 801

Highlight lines in React CodeMirror

I'm using React CodeMirror for a responsive text editor in my project. This is what I have right now:

<CodeMirror
  options={{
    mode: 'python',
    lineNumbers: true,
  }}
/>

My question is, does anyone know if it's possible to add line highlighting by just passing a prop? Maybe something like this?

<CodeMirror
  options={{
    mode: 'python',
    lineNumbers: true,
    lineHighlight: {
      from: 1,
      to: 10
    },
  }}
/>

This would essentially highlight all the lines between 1 and 10.

Thanks!

Upvotes: 2

Views: 8032

Answers (2)

jlai12
jlai12

Reputation: 21

If using react-codemirror2 as suggested by scniro above, you can utilize the editorDidMount event prop which gives you a direct reference to the editor. And so a React solution might look something like:

const highlightLines = (editor, start, end) => {
  const from: {line: start, ch: 0};
  const to: {line: end, ch: MAX_LINE_LENGTH};
  editor.markText(from, to, {className: "codemirror-highlighted"});
}

const HighlightedEditor = ({start, end}) =>
  <CodeMirror
    value={...}
    options={...}
    onBeforeChange={...}
    onChange={...}
    editorDidMount={editor => highlightLines(editor, start, end)}
  />

with codemirror-highlighted being the CSS class with the styling you want to apply. Note that the from and to parameters for markText accept a position which has both line and character properties. Also, note that line and character are both zero indexed.

Edit: If you want to later remove/change the styling applied you will also want to track the TextMarker returned by markText so you can later call clear() on it. If just clearing all marks the editor use editor.getAllMarks() and clear away!

Upvotes: 2

DNB5brims
DNB5brims

Reputation: 30568

Take reference to this docs: https://codemirror.net/demo/markselection.html

and the related code:

 <script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  styleSelectedText: true
});
editor.markText({line: 6, ch: 26}, {line: 6, ch: 42}, {className: "styled-background"});
</script>

Upvotes: 2

Related Questions