How to quickly edit vim variable content?

2018-04-30 10:45:30

In vim I sometimes want to quickly change the content of a variable using its current content as template using vim editing capabilities.

For example I want to append the word "bar" to the existing variable myvar.

let myvar="foo"

A possible workflow could be a ex-command (say Edit) editing myvar in a new buffer with "foo" as its contend and upon saving the buffer it would overwrite the new content (i.e. "foo bar") to the variable:

:Edit myvar

I feel there must be an elegant solution, possibly even another workflow than the one outlined above.

You've picked an unfortunate example, as it's more easily achieved with:

let myvar .= 'bar'

Still, for more complicated edits, you could use the following commands:

Insert the variable into the buffer:

o=myvar

N.B. In the above, denotes a press of Ctrl-R, and is a press of Return.

Perform your edits.

Reassign the contents of the line to the variable and delete the line:

:let myvar = getline(

  • You've picked an unfortunate example, as it's more easily achieved with:

    let myvar .= 'bar'

    Still, for more complicated edits, you could use the following commands:

    Insert the variable into the buffer:

    o=myvar

    N.B. In the above, denotes a press of Ctrl-R, and is a press of Return.

    Perform your edits.

    Reassign the contents of the line to the variable and delete the line:

    :let myvar = getline('.') | d

    Steps 1 & 3 can be converted into mappings:

    :nnoremap ev "o\=" . input('Variable: ', 'myvar', 'var') . "\"

    :nnoremap av ':let ' . input('Variable: ', 'myvar', 'var') . " = getline('.') d\"

    These prompt the user for which variable they want to edit/assign to, offering a default of myvar, and using variable completion so you don't have to type out the whole variable name.

    If you always want to edit myvar, you can just replace the call to input() with myvar. If you only want to be asked in the first mapping,

    2018-04-30 11:16:07