Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vim

macvim

ack

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.

like image 580
John Debs Avatar asked Apr 14 '11 20:04

John Debs


People also ask

How do you pass ampersand in XML string?

xml version="1.0"?> An ampersand a character reference can also be escaped as &amp; in element content of XML.


2 Answers

You just prefix them with a backslash

:!echo %

outputs the current buffer's filename

:!echo \%

prints a solitary '%' character

like image 54
sehe Avatar answered Oct 18 '22 19:10

sehe


Apparently you have to escape multiple times as mentioned in an ack.vim issue:

:Ack \\\#foo
like image 36
brianpeiris Avatar answered Oct 18 '22 19:10

brianpeiris