Is it possible to intercept incoming user commands? For example, if the user executes :echo 'hello', then I would like to compare the string and the command, and change it to execute :echoerr 'hello' instead.

My goal at the end is to intercept commands to check for their uppercase alternative. Vim does not allow lowercase commands as to not conflict with native ones, so I want to intercept commands as they come by and run a check to determine which command to run. For example:

!command Cmd !echo test

If I were to run cmd, Vim would not recognise it as a command. What I want to do is to see if Cmd exists instead, and if so run that command. I would also like to prioritise native commands if there's a conflict.

  • 2
    Could you elaborate a bit more on what you are trying to achieve as this may be an XY problem? This gist by romainl on overloading :grep may be a starting point depending on your use case. Feb 24 '21 at 0:30
  • @AndrewHo-Lee Certainly. I updated my question.
    – daedsidog
    Feb 27 '21 at 14:32
  • My goal at the end is to intercept commands to check for their uppercase alternative. In other words, to overwrite a built-in command. This is forbidden.
    – Matt
    Feb 27 '21 at 15:29
  • What you can do is to play around cnoremap / cnoreabbr. Something that was already pointed by the link above.
    – Matt
    Feb 27 '21 at 15:33
  • I don't want to overwrite a built-in command. I want to redirect a nonexistent command somewhere else. The problem with cnoreabbr is that it abbreviates things I would otherwise not want.
    – daedsidog
    Feb 27 '21 at 15:33

Reading between the lines of your question, I think what you want to do is to to be able to type user-defined commands in lower case. If that is the case, as discussed in the comments, cnoreabbrev is one way of doing this. Something like this may help you get started:

let c_all = getcompletion("*", "command")->filter({_, v -> v =~# "^[A-Z]"})
for c_orig in c_all
    let c_lower = tolower(c_orig)
    if ! exists(':' . c_lower)
        execute "cnoreabbrev <expr> " . c_lower . 
                    \ " (getcmdtype() ==# ':' && getcmdline() ==# '" . c_lower . "') ? '" 
                    \ . c_orig . "' : '" . c_lower . "'"

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.