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/ )
marijn
June 29, 2022, 2:29pm
2
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?
marijn
June 29, 2022, 3:42pm
5
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:
import {basicSetup} from 'codemirror';
import {EditorState, StateField, StateEffect} from '@codemirror/state';
import {python} from '@codemirror/lang-python';
import {EditorView, Decoration} from '@codemirror/view';
const addLineHighlight = StateEffect.define();
const lineHighlightField = StateField.define({
create() {
return Decoration.none;
},
update(lines, tr) {
lines = lines.map(tr.changes);
for (let e of tr.effects) {
if (e.is(addLineHighlight)) {
lines = Decoration.none;
lines = lines.update({add: [lineHighlightMark.range(e.value)]});
}
}
return lines;
This file has been truncated. show original
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.
3 Likes