Home > database >  Terminal Window and Vs Code Variables
Terminal Window and Vs Code Variables

Time:06-04

I'm trying to retrieve vs code variable values from terminal window in VS Code, but all of them return an empty string. I need for example, get the name of the file opened in the vscode editor (from a var)

"Ex: ${fileBasename} - the current opened file's basename"

This is the article I found for these vars, but all return empty:

https://code.visualstudio.com/docs/editor/variables-reference

Thank you and regards

Xabier

CodePudding user response:

The VSCode-native variables are only resolved in configs and settings files, but they are not automatically available in any hosted terminal.

That being said, the integrated terminal that comes with the official PowerShell language extension hooks into VSCode's editor API and exposes it via the $psEditor automatic variable:

# obtain editor context handle
$editorCtx = $psEditor.GetEditorContext()

# get current open file's path, infer name from path
$fileBasename = Split-Path $editorCtx.CurrentFile.Path -Child

# This now works
"Ex: ${fileBasename} - the current opened file's basename"

Beware that the editor context object is a snapshot - if you want to know the current file open in the main editor after some time has passed you have to call GetEditorContext() again.

  • Related