Search code examples
recursionvimscriptingkeymapping

Two consecutive identical calls to echo have different output in Vim function


Original post on Vi and Vim Beta, which has had one interesting answer, but not much attention so far. I am sorry for the crossposting and I will ask for the original to be closed/deleted.

Given the following function in the .vimrc file,

fu! MyFun(count)
  echo a:count
  echo a:count
  if a:count > 0
    normal ,
    call MyFun(a:count - 1)
  endif
endf

calling :call MyFun(3) generates the following output.

3
3
2
2
1
1
0
0

However, if I define the mapping nn , :<C-U>execute "call MyFun(" . v:count . ")"<CR>, then the call to :call MyFun(3) generates

3
0
2
0
1
0
0
0

I do understand that the mapping of , makes the MyFun function call itself twice (if a:count > 0), however I cannot understand how this can cause a different result of the two successive calls to echo a:count.


Solution

  • The problem is all about screen redraw (see :h echo-redraw) in Vim.

    Changing echo to echom still produces the same (broken) screen output (3 0 2 0 1 0 0 0), but :mess reveals what is hidden: 3 3 0 0 2 2 0 0 1 1 0 0 0 0.