Sunday, March 5, 2017

Re: substitute variable into text

On 2017-03-05 12:18, lothar atheling wrote:
> how do i substitute variable into text i am editing?
> also, same question with respect to an expression.
>
> "execute" may work, but it seems something heavy-handed.
> is there a better way?

The usual way to do this is to use

:help sub-replace-special

This lets you do things like

:%s/\d\+/\=submatch(0)+10/g

to increment ever number in your file by 10 (or, due to the lax
expression, decrement negative numbers by 10, as it just finds the
"42" in "-42", and increments that to "52", leaving the result "-52").

You can use any variable in that expression:

:%s/\w\+\(/\=my_prefix.submatch(0).my_suffix/g

which will wrap every "word" in your file with my_prefix/my_suffix.

It's also helpful for remapping words uniformly by creating a
dictionary of inputword->outputword:

:let d={'the': 'DUH', 'a': 'Uh', 'how': 'Huh?'}

and then using them in your replacement:

:%s/\<\(the\|a\|how\)\>\c/\=d[tolower(submatch(0))]/g

Lots of power in that sub-replace-special use of \=

Hope this helps, and leads you to explore whole new worlds of
search & replace power. :-)

-tim





--
--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

---
You received this message because you are subscribed to the Google Groups "vim_use" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vim_use+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments: