VSCode选择摘录

时间:2018-12-03 12:47:47

标签: visual-studio-code vscode-extensions

这是一个初学者的问题,所以不要对我很难。

示例:

A,B,C,D, ..

我需要将此字符串转换为VSCode中的以下输出

enum id name
{
    value(0; A) { Caption = 'A'; }
    value(1; B) { Caption = 'B'; }
    value(2; C) { Caption = 'C'; }
    value(3; D) { Caption = 'D'; }
}

我可以阅读选择并将其拆分为单独的标记。

但是在将其写回我的行时,我陷入了困境。

我的代码:

'use strict';
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
//import * as vscode from 'vscode';
import { window, commands, Disposable, ExtensionContext, StatusBarAlignment, StatusBarItem, TextDocument, TextEditor, ViewColumn, workspace, TextLine, TextEdit, Uri, Position } from 'vscode';
import { stringify } from 'querystring';

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: ExtensionContext) {
    console.log('"Cg Helper" is now active!');
    let cgHelper = new CgALHelper;
    let disp = commands.registerCommand('extension.convertSelection2Enum', () =>{
        cgHelper.convertSelection2Enum(window.activeTextEditor);
    })

    context.subscriptions.push(disp);
}

// this method is called when your extension is deactivated
export function deactivate() {
}

class CgALHelper 
{
    public convertSelection2Enum(editor: TextEditor)
    {        
        this.convertTextLine2Enum(editor);
    }

    public convertInputText2Enum()
    {

    }

    private convertTextLine2Enum(editor: TextEditor)
    {
        let line = editor.document.lineAt(editor.selection.active.line);
        if (line != null && line.text != null)
        {
            window.showInformationMessage(line.text);        
            let tokens = line.text.split(',');
            if (tokens[0] != null && tokens[0] != '' && tokens.length != 0 )
            {

                tokens.forEach(tok => {
                    // I'm stuck here !            
                });

            } else
                window.showErrorMessage('nothing to convert');

        } else
            window.showErrorMessage('Nothing to convert');
    }
}

1 个答案:

答案 0 :(得分:0)

您要构造一个SnippetString。代码段字符串可以逐步构造:

 const snippet = new vscode.SnippetString();
 snippet.appendText('enum id name {');
 tokens.forEach(tok => {
      snippet.appendText(`    value(0; ${tok}) { Caption = '${tok}'; }`)
 });
 snippet.appendText('}');

然后使用TextEditor.insertSnippet将代码段应用于编辑器:

editor.insertSnippet(snippet);