How do I add a keyboard shortcut to open VS Code on the folder from File Explorer? - visual-studio-code

I want to be able to press . in any folder that I'm in File Explorer and open Visual Studio Code on that folder. It is the same effect as right-clicking and clicking "Open with Code". Pressing . is just like I could do on the GitHub website.
It might not be officially possible, but are there any workarounds to make it work?

The biggest issue is getting the current location from windows explorer. This requires some reverse engineering to get the memory address where windows explorer stores the location. If for any reason this address changes, you will need to find it again.
Besides that, windows supports global keyboard hooks. So you'd like to set up a global keyboard hook for your . key. The windows API also provides methods to get the active window. So whenever the . key is pressed, you can check that the active window is an explorer window. Then you'd read the current folder from the explorer window's memory. After that you've got everyting you need to start visual studio code.
This is very hacky, but I guess it's the only choice you have. Topics to research are:
Keyloggers - These for instance use the global hooks I mentioned
Generic reverse engineering - To find the address of the current location in windows explorer
Edit: Autohotkey post about how to get the windows explorer location. If that works as people claim, autohotkey can also be used to register a hook for the . key and launch VS code.

Thank you #AdrAs and #SarvinR for the answers. I used Sarvin's solution for a while, while trying to google and make sense of Adr's solution. Sarvin's solution is very useful if you're not trying to download any external programs, but if you want the true solution to this question, I finally managed it here:
Download AutoHotKey. It's good if you're familiar with it. AHK basically creates hotkeys (or shortcuts) like Adr described.
(If you have an existing ahk that you use, you can skip these steps and copy the code block down below)
Create a new AutoHotKey script by right-clicking on your desktop or anywhere in file explorer (we're gonna move it later so it doesn't matter). Name it whatever you want. I'm going to call it MyScript.ahk for this answer (I actually used david.ahk for myself).
Now, open command prompt (win + r, cmd, enter) and look for where VSCode is by typing where code. It will probably give you two lines. Take note of one of the lines (I chose the top one).
Right-click the ahk script file that you just created and choose Edit Script (or you can open it with notepad++ or VSCode or any editor of your choice, it's just a normal text file). Delete everything and paste this in:
#NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn ; Enable warnings to assist with detecting common errors.
SendMode Input ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory.
GetActiveExplorerPath()
{
explorerHwnd := WinActive("ahk_class CabinetWClass")
if (explorerHwnd)
{
for window in ComObjCreate("Shell.Application").Windows
{
if (window.hwnd==explorerHwnd)
{
return window.Document.Folder.Self.Path
}
}
}
}
#IfWinActive ahk_exe Explorer.exe
.::
path := GetActiveExplorerPath()
run, "C:\Users\david\AppData\Local\Programs\Microsoft VS Code\bin\code" "%path%"
return
On the second last line, replace the VSCode location with what you just saw in cmd. You most likely have to just change the username from david to your name.
Now, save the file try opening it (double click the ahk). If it works, a green H icon should appear on your tray without any errors. Go into any file directory in Windows File Explorer and hit . like you would normally do in GitHub. (Do Not do this in large directories like your root C:. There will be too many files for VSCode to load). It should work like expected, and if it doesn't, you did something wrong (I did the exact same thing like I just described and it works).
Now, of course, you would want to run this script on startup. Copy/Move the .ahk file into C:\Windows\System32. It will ask you for administrator permissions, so click yes. Open the registry editor (win + r, regedit, enter). Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run. On the right side pane, right click on the empty space then create a new String Value with any name (I used davidAHK) and set its value to your ahk file that you just copied/moved with quotes ("C:\Windows\System32\david.ahk" for my case). Close the Registry Editor and safely restart your computer. The ahk script should run on start up and you should be able to click . in any directory in file explorer to open VSCode.
Again, thank you #AdrAs and #SarvinR for your help!

I have an trick for this
Create vs.bat and write this code in that
#echo off
code %cd%
And Move this file to C:/Windows/System32/
Now All Set.
If you type vs on the address bar of explorer your vs code with current folder will open

open VSCode -> command+shift+p -> Enter shell command – > click the prompt "shell command: install 'code' command in path"
open directory -> code .

I wanted launch VS Code with the open folder OR the selected files, using AHK v2, and I wanted it to be plug & play for other users. Here's the result:
#Requires AutoHotkey v2.0
; This is the key combo.
#!.::
{
; Is the current window an Explorer window?
if (WinGetClass("A") == "CabinetWClass") {
; Cache the current clipboard contents.
clipboard := A_Clipboard
; Clear the clipboard & copy selected files.
A_Clipboard := ""
Send "^c"
ClipWait(0.5)
; If no files are selected...
if (A_Clipboard == "") {
; Get the current window's ID.
hwnd := WinGetID("A")
; Find the current window's COM object.
for window in ComObject("Shell.Application").Windows{
if (window && window.hwnd && window.hwnd == hwnd)
; Get the current folder's path.
path := window.Document.Folder.Self.Path
}
}
else {
; Quote & space-concatenate selected files.
path := '"' . StrReplace(A_Clipboard, "`n", '" "') . '"'
}
; Restore the clipboard.
A_Clipboard := clipboard
; Run code.
exe := '"' . StrReplace(A_AppData, "Roaming", "Local\Programs\Microsoft VS Code\code") . '"'
Run(exe . " " . path)
}
}
Works like a charm, and it's a piece of cake to install & run on your machine! Instructions at the repo.

Related

How to open a file from the integrated terminal in VSCode to a new tab

If my script is run within vscode, it want it to open a .txt file in a new tab in vscode. Else, open the folder containing the file. However, the current "code" command opens it in the terminal window instead of a new edit tab.
if ($env:TERM_PROGRAM -eq 'vscode') {
code 'C:\temp\_Release_Evidence\test.txt'
}
else {
explorer 'C:\temp\_Release_Evidence'
}
Normally, code refers Visual Studio Code's CLI, which is assumed to be in one of the directories listed in $env:PATH:
On Windows, it refers to the code.cmd batch file that serves as the CLI entry point.
On Unix-like platforms it refers to a code Bash script.
Its default behavior is to open a given file as a new tab in the most recently activated Visual Studio Code window (which, when run from inside Visual Studio Code, is by definition the current window).
If that doesn't happen for you, perhaps code refers to a different executable on your machine:
To avoid ambiguity, use the full CLI path instead, which, however, requires you to know Visual Studio Code's install location; typical CLI locations are:
Windows: $env:LOCALAPPDATA\Programs\Microsoft VS Code\bin\code.cmd
macOS: /usr/local/bin/code
Linux: /usr/bin/code
On Windows, something as simple as including the filename extension in the invocation - i.e., code.cmd - may help.
However, assuming you're using the PIC (PowerShell Integrated Console), a specialized PowerShell shell that comes with the PowerShell extension for Visual Studio Code, a workaround that also performs better, because it doesn't require launching a child process:
The PIC comes with the psedit command (an alias for the Open-EditorFile function), which quickly opens one or more files in a tab in the current Visual Studio Code window.
Caveat: As of version v2022.5.1 of the PIC, specifying multiple files only works meaningfully if they are individually enumerated, as literal paths. If you try to use a wildcard pattern or a directory path, all matching files / files in the directory are uselessly opened in sequence in a single tab.
Thus, you could use the following:
if ($env:TERM_PROGRAM -eq 'vscode') {
# Use `psedit`, if available; `code` otherwise.
$exe = if ((Get-Command -ErrorAction Ignore psedit)) { 'psedit' } else { 'code' }
& $exe 'C:\temp\_Release_Evidence\test.txt'
}
else {
explorer 'C:\temp\_Release_Evidence'
}
I can't reproduce this or explain why this might occur on your system. Running the following whether in the PowerShell Integrated Terminal (which #mklement0 explained succinctly) or a standard PowerShell terminal in VS Code's Terminal pane should open the file in a new tab where file contents are normally displayed:
code /path/to/file.txt
A suitable workaround may be to get the contents of a text file and pipe them in via STDIN. We can do this by adding a hyphen - as an empty parameter to code when piping data to it:
# Tip: Use the gc alias for Get-Content
Get-Content /path/to/file.txt | code -
You can then use Save As... to save the file to its intended target once you make your changes. You will need to use Ctrl+C in the terminal to close the input stream if you need to run additional commands before closing the file or saving to a one.
Even if this isn't a suitable workaround for you, it's a handy tip in other scenarios. For example, the following command will open documentation for Get-Process inside VSCode:
Reminder: Don't forget to hit Ctrl+C in the terminal once the content finishes populating to be able to run additional commands, or close the temporary file buffer.
Get-Help Get-Process -Detailed | code -

Weird CMD - VSCode behavior

yesterday I had SumatraPDF and VisualStudioCode with latex-workshop working with forward and reverse-search. Today the reverse-search didn't work any more. With a simple bat file I tried to show the commandline arguments.
echo %*
pause
They seemed correct and when I copied the command and paste it into a new cmd it works. To do further testing I tried to direct command and run it.
"C:\....\Code.exe" -g "%1:%2"
pause
Visual Studio Code responds: bad option -g
In SumatraPDF I set cmd as command.
Now the behavior is that I have two cmd windows. With the cmd directly opened the VSC open's the file. With the cmd launched indirect I got the error message.
I have tried resetting the environment variables, changing the current working directory, and checking the code page currently in use.
How can it be that cmd behaves differently with seemingly the same environment? And what can I do to make a cmd started from an application work like a cmd started by windows?
Update: It appears there were a couple of recent security changes in the way VSCODE.exe is allowed to interact with the command line (especially affecting LaTeX-workshop users) so for recent changes twice this year see the discussion at https://forum.sumatrapdfreader.org/t/inverse-search-not-performed-for-vs-code-exe/4486/27
Within SumatraPDF the reverse syntex command for %1 is replaced by %f for file and (l)L for line
It is triggered by a double click near the line of interest and if the synctex index file was compiled correctly by PdfLaTeX (or similar) it will include the tex %f(ilename) and the nearest %l(ine) reference to the point where double clicked.
Thus your tex syctex enhanced "reverse search" call out of SumatraPDF should historically be
"C:\...path to...\Code.exe" -g "%f:%l"
that's Lower L not 1
Avoid using any depreciated -inverse-search parameter from a LaTeX editor just add it once into SumatraPDF-settings.txt and then it's not disturbed by repeated assignments when running your -forward-search.
It will NOT work if the file.synctex or file.synctex.gz is corrupt by a bad PDF compilation.
HOWEVER It seem Microsoft have added the requirement to add a CLI.js handler and requires another switch setting after that ! (see link to discussion in Update above)
For a small test file download https://github.com/GitHubRulesOK/MyNotes/raw/master/AppNotes/SumatraPDF/LATeX%20and%20Reverse-Search.zip unpack and open sync.pdf in SumatraPDF to test that double click on page opens sync.tex in the editor
If the message is cannot start ... then the command line is not configured correctly. A rough test for a bad synctex is to see what happens if the call is changed by adding cmd /k echo to the start, since that will confirm the reverse command. Here I wrote "wrong" as the path to code.exe, once corrected I can remove cmd /k echo.
For some other systems where the reverse might change
see https://github.com/sumatrapdfreader/sumatrapdf/issues/1197#
However there should be no interference in a valid VsCode call.

How to clear terminal command history in VS code?

In VS Code Powershell Terminal, you can simply press up and down arrow keys to navigate through the history of commands entered, even after a restart. However, when there are same commands entered, it will also cycle through these duplicated histories instead of just making them distinct, making it hard to find cycle back to some old history. Is there a way to clear this history entirely?
Try the following command:
Set-PSReadlineOption -HistoryNoDuplicates
It sets the HistoryNoDuplicates option to True and hides duplicate histories.
You can see the value of HistoryNoDuplicates with the following command:
(Get-PSReadLineOption).HistoryNoDuplicates
If you want to set it back to False:
Set-PSReadlineOption -HistoryNoDuplicates:$false
For more information, see Set-PSReadlineOption in Microsoft Docs.
As a conclusion to the answers: my actual process to prevent duplicates, delete history and clear:
Set-PSReadlineOption -HistoryNoDuplicates
Remove-Item (Get-PSReadlineOption).HistorySavePath
Alt-F7
In Windows platform press and hold ctrl+shift+P, in the pop up window write terminal:clear, you'll get it shown, assign shortcut key (crtl+K) for example and hit enter. Now every time you want to clear the terminal you can use the hotkey you just created.
Do the same in Mac but using cmd+shift+P instead.
In v1.65 there will be this command:
workbench.action.terminal.clearCommandHistory
"Clear Command History"
In v1.65 there will also be a new setting:
terminal.integrated.shellIntegration.history
"Controls the number of recently used commands to keep in the terminal
command history. Set to 0 to disable terminal command history."
I suppose to clear the terminal history you could set this to 0 (100 is the default), reload (I'll test this tomorrow to see if a reload is necessary, it may not be) and then reset the limit to 100 or whatever you want.
the Cmdlet Clear-History should do what you want https://learn.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Core/Clear-History?view=powershell-6
If you are using the VS Code PowerShell terminal you can clear the entire history of the terminal or even specific lines with these steps:
Press the Windows key + R at the same time to launch the Run dialog.
Copy and paste the following path: %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline
Press Enter.
The File Explorer will open the specified path.
Edit the ConsoleHost_history.txt and Visual Studio Code Host_history.txt files manually to remove specific lines or all the content.

How to exit Command Prompt after launching VSCode

Here are the steps to reproduce the problem:
Open Command Prompt. ( cmd )
Run code . to launching VSCode.
Type exit and hit Enter in the Command Prompt.
Then the Command Prompt is just paused. I have to wait VSCode exit to let Command Prompt window closed.
Does anyone know why? How can I close Command Prompt window without exiting VSCode?
I found a solution here: https://github.com/Microsoft/vscode/issues/6608. It involves changing the code.cmd file (usually found under "C:\Users\yourUsername\AppData\Local\Programs\Microsoft VS Code\bin").
Changing the fifth line in that file from
call "%~dp0..\Code.exe" "%~dp0..\resources\app\out\cli.js" %*
to
start "" "%~dp0..\Code.exe" "%~dp0..\resources\app\out\cli.js" %*
will make the cmd window close right away. But that change will apparently break some other things (specifically the --wait flag), so I figure it's wiser to leave the code.cmd file alone.
Instead I made a copy ("codeNoCommandPrompt.cmd") right beside it and changed the line in there. That works fine for my usecase, namely having VS Code start on a specific folder alongside a bunch of other programms via a script.
I just tested it (using the latest VSCode 1.24.1), and it does work: the CMD shell session closes immediately when typing "exit".
Try calling the code.cmd script with its full path to see if the issue persists:
"C:\Program Files\Microsoft VS Code\bin\code.cmd" .
Try also the same command after having simplified the PATH (for testing)
set PATH=C:\Program Files\Microsoft VS Code\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\
code .
Simply use this
code . && exit
Check your PATH variable, maybe you have duplicate entries for VS Code
Go System Properties -> Envieronment variables -> select PATH variable then click Edit.
Remove "C:**\Microsoft VS Code".
Leave intact "C:**\Microsoft VS Code\bin"
This happens when you reinstall vscode with "add to PATH" checked

ipython from windows command line

I changed the environment variable PATH, to a new value and then back to what I believe was the original one. But now I can't open a .ipynb file through the Windows command line the was I was used to.
After changing the directory in command line and running
ipython notebook notebook_name.ipynb
I get the following message:
'ipython' is not recognized as an internal or external command.
My environment variable is set to a folder with python.exe, and this folder includes a subfolder with ipython.exe and jupyter-notebook.exe. When I open iPython command line and type %env, I can see the full path to the correct subfolder under PATH.
Can someone point to a solution?
Thanks.
So I figured out a solution - I changed the environment variable PATH to the subfolder with the .exe files. Although the path including this subfolder was listed under %env, it did not work without being referred directly in the System setting.
Looks like you figured out that you have to set the extension association in System Settings.
I've found that I'm using Notebooks often enough that it was well worth using AutoHotKey with the following script to open the Jupyter Notebook server in my default directory (or the currently highlighted directory in Explorer)
#SingleInstance Force
#NoTrayIcon
SetTitleMatchMode RegEx
; Press CTRL+ALT+I in a Windows Explorer window to launch a IPython notebook server in the current folder.
^+!i::
; Get the current path.
Send ^l
; Backup the current clipboard.
ClipSaved := ClipboardAll
; Copy and save the current path.
Send ^c
ClipWait
x = %Clipboard%
; Restore the clipboard.
Clipboard := ClipSaved
ClipSaved = ; Free the memory in case the clipboard was very large.
; Now, run the IPython notebook server.
RunWait, ipython notebook --notebook-dir "%x%", , min
return
^i::
; Now, run the IPython notebook server.
RunWait, jupyter notebook --notebook-dir "C:\Path\To\WorkSpace", , min
return
; Press CTRL+ALT+P to kill all Python processes.
^!p::
Run, taskkill /f /im python.exe, , min
return