9

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

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, this works apart from I had to add 'gv' to the initial normal command to restore the selection before yanking: normal gv"xy
To select the updated string I added: normal [v] (backticks before brackets not showing up in here)
Whoops, missed that, added the gv command in to answer above as you describe.
This almost works. Unfortunately, because of the way vim pastes in front of cursor, unless you're at the end of the line this will shift the selected text forward one character, which was completely wrong for me. See below.
0

I had to back up the cursor position to get this to work properly when text followed selection:

function! Test()
   "yank current visual selection to reg x
   normal! gv"xy
   "get current column position
   let cursor_pos = getpos('.')
   "subtract 1
   let cursor_pos[2] = cursor_pos[2] - 1
   "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
   "set cursor back one
   call setpos('.', cursor_pos)
   "paste new string value back in
   normal "xp
endfunction

Maybe others have Vim's paste functionality configured differently than I do, but unless I used this, the selected/altered text would shift forward on paste.

Update: this still won't work on text selected at the beginning of a line, unfortunately.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.