system() with powershell in vim

前端 未结 2 509
旧时难觅i
旧时难觅i 2021-01-05 16:55

I\'m trying to write a simple function in Vim to return the results of a powershell command. I keep getting gibberish in the results though.

I think this may be an

相关标签:
2条回答
  • 2021-01-05 17:29

    I've finally figured this out.

    The following modification to my function does pretty much exactly what I want:

    function! Test()
      let @r = system("ls")
      put! r
    endfunction
    

    I think Artomegus is correct, the problem is really the carriage return, and not an encoding problem.

    As a side note, I ran into problems when I had only the following in my .vimrc file:

    set shell=powershell
    set shellcmdflag=-c
    

    With just these settings when I ran :call Test() I would get an error about Vim being unable to read the temp file.

    The fix for this problem is to add the following to your .vimrc file:

    set shell=powershell
    set shellcmdflag=-c
    set shellquote=\"
    set shellxquote= 
    

    You must set the shellquote to be \" and shellxquote to be a blank space (i.e. empty) because by default on windows, shellxquote is set to \" which overrides the value of shellquote. This is problematic when using the system function, which runs the vimrun.exe program behind the scenes.

    Hopefully this helps someone else. I've been stuck on this for a long time, but now powershell works perfectly for me with Vim.

    0 讨论(0)
  • 2021-01-05 17:33

    Try instead set shellcmdflag=\ -c

    Explanation:

    Vim uses tempname() to generate a temp file path that system() reads.

    If &shell contains 'sh' and &shellcmdflag starts with '-' then tempname() generates a temp file path with forward slashes.

    Thus, if set shell=powershell set shellcmdflag=-c then Vim will try to read a temp file with forward slashes that cannot be found.

    A remedy is to set instead set shellcmdflag=\ -c that is, add a whitespace to &shellcmdflag so that the first character is no longer '-' and tempname() produces a temp file path with backward slashes that can be found by system().

    0 讨论(0)
提交回复
热议问题