Giter Site home page Giter Site logo

readline's Introduction

Windows build status License: MIT NuGet version

ReadLine

ReadLine is a GNU Readline like library built in pure C#. It can serve as a drop in replacement for the inbuilt Console.ReadLine() and brings along with it some of the terminal goodness you get from unix shells, like command history navigation and tab auto completion.

It is cross platform and runs anywhere .NET is supported, targeting netstandard1.3 means that it can be used with .NET Core as well as the full .NET Framework.

Shortcut Guide

Shortcut Comment
Ctrl+A / HOME Beginning of line
Ctrl+B / Backward one character
Ctrl+C Send EOF
Ctrl+E / END End of line
Ctrl+F / Forward one character
Ctrl+H / Backspace Delete previous character
Tab Command line completion
Shift+Tab Backwards command line completion
Ctrl+J / Enter Line feed
Ctrl+K Cut text to the end of line
Ctrl+L / Esc Clear line
Ctrl+M Same as Enter key
Ctrl+N / Forward in history
Ctrl+P / Backward in history
Ctrl+U Cut text to the start of line
Ctrl+W Cut previous word
Backspace Delete previous character
Ctrl + D / Delete Delete succeeding character

Installation

Available on NuGet

Visual Studio:

PM> Install-Package ReadLine

.NET Core CLI:

dotnet add package ReadLine

Usage

Read input from the console

string input = ReadLine.Read("(prompt)> ");

Read password from the console

string password = ReadLine.ReadPassword("(prompt)> ");

Note: The (prompt>) is optional

History management

// Get command history
ReadLine.GetHistory();

// Add command to history
ReadLine.AddHistory("dotnet run");

// Clear history
ReadLine.ClearHistory();

// Disable history
ReadLine.HistoryEnabled = false;

Note: History information is persisted for an entire application session. Also, calls to ReadLine.Read() automatically adds the console input to history

Auto-Completion

class AutoCompletionHandler : IAutoCompleteHandler
{
    // characters to start completion from
    public char[] Separators { get; set; } = new char[] { ' ', '.', '/' };

    // text - The current text entered in the console
    // index - The index of the terminal cursor within {text}
    public string[] GetSuggestions(string text, int index)
    {
        if (text.StartsWith("git "))
            return new string[] { "init", "clone", "pull", "push" };
        else
            return null;
    }
}

ReadLine.AutoCompletionHandler = new AutoCompletionHandler();

Note: If no "AutoCompletionHandler" is set, tab autocompletion will be disabled

Contributing

Contributions are highly welcome. If you have found a bug or if you have a feature request, please report them at this repository issues section.

Things you can help with:

  • Achieve better command parity with GNU Readline.
  • Add more test cases.

License

This project is licensed under the MIT license. See the LICENSE file for more info.

readline's People

Contributors

dewjunkie avatar guad avatar intelorca avatar psylenced avatar rubberduck203 avatar tonerdo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

readline's Issues

AutoComplete: Index was outside the bounds of the array.

There is a exception in line

https://github.com/tsolarin/readline/blob/master/src/ReadLine/KeyHandler.cs#L137

Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.KeyHandler.AutoComplete() in /app/src/ReadLine/KeyHandler.cs:line 137
   at System.KeyHandler.<>c__DisplayClass31_0.<.ctor>b__3() in /app/src/ReadLine/KeyHandler.cs:line 234
   at System.KeyHandler.Handle(ConsoleKeyInfo keyInfo) in /app/src/ReadLine/KeyHandler.cs:line 250
   at System.ReadLine.Read(String prompt) in /app/src/ReadLine/ReadLine.cs:line 28
   at ConsoleApplication.Program.Main(String[] args) in /app/src/ReadLine.Demo/Program.cs:line 27

using System;

namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("ReadLine Library Demo");
            Console.WriteLine("---------------------");
            Console.WriteLine();

            string[] history = new string[] { "ls -a", "dotnet run", "git init" };
            ReadLine.AddHistory(history);

            ReadLine.AutoCompletionHandler = (t, s) =>
            {
                if (t.StartsWith("ab"))
                    return new string[] { "ab" };
                if (t.StartsWith("a"))
                    return new string[] { "a1", "ab", "acd", "acde", "acdef" };
                return null;
            };
						
           while (true)
	   {
		string input = ReadLine.Read("(prompt)> ");
		Console.Write(input);
            }
        }
    }
}

Scenerio:

  1. press "a"
  2. press TAB (this prints "a1")
  3. clear line
  4. press "ab"
  5. press TAB (throw exception)

Shift Backspace behaviour

If you type:
abd[Shift-Backspace]c
then then resulting string is
abc\bd
(with the \b escape char for backspace)
If you use Backspace instead of Shift-Backspace, then it is fine.
Is this on purpose, and if so, is there a recommended way to sanitise the string when there are escape chars?

Support .Net Framework

You can't install nuget package for .Net Framework, unless you will explicitly specify it.

image

C-d does not delete character

Per #39 C-d isn't behaving as expected on Mac.

Expected behavior: Deletes character under the cursor.
Actual behavior: Moves the cursor forward one character.

.NET version info

.NET Command Line Tools (2.1.4)

Product Information:
 Version:            2.1.4
 Commit SHA-1 hash:  5e8add2190

Runtime Environment:
 OS Name:     Mac OS X
 OS Version:  10.12
 OS Platform: Darwin
 RID:         osx.10.12-x64
 Base Path:   /usr/local/share/dotnet/sdk/2.1.4/

Microsoft .NET Core Shared Framework Host

  Version  : 2.0.5
  Build    : 17373eb129b3b05aa18ece963f8795d65ef8ea54

Add option to disable history

History should be able to be disabled on a global level:

ReadLine.DisableHistory = true;

And overridden on a call level:

ReadLine.Read("", "", true);
ReadLine.Read("", "", false);

It doesn't install correctly

I tried to install it using nuget in visual studio enterprise 2017 in a 4.6 console application. It seems to install but i won't get any references added? Have the same result in vs 2015.

AutoCompletion does not complete the current work

Currently auto complete removes your current word and starts a tab complete session from the beginning of the suggestion list. This should instead only rotate through the suggestions that begin with what has currently been typed.

E.g. if you return these suggestions:
return new [] { "show", "status", "blame", "checkout", "branch" };

and you type:
> git b<TAB>

it should only provide only the following auto completions:
> git blame
> git branch

(Windows 10) Pressing the Windows key enters a null character

Title says it all. I don't actually know if this is intended behavior, but it is relatively unexpected behavior; none of the other terminals I use in Windows (cmd.exe, PowerShell, Git Bash, cygwin64, etc.) write anything when the Windows key is pressed.

This normally wouldn't be a huge issue, but I use a lot of keyboard shortcuts involving the Windows key, so it's frustrating when null characters get thrown in my application input. That said, if this is intended for whatever reason, feel free to close out this issue.

ReadLine.Read is not working in MingW64

I tried to use the our tool on Windows 7 system in a MINGW64 terminal (that is installed when I installed Git client to access github).

Unhandled Exception: System.InvalidOperationException: Cannot read keys when either application does not have a console or when console input has been redirected. Try Console.Read.
   at System.ConsolePal.ReadKey(Boolean intercept)
   at System.ReadLine.GetText(KeyHandler keyHandler)
   at System.ReadLine.Read(String prompt, String default)
   at Campaign.Program.RunAddAndReturnExitCode(Options options)

A little googling efforts directed me to run it on the default command prompt and it worked like a charm.

Please guide, if there is any configuration required for the same. Thanks

Should not use 'System' as the namespace to qualify your library

Readline should not use System namespace. This will make it not possible to use this library in any enterprise project that has any package reviewing process.

I suggest the root namespace be created called something e.g. Tonerdo or similar and a new release be created (version 3) with the new namespace.

Great library btw! nice :D

Keyboard in US International inserts char \0 when pressing '+space (dead keys)

Hello!

Thanks for creating this awesome package. I love what you are doing to improve CLI/CI scenario on the .net environment.

I'm using this package and I've noticed that when you press ' + space outputs \0', which outputs only one ' char in other softwares. I think that this might be related on how you read the input (reading keys vs. reading inserted data - assuming this, not sure).

This happens because when using US International it has dead keys which can be used to change the next key. In this case I just want the ' so I need to press space after.

https://en.wikipedia.org/wiki/Dead_key

Issues with .NET Core 3.0.100-preview7-012821

When using ReadLine in my .NET Core app (running through dotnet run), I sometimes get this:

Unhandled exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
---> System.IO.IOException: The process cannot access the file because it is being used by another process.
   at Interop.ThrowExceptionForIoErrno(ErrorInfo errorInfo, String path, Boolean isDirectory, Func`2 errorRewriter)
   at Interop.CheckIo(Int64 result, String path, Boolean isDirectory, Func`2 errorRewriter)
   at System.IO.StdInReader.ReadKey(Boolean& previouslyProcessed)
   at System.IO.SyncTextReader.ReadKey(Boolean& previouslyProcessed)
   at System.ConsolePal.ReadKey(Boolean intercept)
   at System.ReadLine.GetText(KeyHandler keyHandler)
   at System.ReadLine.Read(String prompt, String default)
   at Flare.Cli.Commands.ReplCommand.Run(Options options, CancellationToken token) in /home/alexrp/flare/flare/src/cli/Commands/ReplCommand.cs:line 37
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Delegate.DynamicInvokeImpl(Object[] args)
   at System.Delegate.DynamicInvoke(Object[] args)
   at System.CommandLine.Invocation.ModelBindingCommandHandler.InvokeAsync(InvocationContext context)
   at System.CommandLine.Invocation.InvocationPipeline.<>c__DisplayClass2_0.<<InvokeAsync>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseParseErrorReporting>b__16_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c__DisplayClass8_0.<<UseTypoCorrections>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseSuggestDirective>b__7_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseParseDirective>b__6_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<UseHelp>b__14_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Builder.CommandLineBuilderExtensions.<>c__DisplayClass3_0.<<UseVersionOption>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c.<<RegisterWithDotnetSuggest>b__17_0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.CommandLine.Invocation.InvocationExtensions.<>c__DisplayClass5_0.<<UseExceptionHandler>b__0>d.MoveNext()

It's not consistent, and I'm not sure how to reliably reproduce it. I am also using System.CommandLine in this app, so at first I thought there might be some kind of conflict, but I don't believe that is the case as System.CommandLine does not appear to touch Console.In anywhere.

Is this repo still alive?

The last version of Readline was published 12.06.2018. There are great PRs, but I don't see responses.
Is this repo still alive?

Add ReadAsync with CancellationToken

Add function to ReadLine static class with following signature:
public static async Task<string> ReadAsync(CancellationToken)

Implement by using Console.In.ReadAsync.

This makes it possible to interrupt input with Control-C, using the CancellationToken before a line is received.

netstandard1.3 support

Is there a reason the latest version (v2.0.0) dropped netstandard1.3 support? The github page still mentions netstandard1.3 support.

Consider doing Console I/O via interfaces

Please consider offering an optional API through which the client supplies I/O methods that do the actual console I/O.

  • Such an API would make testing easier.
  • An async wrapper could use this API to act as a conduit for reads and writes to the console. I’ve written an async wrapper. It works pretty well, but there are tricky situations where being involved in the actual reads and writes would help.

net standard compatibility

Hi,

I'm trying to use this library that looks very promising. Unfortunately, my projects use .Net framework 4.6.1, which is not compatible netstandard1.3.

Do you believe it would be possible to increase the compatibility of the library by changing the required framework ?

(Windows 10) Pressing the Windows key enters a null character

Title says it all. I don't actually know if this is intended behavior, but it is relatively unexpected behavior; none of the other terminals I use in Windows (cmd.exe, PowerShell, Git Bash, cygwin64, etc.) write anything when the Windows key is pressed.

This normally wouldn't be a huge issue, but I use a lot of keyboard shortcuts involving the Windows key, so it's frustrating when null characters get thrown in my application input. That said, if this is intended behavior, feel free to close out this issue.

Smart auto prompting option

Provide option to enable and configuration, disabled by default for normal behavior.

When enabled, would proxy output by redirecting Console.Out stream, and inject a prompt after a configurable grace period (default 10ms?) by starting a delayed task that is cancelled and restarted when new output occurs and the last characters are a newline, which would prevent it from trying to inject a prompt when already sitting at a prompt.

This would be a significant improvement over how traditional readline works by not injecting prompts in the middle of busy output, and will in fact ensure a prompt is provided when output becomes sufficiently idle.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.