1

I'm struggling to write a function that asks the user to input a string, but cuts it off after they've inputted a specific amount of characters (three, for example) and moves on with the rest of the function logic.

An example use-case would be a grep function, where it asks for a pattern, but then automatically begins the grep after three characters and the remaining characters typed act as a filter.

See below for an example of the rough functionality I'm aiming for. After typing "1", "2", "3" the search is automatically executed:

example vim screencast of functionality

I am familiar with getchar() as a way to "fake" it by monitoring raw keypresses and echoing them back, then after three keypresses executing the function. That solution seems imperfect for a number of reasons, the biggest one being that I would have to manually handle several non-ASCII keypresses (backspace, for example) that getchar() captures.

Thank you in advance for the help!

  • 1
    I think you're selling getchar() short. It's exactly what you need but you have to do a little work....not as bad as you make it out to be, though. It's easy to ignore most special (non-ascii) characters, for instance. – B Layer Aug 26 at 2:33
1

Patch 8.0.1445 introduced :h CmdlineChanged , you can use it together with :h input() to get what you want. Here is a simple example i wrote to update last line of current buffer to cmdline while typing in cmdline.

function! s:on_input_change()
  call setline('$', getcmdline())
  redraw
endfunction

function! s:dynamic_input()
  augroup input_test
    au!
    autocmd CmdlineChanged @ call s:on_input_change()
  augroup end

  let str = input("blah : ")

  au! input_test
endfunction

nnoremap \x :call <sid>dynamic_input()<cr>

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.