Skip to content

About

Special console readline intended for interactive console applications or cli-like UI widgets

Resources

Stars

8 stars

Watchers

1 watching

Forks

Repository files navigation

CI NuGet Coverage License: MIT

Interactive ReadLine

An extensible, composable GNU Readline-style line editor for interactive .NET console applications. It includes customizable key behaviors, colored formatting, lexers, tab auto-complete, and navigable history, with ready-made components for common configurations.

InteractiveReadLine targets .NET Standard 2.0 and .NET 10 and has no external runtime dependencies.

Install

InteractiveReadLine is available from NuGet:

dotnet add package InteractiveReadLine

Then import the namespace and read a line:

using InteractiveReadLine;

string? text = ConsoleReadLine.ReadLine();

See the API reference, the detailed history guide, or the demo project for more examples.


Overview

This library provides GNU Readline-like editing for interactive C# programs that use System.Console or another console-like UI component through a custom IReadLineProvider.

var text = ConsoleReadLine.ReadLine();

Example

However, practically every aspect of the system's behavior is configurable. Configuration falls into the following categories:

  • Key Behaviors: determine what happens when a key is emitted from the console, allow for all of the standard behaviors, as well as custom behaviors, to be mapped to key information.

  • Formatters: allows text (in raw form or tokenized) to be intercepted before display and formatted with a prefix/suffix and foreground/background colors. In the simplest form this might simply be display a static prompt, in the most complex it could be active validation with syntax highlighting and a live help tip.

  • Lexers: provide for the splitting of text into tokens. A simple, composable regex-based lexer is provided, but the system was structured to hopefully allow integration of ANTLR style lexers without excessive pain. Lexers form the basis for the autocomplete mechanism.

  • Autocomplete: a way to provide suggestions for the token under the cursor which the system can cycle through, allowing you to provide context aware assistance to the user.

  • History: a way to provide lines that were entered previously so that the user can select from them, similar to how many terminals provide a history of entered commands.

These features are configured by supplying Action<...> and Func<...> delegates to a configuration object, rather than by implementing a large set of custom interfaces.

Below is a more complex example, the full code for which can be seen at Demos/ComplexConfig.cs

var config = ReadLineConfig.Empty
    .AddStandardKeys()
    .AddTabAutoComplete()
    .AddKeyBehavior('?', HelpAction) 
    .SetFormatter(Formatter)
    .SetAutoCompletion(AutoComplete)
    .SetLexer(lexer);

string? result = ConsoleReadLine.ReadLine(config);

Example

Demo Program

The repository includes an interactive demo project with examples of different features and configurations. Run it from the repository root:

dotnet run --project InteractiveReadLine.Demo

Navigate the demo from the console to run each example and display a link to its source file.

Example


Design Philosophy

Obviousness and Correctness

The design of this library's API was based on an attempt to do two things:

  1. Have one obviously correct way of doing each thing
  2. Construct the API in such a way that it's difficult to produce invalid data
  3. Have as few 'special' or hard-coded features as possible, rather use the same customization mechanisms to implement even the basic functionality

Delegates instead of Objects

For the most part, this library makes every attempt to avoid creating a huge taxonomy of objects and interfaces for all of the pluggable components. Because the various actions (like key behaviors, tokenizing, formatting, etc) are simple and have minimal inputs and outputs, this library instead favors the use of delegates.

This approach was selected for the following benefits:

  1. It allows for quicker, easier composition of code, especially via lambdas where possible
  2. It discourages the preservation of state in mechanisms that should primarily exist to perform actions or transformations, but does not preclude an object from exposing a method that can be used instead while still maintaining access to the object state

Documentation

A large part of the motivation for creating this library was my frustration with a dearth of documented alternatives. In the absence of good documentation, it's often true that it takes less time to re-implement a piece of software than it does to understand how the original author intended it to work.

I've made it a priority to provide as many code examples as possible for all of the different library features, as well as heavily comment the internals of the library for anyone who finds themselves having to work with its guts.

Testing

In conjunction with documentation, unit testing is a priority to ensure that the code works as intended even through changes. Most of the complex parts of the library were developed directly through test writing, and my goal has been to cover all of the internal machinery of the library (the readline handler, the console provider, the regex lexing engine, and the token/sequence) with tests immediately. The built-in behaviors, like the various key and formatting behaviors, will be covered by tests as time permits.


Code Documentation

Currently, the library only works with a provider written to wrap the System.Console object. However, a provider only needs to implement four methods which consist of displaying text and reading keyboard input, synchronously and asynchronously, in order to be a usable backend (see the IReadLineProvider interface), so it should be straightforward to write a provider for a WinForms or WPF text box, a console in a game engine, or similar.

Configuration Object

The most trivial version of reading a line of input from the console is:

var text = ConsoleReadLine.ReadLine();

This will produce a prompt-less console input that allows for basic typing, delete, backspace, and arrow keys.

This simple example hides the fact that a handler object (ReadLineHandler) is created behind the scenes in the ConsoleReadLine.ReadLine() method. The ReadLineHandler receives both an IReadLineProvider and a ReadLineConfig configuration object in its constructor. If no configuration object is provided, it creates a basic configuration (ReadLineConfig.Basic) behind the scenes which provides character insertion, enter, and the basic editing keys.

We can create an empty configuration object manually to pass in to the provider. We will need to add some functionality to it if we don't want the user to be trapped in it indefinitely.

var config = ReadLineConfig.Empty
    .SetDefaultKeyBehavior(CommonKeyBehaviors.InsertCharacter)
    .AddEnterToFinish();

var text = ConsoleReadLine.ReadLine(config);

This is the minimum configuration needed to insert characters when they are typed and complete the input when the enter key is pressed. Note that this is less functionality than the basic configuration.

All special behavior relating to the readline operation is added through the configuration object.


Key Behaviors

Key behaviors are actions that are invoked on a keypress and typically perform some mutation on the line being edited by the user. As was mentioned before, an Empty configuration has no functionality in it, and so is a blank starting point for a completely custom setup.

A key behavior is added to a configuration by the .AddKeyBehavior(...) extension method. There are several overloads to make it convenient, but at the heart a ConsoleKeyInfo object is given to define what specific keypress invokes the associated action. This allows for a key character as well as modifier keys (shift/ctrl/alt) to be specified. There is also a shortcut for adding a behavior with a plain control key in the .AddCtrlKeyBehavior(...) method.

The key behavior itself is any function or method that takes an IKeyBehaviorTarget as its single argument, such as an Action<IKeyBehaviorTarget>, a class method, or a lambda. The action is bound to the key information and invoked when the key is pressed. IKeyBehaviorTarget exposes several properties of the readline handler so that the action can mutate it, for example by inserting the pressed key, deleting the last character, or invoking auto-completion.

Pre-Built Key Behaviors and Bindings

There are several pre-made key behaviors and bindings that can be used to satisfy most normal use cases.

To clarify, a key behavior is a mutation that can be applied to the readline state. For example, deleting a character, inserting a character, moving the cursor, these are key behaviors. A comprehensive set of pre-made behaviors exists in the CommonKeyBehaviors class and can be easily added to a configuration. However, you will not likely need to use them directly unless you're trying to set up a non-standard set of key bindings.

A binding links a behavior to an actual key. For example, a behavior which moves the cursor one position to the right can be bound to the right arrow, or to ctrl+arrow, or to the "h" key like in vim.

There are many pre-made bindings as well. These exist in BehaviorExtensionMethods.cs and can be used to compose most standard set of key bindings.

  • AddEnterToFinish() binds the action that completes the line input to the enter key
  • AddHomeAndEndKeys() binds the home and end keys to move the cursor to the beginning and end of the line, respectively
  • AddArrowMovesCursor() binds the left and right arrows to move the cursor one character in their respective directions
  • AddUpDownHistoryNavigation() binds the up and down arrows to history navigation, which will require the history mechanism to be set up for it to work
  • AddCtrlNavKeys() adds navigation and editing commands familiar to Bash users, such as cutting a word, cutting to the beginning or end, and jumping to the beginning or end. It also binds Ctrl+Y to paste back what was cut, and Ctrl+D to delete forward or signal the end of input when the line is empty
  • AddCancelKeys() binds Ctrl+C to abandon the current line
  • AddStandardKeys() adds the complete basic set of bindings used by ReadLineConfig.Basic: default character insertion, Enter to complete the line, Delete, Backspace, Home, End, the arrow keys, and Ctrl+C to abandon the line
  • AddTabAutoComplete() binds tab to the autocompletion behavior

These are cumulative, so the following is a valid way to set up a configuration:

var config = ReadLineConfig.Empty
    .AddStandardKeys()
    .AddCtrlNavKeys()
    .AddTabAutoComplete();

var text = ConsoleReadLine.ReadLine(config);

Custom Key Bindings

A custom key binding is performed with the .AddKeyBehavior(...) method. For example, to bind the down arrow to the delete behavior:

var config = ReadLineConfig.Basic
    .AddKeyBehavior(ConsoleKey.DownArrow, CommonKeyBehaviors.Delete);

Or, to bind the CutToStart action to Alt+s

var config = ReadLineConfig.Empty
    .AddKeyBehavior(new KeyId(ConsoleKey.S, false, true, false), CommonKeyBehaviors.CutToStart)
    .AddEnterToFinish();

You can write the same binding without constructing a KeyId by passing the modifiers directly. The three booleans are control, alt, shift, in that order:

var config = ReadLineConfig.Empty
    .AddKeyBehavior(ConsoleKey.S, false, true, false, CommonKeyBehaviors.CutToStart)
    .AddEnterToFinish();

Or, to bind the '?' character to end the input:

var config = ReadLineConfig.Empty
    .AddKeyBehavior('?', CommonKeyBehaviors.Finish)
    .SetDefaultKeyBehavior(CommonKeyBehaviors.InsertCharacter);

Binding a key that is already bound replaces its existing behavior without raising an error. You can therefore use a pre-built configuration as a starting point and selectively override its bindings:

// Basic maps the down arrow to history navigation; this replaces that binding
var config = ReadLineConfig.Basic
    .AddKeyBehavior(ConsoleKey.DownArrow, CommonKeyBehaviors.Delete);

Custom Key Behaviors

A custom key behavior is simply an action which mutates the state of the IKeyBehaviorTarget. For example, the following creates an action that replaces the text in the buffer and binds it to the down arrow key.

var config = ReadLineConfig.Basic
    .AddKeyBehavior(ConsoleKey.DownArrow, target =>
    {
        target.TextBuffer.Clear();
        target.TextBuffer.Append("I have replaced all of your text");
        target.CursorPosition = target.TextBuffer.Length;
    });

var text = ConsoleReadLine.ReadLine(config);

The following creates a new default input behavior which doesn't insert a character into the text buffer unless it is a digit:

var config = ReadLineConfig.Empty
    .SetDefaultKeyBehavior(target =>
    {
        // target is an IKeyBehaviorTarget
        if (char.IsDigit(target.ReceivedKey.KeyChar))
        {
            // here we add the character to the target's text buffer at the current cursor position and 
            // then advance the cursor position by a single place
            target.TextBuffer.Insert(target.CursorPosition, target.ReceivedKey.KeyChar);
            target.CursorPosition++;
        }
    })
    .AddDeleteBackspace()
    .AddEnterToFinish();

Cutting and Pasting

The three cut behaviors store removed text in a cut buffer. CommonKeyBehaviors.Paste inserts that text at the cursor. AddCtrlNavKeys() binds all four behaviors:

Key Behavior
Ctrl+K cut from the cursor to the end of the line
Ctrl+U cut from the cursor to the start of the line
Ctrl+W cut the word before the cursor
Ctrl+Y paste the cut buffer at the cursor

To move text within a line, cut it, move the cursor, and paste it. Pasting does not empty the buffer, so you can insert the same text more than once.

Why Ctrl+Y? GNU Readline and many terminal applications conventionally use Ctrl+Y to paste. Ctrl+V conventionally inserts the next character literally, and many terminal emulators intercept it before the program receives it.

Consecutive cuts accumulate. Cutting three words in a row with Ctrl+W collects all three in the buffer, so one paste restores them together. The buffer preserves the text's original order on the line. Pressing any other key ends the run, so the next cut starts a fresh buffer.

The buffer belongs to a single read line operation and starts empty each time, so text cut on one line cannot be pasted onto the next.

Cutting From a Custom Behavior

A custom behavior can add text to the buffer. It must specify which side of the cursor the text came from so that consecutive cuts preserve the correct order:

// Removing text from in front of the cursor
target.CutForward(removedText);

// Removing text from behind the cursor
target.CutBackward(removedText);

Calling either method also marks the keypress as part of a cut run, so a custom cut accumulates with the built-in cuts.


Canceling and Ending Input

A user can end a read line operation in three ways. Enter typically finishes the line, Ctrl+C abandons it, and Ctrl+D on an empty line signals that the user has no more input.

The ReadLine() method converts all three outcomes to strings. This convenient API cannot distinguish an abandoned line from an entered empty line:

The user pressed ReadLine() returns
Enter the text they entered
Ctrl+C an empty string
Ctrl+D on an empty line null

Returning null at the end of input matches GNU Readline and Console.ReadLine(), so an ordinary read loop terminates on Ctrl+D without special handling:

string? line;
while ((line = ConsoleReadLine.ReadLine(config)) != null)
{
    Execute(line);
}

When the distinction matters, use Read(). It returns a ReadLineResult containing the text and a Kind that describes how the interaction ended:

var result = ConsoleReadLine.Read(config);

switch (result.Kind)
{
    case ReadLineResultKind.Line:
        Execute(result.Text);
        break;
    case ReadLineResultKind.Cancelled:
        Console.WriteLine("Cancelled, nothing was run");
        break;
    case ReadLineResultKind.EndOfInput:
        return;
}

Abandoned lines and end-of-input signals are not recorded in history because their text is discarded.

A note on Ctrl+C. The console normally treats Ctrl+C as a request to terminate the program, so the keypress does not reach the application. To let a key behavior respond, the ConsoleReadLine provider temporarily configures the console to deliver Ctrl+C as an ordinary keypress. Therefore, while a line is being read, Ctrl+C abandons the line instead of terminating the process. The provider restores the previous console setting when the operation finishes. To make Ctrl+C have no effect during a read, build a configuration without AddCancelKeys().

Canceling From Code

The user initiates each of the three outcomes above. A program can also cancel a read by passing a CancellationToken:

using var source = new CancellationTokenSource(TimeSpan.FromSeconds(30));

try
{
    var line = ConsoleReadLine.ReadLine(config, source.Token);
}
catch (OperationCanceledException)
{
    Console.WriteLine("Timed out waiting for input");
}

Canceling this way raises an OperationCanceledException instead of returning a result. User cancellation is ordinary input and produces a Cancelled result. Programmatic cancellation interrupts control flow and raises an exception. The provider is still disposed after programmatic cancellation, so it restores the console as it would after any other read.

Because a console read cannot be interrupted after it starts, a cancelable read polls for an available keypress and checks the token between polls. The provider waits 15 milliseconds between checks while the prompt is idle. If you omit the token or pass CancellationToken.None, the provider uses the ordinary blocking path without polling.

An interactive console is required. Individual keypresses cannot be read from a pipe or file. Therefore, the ConsoleReadLine constructor throws an InvalidOperationException when standard input is redirected. Use Console.ReadLine() for redirected input or supply a custom IReadLineProvider. The provider checks the IConsole.InputIsRedirected property, so custom console implementations determine whether their input is redirected.


Reading Asynchronously

Every read method has an asynchronous counterpart. ReadLineAsync() returns the converted string, and ReadAsync() returns the full ReadLineResult. Both produce the same outcomes as their synchronous counterparts and differ only in how they wait:

var line = await ConsoleReadLine.ReadLineAsync(config);

var result = await ConsoleReadLine.ReadAsync(config, cancellationToken);

The asynchronous versions do not occupy a thread while waiting for a keypress. This is useful when other work must continue while a prompt remains open, such as in a server with a console or an application that writes progress messages through InsertText while the user types.

Key behaviors, formatters, lexers, and auto-completion still run synchronously on the thread that resumes the wait. Configuration delegates do not require asynchronous implementations.

Implementing an Asynchronous Provider

IReadLineProvider requires both ReadKey and ReadKeyAsync. Because .NET Standard 2.0 has no default interface methods, each provider must implement both methods. The appropriate implementation depends on the backend:

  • A backend whose input arrives through an event or an already asynchronous API should implement ReadKeyAsync natively and build the synchronous version on top of it.
  • A backend whose ReadKey does not block, such as one draining a populated queue, can implement ReadKeyAsync as Task.FromResult(ReadKey(cancellationToken)).
  • A backend that can only block, like System.Console, should wait for input to become available rather than blocking, then read. This is what ConsoleReadLine does, polling every 15 milliseconds.

Do not wrap a blocking read in Task.Run. That approach occupies a thread until the user presses a key, and the token cannot interrupt it. After cancellation, the abandoned read also remains queued and consumes the next keypress when it arrives.


Formatters

Formatters intercept the contents of the text buffer on its way to be displayed and allow it to be changed and formatted. They do not alter the original text residing in the handler's text buffer in any way.

Example

In the technical sense, a formatter is any function which takes either a TokenizedLine (covered in more detail with lexers) or a LineState and returns a LineDisplayState. If you set the ReadLine configuration to use a TokenizedLine the handler must be given a lexer as well, otherwise the formatter which simply receives the LineState must be used. The reason for this distinction is to allow the handler to run the lexer only one time internally if both a formatter and an autocompletion service is used.

A LineDisplayState consists of three pieces of FormattedText (FormattedText is text with both a foreground and background ConsoleColor which can be set individually per character). These three pieces are a prefix, a body, and a suffix. The LineDisplayState also has a cursor position, which is an offset from the first character of the body.

Formatter Example

Before showing some of the built in formatters, it's useful to show what a formatter looks like in its complete form. Ultimately, a formatter can set a prefix, the line body, and a suffix through the returned LineDisplayState.

To that end, a formatter needs to be one of the following types:

  • Func<LineState, LineDisplayState>
  • Func<TokenizedLine, LineDisplayState>

In the following example, we'll add a fixed red prompt at the beginning of the line, a suffix with a count of how many characters are in the text buffer, and an exact copy of the text buffer in the body with the default terminal foreground color.

var formatter = new Func<LineState, LineDisplayState>(ls =>
    {
        var prefix = new FormattedText("prompt $ ", ConsoleColor.Red);
        var suffix = new FormattedText($" [{ls.Text.Length} characters]", ConsoleColor.Blue);
        return new LineDisplayState(prefix, ls.Text, suffix, ls.Cursor);
    });

var config = ReadLineConfig.Basic
    .SetFormatter(formatter);

var result = ConsoleReadLine.ReadLine(config);

Example

In this case the prefix is static, but there is no reason that it needs to be. The character count in the suffix could have been implemented in the prefix just as easily.

Pre-built Formatters

There are a handful of pre-built formatters in the CommonFormatters static class.

A fixed prompt that appears in front of the text input:

var config = ReadLineConfig.Basic
    .SetFormatter(CommonFormatters.FixedPrompt("enter text here > "));

var text = ConsoleReadLine.ReadLine(config);

There are three built in formatters intended for hiding passwords while they're being typed. The first, PasswordBlank, simply displays an empty string instead of the input text. The second PasswordStars replaces the password characters with stars. The one in the following example, PasswordBar, displays a bar based on the SHA256 hash of the input text. The bar moves around as you type, revealing no information about your password or its length, but it will always produce the same visual effect for the same input text.

var config = ReadLineConfig.Basic
    .SetFormatter(CommonFormatters.PasswordBar);

var text = ConsoleReadLine.ReadLine(config);

Finally, formatters can be composed together as well. The following code produces a fixed prompt in front of the password display, and works with all of the password formatters.

var config = ReadLineConfig.Basic
    .SetFormatter(CommonFormatters.PasswordBar.WithFixedPrompt("Enter password:"));

var text = ConsoleReadLine.ReadLine(config);

Example

TokenizedLine Formatters

As mentioned above, a formatter can receive either a LineState or a TokenizedLine. The TokenizedLine is covered in more detail in the section on lexers, but this simple example shows how a lexer can split the input text into tokens for a formatter to use.

The complete demo searches for tokens that contain a valid hexadecimal number (digits 0 through 9 and letters a through f), then displays them in uppercase and cyan. All other tokens are displayed exactly as entered.

var pattern = new Regex(@"^[0-9a-fA-F]+$");

var formatter = new Func<TokenizedLine, LineDisplayState>(tk =>
{
    FormattedText output = string.Empty;
    foreach (var token in tk)
    {
        if (pattern.IsMatch(token.Text))
            output += new FormattedText(token.Text.ToUpper(), ConsoleColor.Cyan);
        else
            output += token.Text;
    }
    
    return new LineDisplayState("try it: ", output, string.Empty, tk.Cursor);
});

var config = ReadLineConfig.Basic
    .SetLexer(CommonLexers.SplitOnWhitespace)
    .SetFormatter(formatter);

var result = ConsoleReadLine.ReadLine(config);

Example


Lexers

Lexers split the current line into tokens. Token-aware formatters and auto-completion providers receive a TokenizedLine, which includes the token under the cursor and the cursor's position within that token. The library includes CommonLexers.SplitOnWhitespace for command-style input and composable regular-expression token definitions for more specialized grammars.

Set a lexer on the configuration before using token-based formatting or auto-completion:

var config = ReadLineConfig.Basic
    .SetLexer(CommonLexers.SplitOnWhitespace);

A lexer receives the complete LineState, so a custom lexer can use both the text and cursor position when it constructs the token sequence.

Auto-Complete

Auto-completion requires three pieces: a lexer, a suggestion provider, and key bindings that invoke completion. The provider receives the tokenized line and returns replacement strings for the token under the cursor. AddTabAutoComplete() binds Tab to the next suggestion and Shift+Tab to the previous suggestion.

var commands = new[] { "build", "clean", "publish", "restore", "test" };

var config = ReadLineConfig.Basic
    .SetLexer(CommonLexers.SplitOnWhitespace)
    .SetAutoCompletion(tokens => commands
        .Where(command => command.StartsWith(
            tokens.CursorToken?.Text ?? string.Empty,
            StringComparison.OrdinalIgnoreCase))
        .ToArray())
    .AddTabAutoComplete();

string? command = ConsoleReadLine.ReadLine(config);

Suggestions are recalculated from the current tokenized line, so the provider can use earlier tokens to offer context-aware values. Auto-completion does nothing unless both the lexer and suggestion provider are configured.

History

ReadLineConfig.Basic already binds the up and down arrows to history navigation. Supply a list to make those bindings active and to append completed lines automatically:

var history = new List<string>();
var config = ReadLineConfig.Basic
    .SetUpdatingHistorySource(history);

while (ConsoleReadLine.ReadLine(config) is { } line)
{
    Execute(line);
}

The default updating history skips blank lines and an entry that is identical to the most recent entry. Use SetHistorySource(IReadOnlyList<string>) for read-only history, or combine it with SetHistoryUpdateAction(Action<string>) when you need persistence, size limits, or different filtering. The configuration keeps a live reference to the history collection, and abandoned lines and end-of-input signals are not recorded.

See the history guide for navigation behavior and complete custom update examples.


License

InteractiveReadLine is available under the MIT License.

About

Special console readline intended for interactive console applications or cli-like UI widgets

Resources

Stars

8 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages