在VSCode中获取当前打开的文件

9

vscode命名空间中是否有一个命令可以让你获取当前打开文件的TextDocument实例?我找到了vscode.workspace.onDidOpenTextDocument,但它不能用于在启动时打开的文件。

3个回答

15

根据您的需求,有几个选择:

// Single active editor. Editors have a `.document` property
vscode.window.activeTextEditor

// All showing text editors. For a split view, there are two active editors 
vscode.window.visibleTextEditors

// All open documents that vscode knows about. Do not have to be showing
vscode.workspace.textDocuments

查看vscode API获取更多信息:https://code.visualstudio.com/docs/extensionAPI/vscode-api


谢谢,它帮了我 :) - Soren
我想在终端上打印出编辑器中当前打开文件的文件位置。我能从您提供的API中获取命令的信息吗?例如:我有一个扩展的配置文件,我想分享它。我可以在编辑器中悬停选项卡和面包屑上看到位置。我想要复制这个位置字符串。 - Timo
2023年怎么样?我打开了开发工具,但是vscode.window已经未定义。 - kungfooman
@kungfooman:VS Code的API无法在VS Code窗口的开发工具中使用,只能在扩展程序中使用。 - Matt Bierner

1
如果当前活动的编辑器是自定义编辑器(使用registerCustomEditorProvider()),则vscode.window.activeTextEditor可能无法获取正确的信息。
您可以尝试使用vscode.window.tabGroups.activeTabGroup.activeTab.input,它具有以下属性{ viewType: string; uri: vscode.Uri; }

0

也许你对任务中的${file}感兴趣。这个脚本测试当前活动文件。

{
  "version": "2.0.0",
  "tasks": [
    {
      "type": "shell",
      "command": [
        "clear &&",
        "node --expose-gc ./node_modules/.bin/jest --runInBand --logHeapUsage ${file}"
      ],
      "options": {
        "cwd": "${workspaceFolder}/backend"
      },
      "group": "test",
      "problemMatcher": [],
      "label": "npm: test - backend - current file",
      "detail": "NODE_ENV=test jest"
    }
  ]
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接