Terminal Window and Vs Code Variables - powershell

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.

Related

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"

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.

Powershell vs GUI shortcuts

I have a file named new.txt. Using GUI I can create a shortcut, for example, "new.lnk". When I click on "new.lnk" file, Notepad is opened with the contents of "new.txt" file. When I create the shortcut using PowerShell
NEW-ITEM -TYPE SYMBOLICLINK -TARGET "NEW.TXT" "NEW.LNK"
I can see the contents of the file using
CAT "NEW.LNK"
but the shortcut file is not working in the GUI: it does nothing.
I expect to see the contents in Notepad editor. The properties of the file created using GUI and PowerShell are the same, except for "Start in" information: blank when the short cut is created using PowerShell and with the path file directory when using GUI.
Symbolic link (symlink) is not the same as Windows shortcut. A symbolic link is created on file system level - it says "here's a file with such filename, but the content is actually in this other file". It's size is 0 Bytes, as it just points to other file.
It would be more proper to name the file "new-linked.txt" instead of "new.lnk".
A shortcut ".lnk" is a separate file that is interpreted by Windows shell. It contains a path to the target file (among other additional properties). If you create shortcut from UI and then try cat my.lnk, you'll see the content of the shortcut file itself, not the target file.
For creating a Windows shortcut from Powershell, see How to create a shortcut using PowerShell.

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

VSCode environment variables besides ${workspaceRoot}

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