【问题标题】:Code not generating when changing active file更改活动文件时未生成代码
【发布时间】:2022-02-10 21:07:45
【问题描述】:

我正在编写一个 vscode 扩展程序,它会根据您选择的语言生成更漂亮的配置。 Javascript 和 JSON。该代码在第一个文档上运行良好,但如果您更改为另一个文件并尝试再次单击该按钮。代码无法启动。有没有办法检查当前文档是否已更改谢谢。

import * as vscode from "vscode";
import { TextDocument } from "vscode";
import {
    activeEditor
} from "./constants";

var statusBar: vscode.StatusBarItem;

export function activate(context: vscode.ExtensionContext) {
    context.subscriptions.push(
        vscode.commands.registerCommand("prettier-config.prettierConfig", async () => {
            var changedDocument = false;
            const fileType = await vscode.window.showInformationMessage(
                "Which file to generate the Prettier Config for?",
                "Javascript",
                "JSON"
            );
            if (fileType === "Javascript" && changedDocument === false) {
                const javascript = activeEditor.edit(
                    (edit: { insert: (arg0: any, arg1: string) => void }) => {
                        edit.insert(
                            new vscode.Position(0, 0),
                            `module.exports = {\n   singleQuote: true,\n   printWidth: 120,\n   tabWidth: 4,\n   trailingComma: all,\n   endOfLine: auto\n};`,
                        );
                    }
                );
            }
            else if (fileType === "JSON" && changedDocument === false) {
                const json = activeEditor.edit(
                    (edit: { insert: (arg0: any, arg1: string) => void }) => {
                        edit.insert(
                            new vscode.Position(0, 0),
                            `{\n   "singleQuote": true,\n   "printWidth": 120,\n   "tabWidth": 4,\n   "trailingComma": "all",\n   "endOfLine": "auto"\n}`,
                        );
                    }
                );
            }
        })
    );
    statusBar = vscode.window.createStatusBarItem(
        vscode.StatusBarAlignment.Right,
        100,
    );
    statusBar.command = "prettier-config.prettierConfig";
    context.subscriptions.push(statusBar);
    context.subscriptions.push(
        vscode.window.onDidChangeActiveTextEditor(updateStatusBar),
        vscode.window.onDidChangeTextEditorSelection(updateStatusBar),
    );
    updateStatusBar();
}

function updateStatusBar(): void {
    statusBar.text = `$(edit) Prettier Config`;
    statusBar.show();
}

function deactivate() {
    statusBar.dispose();
}

【问题讨论】:

  • 您没有在每次调用命令时更新activeEditor
  • 我该怎么做?我应该创建一个新的 activeEditor 变量还是更新它?

标签: typescript visual-studio-code vscode-extensions


【解决方案1】:

如果您需要活动编辑器,只需使用:

const editor = vscode.window.activeTextEditor;

或使用

vscode.commands.registerTextEditorCommand

它将活动编辑器作为参数。

要获取文档的更改状态,请使用:

editor.document.isDirty

【讨论】:

    猜你喜欢
    • 2020-05-15
    • 2012-05-06
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多