Codemirror 6 highlighting specific substring

Looking at another code from here: How to search for and highlight a substring in Codemirror 6? and the solution you gave me I was able to put it up and running!

My error was just an import I had missing (Range) and I forgot to add the parentheses after de define. Thank you very much for everything!

This is my final version if anyone needs it:

import { EditorView } from "codemirror";
import { EditorState, StateField, StateEffect, Range } from "@codemirror/state";
import { SearchCursor } from "@codemirror/search";
import { Decoration } from "@codemirror/view";

initCodeMirror() {

    const highlight_effect = StateEffect.define<Range<Decoration>[]>();

    const highlight_extension = StateField.define({
      create() { return Decoration.none },
      update(value, transaction) {
        value = value.map(transaction.changes)

        for (let effect of transaction.effects) {
          if (effect.is(highlight_effect)) value = value.update({add: effect.value, sort: true})
        }

        return value
      },
      provide: f => EditorView.decorations.from(f)
    });

    let state = EditorState.create({/* ... */ extensions: [highlight_extension]});

    let view = new EditorView({
      state,
      parent: element
    });


    let cursor = new SearchCursor(view.state.doc, "# COMPLETE THIS");

    cursor.next();

    const highlight_decoration = Decoration.mark({
      attributes: {style: "background-color: yellow"}
    });

    view.dispatch({
      effects: highlight_effect.of([highlight_decoration.range(cursor.value.from, cursor.value.to)])
    });

  }

Thank you once again!

4 Likes