在使用 CodeMirror 编辑器时,Decoration.mark 和 MatchDecorator 是两种非常有用的工具,可以帮助我们为编辑器中的内容创建自定义标记。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);通过这种方式,我们可以轻松地为编辑器中的特定语法添加自定义样式,提升用户体验。
发表回复