I am trying to define a string in vimscript containing a literal #
which then gets passed to a shell command using execute
.
function! g:Call_imagemagick_with_hex(hex_color)
let a:display_command = "! display -size 300x300 xc: '\#" . a:hex_color . "'"
execute a:display_command
"echo(a:display_command)
endfunction
and I would call this function like
:call Call_imagemagick_with_hex('34495e')
what I want the shell to see via execute
' is:
display -size 300x300 xc: '#34495e'
The problem is that if #
appears unescaped in the string passed to execute
, vim tries to expand it - it seems #
is like %
but represents the previous buffer. e.g. If I use
let a:display_command = "! display -size 300x300 xc: '#" . a:hex_color . "'"
vim tries to expand #
and throws an error. If I use
let a:display_command = "! display -size 300x300 xc: '\#" . a:hex_color . "'"
the shell sees:
display -size 300x300 xc: '\#34495e'
and the shell command doesn't work. From learning vimscript the hardway
Using single quotes tells Vim that you want the string exactly as-is, with no escape sequences. The one exception is that two single quotes in a row will produce one single quote.
It seems if '
does protects against meta-character expansion, it's possibly only in certain contexts.
Otherwise, how can I pass a #
character to an underlying shell command?
shellescape()
looks interesting. I tried your command and it seems to work from the point of dealing with the#
thanks\\#
? See:help string
.+ display -size 300x300 'xc:\#59a7da'
. I'm still confused by this issue. it seems like vim's user interface, vimscript seems modal too, i.e. the rules about when metacharacters are escaped depends on the command using the string...:execute "!echo \\\\#"
or:execute '!echo \\#
.