Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get visually selected text in VimScript

Tags:

vim

I'm able to get the cursor position with getpos(), but I want to retrieve the selected text within a line, that is '<,'>. How's this done?

UPDATE

I think I edited out the part where I explained that I want to get this text from a Vim script...

like image 917
guillermooo Avatar asked Oct 07 '09 19:10

guillermooo


1 Answers

I came here asking the same question as the topic starter and tried the code by Luc Hermitte but it didn't work for me (when the visual selection is still in effect while my code is executed) so I wrote the function below, which seems to work okay:

function! s:get_visual_selection()     let [line_start, column_start] = getpos("'<")[1:2]     let [line_end, column_end] = getpos("'>")[1:2]     let lines = getline(line_start, line_end)     if len(lines) == 0         return ''     endif     let lines[-1] = lines[-1][: column_end - 2]     let lines[0] = lines[0][column_start - 1:]     return join(lines, "\n") endfunction 

I hope this is useful to someone!

Update (May 2013): Actually that's not quite correct yet, I recently fixed the following bug in one of the Vim plug-ins I published:

function! s:get_visual_selection()     " Why is this not a built-in Vim script function?!     let [line_start, column_start] = getpos("'<")[1:2]     let [line_end, column_end] = getpos("'>")[1:2]     let lines = getline(line_start, line_end)     if len(lines) == 0         return ''     endif     let lines[-1] = lines[-1][: column_end - (&selection == 'inclusive' ? 1 : 2)]     let lines[0] = lines[0][column_start - 1:]     return join(lines, "\n") endfunction 

Update (May 2014): This (trivial) code is hereby licensed as public domain. Do with it what you want. Credits are appreciated but not required.

like image 192
xolox Avatar answered Oct 02 '22 14:10

xolox