codemirror6 实现自定义代码提示
作者:小教学发布时间:2023-09-29分类:程序开发学习浏览:154
导读:1、需求 采用codemirror6版本开发,要求:自定义代码提示,通过输入关键字,实现代码片段覆盖。 类似于Vscode中输入V...
1、需求
采用codemirror 6版本开发 ,要求:自定义代码提示 ,通过输入关键字,实现代码片段覆盖。
类似于Vscode中输入VueInit ,显示代码片段:
<template lang="">
<div>
</div>
</template>
<script>
export default {
}
</script>
<style lang="">
</style>
参考官网:CodeMirror Autocompletion Example 中的Providing Completions。
2、初始化
加载以下依赖包
npm i codemirror
npm i @codemirror/autocomplete
npm i @codemirror/theme-one-dark
添加容器 并绑定id
<div id="codemir" ></div>
js中引用
import { basicSetup, EditorView } from "codemirror";
import { oneDark } from "@codemirror/theme-one-dark"; //黑色主题编辑器
import { autocompletion } from "@codemirror/autocomplete";
在onMounted初始化codemirror ,并添加对应id
const editor = new EditorView({
doc: "Press Ctrl-Space in here...\n",
extensions: [
basicSetup,
oneDark,
],
parent: document.getElementById("coder"),
options: {},
});
3、设置代码提示
其中from为当前位置 , options为自定义提示列表。apply 为需求中提到的自定义代码,还有info 信息提示 等。
function myCompletions(context) {
let word = context.matchBefore(/\w*/)
if (word.from == word.to && !context.explicit) return null;
return {
from: word.from,
options: [
{ label: "match", type: "keyword" },
{ label: "hello", type: "variable", info: "(World)" },
{ label: "magic", type: "text", apply: "⠁⭒*.✩.*⭒⠁", detail: "macro" },
],
};
}
最后,将codemirror绑定自定义的代码提示,使用extensions
const editor = new EditorView({
doc: "Press Ctrl-Space in here...\n",
extensions: [
basicSetup,
oneDark,
autocompletion({ override: [myCompletions] })
],
parent: document.getElementById("coder"),
options: {
},
});
4、其他优化
代码回显:
editor.dispatch({
changes: { from: 0, to: editor.state.doc.length, insert: content },
}); //插入content
以及代码更新监测 :
const editor = new EditorView({
doc: "Press Ctrl-Space in here...\n",
extensions: [
basicSetup,
oneDark,
autocompletion({ override: [myCompletions] }),
EditorView.updateListener.of((v) => {
console.log(v.state.doc.toString()) //监测得到的最新代码
}),
],
parent: document.getElementById("coder"),
options: { },
});
5、实现效果
- 程序开发学习排行
- 最近发表
-
- Wii官方美版游戏Redump全集!游戏下载索引
- 视觉链接预览最好的WordPress常用插件下载博客插件模块
- 预约日历最好的wordpress常用插件下载博客插件模块
- 测验制作人最好的WordPress常用插件下载博客插件模块
- PubNews Plus|WordPress主题博客主题下载
- 护肤品|wordpress主题博客主题下载
- 肯塔·西拉|wordpress主题博客主题下载
- 酷时间轴(水平和垂直时间轴)最好的wordpress常用插件下载博客插件模块
- 作者头像列表/阻止最好的wordPress常用插件下载博客插件模块
- Elementor Pro Forms最好的WordPress常用插件下载博客插件模块的自动完成字段