2

How can I make a visual mapping's behaviour dependent on the number of lines selected?

I tried creating an expr map, but the visual start and end marks don't seem to be correct:

function! Xsurround() abort
    let is_linewise = mode() ==# 'V'
    let line_count = line("'>") - line("'<") + 1
    let g:global_count = line_count
    if is_linewise && line_count == 1
        return "\<Esc>\<Plug>Yssurround"
    else
        return "\<Plug>VSurround"
    endif
endf
xmap <expr> s Xsurround()

After doing vipsb on that block of code and g:global_count is 1. (The current line is surrounded.)

I'm trying to make an xmap for surround so a single selected line gets surrounds at beginning and end of the line instead of on the line before and after (there's already an option to always do the line before and after -- <Plug>VgSurround).

2

I tried creating an expr map, but the visual start and end marks don't seem to be correct:

That's because Vim doesn't set/update the visual marks until you quit visual mode.

Try this:

function! Xsurround() abort
    let is_linewise = mode() ==# 'V'
    let [curpos, pos_v] = [getcurpos()[1:2], getpos('v')[1:2]]
    let control_end = curpos[0] > pos_v[0] || curpos[0] == pos_v[0] && curpos[1] >= pos_v[1]
    if control_end
        let [start, end] = [pos_v, curpos]
    else
        let [start, end] = [curpos, pos_v]
    endif
    let line_count = end[0] - start[0] + 1
    let g:global_count = line_count
    if is_linewise && line_count == 1
        return "\<Esc>\<Plug>Yssurround"
    else
        return "\<Plug>VSurround"
    endif
endf
xmap <expr> s Xsurround()
| improve this answer | |
1
let line_count = line("'>") - line("'<") + 1

This doesn't work as you expect, because you're calling your function from within Visual mode ("expr"-mapping). And so the marks '< and '> are not updated yet. You must do this instead:

let line_count = abs(line(".") - line("v")) + 1

BTW. This is mentioned under :h line().

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.