DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

Loop over Visual Selection in Vim Script


Create file testPos.vim:

function! GetSelection()
  echo "in func"
  let start = line("v")
  echo "start: " . start
  let end = line(".")
  echo "end: " . end
  let firstLine = line("'<")
  echo "start2: " . firstLine
  let lastLine = line("'>")
  echo "end2: " . lastLine
endfunction

noremap <silent> <F4> :call GetSelection()<CR>

In the same folder, open a file with vim, run :so testPos.vim. Move the cursor to line 3, press , get the following output:

in func
start: 3
end: 3
start2: 7
end2: 11

In visual mode, select line 11 to 13, press , the output:

in func
start: 11
end: 11
start2: 11
end2: 13
in func
start: 12
end: 12
start2: 11
end2: 13
in func
start: 13
end: 13
start2: 11
end2: 13

The output shows in visual mode, the function will be run several times for each line.

So a function need only deal with the current line, with content getline('.'), or line number line('.'). No matter in visual mode or not, the function will work fine.



Published

Jul 2, 2016

Last Updated

Jul 2, 2016

Category

Tech

Tags

  • vimscript 1
  • visual 2

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor