How to get visually selected text in VimScript

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.

Leave a Comment