MatchDecorator not respond to mouse movements.

I want the content to appear when the mouse moves over ** and hide when the mouse moves away from **, similar to how it works in Obsidian. My issue is that currently, it only changes when the text is edited; it does not respond to mouse movements.

import { Extension } from '@codemirror/state'
import {
  Decoration,
  DecorationSet,
  EditorView,
  MatchDecorator,
  ViewPlugin,
  ViewUpdate,
  WidgetType,
} from '@codemirror/view'


class EmptyWidget extends WidgetType {
  eq(): boolean {
    return true
  }
  toDOM() {
    return document.createElement('span')
  }
}


const boldRegexp = /\*\*([^*]+)\*\*/g


const boldDecorator = new MatchDecorator({
  regexp: boldRegexp,
  decorate: (add, from, to, match, view) => {
    const boldText = match[1]
    const start = from + match[0].indexOf(boldText)
    const end = start + boldText.length
    console.log(start, end)

    const cursorPos = view.state.selection.main.head


    if (cursorPos < start || cursorPos > end) {
      add(from, start, Decoration.widget({ widget: new EmptyWidget() }))
    }

    add(start, end, Decoration.mark({ class: 'cm-bold' }))

    if (cursorPos < start || cursorPos > end) {
      add(end, to, Decoration.widget({ widget: new EmptyWidget() }))
    }
  },
})


export function boldExtension() {
  return ViewPlugin.fromClass(
    class BoldView {
      decorations: DecorationSet
      constructor(view: EditorView) {
        this.decorations = boldDecorator.createDeco(view)
      }
      update(update: ViewUpdate) {
        this.decorations = boldDecorator.updateDeco(update, this.decorations)
      }
    },
    {
      decorations: (v) => v.decorations,
    },
  )
}

export const boldStyle = EditorView.baseTheme({
  '.cm-bold': {
    fontWeight: 'bold',
    color: 'red',
  },
})


export const bold: Extension = [boldExtension(), boldStyle]

This is not really a use case you can use MatchDecorator for. That assumes that, once decorated, the decorations for a given piece of text stay the same until the text changes. You’ll have to write your own decoration logic for this.

1 Like

Thank you , i will try own decoration

How do I create my own Decorator? I haven’t seen a decorator that can be inherited.

You’ll have to write logic that creates decorations and stores them in a range set. See the decoration example.

1 Like