Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping "%" in Vim when shelling out, so it's not expanded to filename?

Tags:

vim

Say I have this vimscript as "/tmp/example.vim":

let g:input = "START; % END"
exec("! clear && echo " . shellescape(g:input))

If I open that file and run it with :so %, the output will be

START; /tmp/example.vim END

because the "%" is expanded to the buffer name. I want the output to be

START; % END

I can use the generic escape() method to escape percent signs in particular. This works:

let g:input = "START; % END"
exec("! clear && echo " . escape(shellescape(g:input), "%"))

But is that really the best way? I'm sure there're more characters I should escape. Is there a specific escape function for this purpose? Or a better way to shell out?

like image 463
Henrik N Avatar asked Mar 13 '13 19:03

Henrik N


2 Answers

For use with the :! command, you need to pass the optional {special} argument to shellescape():

When the {special} argument is present and it's a non-zero Number or a non-empty String (|non-zero-arg|), then special items such as !, %, # and <cword> will be preceded by a backslash. This backslash will be removed again by the |:!| command.

:exec("! clear && echo " . shellescape(g:input, 1))
like image 129
Ingo Karkat Avatar answered Oct 16 '22 16:10

Ingo Karkat


You need to properly escape the '%'. So it should be:

let g:input = "START; \\% END"
like image 24
Brandon Avatar answered Oct 16 '22 14:10

Brandon