4

I answered a question that needed a user input using the built-in input() function, which works great.

I was wondering if it was possible to ask vim for (let say) the next 3 characters input, without having to use the input function, and without having to press CR to confirm.

So far I have not found anything in the documentation for this.

Any idea?

1
  • 7
    Use getchar(), 3 times?
    – VanLaser
    May 18, 2016 at 10:39

2 Answers 2

8

Thanks to VanLaser comment, here is a little function to achieve what I wanted:

function! GetNChar()
  let l:number = 3
  let l:string = ""

  while l:number > 0
    let l:string .= nr2char(getchar())
    let l:number -= 1
  endwhile

  echo l:string
endfunction

nnoremap gs :call GetNChar()<CR>

Here I append the chars into a string and display it, but one could do whatever he wants with it.

1
  • 6
    Just to add that :h getchar() also describes some tricky cases to avoid (e.g. "synthetic chars" or special chars).
    – VanLaser
    May 18, 2016 at 10:54
0

Here's the solution from nobe4 slightly improved:

function! InputNChars(number_of_chars, prompt)
    echo a:prompt
    let l:number = a:number_of_chars
    let l:result = ""
    while l:number > 0
        let l:input = nr2char(getchar())
        let l:result .= l:input
        let l:number -= 1
        echon l:input
    endwhile
    return l:result
endfunction

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.