Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Access File Contents in VS Code Extension

I would like to scan through the contents of the file currently open in the workspace. I tried:

console.log(vscode.window.activeTextEditor); // Doesn't work

I also tried:

vscode.workspace.openTextDocument(vscode.window.terminals).then(document => {
  let text = document.getText();
  console.log(text);
});

That last one threw an error: "did not find a valid project structure, exiting...." What am I doing wrong?

like image 351
Rupesh Bondili Avatar asked Oct 29 '25 16:10

Rupesh Bondili


1 Answers

Please consider checking out the VS Code Extension Samples and in particular the Document Editing Sample. It does show how to read the text in the currently active document in the editor.

To read text in the currently active document editor, put this code into your extension.ts:

'use strict';

import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {
    const disposable = vscode.commands.registerCommand('extension.scanDocument', function () {
        // Get the active text editor
        const editor = vscode.window.activeTextEditor;

        if (editor) {
            let document = editor.document;

            // Get the document text
            const documentText = document.getText();

            // DO SOMETHING WITH `documentText`
        }
    });

    context.subscriptions.push(disposable);
}

And declare this command in your package.json:

    "contributes": {
        "commands": [
            {
                "command": "extension.scanDocument",
                "title": "Scan current document..."
            }
        ]
    }

... run the extension, open a file and invoke the command from the command pallet.

like image 170
Jan Dolejsi Avatar answered Nov 01 '25 12:11

Jan Dolejsi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!