Highlight line function

Hello!

I want to be able to highlight a line with a function:

function highlightLine(lineNumber) {
  editorView.dispatch({
    effects: highlightLinesEffect.of([executedLineDecoration.range(lineNumber)])
  })
}

My code:

const executedLineDecoration = Decoration.line({ 
  attributes: { class: 'cm-execLine' },
})
const highlightLinesEffect = StateEffect.define()
const resetLinesHighlightEffect = StateEffect.define()

const highlight = StateField.define({
  create() { return Decoration.none },
  update: function(value, tr) {
    value = value.map(tr.changes)
    for (let effect of tr.effects) {
      if (effect.is(highlightLinesEffect)) {
        value = value.update({ add: effect.value })
      }
    }
    return value
  },
  provide: f => EditorView.decorations.from(f)
})

I added StateField value (highlight) to extensions while creating editor state.

The code inside the update runs, but the required class is not added to the line. What am I doing wrong?

I followed Marked Text example from (https://codemirror.net/docs/migration/)

I think what’s going wrong is that you’re using the line number, instead of the line offset (doc.line(lineNumber).from) when calling .range.

1 Like

Thanks, it helped!!

But the documentation says that the .range accepts (from: number, to?: number). A number, not a Line. What does it mean?

Yes, Line.from is a number, and that’s what you want to pass there.

Thanks for the quick response!

If its helpful, I just made a line highlighting extension for an editor today:

It’s bidrectional, so its lines can be highlighted from an external source and it highlights itself on mouse-over.

You can see that in use on www.dis-this.com (example).

I’d love feedback on it and whether it can be improved. It took me a while to figure out the right incantation, and I had similar struggles as you, so I think a line-highlighter might be a good example to put in the documentation.

2 Likes