How to repeatedly add text on both sides of a word in vim?

I have a bunch of local variable references in a Python script that I want to extract from a dictionary. Therefore, I need to change significantly foo, barand others on env['foo'], env['bar']and so on. Do I need to write a regular expression and match each variable name for conversion, or is there a more direct approach that I could just repeat with the command .?

+5
source share
4 answers

You can use a macro: enter these commands at a time (with an interval to insert comments)

             " first move to start of the relevant word (ie via search)
qa           " record macro into the a register.
ienv['<esc>  " insert relevant piece
ea']         " move to end of word and insert relevant piece
q            " stop recording

, , @a, ( @@, ).

+6

- . cmdline, , :

%s/\\(foo\|bar\|baz\\)/env['\1']/

foo, bar baz . , , , OR . , .

+5

, , .vimrc :

function! s:surround()
    let word = expand("<cword>")
    let command = "%s/".word."/env[\'".word."\']/g"
    execute command
endfunction
map cx :call <SID>surround()<CR>

, .

, , :

function! s:surround()
    let word = expand("<cword>")
    let before = input("what should go before? ")
    let after = input("what should go after? ")
    let command = "%s/".word."/".before.word.after."/g"
    execute command
endfunction
map cx :call <SID>surround()<CR>

, :

function! s:surround()
    let word = expand("<cword>")
    let before = input("what should go before? ")
    let after = input("what should go after? ")
    let command = "%s/".word."/".before.word.after."/c"
    execute command
endfunction
map cx :call <SID>surround()<CR>
+3
source

I figured out one way to do what I need. Use q{0-9a-zA-Z"}to write strokes to the buffer. Place the cursor on the descending variable name, then cwenter env['']. Then move the cursor back one space to the last quote and insert the buffer filled with the command cwwith P. Finally, reuse the entry with @{0-9a-z".=*}for each variable.

0
source

All Articles