Reputation: 450
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:
Upvotes: 9
Views: 2192
Reputation: 3678
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.
Upvotes: 0
Reputation: 22266
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
Upvotes: 7