Hi!
I am working on a plugin for Obsidian, which uses Codemirror6. This is my first plugin, so please be nice I wanted to add line numbers to codeblocks, which I succcessfully could finish after struggling for weeks. Now I want to highlight specific lines, or line ranges in codeblock. I can’t figure this one out. I don’t know what I am doing, and there are probably easier methods, but I couldn’t find any simple examples
Could someone please help me. Here is my current code:
export const lineNumberField = StateField.define<DecorationSet>({
create(state): DecorationSet {
return Decoration.none;
},
update(oldState: DecorationSet, transaction: Transaction): DecorationSet {
const builder = new RangeSetBuilder<Decoration>();
let lineNumber = 1;
syntaxTree(transaction.state).iterate({
enter(node) {
if (node.type.id === 3 ) {
// opening ```
}
if (node.type.id === 5 ) {
// code lines
builder.add(
node.from,
node.from,
Decoration.widget({
widget: new LineNumberWidget(lineNumber),
})
);
const line = transaction.state.doc.lineAt(lineNumber);
const start = line.from;
const end = line.to;
builder.add(
start,
end,
Decoration.line({
attributes : {
class: "highlighted"}
})
);
lineNumber++;
}
if (node.type.id === 6 ) {
// closing ```
lineNumber = 1;
}
},
});
return builder.finish();
},
provide(field: StateField<DecorationSet>): Extension {
return EditorView.decorations.from(field);
},
});
class LineNumberWidget extends WidgetType {
constructor(private lineNumber: number) {
super();
}
toDOM(view: EditorView): HTMLElement {
const span = document.createElement("span");
span.classList.add("gutter");
span.innerText = `${this.lineNumber}`;
return span;
}
}
export default class LineNumberingPlugin extends Plugin {
async onload() {
this.registerEditorExtension(lineNumberField);
console.log("Plugin is registered");
}
}