VSCode environment variables besides ${workspaceRoot} - visual-studio-code

I know there is ${workspaceRoot} environment variable available. What other environment variables are there to use?
One that would be of particular interest would be the filename without the ${workspaceRoot} part with all \ chars replaced with /
so we can use this as a url builder. Then you could use a URL like "http://localhost:9876/${relativeFile}".
It would be really helpful if there is something like a ${relativeFile} and a ${relativeFolder}.

Be aware the ${workspaceRoot} variable has been deprecated in favor of the ${workspaceFolder} variable. It was deprecated (and no longer documented) in order to align better with Multi-root workspace support.
You can find the list at this link: https://code.visualstudio.com/docs/editor/variables-reference
For posterity reasons I'm going to list the variables (I've been trying to find them as well today), copying right from the link (and prettifying it), in case it ever changes again:
Visual Studio Code supports variable substitution in Debugging and Task configuration files. Variable substitution is supported inside strings in launch.json and tasks.json files using ${variableName} syntax.
Predefined variables
The following predefined variables are supported:
${workspaceFolder} - the path of the folder opened in VS Code
${workspaceFolderBasename} - the name of the folder opened in VS Code without any slashes (/)
${file} - the current opened file
${fileWorkspaceFolder} - the current opened file's workspace folder
${relativeFile} - the current opened file relative to workspaceFolder
${relativeFileDirname} - the current opened file's dirname relative to workspaceFolder
${fileBasename} - the current opened file's basename
${fileBasenameNoExtension} - the current opened file's basename with no file extension
${fileDirname} - the current opened file's dirname
${fileExtname} - the current opened file's extension
${cwd} - the task runner's current working directory on startup
${lineNumber} - the current selected line number in the active file
${selectedText} - the current selected text in the active file
${execPath} - the path to the running VS Code executable
${defaultBuildTask} - the name of the default build task
${pathSeparator} - the character used by the operating system to separate components in file paths
Note: The ${workspaceRoot} variable is deprecated in favor of the ${workspaceFolder} variable.
Environment variables
You can also reference environment variables through ${env:Name} syntax (for example, ${env:PATH})
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/app.js",
"cwd": "${workspaceFolder}",
"args": [ "${env:USERNAME}" ]
}
Note: Be sure to match the environment variable name's casing, for example ${env:Path} on Windows.
Settings and command variables
You can reference VS Code settings and commands using the following syntax:
${config:Name} - example: ${config:editor.fontSize}
${command:CommandID} - example: ${command:explorer.newFolder}
Variables scoped per workspace folder
By appending the root folder's name to a variable (separated by a colon), it is possible to reach into sibling root folders of a workspace. Without the root folder name, the variable is scoped to the same folder where it is used.
For example, in a multi root workspace with folders Server and Client, a ${workspaceFolder:Client} refers to the path of the Client root.

You can find a list of available substitution variables here:
https://code.visualstudio.com/docs/editor/tasks#_variable-substitution
Edit: The full list can actually be found in the systemVariables.ts source file. The base class defines a resolve() method that uses a regular expression to replace matches with string property values with the same name. Notice that SystemVariables also includes all process.env values, where the pattern is ${env.KEY}.

Related

Terminal Window and Vs Code Variables

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
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.

Windows Powershell Basic Questions - new user

When trying to open a file with text editor VIM, I am unable to open the file unless VIM (shortcut) is in my current working directory. As an example, I am able to write start firefox to open a firefox window. However, start vim C:\filepath\filename.txt does not work unless a vim shortcut is in my current directory. How do I get around this?
Also, is there a way to have a program execute a file in the current working directory without having to reference the entire file path? For example instead of Start-Process vim C:\Users\User\Desktop\File\file.txt is there an available path shortcut like Start-Process vim ~\file.txt with ~ representing the current working directory?
The OS need to determine the full path of the exe, no matter what.
There's 2 ways that it will happen.
You're calling the executable from it's working directory
The executable location is in the Windows environment variable.
You can view the PATH variable content through this simple statement
$env:Path -split ';' | sort
You sill see that the Firefox path is listed there, but not the one from VIM.
That's why the former can be started by it's executable name and the latter require the full path.
You need to add VIM directory to your PATH variable if you want to be able to call it just by typing vim
Otherwise, if you have restricted access or don't want to edit that variable, you can also set a $vim variable, then invoke it whenever you want to call the executable.
Regarding the second part of your question
Powershell use the dot as a reference to the current directory .\file.txt.
You can also just specify the filename without anything else file.txt.
Both backslash \ & slash / work for filepath so .\file.txt and ./file.txt are both valid ways to reference the file.
Use ..\ to reference the parent directory (e.g. ..\file.txt)
$Vim = "c:\Path\To\Vim.exe"
& $vim "file.txt"
& $vim ".\file.txt"
#Forward slash also work for paths
& $vim "./file.txt"

How to specify the AdditionalLibraryDirectories to msbuild?

I'm dealing with a .vcxproj file with the following Link segment:
<Link>
<OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner>
<AdditionalLibraryDirectories>..\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AssemblyDebug>
</AssemblyDebug>
<ProgramDatabaseFile>$(OutDir)$(TargetName).pdb</ProgramDatabaseFile>
<SubSystem>Console</SubSystem>
<RandomizedBaseAddress>false</RandomizedBaseAddress>
<DataExecutionPrevention>
</DataExecutionPrevention>
<TargetMachine>MachineX86</TargetMachine>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
</Link>
It would seem, I should be able to add more elements to the linker's LIBPATH by simply adding one more argument to msbuild's command line: /p:AdditionalLibraryDirectories=D:\Foo\lib. Unfortunately, this seems ignored and link.exe is invoked with only the /LIBPATH:..\lib argument...
If I edit the file and replace the %(AdditionalLibraryDirectories)-part with the desired path, things work -- linker is invoked with two /LIBPATH: arguments and the executable gets built.
Why can't I specify it as property on command-line, though?
I'm using Visual Studio 2017, with msbuild announcing itself as "Build Engine version 15.9.21+g9802d43bc3".
You'll need to use a completely separate MSBuild property.
For example, on your command line:
msbuild ... /p:FooLibDir=..\lib
and in the project file:
<AdditionalLibraryDirectories>$(FooLibDir);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
The reason that setting AdditionalLibraryDirectories on the command line doesn't work, is that the /p command line option for MSBuild sets properties, whereas AdditionalLibraryDirectories is metadata on the Link item (note how the parent of the AdditionalLibraryDirectories tag is a Link tag, not PropertyGroup).
The way to think about the difference is:
A property is a global variable accessible to everything (hence it can be set on the command line).
Metadata is specific to a single item (e.g., what additional directories to search for libs in, when linking this specific .obj).
Metadata in a ItemDefinitionGroup becomes a "template" that each instance of that item will use when declared.

Netbeans.conf: what is the variable for the user home?

When starting Netbeans, I need to add a system property named mEnvironment and set it as a sub-directory of the user's home. Example: In the netbeans.conf, I would like to add:
netbeans_default_options="-J-XX:+UseStringDeduplication -J-Xss2m -J-DmEnvironment=${USER_HOME}/mySubDirectory ......
USER_HOME is given as example of course.
Does someone know how Netbeans get the user home directory in the netbeans.conf file?
Thank you
Paul
Does someone know how Netbeans get the user home directory in the
netbeans.conf file?
The process is convoluted, and varies by operating system, but is described in great detail within netbeans.conf itself. This is the relevant content for my Apache NetBeans 11.1 installation:
# On Windows ${DEFAULT_USERDIR_ROOT} will be replaced by the launcher
# with "<AppData>\NetBeans" where <AppData> is user's
# value of "AppData" key in Windows Registry under
# "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
# and ${DEFAULT_CACHEDIR_ROOT} will be replaced by the launcher
# with "<Local AppData>\NetBeans\Cache" where <Local AppData> is user's
# value of "Local AppData" key in Windows Registry under
# "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
#
# On Mac ${DEFAULT_USERDIR_ROOT} will be replaced by the launcher
# with "~/Library/Application Support/NetBeans" and
# ${DEFAULT_CACHEDIR_ROOT} with "~/Library/Caches/NetBeans"
#
# On other systems ${DEFAULT_USERDIR_ROOT} will be replaced by the launcher
# with "~/.netbeans" and ${DEFAULT_CACHEDIR_ROOT} with "~/.cache/netbeans"
....
netbeans_default_userdir="${DEFAULT_USERDIR_ROOT}/11.1"
However, none of that really helps you, because you cannot access the values of netbeans_default_userdir or DEFAULT_USERDIR_ROOT; they are used internally by NetBeans itself, and are not System properties. You can verify this by displaying the values returned by System.getProperties(); none of the entries in netbeans.conf are shown.
Also, you can't meaningfully add new name/value pairs in netbeans.conf; you can only modify the values of the names used by NetBeans. That file is for NetBeans configuration, not user configuration. So if you add a line containing (say) MyConfSetting="ABC" then NetBeans will simply ignore that, and it won't be accessible to you either.
However, you can use an alternative approach to set a System Property for your directory in your application:
The read-only environment variable APPDATA points to your (operating system's) user directory. On my Windows 10 machine it has the value C:\Users\johndoe\AppData\Roaming.
The default user directory for NetBeans is the value of APPDATA + a sub-directory named NetBeans + a sub-directory named the NetBeans version. On my machine it is C:\Users\johndoe\AppData\Roaming\NetBeans\11.1. See the value of User directory in the Help > About screen for confirmation.
I don't know how to dynamically determine the version of NetBeans, but if that isn't important you can programmatically create a system property specifying your directory path:
String dir = System.getenv("APPDATA") + "\\NetBeans\\mySubDirectory";
System.setProperty("myDir", dir);
System.out.println("myDir=" + System.getProperty("myDir"));
On my machine that println() call displays myDir=C:\Users\johndoe\AppData\Roaming\NetBeans\mySubDirectory. I don't know if that approach meets your requirements, but I don't know of any other simple way to dynamically set your directory name.
Notes:
I checked this on Windows 10. Details may vary on other operating systems, but the overall approach should still work.
You can also specify parameters at run time using {project} > Properties > Run > Arguments (e.g. arg1=%APPDATA%\NetBeans\MyDir) and {project} > Properties > Run > VM Options (e.g. -Dvmopt1=%APPDATA%\NetBeans\MyDir), but that approach won't work because the %APPDATA% is simply treated as the literal "%APPDATA%" rather than evaluated as an environment variable.

Are there variables for current file or folder in the VS Code terminal?

When in the terminal pane, I would like to reference the file or folder of the active editor tab via environment variable or PowerShell variable (preferred). Something like this:
ii $vsActivePath
or
ii $vsActiveFile
Is this possible?
Not sure if this is exactly what you're looking for but you can get access to various variables in vs code such as:
${workspaceRoot} the path of the folder opened in VS Code
${workspaceRootFolderName} the name of the folder opened in VS Code without any slashes (/)
${file} the current opened file
Full details can be found here
They have added some new variables and it contains ${fileDirname} which is the path to the directory where your current ${file} is.
The documentation seems to be a bit misleading here.
Those are the current available options:
${workspaceFolder} - the path of the folder opened in VS Code
${workspaceFolderBasename} - the name of the folder opened in VS Code without any slashes (/)
${file} - the current opened file
${relativeFile} - the current opened file relative to workspaceFolder
${fileBasename} - the current opened file's basename
${fileBasenameNoExtension} - the current opened file's basename with no file extension
${fileDirname} - the current opened file's dirname
${fileExtname} - the current opened file's extension
${cwd} - the task runner's current working directory on startup
${lineNumber} - the current selected line number in the active file
The closest I've found is this: You can set up a keybinding which sends text to the terminal.
In keybindings.json, add an entry like this:
{
"key": "ctrl+shift+f",
"command": "workbench.action.terminal.sendSequence",
"args": { "text": "${relativeFile}" },
"when": "terminalFocus"
},
As you can see, variable substitution works, so you can insert the file, relative file, path, etc. (as described in Sn0wfreeze's answer)
Also note, I used a "when" clause in my example in order to politely override an existing shortcut only when the terminal is the active focus. This is optional.
I think this is distinctly less good than having a variable to type in-line, but it's been good enough for my day-to-day. You could probably get fancy with sequenced shortcuts to give lots of options, such as:
ctrl+f, ctrl+f => ${file}
ctrl+f, ctrl+r => ${relativeFile}
ctrl+f, ctrl+d => ${fileDirname}
etc.
Original source on visualstudio.com