0

I am using this mapping:

" Class: transform init arg to variable assignment
" <Esc> is input as Ctrl + v <Esc> and shows as ^[
nnoremap » :norm 0wiself.<Esc>w"byiwEDa = <Esc>"bp

to be able to transform, in Python, a line taken from a Python Class init args to variable assignment.

1  def __init__():
2      self,
3      arg_1: str,
4      arg_2: str = "default_value",
5      arg_3: str = "another_default_value",
6  ):
7      self.arg_1 = arg_1
8      self.arg_2 = arg_2
9      self.arg_3 = arg_3

I can yank the lines 3, 4 and 5, and paste them after line 6, and then use the custom mapping to transform each line into the variable assignment:

arg_1: str, becomes self.arg_1 = arg_1

How can I adapt the mapping so that I could do to transform all the lines at once instead of going over each line individually ?

1

You know, if you just enter a number before your mapping it almost works. That's because for, say, Vim will behind the scenes add .,.+2 after the : that precedes norm. You'd just need to do a bit more tweaking to your command to get it right. But that command is starting to get a bit unwieldy already. So alternatively...

You can use a routine substitution. For example...

:s/\v^(\s*)([^:]+):.*/\1self.\2 = \2

If you put that in a mapping...

:nnoremap » :s/\v^(\s*)([^:]+):.*/\1self.\2 = \2<cr>

...then, based on the same mechanism described above, you can enter the number of lines first and that number of lines will be effected.

So will effect current line and following two.

4
  • That’s great, thank you very much. However, it highlights many lines or other terms. I tried adding |nohl and |nohl<cr> at the end of the mapping but without success. Any idea on how to prevent this ? Mar 12 at 13:01
  • Sure. An easy way it to just add <c-l> (for Control-L) at the end of the mapping. This is the screen redraw command (:h CTRL-L).
    – B Layer
    Mar 12 at 13:10
  • Great. I also just have found another solution by adding <bar>:nohl<cr> at the end of the mapping. Thanks again. Mar 12 at 13:12
  • 1
    Yes, or \|:nohl<cr>. Both yours and this one escape the bar (or pipe) character | which is required in mappings if you're trying to use it as a command separator.
    – B Layer
    Mar 12 at 13:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.