How to get visually selected text in VimScript

后端 未结 11 1842
北荒
北荒 2020-11-27 14:30

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

11条回答
  •  北海茫月
    2020-11-27 15:03

    Modified version of @DarkWiiPlayer answer.

    The differences are:

    1. It test &selection to give the proper functionality when

    :behave mswin
    

    As well as the default:

    :behave xterm
    

    2. It also works properly for visual block selections testing visualmode()

    I'm also returned the visual selection as an array of lines (becuase that is what I needed). However I've left the return join(lines, "\n") in commented out if you need a signal text block instead.

    function! VisualSelection()
        if mode()=="v"
            let [line_start, column_start] = getpos("v")[1:2]
            let [line_end, column_end] = getpos(".")[1:2]
        else
            let [line_start, column_start] = getpos("'<")[1:2]
            let [line_end, column_end] = getpos("'>")[1:2]
        end
    
        if (line2byte(line_start)+column_start) > (line2byte(line_end)+column_end)
            let [line_start, column_start, line_end, column_end] =
            \   [line_end, column_end, line_start, column_start]
        end
        let lines = getline(line_start, line_end)
        if len(lines) == 0
                return ['']
        endif
        if &selection ==# "exclusive"
            let column_end -= 1 "Needed to remove the last character to make it match the visual selction
        endif
        if visualmode() ==# "\"
            for idx in range(len(lines))
                let lines[idx] = lines[idx][: column_end - 1]
                let lines[idx] = lines[idx][column_start - 1:]
            endfor
        else
            let lines[-1] = lines[-1][: column_end - 1]
            let lines[ 0] = lines[ 0][column_start - 1:]
        endif
        return lines  "use this return if you want an array of text lines
        "return join(lines, "\n") "use this return instead if you need a text block
    endfunction
    

提交回复
热议问题