2

Here's an example:

function! TestCursorPosWithCount() range
    echo virtcol('.')
endfunction

nmap <leader>c :call TestCursorPosWithCount()<CR>

If I press <leader>c, the column number will be shown correctly. But, if I do something like 2<leader>c, the cursor is moved and the column number will be that of the final cursor position.

So, the question: how can I get the original column number inside the function? I.e. the cursor position, as it was before pressing 2 in the last example?


After receiving the answer, I add here my findings: a small function demo with normal & visual mappings, that can extract line & column information from the given situation:

function! TestCursorPosWithCount(mode) range
    if (a:mode == 'n')
        echo 'normal mode'
        echo 'count: ' . v:count
        echo 'position: [' line('.') . ':' . col('.') ']'
    else "visual mode
        echo 'visual mode: ' . visualmode()
        echo 'count: ' . v:count
        if visualmode() !=# 'V'
            echo 'range: [' a:firstline . ':' . col("'<") ' - '
                        \   a:lastline  . ':' . col("'>") ']'
        else
            echo 'range: ['  a:firstline ' - ' a:lastline ']'
        endif
    endif
endfunction

nmap <leader>c :<C-u>call TestCursorPosWithCount('n')<CR>
xmap <leader>c :call TestCursorPosWithCount('v')<CR>
3
  • Did you noticed that, when you remove the <leader> from the mapping, you have no problem calling the function at the right column ? While digging, I yet found nothing about your problem though ...
    – nobe4
    Aug 9, 2015 at 22:22
  • Also, what do you expect to achieve while calling your function with a range ?
    – nobe4
    Aug 9, 2015 at 22:29
  • See :h func-range. By using range, the function will be called only once.
    – VanLaser
    Aug 9, 2015 at 22:51

1 Answer 1

4

When you do :

:2call TestCursorPosWithCount()

... the cursor moves to the beginning of the line 2 and the function is being executed from there.

If you use :<C-u>call TestCursorPosWithCount() instead, the original cursor position is available, and you can also still get the count number using v:count.

1
  • 1
    ... but, you're right about :2call TestCursor... - I can solve it by using :<C-u>call TestCursor ...> (edited your answer a little).
    – VanLaser
    Aug 9, 2015 at 22:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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