> 文章列表 > codemirror6 实现自定义代码提示

codemirror6 实现自定义代码提示

codemirror6 实现自定义代码提示

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) {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、实现效果