CodeMirror 的 MatchDecorator

在使用 CodeMirror 编辑器时,Decoration.markMatchDecorator 是两种非常有用的工具,可以帮助我们为编辑器中的内容创建自定义标记。Decoration.mark 用于为指定内容添加类名或标签名,而 MatchDecorator 则基于正则表达式与 Decoration 为编辑内容生成 DecorationSet

要使用 MatchDecorator,可以将其封装成一个 CodeMirror 扩展,如下所示:

function matcher(decorator: MatchDecorator): Extension {
  return ViewPlugin.define(view => ({
    decorations: decorator.createDeco(view),
    update(u): void {
      this.decorations = decorator.updateDeco(u, this.decorations);
    },
  }), {
    decorations: v => v.decorations,
  });
}

下面是一个完整的示例,展示了如何为 ==mark== 语法创建自定义标记类型:

import { Decoration, EditorView, MatchDecorator, ViewPlugin } from '@codemirror/view';
import { Extension } from '@uiw/react-codemirror';

function matcher(decorator: MatchDecorator): Extension {
  return ViewPlugin.define(view => ({
    decorations: decorator.createDeco(view),
    update(u): void {
      this.decorations = decorator.updateDeco(u, this.decorations);
    },
  }), {
    decorations: v => v.decorations,
  });
}

export const HighlightMark = Decoration.mark({
  class: 'md-highlight',
});

const mdMarkSyntaxMatcher = new MatchDecorator({
  regexp: /==[^=]+==/g,
  decoration: HighlightMark,
});

const mdMarkSyntaxStyling = matcher(mdMarkSyntaxMatcher);

通过这种方式,我们可以轻松地为编辑器中的特定语法添加自定义样式,提升用户体验。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注