1

It looks like quite a simple question, but I cannot find an answer. Is there a way to detect that the user pressed ESC key while waiting for user input in vimscript? I would like an intuitive way to cancel my function. I've seen that in this similar question, pressing <C-C> is an option, but this doesn't solve the issue and it is not as intuitive from my point of view. Is there an standard approach? What options do we have?

How to stop a function when <esc> is pressed? OR how to catch a <esc> signal in vimscript?

  • 1
    In the title you mention getchar(), the command :echo getchar() returns 27 when the user presses the escape key. So the direct answer to your question would be to check that the result id 27. However you ask for a standard approach: In vim the standard approach to stop something is to press <C-c> so I really don't think that introducing a custom behavior would be more intuitive since it would mean for the user to actively remember that your function doesn't work as all the other functions they are used to. – statox Oct 19 '19 at 17:07
  • 1
    It's not a function, it is an operator that waits for input. I think <C-c> is not intuitive, but maybe you are right. Is the 27 consistent among different OS? – Blasco Oct 19 '19 at 17:46
  • 1
    27 is the ascii ordinal of esc, so yes. – eyal karni Oct 19 '19 at 21:28
1

Here is a (modified) piece from one of my scripts. This now also returns a empty string if <Esc> is hit.

let s:ESC = char2nr("\e")

" Gets a single char from user, returns empty string if Ctrl-C or ESC was hit.
" Ignores special keys (F-Keys, mouse clicks etc).
function! GetChar(message)
    let msg = a:message . " (Ctrl-C to cancel) > "
    try
        echo msg
        let code = ''
        while type(code) != v:t_number
            let code = getchar()
        endwhile
        return code == s:ESC ? '' : nr2char(code)
    catch /Vim:Interrupt/
        return ''
    endtry
endfunction 

A quote from :help getchar():

When [expr] is 0 and Esc is typed, there will be a short delay while Vim waits to see if this is the start of an escape sequence.

| improve this answer | |

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.