Skip to content

Instantly share code, notes, and snippets.

@lhlyu
Last active January 29, 2023 16:08
Show Gist options
  • Save lhlyu/2b7007365c7c8ccad6ee357cd4ebf69c to your computer and use it in GitHub Desktop.
Save lhlyu/2b7007365c7c8ccad6ee357cd4ebf69c to your computer and use it in GitHub Desktop.
codemirror6 一些用法记录
<template>
<div ref="editor"></div>
</template>
<script setup lang="ts">
import { onMounted, ref} from "vue";
import { EditorState } from "@codemirror/state"
import { EditorView, highlightActiveLine, keymap } from "@codemirror/view"
import { defaultKeymap, indentWithTab } from "@codemirror/commands"
import { indentUnit } from "@codemirror/language";
import { searchKeymap} from "@codemirror/search"
const doc = `滕王高阁临江渚,佩玉鸣鸾罢歌舞。
画栋朝飞南浦云,珠帘暮卷西山雨。
闲云潭影日悠悠,物换星移几度秋。
阁中帝子今何在?槛外长江空自流。`
let startState = EditorState.create({
doc: doc,
extensions: [
keymap.of(defaultKeymap),
keymap.of(searchKeymap),
keymap.of([indentWithTab]),
indentUnit.of('\t\t'),
EditorView.theme({
'.cm-content': {padding: '0'},
'&.cm-focused': {outline: "none"},
'.cm-scroller': {
lineHeight: '1.8',
fontSize: '16px',
letterSpacing: '0.8px',
wordSpacing: '0.8px',
fontFamily: "-apple-system, 'Noto Sans', 'Helvetica Neue', Helvetica, 'Nimbus Sans L', Arial, 'Liberation Sans', 'PingFang SC', 'Hiragino Sans GB', 'Noto Sans CJK SC', 'Source Han Sans SC', 'Source Han Sans CN', 'Microsoft YaHei', 'Wenquanyi Micro Hei', 'WenQuanYi Zen Hei', 'ST Heiti', SimHei, 'WenQuanYi Zen Hei Sharp', sans-serif"
},
'.cm-line': {
padding: '4px 2em'
}
}),
// 高亮当前行
highlightActiveLine(),
// 自动换行
EditorView.lineWrapping
]
})
const editor = ref<HTMLElement>()
onMounted(() => {
let view = new EditorView({
state: startState,
parent: editor.value,
})
// 实现回车下一行缩进
view.dom.addEventListener('keydown', ev => {
if (ev.code === 'Enter') {
const range = view.state.selection.ranges[0]
view.dispatch({
changes: {
from: range.from,
to: range.to,
insert: '\t\t'
},
selection: { anchor: range.from + 2 }
})
}
})
// 聚焦
view.focus()
// 将光标移到末尾
view.dispatch({selection: {anchor: view.state.doc.length}})
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment