Search code examples
vim

Vim does not recognize previous command when issued within a function


I can execute the following command in Vim and then enter @: to repeat the command. This works fine:

:windo silent/foo/|wincmd w
@:

However, when I execute the same command within a function, @: displays an error message saying there is no previous command. How can I get the command within the function to be registered as a command for @:?

function! Find_In_Multiple_Windows(pattern)
  if !empty(a:pattern)
    execute ":windo silent /" . a:pattern . "/|wincmd w"
  endif
endfunction
nnoremap <silent>fw :call Find_In_Multiple_Windows(input("Search for:"))<CR>
fw
Search for: foo
@:
E30: No previous command line

Solution

  • Replace

    execute ":windo silent /" . a:pattern . "/|wincmd w"
    

    with

    call feedkeys(":windo silent /" . a:pattern . "/|wincmd w\n", "t")
    

    which will literally type the command to the command line and execute it, and so the command will be stored to @:.