codemirror6 实现自定义代码提示
作者:小教学发布时间:2023-09-29分类:程序开发学习浏览:206
导读: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、实现效果
- 程序开发学习排行
- 最近发表
-
- Otter Blocks Gutenberg Blocks,Page Builder for Gutenberg Editor amp; FSE 最好的WordPress常用插件下载 博客插件模块
- 支付表格、立即购买按钮和发票系统|GetPaid 最好的WordPress通用插件下载 博客插件模块
- Super Web Share Native Social Sharing Button 最好的WordPress常用插件下载 博客插件模块
- Post to PDF Exporter 最好的WordPress通用插件下载 博客插件模块
- 队列Ajax Calls性能最好的WordPress常用插件下载 博客插件模块
- Ultimate Tag Cloud Elementor Addon 最好的WordPress常用插件下载 博客插件模块
- 产品布局Elementor Addon 最好的WordPress常用插件下载 博客插件模块
- Shiptastic集成for UPS 最好的WordPress通用插件下载 博客插件模块
- Ninox Integration for WooCommerce 最好的WordPress通用插件下载 博客插件模块
- Store Engine强大的WordPress电子商务插件用于支付、会员、附属机构、销售和;更多最佳的WordPress通用插件下载 博客插件模块