any-rule/src/useCommand.ts

35 lines
1.3 KiB
TypeScript
Raw Normal View History

import {window,commands,Range,ExtensionContext} from "vscode";
2020-02-21 01:17:23 +08:00
import { Rule } from './interface';
import insertLog from './insertLog';
import showResultMessage from './showResultMessage';
2020-02-22 01:08:31 +08:00
export default function (context: ExtensionContext, RULES: Rule[]) {
2020-02-21 01:17:23 +08:00
RULES.forEach(({ title, rule }, index) => {
const disposable = commands.registerCommand(`extension.rule${index}`, () => {
2020-02-22 01:08:31 +08:00
const editor = window.activeTextEditor;
2020-02-21 01:17:23 +08:00
if (editor) {
const { selections } = editor;
editor.edit(editBuilder => {
selections.forEach(selection => {
const { start, end } = selection;
2020-02-22 01:08:31 +08:00
const range = new Range(start, end);
2020-02-21 01:17:23 +08:00
editBuilder.replace(range, String(rule));
});
});
2020-02-22 01:08:31 +08:00
// 日志
insertLog({
2020-02-22 01:08:31 +08:00
rule: String(rule),
title,
method: 'Command'
});
showResultMessage(title);
2020-02-21 01:17:23 +08:00
} else {
2020-02-22 01:08:31 +08:00
window.showWarningMessage('any-rule: 只有在编辑文本的时候才可以使用!');
2020-02-21 01:17:23 +08:00
}
});
context.subscriptions.push(disposable);
});
}