1

Wanting to create a function which will add me python logger at each function define I came up on macro:

nnoremap <leader>L :%s/\(\s*\)def \(\w\S*\)\(self.*\):/\0\r\1\tlogging.info(\'\2)\')/g<cr>

It works, but I need eddited filename too, so I added to macro: in \=expand("%p"). Now macro looks like that:

nnoremap <leader>L :%s/\(\s*\)def \(\w\S*\)\(self.*\):/\0\r\1\tlogging.info(\' \=expand("%p") \2)\')/g<cr>

Which doesn't work, because it prints whole =expand("%p") as a text, not as a file name.

It seems to me that in general in text substitution I can use expand if I do not use regex.

I would be terribly grateful for correct macro and explanation why didn't it work.

Sato Katsura
  • 3,066
  • 15
  • 21
pholat
  • 467
  • 5
  • 20

1 Answers1

1

This should work:

nnoremap <leader>L :%s/\(\s*\)def \(\w\S*\)\(self.*\):/\=substitute(submatch(0),submatch(0),'&\r'.submatch(1).'\tlogging.info('''.expand("%p").' '.submatch(2).''')','g')/<cr>

4.2 Substitute *:substitute* *:s* *:su*

:[range]s[ubstitute]/{pattern}/{string}/[flags] [count]

                                    *sub-replace-special* *:s\=*

When the {string} starts with "\=" it is evaluated as an expression, see |sub-replace-expression|. You can use that for complex replacement or special characters.

\= if it is used inside the {string}(i.e not at the begining) it will be taken literally(i.e not as a special character)