57 lines
1.6 KiB
TypeScript
57 lines
1.6 KiB
TypeScript
import { EditorView, keymap } from '@codemirror/view';
|
|
import { EditorState } from '@codemirror/state';
|
|
import { defaultKeymap, indentWithTab, insertTab } from '@codemirror/commands';
|
|
import prettier from 'prettier';
|
|
// import parserBabel from 'prettier/plugins/babel';
|
|
import parserEstree from 'prettier/plugins/estree';
|
|
// import parserHtml from 'prettier/plugins/html';
|
|
import parserTypescript from 'prettier/plugins/typescript';
|
|
|
|
// 格式化函数
|
|
// Function to format the code using Prettier
|
|
type FormatCodeOptions = {
|
|
type: 'typescript';
|
|
plugins?: any[];
|
|
};
|
|
async function formatCode(view: EditorView, opts?: FormatCodeOptions) {
|
|
const editor = view;
|
|
const code = editor.state.doc.toString();
|
|
const plugins = opts?.plugins || [];
|
|
plugins.push(parserEstree);
|
|
const parser = opts?.type || 'typescript';
|
|
if (parser === 'typescript') {
|
|
plugins.push(parserTypescript);
|
|
}
|
|
try {
|
|
const formattedCode = await prettier.format(code, {
|
|
parser: parser,
|
|
plugins: plugins,
|
|
});
|
|
|
|
editor.dispatch({
|
|
changes: {
|
|
from: 0,
|
|
to: editor.state.doc.length,
|
|
insert: formattedCode.trim(),
|
|
},
|
|
});
|
|
} catch (error) {
|
|
console.error('Error formatting code:', error);
|
|
}
|
|
}
|
|
|
|
export const formatKeymap = keymap.of([
|
|
{
|
|
// bug, 必须小写
|
|
key: 'alt-shift-f', // 快捷键绑定
|
|
// mac: 'cmd-shift-f',
|
|
run: (view) => {
|
|
formatCode(view);
|
|
return true; // 表示按键事件被处理
|
|
},
|
|
},
|
|
// indentWithTab, // Tab键自动缩进
|
|
{ key: 'Tab', run: insertTab }, // 在光标位置插入Tab字符
|
|
...defaultKeymap, // 默认快捷键
|
|
]);
|