Question

I am trying to do something really simple in an Ex one-liner: Wrap a HTML line in a PHP echo statement.

<p>Greetings</p>
*run command*
echo "<p>Greetings</p>";

This should be quite simple, given there exists a placeholder to work on the current line only.

I made it work using this command

:s/\v(.*)/echo "\1";/g

However, this makes Vim search for and consequently highlight everything that matches .* (= anything). The entire file is thus highlighted and I have to manually clear the last search or search for some rubbish to clear it.

So to summarize: Is there any existing placeholder or way to refer to the current line during an Ex command?

Was it helpful?

Solution

You can stop the highlighting with :nohlsearch:

:s/\v(.*)/echo "\1";/g | noh

That will still clobber the last search pattern; for full neutralization, use:

:s/\v(.*)/echo "\1";/g | call histdel('search', -1) | let @/ = histget('search', -1) | nohlsearch

Alternatively, you can switch to lower-level functions, to avoid the matching:

:call setline('.', 'echo "' . getline('.') . '";')

PS: You can simplify your search pattern; there's no need to explicitly capture something; have a look at the many other answers for how to simplify it.

OTHER TIPS

this would do:

:s/.*/echo "&";/

It looks like the (.*) is consuming everything, including line breaks. Try something like:

:s/\v(.*)\n/echo "\1";/g

Yes, you can refer to the current line with a dot. For example, ".s/a/b/" substitutes just in the current line, or "3,.s/a/b/" substitutes all lines between the 3rd and the current one. If you do not place a line range in front of the "s", just the current line (".") is assumed automatically.

But that's not your problem. Vim doesn't change the other lines, does it? So the substitute is restricted to the current line, just as it should. The problem is that Vim, after searching for a pattern, highlights this pattern in the whole file. And there's not much you can do about that, except search for rubbish, as you propose yourself.

I'll bet if you look in the source for vim-surround there will be something in there. Or just install that plugin!

I would use...

:s!.*!echo "&";!

...for this job, since it's nice and short, and then...

The entire file is thus highlighted and I have to manually clear the last search or search for some rubbish to clear it.

I have the following mapping in my .vimrc for just such occasions:

nnoremap <Leader>/ :<C-U>nohlsearch<CR>

This allows me to clear the highlight by typing \/.

See:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top