Weird CMD - VSCode behavior - visual-studio-code

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.

Related

Editing WSL2 instance of Ubuntu Crontab using Windows VSCode

My question is whether it is possible to edit the crontab of a WSL2-based instance of Ubuntu with my Windows VSCode that is connected via WSL remote SSH.
If I type export EDITOR=code inside my WSL instance and then crontab -e, I am able to see a /tmp/crontab.sygFAU file load inside my VSCode instance.
The problem is that once I make edits to this file, it will save the file to /tmp/crontab.sysFAU but it doesn't actually take the next step of replacing the the real crontab file in /var/spool/cron/crontabs.
So once I re-open the crontab, it will just show what I had previously, and not my saved edits.
It would be nice to know if this is not possible or if there are any alternative ways to run a GUI editor because using nano is a pain!
An interesting question that I haven't considered before, myself. Here's what's happening:
You set your editor to code
You crontab -e, which properly loads VSCode with the temporary crontab.
However, because this is a Windows GUI application, it returns control to the parent Linux application (crontab) immediately after starting VSCode. You can see the same result if you just start notepad.exe from your shell in WSL -- Once Notepad starts (rather than exits) control is returned to the shell.
If you switch back to your terminal at this point, you'll see that crontab detected that the editor that it launched exited (returned), and so it has already tried to copy the temporary file to the permanent location.
However, since the temporary files doesn't yet have any changes, crontab decides there's nothing to do.
Editing the file in VSCode and saving it has no effect, other than to leave a dangling /tmp/... file hanging around (since crontab isn't there to clean up).
So what's the solution? We need a way to launch a Windows GUI application and prevent it from returning control to crontab until you are done editing.
I originally thought something from this question might work, but the problem is that the actual command that launches the Windows process is embedded in a shell script, which you can see with less "$(which code)" (or code "$(which code)"), but it's probably not a great idea to edit this.
So the next-best thing I came up with is a simple "wrapper" script around the (already-a-wrapper) code command. Create ~/.local/bin/code_no_fork.sh (could be anywhere) with:
#!/usr/bin/env bash
code $* > /dev/null
echo Press Spacebar to continue
read -r -s -d ' '
Credit: This answer for the Spacebar approach
Then:
EDITOR=~/.local/bin/code_no_fork crontab -e
After you make your edits in VSCode, simply press Space to allow the script to continue/exit, at which point crontab will (assuming no errors were detected) install the new Crontab.
Alternatives
This is should typically only be a problem with Windows GUI applications, so the other possible avenue is to simply use any Linux editor that doesn't fork. If you want a GUI editor, that's entirely possible as long as you are running a WSL release that includes WSLg support (now available for Windows 10 and 11).
I won't offer any individual editor suggestions since that would get into "opinion" and "software recommendation" territory, which is off-topic here.

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

Broke my terminal with a bad PATH [duplicate]

This question already has an answer here:
Wrong path set and now .bashrc throws errors [duplicate]
(1 answer)
Closed 6 years ago.
I put an invalid path into my bashrc and now my terminal doesn't work. I've deleted my bash_profile as well as my bashrc and I still can't get it to work.
Every command I use in terminal gives me the error:
sh: parse_git_branch: command not found
This was something I had in my bash_profile for git autocompletion. The problem is once I've deleted the files using /bin/rm <file>, I can't apply my changes with source ~/.bash_profile because it's giving me errors. I've looked at this question, and this question, but I still am having no luck.
How can I fix my command line after breaking things like this?
You can export a correct PATH in your current session using a command similar to :
export PATH=/usr/local/bin:/usr/bin:/bin
After using this, you should be able to source your bashrc.
You can always change your path right on the command line for the rest of the current shell session: PATH="/usr/local/bin:/usr/sbin:/usr/bin:/bin:/sbin:"
Exporting the PATH won't solve your problem. It will only export the value of PATH to child shells/processes. This only achieves the same thing as resetting/changing the PATH variable from the command-line (as shown above), because your scope is limited to the current shell process (and its children) while you are working within that shell environment (working from the command-line). If you open a new terminal (start a new login shell, which is a parent process), bash will still be trying to read from the resource files (.bash_profile and .bashrc), which no longer exist.
So, we need to be able to widen our scope and tell bash that we want to make changes for all future bashes (shell processes--new shells, shells within shells, etc.), and the way that is done is by writing those statements in the resource files.
Once you set your PATH there, every shell session will spawn with those resources (all the aliases, commands, variables, and functions stored in those files), loaded, regardless of whether you export it or not, since each shell process will always consult those files before it does anything else (so they effectively pre-emptively import what you are trying to export to them).
bash is like any other script or program. You took away all its inputs and pointers and shortcuts, and now its just been made pretty dumb, so you've got to be explicit with everything you do till you can teach it where to look for stuff (give it a PATH to search) and shorten your conversations with it.
If you don't have a backup of your .bash_profile, here's one that you can use:
# This loads in the configuration in .bashrc
# Put all configuration in there!
if [ -f ~/.bashrc ]; then
source ~/.bashrc
fi
And here's a .bashrc that can get you started:
export PATH="/bin:/sbin:/usr/local/bin:/usr/bin:/usr/sbin:"

Associate .pl with Perl.exe [duplicate]

I want my Perl scripts to behave just like any other executable (*.exe file).
When I double-click on myscript.pl I want it to execute instead of opening in a text editor.
I want to run myscript.pl instead of perl myscript.pl.
I really want to run myscript instead of myscript.pl.
I want to run program | myscript instead of program | perl myscript.pl.
I want to be able to run my script via drag & drop.
There are a number of changes you have to make on Windows to make all of
these things work. Users typically stumble upon things that don't work one at
a time; leaving them confused whether they've made an error, there's a bug in
Perl, there's a bug in Windows, or the behavior they want just isn't possible.
This question is intended to provide a single point of reference for making
everything work up front; ideally before these problems even occur.
Related questions:
How do I make Perl scripts recognize parameters in the Win32 cmd console?
Running a perl script on windows without extension
Perl execution from command line question
How can I read piped input in Perl on Windows?
Perl on Windows, file associations and I/O redirection
How do I create drag-and-drop Strawberry Perl programs?
Note: The actions below require administrative privileges. For
steps utilizing the command prompt it must be launched via "Run as
administrator" on Windows Vista / Windows 7.
Associate *.pl files with perl
Run the following commands at a shell prompt:
assoc .pl=PerlScript
ftype PerlScript=C:\bin\perl.exe "%1" %*
Replace C:\Perl\bin\perl.exe with the path to your Perl installation. This
enables you to run myscript.pl instead of perl myscript.pl.
Default install locations are:
ActivePerl: C:\Perl
Strawberry Perl: C:\Strawberry
Add .PL to your PATHEXT environment variable.
This makes Windows consider *.pl files to be executable when searching your
PATH. It enables you to run myscript instead of myscript.pl.
You can set it for the current cmd session
set PATHEXT=%PATHEXT%;.PL
To set it permanently (under Windows Vista or Windows 7)
setx PATHEXT %PATHEXT%;.PL
Under Windows XP you have to use the GUI:
Right-click My Computer, and then click Properties.
Click the Advanced tab.
Click Environment variables.
Select PATHEXT, then click Edit.
Append ;.PL to the current value.
Make I/O redirection work
I/O redirection (e.g. program | myscript) doesn't work for programs started
via a file association. There is a registry patch to correct the problem.
Start Registry Editor.
Locate and then click the following key in the registry:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
On the Edit menu, click Add Value, and then add the following registry value:
Value name: InheritConsoleHandles
Data type: REG_DWORD
Radix: Decimal
Value data: 1
Quit Registry Editor.
Warning: In principle, this should only be necessary on Windows XP. In my experience it's also necessary in Windows 7. In Windows 10 this is actively harmful—programs execute but produce nothing on stdout/stderr. The registry key needs to be set to 0 instead of 1.
See also:
STDIN/STDOUT Redirection May Not Work If Started from a File Association
Perl Scripts on Windows 10 run from Explorer but not Command Prompt
If patching the registry isn't an option running program | perl -S myscript.pl
is a less annoying work-around for scripts in your PATH.
Add a drop handler
Adding a drop handler for Perl allows you to run a Perl script via drag & drop;
e.g. dragging a file over the file icon in Windows Explorer and dropping it
there. Run the following script to add the necessary entries to the registry:
use Win32::TieRegistry;
$Registry->Delimiter("/");
$perlKey = $Registry-> {"HKEY_CLASSES_ROOT/Perl/"};
$perlKey-> {"shellex/"} = {
"DropHandler/" => {
"/" => "{86C86720-42A0-1069-A2E8-08002B30309D}"
}};
Convert your perl scripts into batch files using pl2bat once they are ready to be run by users.
The trick works through the perl -x switch which, according to perldoc perlrun, makes Perl search for the first line looking like #!.*perl.
After following the instructions in the accepted answer, a double click still led to .pl files opening with Notepad in Windows 10 — even when perl.exe was set as the default file handler.
After finding Jack Wu's comment at ActivePerl. .pl files no longer execute but open in Notepad instead I was able to run perl scripts on double-click as such:
Select and right-click a .pl file
Use the "Open With" submenu to "Choose another app"
Select "Always use this app to open .pl files" (do this now – you won't get the chance after you have selected a program)
Scroll to the bottom of the "Other options" to find "More apps", and select "Look for another app on this PC"
Navigate to C:/path/to/perl/bin/ and select Perl5.16.3.exe (or the equivalent, depending on which version of Perl you have installed: but not Perl.exe)
Then the Perl icon appears next to .pl files and a double-click leads to them opening in Perl every time, as desired.
I tried the assoc and ftype methods and they didn't work for me.
What worked was editing this registry key:
Computer\HKEY_CURRENT_USER\Software\Classes\Applications\perl.exe\shell\open\command
It was set to:
"C:\Perl64\bin\perl.exe" "%1"
When it should be:
"C:\Perl64\bin\perl.exe" "%1" %*
It is the same content as the ftype, but for arcane windows reasons, I had to set it there too.
Like some others, I had set 'assoc' and 'ftype', but also had set Notepad text editor via the GUI, and when I tried to execute a script via the command line, Windows invoked Notepad to edit the script instead of running my script.
Using the GUI to instead point the .pl file association to the script-running executable was not much of an improvement, since it would invoke the executable on my script, but would pass no command-line arguments (even when I invoked my script from the command line).
I finally found salvation here which advised me to delete some registry keys.
Key quote:
"The problem is that if you have already associated the program with the extension via the Open With dialog then you will have created an application association, instead of a file extension association, between the two. And application associations take precedence."
In my case, following the instructions to use RegEdit to delete
HKEY_CLASSES_ROOT \ Applications \ perl.exe
where perl.exe is the name of my Perl executable, and then also deleting:
HKEY_CLASSES_ROOT \ .pl
seemed to solve my problem, and then (after re-executing 'assoc' and 'ftype' commands as shown in other answers) I could then execute scripts from cmd.exe and have them run with access to their command-line parameters.
Some other related information here.

Calling a command line program

I have a executable that when double clicked opens in a command line window.
Now there is a input file (i.e named "sphere_15000.inp") in the same directory where the executable apame_win64.exe is located. So we can inter the file name in the command line.
The question is how this can be done from mathematica front end? With the RunThrough command I tried to do it with no avail.
RunThrough["Executable Location", "sphere_15000"]
Do I need to put this file location in my Windows 7 environment path variable? Hope for some suggestion in this regard.
UPDATE
Found a solution to my problem.
First set the Mathematica directory to the folder where the executable is located.
path="C:\Users\FlowCrusher\Desktop\CUSP solver\Apame_build_2011_01_09\solver";
SetDirectory[path];
Then use the following style of input.
Run["\"\"apame_win64.exe\" \"input\"\""]
Here "apame_win64.exe" is the executable one want to run and "input" is the input file for the executable. This solves the problem. But a new item in the wishlist.
Is there a way to hide the console window in the background?
Here is how it looks on my screen.
As Chris suggested if we use minimized console in the Run command we get a minimized window but the program does not execute.
I hope that a solution exists.
BR
Yes, you might put the folder of you executable into the Path variable, or provide the full path name.
However, RunThrough seems to have been superseeded (on Windows) by
Import["!command ","Text"], which will execute command and read the comaand line output into Matheamtica as a string.
E.g.:
Export["testit.txt", "bla", "Text"];
Import["!dir" <> " testit* > dir.log", "Text"];
FilePrint["dir.log"]
--
Otherwise, I also had good results in the past using NETLink (not sure if WScript.shell
still works on Windows7/8 or if one should use something else).
Emulating Run (RunThrough is not really needed I think):
Run2[cmd_String] := Module[{shell},
Switch[$OperatingSystem,
"Windows",
Needs["NETLink`"];
shell = NETLink`CreateCOMObject["WScript.shell"];
shell # run[cmd,0,True],
"Unix",
Run # cmd,
"MacOSX",
Run # cmd ] ];
Can you run your application with input from a basic command window instead of the application console? This might be the form of command you would need:
apame_win64 -input sphere_15000.inp
or simply
apame_win64 sphere_15000.inp
You can probably check the available switches by running apame_win64 -help
A multi-part command can be run from Mathematica, e.g.
Run["type c:\\temp\\test.txt"]
Alternatively, also returning output to the Mathematica session:
ReadList["!type c:\\temp\\test.txt", String]
I landed here wanting to run abaqus command line on windows.
The solutions provided here worked out for me (Windows 7, Mathematica 9):
SetDirectory#path;
Run["start /min abaqus job=" <> fileName <> " interactive ask_delete=OFF >> log.txt"]
(Here the abaqus option ask_delete=OFF overwrites an existing simulation results and the >> redirects all the output to a file)
I think, minimizing the window did not run in your case since the executable throws open that window. In that case, this might be of some help