Spaces don't work when I add a decoration to snippets (i.e anything inside {{ }})

I’m trying to add background color on anything that is within {{ }} or [[ ]] in codemirror

I got the background on the text but I’m unable to insert spaces after the last }. If it is anything other than space then it shows up and the space is behind that letter.

removing plugin, spaces work fine - Screen-Recording-2022-05-21-at-7.36.39-PM GIF | Gfycat

adding plugin spaces don’t work then - Screen-Recording-2022-05-21-at-7.37.24-PM GIF | Gfycat

here is the codemirror plugin/extension that handles the decoration

const expression = Decoration.mark({
  attributes: { class: 'cm-mdb-expression' },
});

function expressionDeco(view: EditorView) {
  const builder = new RangeSetBuilder<Decoration>();

  for (const { from, to } of view.visibleRanges) {
    for (let pos = from; pos <= to; ) {
      const line = view.state.doc.lineAt(pos);
      const from = line.text.indexOf('{{');
      const to = line.text.indexOf('}}');
      if (from > -1 && to > -1 && to + 2 <= line.length) {
        builder.add(from, to + 2, expression); // if changed to to + 1, then spaces work but then styles are not applied to the last }
      }
      pos = line.to + 1;
    }
  }
  return builder.finish();
}

const showExpressionPlugin = ViewPlugin.fromClass(
  class {
    decorations: DecorationSet;

    constructor(view: EditorView) {
      this.decorations = expressionDeco(view);
    }

    update(update: ViewUpdate) {
      if (update.docChanged || update.viewportChanged) this.decorations = expressionDeco(update.view);
    }
  },
  {
    decorations: (v) => v.decorations,
  }
);

export function expressionBackground(): Extension {
  return [showExpressionPlugin];
}

That code doesn’t look like it could interfere with the rendering of spaces. Can you try to set up a minimal editor that shows the problem on Try CodeMirror ?

It seems to be working fine in try codemirror but not in my app, any idea what might be interfering with the space rendering ?

try codemirror

Possibly some CSS is causing the white-space property to be set incorrectly? I guess the quickest way to figure this out is to progressively disable parts of your code until the problem goes away and you find out which part caused it.

1 Like

I was setting .cm-line display to flex changed it to block and it seems to be working fine now. Thanks for your help :slight_smile: