The purpose of this article is to detail a new method to react to user input as it is typed. This article will discuss the old method used in many fuzzy-finders, then I will show a heavily annotated code snippet which details the new method along with various pros and cons, finally I will provide two use cases.

Old Method

Previously, the popular method would be to use a combination of a loop and calls to getchar(). While this works, it is not pretty and the implementation can get hairy since you must implement all non-character keys such as delete/backspace, <C-u>, carriage return, etc.. The following is a simple implementation which doesn’t handle many edge cases.

Another method that could be used in Neovim (although it has edge-cases which don’t trigger the callback) would be to call input() and provide it a highlight callback in the {opts} dictionary. This callback would have to return an empty list.

New Method

With the release of Vim (v8.0.1445) and Neovim (v0.3.2), there is now a new (and in my opinion simpler) approach to achieve the same result. It consists of combining a call to input() along with the autocmd CmdlineChanged (which was the change to both Vim and Neovim which gave rise this new method). The following is an annotated snippet which demonstrates this method in action.

The above code will query input from the user, update the first line in the file with the currently typed word, and update the second line in the file with the result of the call to input(). Nothing special, but it could easily be modified to perform significantly more complex tasks as will be shown below.

Pros

The biggest pro is that you don’t have to account for edge-cases. If someone has a command-line mode mapping, it will just work. As well, all the keys such as backspace/delete, carriage return, etc. work and all you must implement is what happens when the text actually changes. Those gory details are abstracted for you.

Cons

As with most abstractions, the downside with this approach is the loss of granularity. Even though I had mentioned fuzzy-finders previously, this method would not work well with a standard fuzzy finder since you don’t have the ability to override what keys do. For example, as input is typed, you may wish to override <Up> and <Down> to allow the user to choose from a list of suggestions. With this new method it is not possible.