0

I have the start and end (line/col) pairs for my desired selection.

How to set that as the actual visual selection?

Ex:

I have the buffer:

 1 2
 3 4
 5 6

Start: 2,1

End: 3,2

:cal SetSelection()

Desired visual selection after call:

3 4
5 6

What does 'SetSelection()' look like?

EDIT

best solution so far with error checking based on answers

"put user in visual mode and set the visual selection

"if arguments are not valid, nothing is changed, and raises an exception

":param 1:

    "Visual mode to leave user in.

    "must be either one of:

    "- 'v' for visual (default)
    "- "\<s-v>" for line visual
    "- "\<c-v>" for block visual
":type 1: string

":returns: 0

":raises: bad mode argument, bad position argument
fu! SetSelection( x, y, x2, y2, ... )
    let valid_mode_strings = ["v","\<s-v>","\<c-v>"]

    if a:0 > 0
        if index( valid_mode_strings, a:1 ) >= 0
            let mode = a:1
        el
            th 'bad mode argument: ' . a:1 . ' valid options: ' . join( valid_mode_strings, ', ' )
        en
    el
        let mode = 'v'
    en

    let oldpos = getpos('.')

    if setpos( '.', [0,a:x,a:y] ) != 0
        exe "norm! \<esc>"
        th 'bad position argument: ' . a:x . ' ' . a:y . ' ' . a:x2 . ' ' . a:y2
    en

    exe 'norm! ' . mode

    if setpos( '.', [0,a:x2,a:y2] ) != 0
        exe "norm! \<esc>"
        cal setpos( '.', oldpos )
        th 'bad position argument: ' . a:x . ' ' . a:y . ' ' . a:x2 . ' ' . a:y2
    en
endf
4

2 回答 2

4

你可以使用函数setpos()来完成这项工作:

fun! SetSelection()
    call setpos('.',[0,2,1])
    normal! v
    call setpos('.',[0,3,2])
endf

在上面的代码中,[2,1]and[3,2]应该作为传入的参数。我只是硬编码以使其简单。

还有一些错误处理留给你。例如参数验证等。

于 2013-04-23T22:40:27.917 回答
3

大多数 vim 都有一个m<m>标记用于这个目的。:help m<

call setpos("'<", [0, 2, 1])
call setpos("'>", [0, 3, 2])
normal! gv

一些 vim 安装没有。在这些情况下,您可以保存和恢复用户标记,或使用上下文标记`

call cursor([2, 1])
normal! m`
call cursor([3, 2])
normal! v``
于 2013-04-24T00:45:46.317 回答