Thursday, May 20, 2021

Re: using a variable in a substitute command

On 2021-05-19 19:16, Chris Jones wrote:
> Now I tried to replace the "echom g:counter" command by a
> :s(ubstitute) command, e.g.
>
> | :s/^# \(.*$\)/# \\textit{\=g:counter: \0}
>
> Unfortunately this is what I got:
>
> | # \textit{=g:counter: <header content>}
> | ... i.e.
> | # \textit{=g:counter: title of chapter #1}
> | # \textit{=g:counter: title of chapter #2}
> | # \textit{=g:counter: title of chapter #3}
> | etc.
>
> In other words what gets substituted is (among other things) the
> *name* of the variable NOT its contents.

So close.

The magic you're looking for is to *begin* your replacement with

\=

and everything that follows (up to the next delimiter, usually a "/")
is evaluated as an expression. So you can do something like

:s/^# \zs\(.*\)/\='\\textit{'.g:counter.': '.submatch(0).'}'

(I might have the number of escaping "\"s wrong before the "textit")

You can even use the filename itself (available in the "%" register)
in that expression, something like

s/^# \zs\(.*\)/\='\\textit{'.substitute(@%, 'f\(.*\).md', '\1',
'').': '.submatch(0).'}'

to capture the filename. That way, even if the buffer-list gets out
of order, you're still pulling in the expected file-number based on
the filename.

Hope this gives you the tools you need to feel like you can dominate
this task. :-)

-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.
To view this discussion on the web visit https://groups.google.com/d/msgid/vim_use/20210520113716.59eaa2c1%40bigbox.attlocal.net.

No comments: