Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: use specified shell on windows #182

Merged
merged 1 commit into from
Mar 22, 2022
Merged

fix: use specified shell on windows #182

merged 1 commit into from
Mar 22, 2022

Conversation

hat0uma
Copy link
Contributor

@hat0uma hat0uma commented Mar 21, 2022

Fix newline_chr,command_sep,comment_sep to be set correctly even if vim.o.shell and the specified shell are different on windows.

Use specified shell to determine command_sep, comment_sep, newline_chr
@akinsho
Copy link
Owner

akinsho commented Mar 21, 2022

This seems to have broken one of the tests for toggling the terminal. Can you have a look? tests are run using plenary
you can run them using PlenaryBustedDirectory tests/ {minimal_init = 'tests/minimal.vim'} from inside a test file

@hat0uma
Copy link
Contributor Author

hat0uma commented Mar 21, 2022

OK. I will check it later.

@hat0uma
Copy link
Contributor Author

hat0uma commented Mar 22, 2022

I checked it, but it seems the test is already broken.
The latest test in master fails the same item.

@akinsho akinsho merged commit 36704dd into akinsho:master Mar 22, 2022
@akinsho
Copy link
Owner

akinsho commented Mar 22, 2022

Thanks @rikuma-t tested this out (on Mac) and nothing exploded, so LGTM, let's hope no other Windows users complain

@Shatur
Copy link

Shatur commented Apr 1, 2022

@rikuma-t this commit breaks my setup. I use cmd as built-in shell (because Neovim is faster with it) and pwsh for toggleterm.
After this commit toggleterm closes right away.

end

local function get_command_sep()
return is_windows and is_cmd() and "&" or ";"
Copy link

@Shatur Shatur Apr 1, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tested it on my machine, on windows separator should always be &.

@hat0uma
Copy link
Contributor Author

hat0uma commented Apr 1, 2022

@rikuma-t this commit breaks my setup. I use cmd as built-in shell (because Neovim is faster with it) and pwsh for toggleterm. After this commit toggleterm closes right away.

I am sorry. My check was insufficient. In my environment, the -NoExit parameter was included, so it was working.

@Shatur
Copy link

Shatur commented Apr 1, 2022

@rikuma-t it's okay. I submitted a fix for it in #191. Could you check it?

@hat0uma
Copy link
Contributor Author

hat0uma commented Apr 1, 2022

& does not seem to work when the built-in shell is powershell.
I have checked with the settings described in :h shell-powershell.

Since command_sep,comment_sep is used to spawn a shell for toggleterm, it appears that vim.o.shell is the correct way to determine this. Looks like I should have fixed only newline_chr.

I reverted command_sep,comment_sep to be determined by vim.o.shell and tested it and it works in both cmd and powershell.
Could you check it as well?

@Shatur
Copy link

Shatur commented Apr 1, 2022

& does not seem to work when the built-in shell is powershell.

Are you using powershell or pwsh (a.k.a powershell core)?

@hat0uma
Copy link
Contributor Author

hat0uma commented Apr 2, 2022

I checked with both to be sure, but neither worked as expected.
Powershell notifies me of AmpersandNotArrowed.
In pwsh, & acts as a Background Operator and exits immediately.

I checked with the following
powershell : 5.1.19041.1320
pwsh : 7.2.2

toggleterm shell : powershell -NoProfile / pwsh -NoProfile
built in shell : same as :h shell-powershell.

  let &shell = 'poweshell " or pwsh
  let &shellcmdflag = '-NoLogo -NoProfile -ExecutionPolicy RemoteSigned - Command [Console]::InputEncoding=[Console]::OutputEncoding=[System.Text.Encoding]::UTF8;'
  let &shellredir = '2>&1 | Out-File -Encoding UTF8 %s; exit $LastExitCode'
  let &shellpipe = '2>&1 | Out-File -Encoding UTF8 %s; exit $LastExitCode'
  set shellquote= shellxquote=

@Shatur
Copy link

Shatur commented Apr 2, 2022

@rikuma-t strange with exactly your configuration I have the following:

powershell:

'-' was specified with the -Command parameter; no other arguments to -Command are permitted.

PowerShell[.exe] [-PSConsoleFile <file> | -Version <version>]
    [-NoLogo] [-NoExit] [-Sta] [-Mta] [-NoProfile] [-NonInteractive]
    [-InputFormat {Text | XML}] [-OutputFormat {Text | XML}]
    [-WindowStyle <style>] [-EncodedCommand <Base64EncodedCommand>]
    [-ConfigurationName <string>]
    [-File <filePath> <args>] [-ExecutionPolicy <ExecutionPolicy>]
    [-Command { - | <script-block> [-args <arg-array>]
                  | <string> [<CommandParameters>] } ]

PowerShell[.exe] -Help | -? | /?

-PSConsoleFile
    Loads the specified Windows PowerShell console file. To create a console
    file, use Export-Console in Windows PowerShell.

-Version
    Starts the specified version of Windows PowerShell.
    Enter a version number with the parameter, such as "-version 2.0".

-NoLogo
    Hides the copyright banner at startup.

-NoExit
    Does not exit after running startup commands.

-Sta
    Starts the shell using a single-threaded apartment.
    Single-threaded apartment (STA) is the default.

-Mta
    Start the shell using a multithreaded apartment.

-NoProfile
    Does not load the Windows PowerShell profile.

-NonInteractive
    Does not present an interactive prompt to the user.

-InputFormat
    Describes the format of data sent to Windows PowerShell. Valid values are
    "Text" (text strings) or "XML" (serialized CLIXML format).

-OutputFormat
    Determines how output from Windows PowerShell is formatted. Valid values
    are "Text" (text strings) or "XML" (serialized CLIXML format).

-WindowStyle
    Sets the window style to Normal, Minimized, Maximized or Hidden.

-EncodedCommand
    Accepts a base-64-encoded string version of a command. Use this parameter
    to submit commands to Windows PowerShell that require complex quotation
    marks or curly braces.

-ConfigurationName
    Specifies a configuration endpoint in which Windows PowerShell is run.
    This can be any endpoint registered on the local machine including the
    default Windows PowerShell remoting endpoints or a custom endpoint having
    specific user role capabilities.

-File
    Runs the specified script in the local scope ("dot-sourced"), so that the
    functions and variables that the script creates are available in the
    current session. Enter the script file path and any parameters.
    File must be the last parameter in the command, because all characters
    typed after the File parameter name are interpreted
    as the script file path followed by the script parameters.

-ExecutionPolicy
    Sets the default execution policy for the current session and saves it
    in the $env:PSExecutionPolicyPreference environment variable.
    This parameter does not change the Windows PowerShell execution policy
    that is set in the registry.

-Command
    Executes the specified commands (and any parameters) as though they were
    typed at the Windows PowerShell command prompt, and then exits, unless
    NoExit is specified. The value of Command can be "-", a string. or a
    script block.

    If the value of Command is "-", the command text is read from standard
    input.

    If the value of Command is a script block, the script block must be enclosed
    in braces ({}). You can specify a script block only when running PowerShell.exe
    in Windows PowerShell. The results of the script block are returned to the
    parent shell as deserialized XML objects, not live objects.

    If the value of Command is a string, Command must be the last parameter
    in the command , because any characters typed after the command are
    interpreted as the command arguments.

    To write a string that runs a Windows PowerShell command, use the format:
        "& {<command>}"
    where the quotation marks indicate a string and the invoke operator (&)
    causes the command to be executed.

-Help, -?, /?
    Shows this message. If you are typing a PowerShell.exe command in Windows
    PowerShell, prepend the command parameters with a hyphen (-), not a forward
    slash (/). You can use either a hyphen or forward slash in Cmd.exe.

EXAMPLES
    PowerShell -PSConsoleFile SqlSnapIn.Psc1
    PowerShell -version 2.0 -NoLogo -InputFormat text -OutputFormat XML
    PowerShell -ConfigurationName AdminRoles
    PowerShell -Command {Get-EventLog -LogName security}
    PowerShell -Command "& {Get-EventLog -LogName security}"

    # To use the -EncodedCommand parameter:
    $command = 'dir "c:\program files" '
    $bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
    $encodedCommand = [Convert]::ToBase64String($bytes)
    powershell.exe -encodedCommand $encodedCommand

[Process exited -196608]

pwsh:

The argument ';#toggleterm#1' is not recognized as the name of a script file.
Check the spelling of the name, or if a path was included, verify that the pat
h is correct and try again.

Usage: pwsh[.exe] [-Login] [[-File] <filePath> [args]]
                  [-Command { - | <script-block> [-args <arg-array>]
                                | <string> [<CommandParameters>] } ]
                  [-ConfigurationName <string>] [-CustomPipeName <string>]
                  [-EncodedCommand <Base64EncodedCommand>]
                  [-ExecutionPolicy <ExecutionPolicy>] [-InputFormat {Text | X
ML}]
                  [-Interactive] [-MTA] [-NoExit] [-NoLogo] [-NonInteractive]
[-NoProfile]
                  [-OutputFormat {Text | XML}] [-SettingsFile <filePath>] [-SS
HServerMode] [-STA]
                  [-Version] [-WindowStyle <style>] [-WorkingDirectory <direct
oryPath>]

       pwsh[.exe] -h | -Help | -? | /?

PowerShell Online Help https://aka.ms/powershell-docs

All parameters are case-insensitive.

[Process exited 64]

@Shatur
Copy link

Shatur commented Apr 2, 2022

Toggleterm settings:

require('toggleterm').setup({
  open_mapping = '<F4>',
  shade_terminals = false,
})

@hat0uma
Copy link
Contributor Author

hat0uma commented Apr 2, 2022

@Shatur Thanks for testing.
I tried running the command generated by Terminal:__spawn() directly on powershell as I don't know the cause.
If I separate them with ;, the subsequent operations are performed in the shell that was launched, but & doesn't seem to work.

PS C:\> echo $PSVersionTable.PSVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      19041  1320


PS C:\> pwsh -NoProfile&#togglerm#1
At line:1 char:16
+ pwsh -NoProfile&#togglerm#1
+                ~
The ampersand (&) character is not allowed. The & operator is reserved for future use; wrap an ampersand in double quotation marks ("&") to pass it as part of a string.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : AmpersandNotAllowed

PS C:\> pwsh -NoProfile;#togglerm#1
PowerShell 7.2.2
Copyright (c) Microsoft Corporation.

https://aka.ms/powershell
Type 'help' to get help.

PS C:\> echo $PSVersionTable.PSVersion

Major  Minor  Patch  PreReleaseLabel BuildLabel
-----  -----  -----  --------------- ----------
7      2      2

PS C:\> powershell -NoProfile&#togglerm#1

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
1      Job1            BackgroundJob   Running       True            localhost            Microsoft.PowerShell.Man…

PS C:\> echo $PSVersionTable.PSVersion

Major  Minor  Patch  PreReleaseLabel BuildLabel
-----  -----  -----  --------------- ----------
7      2      2

PS C:\>

@hat0uma
Copy link
Contributor Author

hat0uma commented Apr 2, 2022

@Shatur I have tested with the following minimum configurations without success...

  • command
nvim -u init.vim
  • Toggleterm output
At line:1 char:92
+ ... le]::OutputEncoding=[System.Text.Encoding]::UTF8; powershell&#togglet ...
+                                                                 ~
The ampersand (&) character is not allowed. The & operator is reserved for future use; wrap an ampersand in double quotation marks ("&") to pass it as part of a string.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : AmpersandNotAllowed

  • cat init.vim
let &shell = has('win32') ? 'powershell' : 'pwsh'
let &shellcmdflag = '-NoLogo -NoProfile -ExecutionPolicy RemoteSigned -Command [Console]::InputEncoding=[Console]::OutputEncoding=[System.Text.Encoding]::UTF8;'
let &shellredir = '2>&1 | Out-File -Encoding UTF8 %s; exit $LastExitCode'
let &shellpipe = '2>&1 | Out-File -Encoding UTF8 %s; exit $LastExitCode'
set shellquote= shellxquote=

lua <<EOF
require('toggleterm').setup({
  open_mapping = '<F4>',
  shade_terminals = false,
})
EOF
  • under stdpath("data")
├─shada
├─site
│  └─pack
│      └─test
│          └─start
│              └─toggleterm.nvim 
└─swap

(branch is Shatur:pwsh-separator)

@Shatur
Copy link

Shatur commented Apr 2, 2022

If I separate them with ;, the subsequent operations are performed in the shell that was launched, but & doesn't seem to work.

Tried the same commands on my machine, I have the same output.

I have tested with the following minimum configuration

Hm... Can confirm, my branch it doesn't work with your configuration. Okay, I will close the PR until we find a better solution.

Could you try the same setup, but with the following init.lua instead of your init.vim:

require('toggleterm').setup({
  shell = 'pwsh',
  open_mapping = '<F4>',
  shade_terminals = false,
})

Run with nvim -u init.lua on the latest mater. You should be able to reproduce my issue.

@Shatur Shatur mentioned this pull request Apr 2, 2022
@hat0uma
Copy link
Contributor Author

hat0uma commented Apr 2, 2022

@Shatur

Run with nvim -u init.lua on the latest mater. You should be able to reproduce my issue.

Can confirm too...

Will my new solution solve your problem?
It worked in my environment with the init.vim and init.lua you presented.If it seems to work, I will open a new PR.

@Shatur
Copy link

Shatur commented Apr 2, 2022

Will my new solution solve your problem?

Yes!

@hat0uma
Copy link
Contributor Author

hat0uma commented Apr 2, 2022

Thank you so much!

@Shatur
Copy link

Shatur commented Apr 2, 2022

Thank you so much!

Thank you too!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants