Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Vim a script/plugin, how do I visual selection string then replace with a new string?

Tags:

vim

I want to try writing a few simple VIM plugins. What I have in mind to would involve taking the current visual selection, processing that string then replacing the selection with the result. Later I'd like to try extend this to work with text objects and ranges.

Specifically I'd like to know how to:

  • Get a string from the current character-wise selection
  • Delete the selection
  • Insert my new string
like image 494
DavidNorth Avatar asked Dec 18 '10 21:12

DavidNorth


People also ask

How do I highlight and replace in Vim?

By pressing ctrl + r in visual mode, you will be prompted to enter text to replace with. Press enter and then confirm each change you agree with y or decline with n .

How do I use visual mode in Vim?

To get into the Vim Visual Line mode, press “Shift+V” while you are in Vim's Normal mode.


1 Answers

There are different ways to do it. Below is one. Assumes you want to get value of current selection and use it somehow in deciding what new string to substitute; if new string is completely independent you could take out a step or two below:

"map function to a key sequence in visual mode
vmap ,t :call Test()<CR>

function! Test()
   "yank current visual selection to reg x
   normal gv"xy
   "put new string value in reg x
   " would do your processing here in actual script
   let @x = @x . 'more'
   "re-select area and delete
   normal gvd
   "paste new string value back in
   normal "xp
endfunction
like image 191
Herbert Sitz Avatar answered Oct 22 '22 13:10

Herbert Sitz