How can I escape the % and # characters in a Vim command?

John Debs picture John Debs · Apr 14, 2011 · Viewed 9.7k times · Source

I'm using Ack (https://github.com/mileszs/ack.vim) with the --literal flag to search through projects in Vim. I noticed that whenever I search for a string with the % or # characters, the search doesn't match things as I'd expect it to. I did some research and found that it's because Vim will expand these characters in commands (% is the current file and # to something else, not sure what).

This is pretty annoying behavior when performing a search, considering these symbols come up pretty often in code. Is there a way to escape them, preferably automatically, so that the search works as expected? My current mapping is: nnoremap <leader>al :Ack --literal<space>.

Example

Say I have a selector #body in a CSS file someplace and I want to find it. These are the things I've tried (that haven't worked):

:Ack --literal #body
:Ack --literal \#body
:Ack --literal "#body"
:Ack --literal "\#body"

Any ideas why escaping wouldn't work as usual here, or what this is even searching for? I haven't had these examples match anything.

Solution

I've gotten it to work by double-escaping the characters. For example, :Ack --literal "\\#body" will show :ack -H --nocolor --nogroup --column --literal "#body" in the statusline of the result window and bring up the expected results. The quotes seem to be required as well.

Answer

sehe picture sehe · Apr 15, 2011

You just prefix them with a backslash

:!echo %

outputs the current buffer's filename

:!echo \%

prints a solitary '%' character