VSCode插件开发 在编辑窗口打开文件或文本

打开本地文件

```javascript
export function openLocalFile(filePath: string) {
// 获取TextDocument对象
vscode.workspace.openTextDocument(filePath)
    .then(doc => {
        // 在VSCode编辑窗口展示读取到的文本
        vscode.window.showTextDocument(doc);
    }, err => {
        console.log(`Open ${filePath} error, ${err}.`);
    }).then(undefined, err => {
        console.log(`Open ${filePath} error, ${err}.`);
    })
}
```

打开字符串文本

```javascript
/**
 * @param fileContent 
 * @param fileLanguage  常见类型有 xml, python, java, javascript, typescript, c 等
 */
export function openStrInWindow(fileContent: string, fileLanguage: string = 'xml') {
    var option = {
        language: fileLanguage,
        content: fileContent
    }
    vscode.workspace.openTextDocument(option)
        .then(doc => {
            vscode.window.showTextDocument(doc);
        }, err => {
            console.error('Open string in window err,' + err);
        }).then(undefined, err => {
            // 捕获异常,相当于try-catch
            console.error('Open string in window err,' + err);
        });
}
```

编辑在VSCode窗口打开的文件并且显示

```javascript
/**
 * 修改在VSCode编辑器中打开的文档内容并且继续展示
 */
export function editOpenedFileInWindow(filePath: string) {
    // 获取 vscode.TextDocument对象
    vscode.workspace.openTextDocument(filePath).then(doc => {
        // 获取 vscode.TextEditor对象
        vscode.window.showTextDocument(doc).then(editor => {
            // 获取 vscode.TextEditorEdit对象, 然后进行字符处理
            editor.edit(editorEdit => {
                // 这里可以做以下操作: 删除, 插入, 替换, 设置换行符
                // 以插入字符串为例: "Hello Word\r\n"
                editorEdit.insert(new vscode.Position(0, 0), "Hello Word\r\n");
            }).then(isSuccess => {
                if (isSuccess) {
                    console.log("Edit successed");
                } else {
                    console.log("Edit failed");
                }
            }, err => {
                console.error("Edit error, " + err);
            });
        });
    }).then(undefined, err => {
        console.error(err);
    });
}
```

VSCode插件开发系列之目录

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值