Reputation: 20211
Is there some kind of trigger or event in Vim that is fired whenever a Vim command is executed?
Eg. say I execute tabnext
or NERDTree
is there some function which can be setup to listen for required events and perform some action when it detects that those events?
Upvotes: 2
Views: 1327
Reputation:
Vim has something called "autocommands" (:help autocmd-intro
). These allow you to execute arbitrary code upon events like saving a file or changing to a different window.
Unfortunately, to my knowledge, there's no autocommand that is executed for any command. It might be possible to do something different, though:
cnoremap <silent> <cr> <cr>:call <SID>CommandCallback()<cr>
function! s:CommandCallback()
let last_command = @:
if last_command =~ 'tabnew'
echomsg "Tabnew was called"
endif
endfunction
This code overrides the <cr>
key ("carriage return", the "enter" key) in command-line mode to press <cr>
and then call the function s:CommandCallback
. You can check the last command in the command-line history with the @:
magic variable, or by using histget
(:help histget()
). You can then inspect the command and do whatever you like with it.
EDIT: Some elaboration on "do whatever you like with it"
If you want some status message visible in the statusline, you could set a global variable with the value, something like let g:command_message = 'Tabnew was called'
. Then, you can render it in your statusline with %{g:command_message}
. You'll need to read :help statusline
to learn how to fit it in your particular statusline, but it shouldn't be difficult.
Opening it in a separate window would be more tricky, because you'd need to open a scratch buffer with particular settings, check if one already exists, and so on. It's perfectly doable, but a pretty long topic. I've got a plugin that might help, but not sure if it would be appropriate for this: https://github.com/AndrewRadev/bufferize.vim. You could also check out this plugin: https://github.com/mtth/scratch.vim. You'll need to experiment, see if any one of these can fit your use case, or you could poke around in their source code, and try to learn how to manage the window yourself (it would be a useful skill to have, so I'd definitely recommend it :)).
Upvotes: 3