diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000..31d4419 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,2 @@ +# Normalize line endings via .gitattributes +0c13f9c93ad456ab66c4690b553979cd865dff2c diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..bc7d119 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,26 @@ +# Normalize line endings +# +# This file was added after the repository had already accumulated a mix of +# CRLF and LF files; the history was renormalized in a single dedicated commit +# (see .git-blame-ignore-revs). + +* text=auto + +# Source and project files. diff=csharp gives hunk headers that name the +# enclosing type or method. +*.cs text diff=csharp +*.csproj text +*.props text +*.targets text + +*.sln text + +# Always LF: these are consumed by tools that dislike CR. +*.sh text eol=lf +*.yml text eol=lf +*.yaml text eol=lf + +*.md text diff=markdown +*.json text +*.svg text +LICENSE text diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..c0dc7a5 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,63 @@ +name: CI + +on: + push: + branches: [main, develop] + pull_request: + +jobs: + test: + name: Test on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + + steps: + - uses: actions/checkout@v7 + with: + # MinVer reads the version from Git tags, so it requires the tags and full history. + fetch-depth: 0 + + - uses: actions/setup-dotnet@v6 + with: + dotnet-version: '10.0.x' + + - name: Build + run: dotnet build --configuration Release + + - name: Test + run: dotnet test --configuration Release --no-build --collect:"XPlat Code Coverage" + + - name: Upload coverage + # Upload coverage from one platform. An upload error does not fail the build. + if: matrix.os == 'ubuntu-latest' + uses: codecov/codecov-action@v7 + with: + token: ${{ secrets.CODECOV_UPLOAD_TOKEN }} + fail_ci_if_error: false + + pack: + name: Verify the package builds + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + + - uses: actions/setup-dotnet@v6 + with: + dotnet-version: '10.0.x' + + # Packing every change detects packaging faults before a release tag fixes the package version. + - name: Pack + run: dotnet pack InteractiveReadLine/InteractiveReadLine.csproj --configuration Release --output ./artifacts + + - name: Upload package + uses: actions/upload-artifact@v7 + with: + name: nuget-package + path: ./artifacts/*.nupkg + if-no-files-found: error diff --git a/.github/workflows/ci_netcore.yml b/.github/workflows/ci_netcore.yml deleted file mode 100644 index 5eff2d6..0000000 --- a/.github/workflows/ci_netcore.yml +++ /dev/null @@ -1,29 +0,0 @@ -name: CI netcore - -on: - push: - branches: - - master - - develop - pull_request: - branches: - - master - - develop - -jobs: - build: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v1 - - - name: Setup .NET Core - uses: actions/setup-dotnet@v1 - with: - dotnet-version: 3.1.100 - - - name: Build and test with dotnet - run: dotnet test /p:CollectCoverage=true /p:CoverletOutput=TestResults/ /p:CoverletOutputFormat=lcov --configuration Release - - - name: Publish coverage - run: curl -s https://codecov.io/bash | bash -s -- -f InteractiveReadLine.Tests/TestResults/coverage.info -t ${{secrets.CODECOV_UPLOAD_TOKEN}} -Z diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000..ef40f41 --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,62 @@ +name: Documentation + +on: + push: + branches: [main] + paths: + - 'InteractiveReadLine/**' + - 'docs/**' + - '.github/workflows/docs.yml' + workflow_dispatch: + +permissions: + contents: read + pages: write + id-token: write + +# Let the active deployment finish. If other runs are pending, GitHub Actions keeps only the newest one, +# which then deploys after the active run completes. +concurrency: + group: pages + cancel-in-progress: false + +jobs: + build: + name: Build the site + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v7 + + - uses: actions/setup-dotnet@v6 + with: + dotnet-version: '10.0.x' + + - name: Install DocFX + run: dotnet tool update -g docfx + + # DocFX compiles the library to extract API metadata, so restore and build the project first. DocFX + # also reads the XML documentation generated by this build. + - name: Build the library + run: dotnet build InteractiveReadLine/InteractiveReadLine.csproj --configuration Release + + - name: Build the documentation + run: docfx docs/docfx.json --warningsAsErrors + + - name: Upload the site + uses: actions/upload-pages-artifact@v5 + with: + path: docs/_site + + deploy: + name: Deploy to GitHub Pages + needs: build + runs-on: ubuntu-latest + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + + steps: + - name: Deploy + id: deployment + uses: actions/deploy-pages@v5 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..3758ac4 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,62 @@ +name: Release + +on: + push: + tags: ['v*'] + +permissions: + contents: write + +jobs: + release: + name: Publish to NuGet + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v7 + with: + # Without the full history and tags, MinVer cannot see the release tag and silently + # produces 0.0.0-alpha, which would publish a package under the wrong version. + fetch-depth: 0 + + - uses: actions/setup-dotnet@v6 + with: + dotnet-version: '10.0.x' + + - name: Test + run: dotnet test --configuration Release + + - name: Pack + run: > + dotnet pack InteractiveReadLine/InteractiveReadLine.csproj + --configuration Release + -p:ContinuousIntegrationBuild=true + --output ./artifacts + + - name: Confirm the packed version matches the tag + # MinVer derives the version from the tag, so a mismatch means that MinVer did not resolve the + # release tag. Stop before publishing because NuGet packages cannot be replaced after publication. + run: | + expected="${GITHUB_REF_NAME#v}" + actual=$(ls ./artifacts/InteractiveReadLine.*.nupkg | sed -E 's|.*/InteractiveReadLine\.(.*)\.nupkg|\1|') + echo "tag: $expected packed: $actual" + if [ "$expected" != "$actual" ]; then + echo "::error::Packed version '$actual' does not match tag '$expected'" + exit 1 + fi + + - name: Push to NuGet + run: > + dotnet nuget push "./artifacts/*.nupkg" + --api-key ${{ secrets.NUGET_API_KEY }} + --source https://api.nuget.org/v3/index.json + --skip-duplicate + + - name: Create the GitHub release + env: + GH_TOKEN: ${{ github.token }} + run: > + gh release create "$GITHUB_REF_NAME" + --title "$GITHUB_REF_NAME" + --generate-notes + ./artifacts/*.nupkg diff --git a/.gitignore b/.gitignore index 3e759b7..6bd9fdd 100644 --- a/.gitignore +++ b/.gitignore @@ -328,3 +328,8 @@ ASALocalRun/ # MFractors (Xamarin productivity tool) working folder .mfractor/ + +# DocFX generates the API metadata and site output from the source during each documentation build, +# so these directories do not belong in the repository. +docs/api/ +docs/_site/ diff --git a/InteractiveReadLine.Demo/DemoNode.cs b/InteractiveReadLine.Demo/DemoNode.cs index 21efefc..6f095fa 100644 --- a/InteractiveReadLine.Demo/DemoNode.cs +++ b/InteractiveReadLine.Demo/DemoNode.cs @@ -1,66 +1,66 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security.Cryptography; - -namespace InteractiveReadLine.Demo -{ - public class DemoNode - { - private readonly Dictionary _children; - private readonly List _childOrder; - - public DemoNode(DemoNode parent, string name, IDemo demo) - : this(parent, name, demo?.Description) - { - Demo = demo; - } - - public DemoNode(DemoNode parent, string name, string description) - { - Description = description; - Name = name; - Parent = parent; - _children = new Dictionary(); - _childOrder = new List(); - } - - public DemoNode Parent { get; } - - public string Name { get; } - - public string Description { get; } - - public IDemo Demo { get; } - - public string Path => string.Join("/", this.GetPath(Array.Empty())); - - public IReadOnlyDictionary Children => _children; - - public string[] OrderedChildKeys => _childOrder.ToArray(); - - public DemoNode AddChild(string name, string description) - { - var node = new DemoNode(this, name, description); - _childOrder.Add(name); - _children[name] = node; - return node; - } - - public DemoNode AddChild(string name, IDemo demo) - { - var node = new DemoNode(this, name, demo); - _childOrder.Add(name); - _children[name] = node; - return node; - } - - private string[] GetPath(string[] basePath) - { - var path = new string[]{this.Name}.Concat(basePath).ToArray(); - return this.Parent == null ? path : this.Parent.GetPath(path); - } - - - } +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography; + +namespace InteractiveReadLine.Demo +{ + public class DemoNode + { + private readonly Dictionary _children; + private readonly List _childOrder; + + public DemoNode(DemoNode parent, string name, IDemo demo) + : this(parent, name, demo?.Description) + { + Demo = demo; + } + + public DemoNode(DemoNode parent, string name, string description) + { + Description = description; + Name = name; + Parent = parent; + _children = new Dictionary(); + _childOrder = new List(); + } + + public DemoNode Parent { get; } + + public string Name { get; } + + public string Description { get; } + + public IDemo Demo { get; } + + public string Path => string.Join("/", this.GetPath(Array.Empty())); + + public IReadOnlyDictionary Children => _children; + + public string[] OrderedChildKeys => _childOrder.ToArray(); + + public DemoNode AddChild(string name, string description) + { + var node = new DemoNode(this, name, description); + _childOrder.Add(name); + _children[name] = node; + return node; + } + + public DemoNode AddChild(string name, IDemo demo) + { + var node = new DemoNode(this, name, demo); + _childOrder.Add(name); + _children[name] = node; + return node; + } + + private string[] GetPath(string[] basePath) + { + var path = new string[]{this.Name}.Concat(basePath).ToArray(); + return this.Parent == null ? path : this.Parent.GetPath(path); + } + + + } } \ No newline at end of file diff --git a/InteractiveReadLine.Demo/Demos/BasicConfig.cs b/InteractiveReadLine.Demo/Demos/BasicConfig.cs index be0b6c1..89187df 100644 --- a/InteractiveReadLine.Demo/Demos/BasicConfig.cs +++ b/InteractiveReadLine.Demo/Demos/BasicConfig.cs @@ -1,26 +1,26 @@ -using System; - -namespace InteractiveReadLine.Demo.Demos -{ - public class BasicConfig : IDemo - { - public string Description => "Demonstrates a default configuration"; - - public void Action() - { - Console.WriteLine("This is a basic, default configuration for the handler without any customizations.\n"); - - /* This demonstrates a default configuration of the ReadLine without any customizations. - Under the hood this uses a ReadLineConfig.Basic configuration, which contains only the - standard key behavior (enter, backspace, home/end, arrow keys, and up/down for history)." - - Note that this is different from the ReadLineConfig.Empty configuration (an Empty - configuration is useless until at least the default and finish key behavior is added). - - This is the simplest way to use ReadLine, but typically you will want to use a configuration. - */ - - var result = ConsoleReadLine.ReadLine(); - } - } +using System; + +namespace InteractiveReadLine.Demo.Demos +{ + public class BasicConfig : IDemo + { + public string Description => "Demonstrates a default configuration"; + + public void Action() + { + Console.WriteLine("This is a basic, default configuration for the handler without any customizations.\n"); + + /* This demonstrates a default configuration of the ReadLine without any customizations. + Under the hood this uses a ReadLineConfig.Basic configuration, which contains only the + standard key behavior (enter, backspace, home/end, arrow keys, and up/down for history)." + + Note that this is different from the ReadLineConfig.Empty configuration (an Empty + configuration is useless until at least the default and finish key behavior is added). + + This is the simplest way to use ReadLine, but typically you will want to use a configuration. + */ + + var result = ConsoleReadLine.ReadLine(); + } + } } \ No newline at end of file diff --git a/InteractiveReadLine.Demo/Demos/Formatters/FixedPrompt.cs b/InteractiveReadLine.Demo/Demos/Formatters/FixedPrompt.cs index 30708dd..1475d9a 100644 --- a/InteractiveReadLine.Demo/Demos/Formatters/FixedPrompt.cs +++ b/InteractiveReadLine.Demo/Demos/Formatters/FixedPrompt.cs @@ -1,20 +1,20 @@ -using System; -using InteractiveReadLine.Formatting; - -namespace InteractiveReadLine.Demo.Demos.Formatters -{ - public class FixedPrompt : IDemo - { - public string Description => "Demonstrates a fixed prompt"; - - public void Action() - { - Console.WriteLine("This shows a very basic use of a formatter; to insert fixed text in front of the input area."); - - var config = ReadLineConfig.Basic - .SetFormatter(CommonFormatters.FixedPrompt("prompt text #")); - - var result = ConsoleReadLine.ReadLine(config); - } - } +using System; +using InteractiveReadLine.Formatting; + +namespace InteractiveReadLine.Demo.Demos.Formatters +{ + public class FixedPrompt : IDemo + { + public string Description => "Demonstrates a fixed prompt"; + + public void Action() + { + Console.WriteLine("This shows a very basic use of a formatter; to insert fixed text in front of the input area."); + + var config = ReadLineConfig.Basic + .SetFormatter(CommonFormatters.FixedPrompt("prompt text #")); + + var result = ConsoleReadLine.ReadLine(config); + } + } } \ No newline at end of file diff --git a/InteractiveReadLine.Demo/Demos/Keys/BareKeys.cs b/InteractiveReadLine.Demo/Demos/Keys/BareKeys.cs index 4a879d6..ce4192b 100644 --- a/InteractiveReadLine.Demo/Demos/Keys/BareKeys.cs +++ b/InteractiveReadLine.Demo/Demos/Keys/BareKeys.cs @@ -1,21 +1,21 @@ -using System; -using InteractiveReadLine.KeyBehaviors; - -namespace InteractiveReadLine.Demo.Demos.Keys -{ - public class BareKeys : IDemo - { - public string Description => "Shows an almost bare key configuration"; - - public void Action() - { - Console.WriteLine("This is a bare key configuration with only the enter key and default insert behavior.\n"); - - var config = ReadLineConfig.Empty - .SetDefaultKeyBehavior(CommonKeyBehaviors.InsertCharacter) - .AddEnterToFinish(); - - var result = ConsoleReadLine.ReadLine(config); - } - } +using System; +using InteractiveReadLine.KeyBehaviors; + +namespace InteractiveReadLine.Demo.Demos.Keys +{ + public class BareKeys : IDemo + { + public string Description => "Shows an almost bare key configuration"; + + public void Action() + { + Console.WriteLine("This is a bare key configuration with only the enter key and default insert behavior.\n"); + + var config = ReadLineConfig.Empty + .SetDefaultKeyBehavior(CommonKeyBehaviors.InsertCharacter) + .AddEnterToFinish(); + + var result = ConsoleReadLine.ReadLine(config); + } + } } \ No newline at end of file diff --git a/InteractiveReadLine.Demo/IDemo.cs b/InteractiveReadLine.Demo/IDemo.cs index 46f7b1b..63c4d18 100644 --- a/InteractiveReadLine.Demo/IDemo.cs +++ b/InteractiveReadLine.Demo/IDemo.cs @@ -1,9 +1,9 @@ -namespace InteractiveReadLine.Demo -{ - public interface IDemo - { - string Description { get; } - - void Action(); - } +namespace InteractiveReadLine.Demo +{ + public interface IDemo + { + string Description { get; } + + void Action(); + } } \ No newline at end of file diff --git a/InteractiveReadLine.Demo/InteractiveReadLine.Demo.csproj b/InteractiveReadLine.Demo/InteractiveReadLine.Demo.csproj index 318c18b..253549a 100644 --- a/InteractiveReadLine.Demo/InteractiveReadLine.Demo.csproj +++ b/InteractiveReadLine.Demo/InteractiveReadLine.Demo.csproj @@ -1,12 +1,12 @@ - - - - Exe - netcoreapp3.0 - - - - - - - + + + + Exe + net10.0 + + + + + + + diff --git a/InteractiveReadLine.Demo/OptionSet.cs b/InteractiveReadLine.Demo/OptionSet.cs index a564ee4..9bcb8d2 100644 --- a/InteractiveReadLine.Demo/OptionSet.cs +++ b/InteractiveReadLine.Demo/OptionSet.cs @@ -1,58 +1,58 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; - -namespace InteractiveReadLine.Demo -{ - public class OptionSet - { - private List _keys; - private Dictionary _actions; - private Dictionary _descriptions; - - public OptionSet() - { - _keys = new List(); - _actions = new Dictionary(); - _descriptions = new Dictionary(); - } - - public string[] Keys => _keys.ToArray(); - - public string[] NonBlankKeys => _keys.Where(k => !string.IsNullOrEmpty(k)).ToArray(); - - public string[] Descriptions => _keys.Select(GetDescription).ToArray(); - - public void AddSpace() - { - _keys.Add(string.Empty); - _descriptions[string.Empty] = ""; - } - - public void Add(string key, string description, Action action) - { - if (_actions.ContainsKey(key)) - throw new DuplicateNameException(); - _keys.Add(key); - _descriptions[key] = description; - _actions[key] = action; - } - - public void AddToStart(string key, string description, Action action) - { - if (_actions.ContainsKey(key)) - throw new DuplicateNameException(); - _keys.Insert(0, key); - _descriptions[key] = description; - _actions[key] = action; - } - - public string GetDescription(string key) => _descriptions[key]; - - public Action GetAction(string key) => _actions[key]; - - public bool ContainsKey(string key) => _actions.ContainsKey(key); - - } +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; + +namespace InteractiveReadLine.Demo +{ + public class OptionSet + { + private List _keys; + private Dictionary _actions; + private Dictionary _descriptions; + + public OptionSet() + { + _keys = new List(); + _actions = new Dictionary(); + _descriptions = new Dictionary(); + } + + public string[] Keys => _keys.ToArray(); + + public string[] NonBlankKeys => _keys.Where(k => !string.IsNullOrEmpty(k)).ToArray(); + + public string[] Descriptions => _keys.Select(GetDescription).ToArray(); + + public void AddSpace() + { + _keys.Add(string.Empty); + _descriptions[string.Empty] = ""; + } + + public void Add(string key, string description, Action action) + { + if (_actions.ContainsKey(key)) + throw new DuplicateNameException(); + _keys.Add(key); + _descriptions[key] = description; + _actions[key] = action; + } + + public void AddToStart(string key, string description, Action action) + { + if (_actions.ContainsKey(key)) + throw new DuplicateNameException(); + _keys.Insert(0, key); + _descriptions[key] = description; + _actions[key] = action; + } + + public string GetDescription(string key) => _descriptions[key]; + + public Action GetAction(string key) => _actions[key]; + + public bool ContainsKey(string key) => _actions.ContainsKey(key); + + } } \ No newline at end of file diff --git a/InteractiveReadLine.Demo/Program.cs b/InteractiveReadLine.Demo/Program.cs index a359e46..c577d35 100644 --- a/InteractiveReadLine.Demo/Program.cs +++ b/InteractiveReadLine.Demo/Program.cs @@ -1,191 +1,194 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.InteropServices; -using InteractiveReadLine.Demo.Demos; -using InteractiveReadLine.Demo.Demos.Formatters; -using InteractiveReadLine.Demo.Demos.Keys; -using InteractiveReadLine.Formatting; -using InteractiveReadLine.KeyBehaviors; -using InteractiveReadLine.Tokenizing; -using Microsoft.VisualBasic.CompilerServices; - -namespace InteractiveReadLine.Demo -{ - class Program - { - private static ConsoleReadLine _provider; - private static string[] _options; - - private static DemoNode _demoHome; - private static DemoNode _activeNode; - - static void Main(string[] args) - { - _demoHome = SetupDemo(); - _activeNode = _demoHome; - var isRunning = true; - - Console.WriteLine("InteractiveReadLine Demo Program"); - Console.WriteLine("\nThis executable is a demonstration to showcase some of the features of this library.\nYou can exit at any time with the command 'exit'.''"); - Console.WriteLine(); - - while (isRunning) - { - var options = new OptionSet(); - Console.Clear(); - - if (_activeNode.Demo != null) - { - // This is a demo node - Console.WriteLine($"Demo: {_activeNode.Name} ({_activeNode.Description})"); - options.AddToStart("run", "Run this demo", () => - { - Console.Clear(); - _activeNode.Demo.Action(); - }); - } - else - { - // This is a menu node, show the node and its first level children - Console.WriteLine($" {_activeNode.Description}"); - - var names = _activeNode.OrderedChildKeys; - foreach (var name in names) - { - options.Add(name, _activeNode.Children[name].Description, () => _activeNode = _activeNode.Children[name]); - } - } - - options.AddSpace(); - - if (_activeNode.Parent != null) - options.Add("back", "Go back", () => _activeNode = _activeNode.Parent); - - options.Add("home", "Return to demo home", () => _activeNode = _demoHome); - options.Add("exit", "Exit the demo program", () => isRunning = false); - - var padding = options.Keys.Select(n => " ").ToArray(); - if (_activeNode.Demo != null) - { - var link = GetGithubLink(_activeNode.Demo); - if (link != null) - Console.WriteLine($" * {link}"); - } - Console.WriteLine(FormatTable(false, padding, options.Keys, options.Descriptions)); - - var config = ReadLineConfig.Basic - .AddCtrlNavKeys() - .AddTabAutoComplete() - .SetLexer(CommonLexers.SplitOnWhitespace) - .SetAutoCompletion(t => options.NonBlankKeys.Where(o => o.StartsWith(t.CursorToken.Text)).ToArray()) - .SetFormatter(NodeFormatter(options.NonBlankKeys.ToArray())); - - var result = ConsoleReadLine.ReadLine(config); - - if (options.ContainsKey(result)) - { - options.GetAction(result).Invoke(); - } - } - } - - static DemoNode SetupDemo() - { - // Demo home node - _demoHome = new DemoNode(null, "home", "Demo Home"); - - // featured demos - var featuredNode = _demoHome.AddChild("featured", "Featured Demos"); - featuredNode.AddChild("basic", new BasicConfig()); - featuredNode.AddChild("complex", new ComplexConfig()); - featuredNode.AddChild("hunter2", new Hunter2()); - - // Key behavior demos - var keyNode = _demoHome.AddChild("keys", "Key Behaviors and Customization"); - keyNode.AddChild("bare", new BareKeys()); - keyNode.AddChild("default-behavior", new CustomInsertCharacter()); - - // Formatting demos - var formatNode = _demoHome.AddChild("formatters", "Display Formatting and Customization"); - formatNode.AddChild("fixed-prompt", new FixedPrompt()); - formatNode.AddChild("custom-simple", new SimpleCustomFormatter()); - formatNode.AddChild("custom-token", new TokenCustomFormatter()); - formatNode.AddChild("passwd-stars", new PasswordStarPrompt()); - formatNode.AddChild("passwd-bars", new PasswordBarPrompt()); - - // Lexing demos - var lexingNode = _demoHome.AddChild("lexing", "Lexers and Tokenizing"); - - // Autocomplete demos - var autocompleteNode = _demoHome.AddChild("autocomplete", "Autocomplete Demos"); - - // History demos - var historyNode = _demoHome.AddChild("history", "History Demos"); - - - return _demoHome; - } - - private static string GetGithubLink(IDemo demo) - { - const string rootUrl = "https://github.com/mattj23/InteractiveReadLine/tree/master/InteractiveReadLine.Demo/"; - var typeInfo = demo.GetType(); - var path = typeInfo.FullName?.Replace("InteractiveReadLine.Demo.", "").Split("."); - if (path != null) - { - return rootUrl + string.Join("/", path) + ".cs"; - } - - return null; - } - - private static Func NodeFormatter(IReadOnlyList options) - { - var path = _activeNode.Path; - - return line => - { - var prefix = new FormattedText($"{path} > "); - - FormattedText suffix = ""; - if (line.FirstNonHidden.Text == "exit") - suffix = new FormattedText(" [exits the demo program]", ConsoleColor.Red); - else if (line.FirstNonHidden.Text == "home") - suffix = new FormattedText(" [returns to demo root]", ConsoleColor.Blue); - else if (line.FirstNonHidden.Text == "back" && _activeNode.Parent != null) - suffix = new FormattedText($" [return to {_activeNode.Parent.Name}]", ConsoleColor.Blue); - - return new LineDisplayState(prefix, line.Text, suffix, line.Cursor); - - }; - } - - - private static string FormatTable(bool header, params IReadOnlyList[] columns) - { - var rows = new List(); - var colWidths = columns.Select(c => c.Max(x => x.Length)).ToArray(); - - for (int i = 0; i < columns[0].Count; i++) - { - var cols = new List(); - for (int j = 0; j < columns.Length; j++) - { - cols.Add(columns[j][i] + new string(' ', colWidths[j] - columns[j][i].Length + 1)); - } - rows.Add(string.Join(" ", cols)); - } - - // Find the longest row, and insert a horizontal rule after the first row - var longest = rows.Select(x => x.Length).Max(); - - if (header) - rows.Insert(1, new string('-', longest)); - - return string.Join("\n", rows); - - } - - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using InteractiveReadLine.Demo.Demos; +using InteractiveReadLine.Demo.Demos.Formatters; +using InteractiveReadLine.Demo.Demos.Keys; +using InteractiveReadLine.Formatting; +using InteractiveReadLine.KeyBehaviors; +using InteractiveReadLine.Tokenizing; +using Microsoft.VisualBasic.CompilerServices; + +namespace InteractiveReadLine.Demo +{ + class Program + { + private static DemoNode _demoHome; + private static DemoNode _activeNode; + + static void Main(string[] args) + { + _demoHome = SetupDemo(); + _activeNode = _demoHome; + var isRunning = true; + + Console.WriteLine("InteractiveReadLine Demo Program"); + Console.WriteLine("\nThis executable is a demonstration to showcase some of the features of this library.\nYou can exit at any time with the command 'exit'.''"); + Console.WriteLine(); + + while (isRunning) + { + var options = new OptionSet(); + Console.Clear(); + + if (_activeNode.Demo != null) + { + // This is a demo node + Console.WriteLine($"Demo: {_activeNode.Name} ({_activeNode.Description})"); + options.AddToStart("run", "Run this demo", () => + { + Console.Clear(); + _activeNode.Demo.Action(); + }); + } + else + { + // This is a menu node, show the node and its first level children + Console.WriteLine($" {_activeNode.Description}"); + + var names = _activeNode.OrderedChildKeys; + foreach (var name in names) + { + options.Add(name, _activeNode.Children[name].Description, () => _activeNode = _activeNode.Children[name]); + } + } + + options.AddSpace(); + + if (_activeNode.Parent != null) + options.Add("back", "Go back", () => _activeNode = _activeNode.Parent); + + options.Add("home", "Return to demo home", () => _activeNode = _demoHome); + options.Add("exit", "Exit the demo program", () => isRunning = false); + + var padding = options.Keys.Select(n => " ").ToArray(); + if (_activeNode.Demo != null) + { + var link = GetGithubLink(_activeNode.Demo); + if (link != null) + Console.WriteLine($" * {link}"); + } + Console.WriteLine(FormatTable(false, padding, options.Keys, options.Descriptions)); + + var config = ReadLineConfig.Basic + .AddCtrlNavKeys() + .AddTabAutoComplete() + .SetLexer(CommonLexers.SplitOnWhitespace) + .SetAutoCompletion(t => options.NonBlankKeys.Where(o => o.StartsWith(t.CursorToken.Text)).ToArray()) + .SetFormatter(NodeFormatter(options.NonBlankKeys.ToArray())); + + var result = ConsoleReadLine.Read(config); + + // Ctrl+D on an empty line means the user is done, which for this menu is the same as choosing + // "exit". Ctrl+C abandons whatever was typed and simply redraws the menu. + if (result.Kind == ReadLineResultKind.EndOfInput) + { + isRunning = false; + } + else if (result.IsLine && options.ContainsKey(result.Text)) + { + options.GetAction(result.Text).Invoke(); + } + } + } + + static DemoNode SetupDemo() + { + // Demo home node + _demoHome = new DemoNode(null, "home", "Demo Home"); + + // featured demos + var featuredNode = _demoHome.AddChild("featured", "Featured Demos"); + featuredNode.AddChild("basic", new BasicConfig()); + featuredNode.AddChild("complex", new ComplexConfig()); + featuredNode.AddChild("hunter2", new Hunter2()); + + // Key behavior demos + var keyNode = _demoHome.AddChild("keys", "Key Behaviors and Customization"); + keyNode.AddChild("bare", new BareKeys()); + keyNode.AddChild("default-behavior", new CustomInsertCharacter()); + + // Formatting demos + var formatNode = _demoHome.AddChild("formatters", "Display Formatting and Customization"); + formatNode.AddChild("fixed-prompt", new FixedPrompt()); + formatNode.AddChild("custom-simple", new SimpleCustomFormatter()); + formatNode.AddChild("custom-token", new TokenCustomFormatter()); + formatNode.AddChild("passwd-stars", new PasswordStarPrompt()); + formatNode.AddChild("passwd-bars", new PasswordBarPrompt()); + + // Lexing demos + var lexingNode = _demoHome.AddChild("lexing", "Lexers and Tokenizing"); + + // Autocomplete demos + var autocompleteNode = _demoHome.AddChild("autocomplete", "Autocomplete Demos"); + + // History demos + var historyNode = _demoHome.AddChild("history", "History Demos"); + + + return _demoHome; + } + + private static string GetGithubLink(IDemo demo) + { + const string rootUrl = "https://github.com/mattj23/InteractiveReadLine/tree/main/InteractiveReadLine.Demo/"; + var typeInfo = demo.GetType(); + var path = typeInfo.FullName?.Replace("InteractiveReadLine.Demo.", "").Split("."); + if (path != null) + { + return rootUrl + string.Join("/", path) + ".cs"; + } + + return null; + } + + private static Func NodeFormatter(IReadOnlyList options) + { + var path = _activeNode.Path; + + return line => + { + var prefix = new FormattedText($"{path} > "); + + FormattedText suffix = ""; + if (line.FirstNonHidden.Text == "exit") + suffix = new FormattedText(" [exits the demo program]", ConsoleColor.Red); + else if (line.FirstNonHidden.Text == "home") + suffix = new FormattedText(" [returns to demo root]", ConsoleColor.Blue); + else if (line.FirstNonHidden.Text == "back" && _activeNode.Parent != null) + suffix = new FormattedText($" [return to {_activeNode.Parent.Name}]", ConsoleColor.Blue); + + return new LineDisplayState(prefix, line.Text, suffix, line.Cursor); + + }; + } + + + private static string FormatTable(bool header, params IReadOnlyList[] columns) + { + var rows = new List(); + var colWidths = columns.Select(c => c.Max(x => x.Length)).ToArray(); + + for (int i = 0; i < columns[0].Count; i++) + { + var cols = new List(); + for (int j = 0; j < columns.Length; j++) + { + cols.Add(columns[j][i] + new string(' ', colWidths[j] - columns[j][i].Length + 1)); + } + rows.Add(string.Join(" ", cols)); + } + + // Find the longest row, and insert a horizontal rule after the first row + var longest = rows.Select(x => x.Length).Max(); + + if (header) + rows.Insert(1, new string('-', longest)); + + return string.Join("\n", rows); + + } + + } +} diff --git a/InteractiveReadLine.Tests/AsyncReadLineTests.cs b/InteractiveReadLine.Tests/AsyncReadLineTests.cs new file mode 100644 index 0000000..f9f8d74 --- /dev/null +++ b/InteractiveReadLine.Tests/AsyncReadLineTests.cs @@ -0,0 +1,198 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using InteractiveReadLine.KeyBehaviors; +using InteractiveReadLine.Tests.Fakes; +using Xunit; + +namespace InteractiveReadLine.Tests +{ + public class AsyncReadLineTests + { + [Fact] + public async Task ReadAsync_ProducesALineResult() + { + var keys = KeyBuilder.Create().Add("typed asynchronously").Enter().Keys; + var provider = new ConsoleReadLine(new TestConsole(10, 80, keys)); + + var result = await provider.ReadAsync(ReadLineConfig.Basic); + + Assert.Equal(ReadLineResultKind.Line, result.Kind); + Assert.Equal("typed asynchronously", result.Text); + } + + [Fact] + public async Task ReadLineAsync_ReturnsTheText() + { + var keys = KeyBuilder.Create().Add("hello").Enter().Keys; + var provider = new ConsoleReadLine(new TestConsole(10, 80, keys)); + + Assert.Equal("hello", await provider.ReadLineAsync(ReadLineConfig.Basic)); + } + + /// + /// The two loops differ only in how they wait for a key, so the same key sequence must produce the same + /// result and console output. + /// + [Theory] + [InlineData("plain text")] + [InlineData("editing")] + public async Task ReadAsync_MatchesRead_ForTheSameKeys(string text) + { + var syncConsole = new TestConsole(10, 80, Editing(text)); + var asyncConsole = new TestConsole(10, 80, Editing(text)); + + var syncResult = new ConsoleReadLine(syncConsole).Read(ReadLineConfig.Basic); + var asyncResult = await new ConsoleReadLine(asyncConsole).ReadAsync(ReadLineConfig.Basic); + + Assert.Equal(syncResult.Kind, asyncResult.Kind); + Assert.Equal(syncResult.Text, asyncResult.Text); + Assert.Equal(syncConsole.BufferToString(), asyncConsole.BufferToString()); + } + + [Fact] + public async Task ReadAsync_HistoryNavigationBehavesTheSameAsTheSyncLoop() + { + var syncHistory = new List {"first", "second"}; + var asyncHistory = new List {"first", "second"}; + + var keys = KeyBuilder.Create().UpArrow(2).Enter().Keys; + + var syncResult = new ConsoleReadLine(new TestConsole(10, 80, keys)) + .Read(ReadLineConfig.Basic.SetUpdatingHistorySource(syncHistory)); + var asyncResult = await new ConsoleReadLine(new TestConsole(10, 80, keys)) + .ReadAsync(ReadLineConfig.Basic.SetUpdatingHistorySource(asyncHistory)); + + Assert.Equal("first", syncResult.Text); + Assert.Equal(syncResult.Text, asyncResult.Text); + Assert.Equal(syncHistory, asyncHistory); + } + + [Fact] + public async Task ReadAsync_CtrlC_ProducesACancelledResultRatherThanThrowing() + { + var keys = KeyBuilder.Create().Add("abandon me").CtrlC().Keys; + var provider = new ConsoleReadLine(new TestConsole(10, 80, keys)); + + var result = await provider.ReadAsync(ReadLineConfig.Basic); + + Assert.Equal(ReadLineResultKind.Cancelled, result.Kind); + } + + [Fact] + public async Task ReadAsync_CtrlD_OnAnEmptyLine_ProducesAnEndOfInputResult() + { + var config = ReadLineConfig.Basic.AddCtrlNavKeys(); + var provider = new ConsoleReadLine(new TestConsole(10, 80, KeyBuilder.Create().CtrlD().Keys)); + + var result = await provider.ReadAsync(config); + + Assert.Equal(ReadLineResultKind.EndOfInput, result.Kind); + } + + [Fact] + public async Task ReadKeyAsync_WithAnAlreadyCancelledToken_ThrowsWithoutConsumingAKey() + { + var keys = KeyBuilder.Create().Add("ab").Keys; + var provider = new ConsoleReadLine(new TestConsole(10, 80, keys)); + + using (var source = new CancellationTokenSource()) + { + source.Cancel(); + + await Assert.ThrowsAnyAsync( + () => provider.ReadKeyAsync(source.Token)); + } + + Assert.Equal('a', provider.ReadKey().KeyChar); + } + + [Fact] + public async Task ReadKeyAsync_WaitsUntilAKeyBecomesAvailable() + { + var console = new TestConsole(10, 80, KeyBuilder.Create().Add("z").Keys) + { + PollsBeforeKeyAvailable = 3 + }; + var provider = new ConsoleReadLine(console); + + var key = await provider.ReadKeyAsync(); + + Assert.Equal('z', key.KeyChar); + Assert.Equal(0, console.PollsBeforeKeyAvailable); + } + + /// + /// The asynchronous path does not occupy a thread while waiting for the user. When no key is available, + /// the returned task must remain incomplete so that control returns to the caller. + /// + [Fact] + public async Task ReadKeyAsync_ReturnsAnIncompleteTaskWhileWaiting() + { + var provider = new ConsoleReadLine(new TestConsole(10, 80)); + + using (var source = new CancellationTokenSource()) + { + var pending = provider.ReadKeyAsync(source.Token); + + Assert.False(pending.IsCompleted); + + source.Cancel(); + await Assert.ThrowsAnyAsync(() => pending); + } + } + + [Fact] + public async Task ReadAsync_WhenCancelled_Throws() + { + // No keys are queued, so the read waits until the token is canceled. + var provider = new ConsoleReadLine(new TestConsole(10, 80)); + + using (var source = new CancellationTokenSource()) + { + source.CancelAfter(TimeSpan.FromMilliseconds(50)); + + await Assert.ThrowsAnyAsync( + () => provider.ReadAsync(ReadLineConfig.Basic, source.Token)); + } + } + + /// + /// A canceled asynchronous read still disposes its provider, so it restores the console as an ordinary + /// read does. + /// + [Fact] + public async Task ReadAsync_WhenCancelled_StillRestoresTheConsole() + { + var console = new TestConsole(10, 80) {TreatControlCAsInput = false}; + var provider = new ConsoleReadLine(console); + + using (var source = new CancellationTokenSource()) + { + source.CancelAfter(TimeSpan.FromMilliseconds(50)); + + await Assert.ThrowsAnyAsync( + () => provider.ReadAsync(ReadLineConfig.Basic, source.Token)); + } + + Assert.False(console.TreatControlCAsInput); + } + + [Fact] + public async Task ReadLineAsync_FlattensCancelledToEmptyAndEndOfInputToNull() + { + var cancelled = await new ConsoleReadLine(new TestConsole(10, 80, KeyBuilder.Create().CtrlC().Keys)) + .ReadLineAsync(ReadLineConfig.Basic); + + var ended = await new ConsoleReadLine(new TestConsole(10, 80, KeyBuilder.Create().CtrlD().Keys)) + .ReadLineAsync(ReadLineConfig.Basic.AddCtrlNavKeys()); + + Assert.Equal(string.Empty, cancelled); + Assert.Null(ended); + } + + private static ConsoleKeyInfo[] Editing(string text) => + KeyBuilder.Create().Add(text).LeftArrow(2).Add("XY").Enter().Keys; + } +} diff --git a/InteractiveReadLine.Tests/BehaviorExtensionMethodTests.cs b/InteractiveReadLine.Tests/BehaviorExtensionMethodTests.cs new file mode 100644 index 0000000..5a26ed1 --- /dev/null +++ b/InteractiveReadLine.Tests/BehaviorExtensionMethodTests.cs @@ -0,0 +1,151 @@ +using System; +using InteractiveReadLine.KeyBehaviors; +using InteractiveReadLine.Tests.Fakes; +using Xunit; + +namespace InteractiveReadLine.Tests +{ + public class BehaviorExtensionMethodTests + { + [Theory] + [InlineData(false, false, false)] + [InlineData(true, false, false)] + [InlineData(false, true, false)] + [InlineData(false, false, true)] + [InlineData(true, true, true)] + public void AddKeyBehavior_WithModifiers_RegistersThoseModifiers(bool control, bool alt, bool shift) + { + var config = ReadLineConfig.Empty + .AddKeyBehavior(ConsoleKey.X, control, alt, shift, t => { }); + + var key = Assert.Single(config.KeyBehaviors.Keys); + Assert.Equal(ConsoleKey.X, key.Key); + Assert.Equal(control, key.HasCtrl); + Assert.Equal(alt, key.HasAlt); + Assert.Equal(shift, key.HasShift); + } + + [Fact] + public void AddKeyBehavior_WithControlModifier_FiresOnTheModifiedKey() + { + var fired = false; + var config = ReadLineConfig.Basic + .AddKeyBehavior(ConsoleKey.X, true, false, false, t => fired = true); + + // KeyBuilder.Add takes (key, shift, alt, control) + var keys = KeyBuilder.Create().Add(ConsoleKey.X, false, false, true).Enter().Keys; + new ConsoleReadLine(new TestConsole(10, 80, keys)).ReadLine(config); + + Assert.True(fired); + } + + /// + /// Regression test for dropped modifiers: a Ctrl+X binding used to register as a plain X, so typing + /// an unmodified "x" would run the behavior instead of inserting the character. + /// + [Fact] + public void AddKeyBehavior_WithControlModifier_DoesNotFireOnTheUnmodifiedKey() + { + var fired = false; + var config = ReadLineConfig.Basic + .AddKeyBehavior(ConsoleKey.X, true, false, false, t => fired = true); + + var keys = KeyBuilder.Create().Add("x").Enter().Keys; + var result = new ConsoleReadLine(new TestConsole(10, 80, keys)).ReadLine(config); + + Assert.False(fired); + Assert.Equal("x", result); + } + + [Fact] + public void AddKeyBehavior_RebindingAKeyBoundByBasic_DoesNotThrow() + { + // ReadLineConfig.Basic already binds DownArrow through AddUpDownHistoryNavigation. This is the + // "Custom Key Behaviors" example in the README, which used to throw an ArgumentException. + var exception = Record.Exception(() => + ReadLineConfig.Basic.AddKeyBehavior(ConsoleKey.DownArrow, t => { })); + + Assert.Null(exception); + } + + [Fact] + public void AddKeyBehavior_RebindingAKey_ReplacesTheEarlierBehavior() + { + var firstFired = false; + var secondFired = false; + + var config = ReadLineConfig.Empty + .SetDefaultKeyBehavior(CommonKeyBehaviors.InsertCharacter) + .AddEnterToFinish() + .AddKeyBehavior(ConsoleKey.F1, t => firstFired = true) + .AddKeyBehavior(ConsoleKey.F1, t => secondFired = true); + + var keys = KeyBuilder.Create().Add(ConsoleKey.F1, false, false, false).Enter().Keys; + new ConsoleReadLine(new TestConsole(10, 80, keys)).ReadLine(config); + + Assert.False(firstFired); + Assert.True(secondFired); + + // Rebinding replaced the entry, so only Enter and F1 are registered. + Assert.Equal(2, config.KeyBehaviors.Count); + } + + [Fact] + public void AddKeyBehavior_OverridingADefaultBinding_TakesEffect() + { + var config = ReadLineConfig.Basic + .AddKeyBehavior(ConsoleKey.DownArrow, CommonKeyBehaviors.InsertCharacter); + + var keys = KeyBuilder.Create().Add("ab").DownArrow().Enter().Keys; + var result = new ConsoleReadLine(new TestConsole(10, 80, keys)).ReadLine(config); + + // DownArrow now runs InsertCharacter instead of navigating history. The key carries no character, + // so the buffer is unchanged. History navigation therefore does not clear the buffer. + Assert.Equal("ab", result); + } + + [Fact] + public void AddCtrlKeyBehavior_RegistersOnlyTheControlModifier() + { + var config = ReadLineConfig.Empty.AddCtrlKeyBehavior(ConsoleKey.W, t => { }); + + var key = Assert.Single(config.KeyBehaviors.Keys); + Assert.Equal(ConsoleKey.W, key.Key); + Assert.True(key.HasCtrl); + Assert.False(key.HasAlt); + Assert.False(key.HasShift); + } + + [Fact] + public void AddKeyBehavior_ByConsoleKey_RegistersNoModifiers() + { + var config = ReadLineConfig.Empty.AddKeyBehavior(ConsoleKey.Home, t => { }); + + var key = Assert.Single(config.KeyBehaviors.Keys); + Assert.Equal(ConsoleKey.Home, key.Key); + Assert.False(key.HasCtrl); + Assert.False(key.HasAlt); + Assert.False(key.HasShift); + } + + [Fact] + public void AddKeyBehavior_ByChar_RegistersTheCharacter() + { + var config = ReadLineConfig.Empty.AddKeyBehavior('q', t => { }); + + var key = Assert.Single(config.KeyBehaviors.Keys); + Assert.Equal('q', key.Char); + Assert.Null(key.Key); + } + + [Fact] + public void AddTabAutoComplete_BindsTabAndShiftTabSeparately() + { + var config = ReadLineConfig.Empty.AddTabAutoComplete(); + + Assert.Equal(2, config.KeyBehaviors.Count); + Assert.True(config.KeyBehaviors.ContainsKey(new KeyId(ConsoleKey.Tab, false, false, false))); + Assert.True(config.KeyBehaviors.ContainsKey(new KeyId(ConsoleKey.Tab, false, false, true))); + } + } +} diff --git a/InteractiveReadLine.Tests/CancelAndEndOfInputTests.cs b/InteractiveReadLine.Tests/CancelAndEndOfInputTests.cs new file mode 100644 index 0000000..ae86943 --- /dev/null +++ b/InteractiveReadLine.Tests/CancelAndEndOfInputTests.cs @@ -0,0 +1,177 @@ +using System; +using System.Collections.Generic; +using InteractiveReadLine.KeyBehaviors; +using InteractiveReadLine.Tests.Fakes; +using Xunit; + +namespace InteractiveReadLine.Tests +{ + public class CancelAndEndOfInputTests + { + [Fact] + public void Enter_ProducesALineResult() + { + var keys = KeyBuilder.Create().Add("some text").Enter().Keys; + var result = new ConsoleReadLine(new TestConsole(10, 80, keys)).Read(ReadLineConfig.Basic); + + Assert.Equal(ReadLineResultKind.Line, result.Kind); + Assert.True(result.IsLine); + Assert.Equal("some text", result.Text); + } + + [Fact] + public void CtrlC_ProducesACancelledResult() + { + var keys = KeyBuilder.Create().Add("abandon me").CtrlC().Keys; + var result = new ConsoleReadLine(new TestConsole(10, 80, keys)).Read(ReadLineConfig.Basic); + + Assert.Equal(ReadLineResultKind.Cancelled, result.Kind); + Assert.False(result.IsLine); + Assert.Null(result.Text); + } + + /// + /// The string API converts a canceled line to an empty string. In a read-evaluate loop, this behaves as + /// a no-op and does not terminate the loop as a null result would. + /// + [Fact] + public void CtrlC_FlattensToAnEmptyString() + { + var keys = KeyBuilder.Create().Add("abandon me").CtrlC().Keys; + var result = new ConsoleReadLine(new TestConsole(10, 80, keys)).ReadLine(ReadLineConfig.Basic); + + Assert.Equal(string.Empty, result); + } + + [Fact] + public void CtrlC_DoesNotRecordAnythingInTheHistory() + { + var history = new List {"existing entry"}; + var config = ReadLineConfig.Basic.SetUpdatingHistorySource(history); + var keys = KeyBuilder.Create().Add("abandon me").CtrlC().Keys; + + new ConsoleReadLine(new TestConsole(10, 80, keys)).Read(config); + + Assert.Single(history); + } + + [Fact] + public void CtrlD_OnAnEmptyLine_ProducesAnEndOfInputResult() + { + var config = ReadLineConfig.Basic.AddCtrlNavKeys(); + var keys = KeyBuilder.Create().CtrlD().Keys; + var result = new ConsoleReadLine(new TestConsole(10, 80, keys)).Read(config); + + Assert.Equal(ReadLineResultKind.EndOfInput, result.Kind); + Assert.Null(result.Text); + } + + /// + /// The string API converts the end-of-input result to null, matching both GNU Readline and + /// Console.ReadLine, so that a "while the line is not null" loop terminates on Ctrl+D. + /// + [Fact] + public void CtrlD_OnAnEmptyLine_FlattensToNull() + { + var config = ReadLineConfig.Basic.AddCtrlNavKeys(); + var keys = KeyBuilder.Create().CtrlD().Keys; + var result = new ConsoleReadLine(new TestConsole(10, 80, keys)).ReadLine(config); + + Assert.Null(result); + } + + [Fact] + public void CtrlD_OnAnEmptyLine_DoesNotRecordAnythingInTheHistory() + { + var history = new List {"existing entry"}; + var config = ReadLineConfig.Basic.AddCtrlNavKeys().SetUpdatingHistorySource(history); + var keys = KeyBuilder.Create().CtrlD().Keys; + + new ConsoleReadLine(new TestConsole(10, 80, keys)).Read(config); + + Assert.Single(history); + } + + /// + /// With text in the buffer, Ctrl+D deletes forward instead of ending the input, matching shell behavior. + /// + [Fact] + public void CtrlD_WithTextInTheBuffer_DeletesForwardAndContinues() + { + var config = ReadLineConfig.Basic.AddCtrlNavKeys(); + var keys = KeyBuilder.Create().Add("abc").LeftArrow(3).CtrlD().Enter().Keys; + var result = new ConsoleReadLine(new TestConsole(10, 80, keys)).Read(config); + + Assert.Equal(ReadLineResultKind.Line, result.Kind); + Assert.Equal("bc", result.Text); + } + + [Fact] + public void BasicConfiguration_BindsCtrlC() + { + var config = ReadLineConfig.Basic; + + Assert.True(config.KeyBehaviors.ContainsKey(new KeyId(ConsoleKey.C, true, false, false))); + } + + [Fact] + public void Provider_EnablesTreatControlCAsInput_AndRestoresItOnDispose() + { + var console = new TestConsole(10, 80) {TreatControlCAsInput = false}; + var provider = new ConsoleReadLine(console); + + Assert.True(console.TreatControlCAsInput); + + provider.Dispose(); + + Assert.False(console.TreatControlCAsInput); + } + + [Fact] + public void Provider_RestoresTreatControlCAsInput_WhenItWasAlreadyEnabled() + { + var console = new TestConsole(10, 80) {TreatControlCAsInput = true}; + var provider = new ConsoleReadLine(console); + provider.Dispose(); + + Assert.True(console.TreatControlCAsInput); + } + + [Theory] + [InlineData("")] + [InlineData("some text")] + public void ForLine_RoundTripsThroughToText(string text) + { + var result = ReadLineResult.ForLine(text); + + Assert.Equal(text, result.ToText()); + Assert.True(result.IsLine); + } + + [Fact] + public void ToText_MapsCancelledToEmptyAndEndOfInputToNull() + { + Assert.Equal(string.Empty, ReadLineResult.Cancelled.ToText()); + Assert.Null(ReadLineResult.EndOfInput.ToText()); + } + + /// + /// The result type distinguishes an empty line that the user entered from a line that they abandoned. + /// + [Fact] + public void AnEnteredEmptyLine_IsDistinctFromACancelledOne() + { + var entered = new ConsoleReadLine(new TestConsole(10, 80, KeyBuilder.Create().Enter().Keys)) + .Read(ReadLineConfig.Basic); + var cancelled = new ConsoleReadLine(new TestConsole(10, 80, KeyBuilder.Create().CtrlC().Keys)) + .Read(ReadLineConfig.Basic); + + Assert.Equal(string.Empty, entered.ToText()); + Assert.Equal(string.Empty, cancelled.ToText()); + + Assert.NotEqual(entered.Kind, cancelled.Kind); + Assert.True(entered.IsLine); + Assert.False(cancelled.IsLine); + } + } +} diff --git a/InteractiveReadLine.Tests/CancellationTests.cs b/InteractiveReadLine.Tests/CancellationTests.cs new file mode 100644 index 0000000..bfc7225 --- /dev/null +++ b/InteractiveReadLine.Tests/CancellationTests.cs @@ -0,0 +1,156 @@ +using System; +using System.Diagnostics; +using System.Threading; +using InteractiveReadLine.Tests.Fakes; +using Xunit; + +namespace InteractiveReadLine.Tests +{ + public class CancellationTests + { + [Fact] + public void ReadKey_WithAnAlreadyCancelledToken_Throws() + { + var keys = KeyBuilder.Create().Add("unread").Keys; + var console = new TestConsole(10, 80, keys); + var provider = new ConsoleReadLine(console); + + using (var source = new CancellationTokenSource()) + { + source.Cancel(); + + Assert.ThrowsAny(() => provider.ReadKey(source.Token)); + } + } + + /// + /// Cancellation must not consume a keypress because the caller can read the same input through another + /// route afterward. + /// + [Fact] + public void ReadKey_WithAnAlreadyCancelledToken_LeavesTheKeysUnread() + { + var keys = KeyBuilder.Create().Add("ab").Enter().Keys; + var console = new TestConsole(10, 80, keys); + var provider = new ConsoleReadLine(console); + + using (var source = new CancellationTokenSource()) + { + source.Cancel(); + Assert.ThrowsAny(() => provider.ReadKey(source.Token)); + } + + // The complete sequence is still queued, so a subsequent read receives the first key. + Assert.Equal('a', provider.ReadKey().KeyChar); + } + + [Fact] + public void ReadKey_WithoutACancellableToken_ReadsNormally() + { + var keys = KeyBuilder.Create().Add("x").Keys; + var provider = new ConsoleReadLine(new TestConsole(10, 80, keys)); + + Assert.Equal('x', provider.ReadKey(CancellationToken.None).KeyChar); + } + + /// + /// When a token can be canceled, the provider polls until a key is available so that it can observe the + /// token between polls. + /// + [Fact] + public void ReadKey_PollsUntilAKeyBecomesAvailable() + { + var keys = KeyBuilder.Create().Add("z").Keys; + var console = new TestConsole(10, 80, keys) {PollsBeforeKeyAvailable = 3}; + var provider = new ConsoleReadLine(console); + + using (var source = new CancellationTokenSource()) + { + var key = provider.ReadKey(source.Token); + + Assert.Equal('z', key.KeyChar); + Assert.Equal(0, console.PollsBeforeKeyAvailable); + } + } + + [Fact] + public void ReadKey_CancelledWhileWaiting_Throws() + { + // No keys are queued, so the read waits until the token is canceled. + var console = new TestConsole(10, 80); + var provider = new ConsoleReadLine(console); + + using (var source = new CancellationTokenSource()) + { + source.CancelAfter(TimeSpan.FromMilliseconds(50)); + + var stopwatch = Stopwatch.StartNew(); + Assert.ThrowsAny(() => provider.ReadKey(source.Token)); + stopwatch.Stop(); + + // It waited rather than failing immediately, and it did not wait far longer than asked. + Assert.True(stopwatch.ElapsedMilliseconds >= 25, $"returned after only {stopwatch.ElapsedMilliseconds}ms"); + } + } + + [Fact] + public void Read_WhenCancelled_Throws() + { + var provider = new ConsoleReadLine(new TestConsole(10, 80)); + + using (var source = new CancellationTokenSource()) + { + source.CancelAfter(TimeSpan.FromMilliseconds(50)); + + Assert.ThrowsAny( + () => provider.Read(ReadLineConfig.Basic, source.Token)); + } + } + + /// + /// A canceled read still disposes its provider, which restores the console instead of leaving Ctrl+C + /// interception enabled. + /// + [Fact] + public void Read_WhenCancelled_StillRestoresTheConsole() + { + var console = new TestConsole(10, 80) {TreatControlCAsInput = false}; + var provider = new ConsoleReadLine(console); + + using (var source = new CancellationTokenSource()) + { + source.CancelAfter(TimeSpan.FromMilliseconds(50)); + + Assert.ThrowsAny( + () => provider.Read(ReadLineConfig.Basic, source.Token)); + } + + Assert.False(console.TreatControlCAsInput); + } + + [Fact] + public void Read_WithAnUncancelledToken_CompletesNormally() + { + var keys = KeyBuilder.Create().Add("still works").Enter().Keys; + var provider = new ConsoleReadLine(new TestConsole(10, 80, keys)); + + using (var source = new CancellationTokenSource()) + { + var result = provider.Read(ReadLineConfig.Basic, source.Token); + + Assert.Equal(ReadLineResultKind.Line, result.Kind); + Assert.Equal("still works", result.Text); + } + } + + [Fact] + public void Constructor_WhenInputIsRedirected_Throws() + { + var console = new TestConsole(10, 80) {InputIsRedirected = true}; + + var exception = Assert.Throws(() => new ConsoleReadLine(console)); + + Assert.Contains("redirected", exception.Message, StringComparison.OrdinalIgnoreCase); + } + } +} diff --git a/InteractiveReadLine.Tests/CommonBehaviorTests.cs b/InteractiveReadLine.Tests/CommonBehaviorTests.cs index ad06bdf..e0c2705 100644 --- a/InteractiveReadLine.Tests/CommonBehaviorTests.cs +++ b/InteractiveReadLine.Tests/CommonBehaviorTests.cs @@ -1,221 +1,221 @@ -using System; -using System.Text; -using InteractiveReadLine.KeyBehaviors; -using Moq; -using Xunit; - -namespace InteractiveReadLine.Tests -{ - public class CommonBehaviorTests - { - [Theory] - [InlineData("test", 0, "est")] - [InlineData("test", 1, "tst")] - [InlineData("test", 2, "tet")] - [InlineData("test", 3, "tes")] - [InlineData("test", 4, "test")] - public void DeleteAtCursor_Works(string text, int cursor, string expected) - { - var buffer = new StringBuilder(text); - var mock = new Mock(); - mock.SetupGet(x => x.TextBuffer).Returns(buffer); - mock.SetupProperty(x => x.CursorPosition); - mock.Object.CursorPosition = cursor; - - CommonKeyBehaviors.Delete(mock.Object); - - Assert.Equal(cursor, mock.Object.CursorPosition); - Assert.Equal(expected, buffer.ToString()); - } - - - [Theory] - [InlineData("test", 0, "test", 0)] - [InlineData("test", 1, "est", 0)] - [InlineData("test", 2, "tst", 1)] - [InlineData("test", 3, "tet", 2)] - [InlineData("test", 4, "tes", 3)] - public void BackspaceAtCursor_Works(string text, int cursor, string expected, int expectedCursor) - { - var buffer = new StringBuilder(text); - var mock = new Mock(); - mock.SetupGet(x => x.TextBuffer).Returns(buffer); - mock.SetupProperty(x => x.CursorPosition); - mock.Object.CursorPosition = cursor; - - CommonKeyBehaviors.Backspace(mock.Object); - - Assert.Equal(expectedCursor, mock.Object.CursorPosition); - Assert.Equal(expected, buffer.ToString()); - } - - [Fact] - public void CursorMoveToEnd_Works() - { - var buffer = new StringBuilder("this is a test"); - var mock = new Mock(); - mock.SetupGet(x => x.TextBuffer).Returns(buffer); - mock.SetupProperty(x => x.CursorPosition); - mock.Object.CursorPosition = 4; - - CommonKeyBehaviors.MoveCursorToEnd(mock.Object); - - Assert.Equal(14, mock.Object.CursorPosition); - } - - [Fact] - public void CursorMoveToStart_Works() - { - var buffer = new StringBuilder("this is a test"); - var mock = new Mock(); - mock.SetupGet(x => x.TextBuffer).Returns(buffer); - mock.SetupProperty(x => x.CursorPosition); - mock.Object.CursorPosition = 14; - - CommonKeyBehaviors.MoveCursorToStart(mock.Object); - - Assert.Equal(0, mock.Object.CursorPosition); - } - - [Theory] - [InlineData(0, 0)] - [InlineData(4, 3)] - [InlineData(2, 1)] - public void MoveCursorLeft_Works(int cursor, int expected) - { - var buffer = new StringBuilder("test"); - var mock = new Mock(); - mock.SetupGet(x => x.TextBuffer).Returns(buffer); - mock.SetupProperty(x => x.CursorPosition); - mock.Object.CursorPosition = cursor; - - CommonKeyBehaviors.MoveCursorLeft(mock.Object); - - Assert.Equal(expected, mock.Object.CursorPosition); - } - - - [Theory] - [InlineData(0, 1)] - [InlineData(4, 4)] - [InlineData(2, 3)] - public void MoveCursorRight_Works(int cursor, int expected) - { - var buffer = new StringBuilder("test"); - var mock = new Mock(); - mock.SetupGet(x => x.TextBuffer).Returns(buffer); - mock.SetupProperty(x => x.CursorPosition); - mock.Object.CursorPosition = cursor; - - CommonKeyBehaviors.MoveCursorRight(mock.Object); - - Assert.Equal(expected, mock.Object.CursorPosition); - } - - [Fact] - public void ClearBuffer_Works() - { - var buffer = new StringBuilder("test"); - var mock = new Mock(); - mock.SetupGet(x => x.TextBuffer).Returns(buffer); - mock.SetupProperty(x => x.CursorPosition); - mock.Object.CursorPosition = 4; - - CommonKeyBehaviors.ClearAll(mock.Object); - - Assert.Equal("", buffer.ToString()); - Assert.Equal(0, mock.Object.CursorPosition); - } - - [Theory] - [InlineData('A', 0, "Atest")] - [InlineData('9', 2, "te9st")] - [InlineData('0', 4, "test0")] - [InlineData(' ', 0, " test")] - [InlineData(' ', 2, "te st")] - [InlineData(' ', 4, "test ")] - [InlineData('.', 0, ".test")] - [InlineData(';', 2, "te;st")] - [InlineData(',', 4, "test,")] - [InlineData('*', 0, "*test")] - [InlineData('%', 2, "te%st")] - [InlineData('$', 4, "test$")] - public void InsertCharacters_Works(char c, int cursor, string expected) - { - var buffer = new StringBuilder("test"); - var mock = new Mock(); - mock.SetupGet(x => x.TextBuffer).Returns(buffer); - mock.SetupProperty(x => x.CursorPosition); - mock.SetupGet(x => x.ReceivedKey).Returns(new ConsoleKeyInfo(c, ConsoleKey.Oem1, false, false, false)); - mock.Object.CursorPosition = cursor; - - CommonKeyBehaviors.InsertCharacter(mock.Object); - - Assert.Equal(expected, buffer.ToString()); - Assert.Equal(cursor + 1, mock.Object.CursorPosition); - } - - [Theory] - [InlineData(0, "")] - [InlineData(3, "tes")] - [InlineData(8, "test dat")] - [InlineData(9, "test data")] - public void CutToEnd_Works(int cursor, string expected) - { - // 0123456789 - var buffer = new StringBuilder("test data"); - var mock = new Mock(); - mock.SetupGet(x => x.TextBuffer).Returns(buffer); - mock.SetupProperty(x => x.CursorPosition); - mock.Object.CursorPosition = cursor; - - CommonKeyBehaviors.CutToEnd(mock.Object); - - Assert.Equal(expected, buffer.ToString()); - Assert.Equal(cursor, mock.Object.CursorPosition); - } - - [Theory] - [InlineData(0, "test data")] - [InlineData(3, "t data")] - [InlineData(8, "a")] - [InlineData(9, "")] - public void CutToStart_Works(int cursor, string expected) - { - // 0123456789 - var buffer = new StringBuilder("test data"); - var mock = new Mock(); - mock.SetupGet(x => x.TextBuffer).Returns(buffer); - mock.SetupProperty(x => x.CursorPosition); - mock.Object.CursorPosition = cursor; - - CommonKeyBehaviors.CutToStart(mock.Object); - - Assert.Equal(expected, buffer.ToString()); - Assert.Equal(0, mock.Object.CursorPosition); - } - - [Theory] - [InlineData(0, "test data here ", 0)] - [InlineData(2, "st data here ", 0)] - [InlineData(4, " data here ", 0)] - [InlineData(5, "data here ", 0)] - [InlineData(7, "test ta here ", 5)] - [InlineData(10, "test here ", 5)] - [InlineData(15, "test data ", 10)] - public void CutPreviousWord_WithNoTokens_Works(int cursor, string expected, int expectedCursor) - { - // 0123456789012345 - var buffer = new StringBuilder("test data here "); - var mock = new Mock(); - mock.SetupGet(x => x.TextBuffer).Returns(buffer); - mock.SetupProperty(x => x.CursorPosition); - mock.Object.CursorPosition = cursor; - - CommonKeyBehaviors.CutPreviousWord(mock.Object); - - Assert.Equal(expected, buffer.ToString()); - Assert.Equal(expectedCursor, mock.Object.CursorPosition); - } - } +using System; +using System.Text; +using InteractiveReadLine.KeyBehaviors; +using Moq; +using Xunit; + +namespace InteractiveReadLine.Tests +{ + public class CommonBehaviorTests + { + [Theory] + [InlineData("test", 0, "est")] + [InlineData("test", 1, "tst")] + [InlineData("test", 2, "tet")] + [InlineData("test", 3, "tes")] + [InlineData("test", 4, "test")] + public void DeleteAtCursor_Works(string text, int cursor, string expected) + { + var buffer = new StringBuilder(text); + var mock = new Mock(); + mock.SetupGet(x => x.TextBuffer).Returns(buffer); + mock.SetupProperty(x => x.CursorPosition); + mock.Object.CursorPosition = cursor; + + CommonKeyBehaviors.Delete(mock.Object); + + Assert.Equal(cursor, mock.Object.CursorPosition); + Assert.Equal(expected, buffer.ToString()); + } + + + [Theory] + [InlineData("test", 0, "test", 0)] + [InlineData("test", 1, "est", 0)] + [InlineData("test", 2, "tst", 1)] + [InlineData("test", 3, "tet", 2)] + [InlineData("test", 4, "tes", 3)] + public void BackspaceAtCursor_Works(string text, int cursor, string expected, int expectedCursor) + { + var buffer = new StringBuilder(text); + var mock = new Mock(); + mock.SetupGet(x => x.TextBuffer).Returns(buffer); + mock.SetupProperty(x => x.CursorPosition); + mock.Object.CursorPosition = cursor; + + CommonKeyBehaviors.Backspace(mock.Object); + + Assert.Equal(expectedCursor, mock.Object.CursorPosition); + Assert.Equal(expected, buffer.ToString()); + } + + [Fact] + public void CursorMoveToEnd_Works() + { + var buffer = new StringBuilder("this is a test"); + var mock = new Mock(); + mock.SetupGet(x => x.TextBuffer).Returns(buffer); + mock.SetupProperty(x => x.CursorPosition); + mock.Object.CursorPosition = 4; + + CommonKeyBehaviors.MoveCursorToEnd(mock.Object); + + Assert.Equal(14, mock.Object.CursorPosition); + } + + [Fact] + public void CursorMoveToStart_Works() + { + var buffer = new StringBuilder("this is a test"); + var mock = new Mock(); + mock.SetupGet(x => x.TextBuffer).Returns(buffer); + mock.SetupProperty(x => x.CursorPosition); + mock.Object.CursorPosition = 14; + + CommonKeyBehaviors.MoveCursorToStart(mock.Object); + + Assert.Equal(0, mock.Object.CursorPosition); + } + + [Theory] + [InlineData(0, 0)] + [InlineData(4, 3)] + [InlineData(2, 1)] + public void MoveCursorLeft_Works(int cursor, int expected) + { + var buffer = new StringBuilder("test"); + var mock = new Mock(); + mock.SetupGet(x => x.TextBuffer).Returns(buffer); + mock.SetupProperty(x => x.CursorPosition); + mock.Object.CursorPosition = cursor; + + CommonKeyBehaviors.MoveCursorLeft(mock.Object); + + Assert.Equal(expected, mock.Object.CursorPosition); + } + + + [Theory] + [InlineData(0, 1)] + [InlineData(4, 4)] + [InlineData(2, 3)] + public void MoveCursorRight_Works(int cursor, int expected) + { + var buffer = new StringBuilder("test"); + var mock = new Mock(); + mock.SetupGet(x => x.TextBuffer).Returns(buffer); + mock.SetupProperty(x => x.CursorPosition); + mock.Object.CursorPosition = cursor; + + CommonKeyBehaviors.MoveCursorRight(mock.Object); + + Assert.Equal(expected, mock.Object.CursorPosition); + } + + [Fact] + public void ClearBuffer_Works() + { + var buffer = new StringBuilder("test"); + var mock = new Mock(); + mock.SetupGet(x => x.TextBuffer).Returns(buffer); + mock.SetupProperty(x => x.CursorPosition); + mock.Object.CursorPosition = 4; + + CommonKeyBehaviors.ClearAll(mock.Object); + + Assert.Equal("", buffer.ToString()); + Assert.Equal(0, mock.Object.CursorPosition); + } + + [Theory] + [InlineData('A', 0, "Atest")] + [InlineData('9', 2, "te9st")] + [InlineData('0', 4, "test0")] + [InlineData(' ', 0, " test")] + [InlineData(' ', 2, "te st")] + [InlineData(' ', 4, "test ")] + [InlineData('.', 0, ".test")] + [InlineData(';', 2, "te;st")] + [InlineData(',', 4, "test,")] + [InlineData('*', 0, "*test")] + [InlineData('%', 2, "te%st")] + [InlineData('$', 4, "test$")] + public void InsertCharacters_Works(char c, int cursor, string expected) + { + var buffer = new StringBuilder("test"); + var mock = new Mock(); + mock.SetupGet(x => x.TextBuffer).Returns(buffer); + mock.SetupProperty(x => x.CursorPosition); + mock.SetupGet(x => x.ReceivedKey).Returns(new ConsoleKeyInfo(c, ConsoleKey.Oem1, false, false, false)); + mock.Object.CursorPosition = cursor; + + CommonKeyBehaviors.InsertCharacter(mock.Object); + + Assert.Equal(expected, buffer.ToString()); + Assert.Equal(cursor + 1, mock.Object.CursorPosition); + } + + [Theory] + [InlineData(0, "")] + [InlineData(3, "tes")] + [InlineData(8, "test dat")] + [InlineData(9, "test data")] + public void CutToEnd_Works(int cursor, string expected) + { + // 0123456789 + var buffer = new StringBuilder("test data"); + var mock = new Mock(); + mock.SetupGet(x => x.TextBuffer).Returns(buffer); + mock.SetupProperty(x => x.CursorPosition); + mock.Object.CursorPosition = cursor; + + CommonKeyBehaviors.CutToEnd(mock.Object); + + Assert.Equal(expected, buffer.ToString()); + Assert.Equal(cursor, mock.Object.CursorPosition); + } + + [Theory] + [InlineData(0, "test data")] + [InlineData(3, "t data")] + [InlineData(8, "a")] + [InlineData(9, "")] + public void CutToStart_Works(int cursor, string expected) + { + // 0123456789 + var buffer = new StringBuilder("test data"); + var mock = new Mock(); + mock.SetupGet(x => x.TextBuffer).Returns(buffer); + mock.SetupProperty(x => x.CursorPosition); + mock.Object.CursorPosition = cursor; + + CommonKeyBehaviors.CutToStart(mock.Object); + + Assert.Equal(expected, buffer.ToString()); + Assert.Equal(0, mock.Object.CursorPosition); + } + + [Theory] + [InlineData(0, "test data here ", 0)] + [InlineData(2, "st data here ", 0)] + [InlineData(4, " data here ", 0)] + [InlineData(5, "data here ", 0)] + [InlineData(7, "test ta here ", 5)] + [InlineData(10, "test here ", 5)] + [InlineData(15, "test data ", 10)] + public void CutPreviousWord_WithNoTokens_Works(int cursor, string expected, int expectedCursor) + { + // 0123456789012345 + var buffer = new StringBuilder("test data here "); + var mock = new Mock(); + mock.SetupGet(x => x.TextBuffer).Returns(buffer); + mock.SetupProperty(x => x.CursorPosition); + mock.Object.CursorPosition = cursor; + + CommonKeyBehaviors.CutPreviousWord(mock.Object); + + Assert.Equal(expected, buffer.ToString()); + Assert.Equal(expectedCursor, mock.Object.CursorPosition); + } + } } \ No newline at end of file diff --git a/InteractiveReadLine.Tests/ConsoleReadLineTests.cs b/InteractiveReadLine.Tests/ConsoleReadLineTests.cs index cacff37..9efc17f 100644 --- a/InteractiveReadLine.Tests/ConsoleReadLineTests.cs +++ b/InteractiveReadLine.Tests/ConsoleReadLineTests.cs @@ -1,58 +1,86 @@ -using System; -using InteractiveReadLine.Formatting; -using InteractiveReadLine.Tests.Fakes; -using Xunit; - -namespace InteractiveReadLine.Tests -{ - public class ConsoleReadLineTests - { - [Fact] - public void ConsoleProvider_InitializesWithPrompt() - { - var fakeConsole = new TestConsole(5, 10); - var readLine = new ConsoleReadLine(fakeConsole); - - Assert.Equal("", fakeConsole.GetRow(0)); - } - - [Fact] - public void ConsoleProvider_ReceivesShortTyping_Correctly() - { - var keys = KeyBuilder.Create().Add("test!").Enter().Keys; - var fakeConsole = new TestConsole(5, 10, keys); - var result = new ConsoleReadLine(fakeConsole).ReadLine(); - - Assert.Equal("test!", fakeConsole.GetRow(0)); - } - - [Fact] - public void ConsoleProvider_ReceivesOverflowTyping_Correctly() - { - var keys = KeyBuilder.Create().Add("456789abcd").Enter().Keys; - var fakeConsole = new TestConsole(5, 10, keys); - var config = ReadLineConfig.Basic.SetFormatter(CommonFormatters.FixedPrompt("012>")); - var result = new ConsoleReadLine(fakeConsole).ReadLine(config); - - Assert.Equal("012>456789", fakeConsole.GetRow(0)); - Assert.Equal("abcd", fakeConsole.GetRow(1)); - } - - [Fact] - public void ConsoleProvider_ReceivesBufferHeightOverflow_Correctly() - { - var keys = KeyBuilder.Create() - .Add(new string('0', 6)) - .Add(new string('1', 10)) - .Add(new string('2', 10)) - .Enter().Keys; - var fakeConsole = new TestConsole(7, 10, keys) {CursorTop = 5}; - var config = ReadLineConfig.Basic.SetFormatter(CommonFormatters.FixedPrompt("012>")); - var result = new ConsoleReadLine(fakeConsole).ReadLine(config); - - Assert.Equal("012>000000", fakeConsole.GetRow(2)); - Assert.Equal("1111111111", fakeConsole.GetRow(3)); - Assert.Equal("2222222222", fakeConsole.GetRow(4)); - } - } -} \ No newline at end of file +using System; +using InteractiveReadLine.Abstractions; +using InteractiveReadLine.Formatting; +using InteractiveReadLine.Tests.Fakes; +using Xunit; + +namespace InteractiveReadLine.Tests +{ + public class ConsoleReadLineTests + { + [Fact] + public void ConsoleProvider_InitializesWithPrompt() + { + var fakeConsole = new TestConsole(5, 10); + var readLine = new ConsoleReadLine(fakeConsole); + + Assert.Equal("", fakeConsole.GetRow(0)); + } + + /// + /// The ReadLine extension method disposes its provider. A caller who also wraps the provider in a using + /// block therefore disposes it twice, but only the first call should move the cursor to a new row. + /// + [Fact] + public void Dispose_CalledTwice_FinishesOnlyOnce() + { + var fakeConsole = new TestConsole(10, 40); + var provider = new ConsoleReadLine(fakeConsole); + + provider.Dispose(); + var rowAfterFirstDispose = fakeConsole.CursorTop; + + provider.Dispose(); + + Assert.Equal(rowAfterFirstDispose, fakeConsole.CursorTop); + } + + [Fact] + public void SystemConsoleWrapper_IsPubliclyConstructable() + { + // IConsole is public, so callers must be able to access its default implementation to decorate it. + IConsole console = new SystemConsoleWrapper(); + + Assert.NotNull(console); + } + + [Fact] + public void ConsoleProvider_ReceivesShortTyping_Correctly() + { + var keys = KeyBuilder.Create().Add("test!").Enter().Keys; + var fakeConsole = new TestConsole(5, 10, keys); + var result = new ConsoleReadLine(fakeConsole).ReadLine(); + + Assert.Equal("test!", fakeConsole.GetRow(0)); + } + + [Fact] + public void ConsoleProvider_ReceivesOverflowTyping_Correctly() + { + var keys = KeyBuilder.Create().Add("456789abcd").Enter().Keys; + var fakeConsole = new TestConsole(5, 10, keys); + var config = ReadLineConfig.Basic.SetFormatter(CommonFormatters.FixedPrompt("012>")); + var result = new ConsoleReadLine(fakeConsole).ReadLine(config); + + Assert.Equal("012>456789", fakeConsole.GetRow(0)); + Assert.Equal("abcd", fakeConsole.GetRow(1)); + } + + [Fact] + public void ConsoleProvider_ReceivesBufferHeightOverflow_Correctly() + { + var keys = KeyBuilder.Create() + .Add(new string('0', 6)) + .Add(new string('1', 10)) + .Add(new string('2', 10)) + .Enter().Keys; + var fakeConsole = new TestConsole(7, 10, keys) {CursorTop = 5}; + var config = ReadLineConfig.Basic.SetFormatter(CommonFormatters.FixedPrompt("012>")); + var result = new ConsoleReadLine(fakeConsole).ReadLine(config); + + Assert.Equal("012>000000", fakeConsole.GetRow(2)); + Assert.Equal("1111111111", fakeConsole.GetRow(3)); + Assert.Equal("2222222222", fakeConsole.GetRow(4)); + } + } +} diff --git a/InteractiveReadLine.Tests/CutAndPasteTests.cs b/InteractiveReadLine.Tests/CutAndPasteTests.cs new file mode 100644 index 0000000..6421b49 --- /dev/null +++ b/InteractiveReadLine.Tests/CutAndPasteTests.cs @@ -0,0 +1,192 @@ +using System; +using InteractiveReadLine.KeyBehaviors; +using InteractiveReadLine.Tests.Fakes; +using Xunit; + +namespace InteractiveReadLine.Tests +{ + public class CutAndPasteTests + { + [Fact] + public void CutToEnd_ThenPaste_RestoresTheLine() + { + var keys = KeyBuilder.Create() + .Add("hello world") + .LeftArrow(6) + .Ctrl(ConsoleKey.K) + .Ctrl(ConsoleKey.Y) + .Enter().Keys; + + Assert.Equal("hello world", Read(keys)); + } + + [Fact] + public void CutToStart_ThenPaste_RestoresTheLine() + { + var keys = KeyBuilder.Create() + .Add("hello world") + .LeftArrow(5) + .Ctrl(ConsoleKey.U) + .Ctrl(ConsoleKey.Y) + .Enter().Keys; + + Assert.Equal("hello world", Read(keys)); + } + + [Fact] + public void CutPreviousWord_ThenPaste_RestoresTheLine() + { + var keys = KeyBuilder.Create() + .Add("alpha beta") + .Ctrl(ConsoleKey.W) + .Ctrl(ConsoleKey.Y) + .Enter().Keys; + + Assert.Equal("alpha beta", Read(keys)); + } + + /// + /// The cut buffer can move text to a different position instead of only restoring it. + /// + [Fact] + public void CutToEnd_ThenPasteElsewhere_MovesTheText() + { + var keys = KeyBuilder.Create() + .Add("hello world") + .LeftArrow(6) // cursor sits just after "hello" + .Ctrl(ConsoleKey.K) // cuts " world", leaving "hello" + .Ctrl(ConsoleKey.A) // move to the start of the line + .Ctrl(ConsoleKey.Y) // paste there + .Enter().Keys; + + Assert.Equal(" worldhello", Read(keys)); + } + + /// + /// Consecutive cuts accumulate in one buffer. The buffer preserves the text's order on the line, so one + /// paste restores the complete sequence. + /// + [Fact] + public void ConsecutiveWordCuts_AccumulateInTheOriginalOrder() + { + var keys = KeyBuilder.Create() + .Add("alpha beta gamma") + .Ctrl(ConsoleKey.W, 3) + .Ctrl(ConsoleKey.Y) + .Enter().Keys; + + Assert.Equal("alpha beta gamma", Read(keys)); + } + + [Fact] + public void ConsecutiveCutsToEnd_AccumulateInTheOriginalOrder() + { + // Two forward cuts from the same position take the line apart from left to right. + var keys = KeyBuilder.Create() + .Add("abcdef") + .LeftArrow(4) // cursor after "ab" + .Ctrl(ConsoleKey.K) // cuts "cdef" + .Ctrl(ConsoleKey.K) // cuts nothing, the run continues + .Ctrl(ConsoleKey.Y) + .Enter().Keys; + + Assert.Equal("abcdef", Read(keys)); + } + + /// + /// A key that does not perform a cut ends the run, so the next cut starts a fresh buffer. + /// + [Fact] + public void AKeyBetweenCuts_StartsANewBuffer() + { + var keys = KeyBuilder.Create() + .Add("alpha beta gamma") + .Ctrl(ConsoleKey.W) // cuts "gamma" + .Ctrl(ConsoleKey.E) // move to end of line, which is not a cut + .Ctrl(ConsoleKey.W) // cuts "beta ", starting the buffer over + .Ctrl(ConsoleKey.A) // move to the start + .Ctrl(ConsoleKey.Y) + .Enter().Keys; + + // Only the second cut is in the buffer. If the run had continued, "gamma" would appear too. + var result = Read(keys); + Assert.DoesNotContain("gamma", result); + Assert.StartsWith("beta", result); + } + + [Fact] + public void Paste_WithNothingCut_DoesNothing() + { + var keys = KeyBuilder.Create() + .Add("untouched") + .Ctrl(ConsoleKey.Y) + .Enter().Keys; + + Assert.Equal("untouched", Read(keys)); + } + + /// + /// Pasting does not consume the buffer, so the same text can be placed more than once. + /// + [Fact] + public void Paste_CanBeRepeated() + { + var keys = KeyBuilder.Create() + .Add("ab") + .Ctrl(ConsoleKey.U) // cuts "ab" + .Ctrl(ConsoleKey.Y) + .Ctrl(ConsoleKey.Y) + .Ctrl(ConsoleKey.Y) + .Enter().Keys; + + Assert.Equal("ababab", Read(keys)); + } + + [Fact] + public void Paste_InsertsAtTheCursorAndLeavesItAfterTheText() + { + var keys = KeyBuilder.Create() + .Add("XY") + .Ctrl(ConsoleKey.U) // cuts "XY", line is now empty + .Add("ab") + .LeftArrow() // cursor between a and b + .Ctrl(ConsoleKey.Y) // paste "XY" there + .Add("!") // typed at the cursor, which must sit after the pasted text + .Enter().Keys; + + Assert.Equal("aXY!b", Read(keys)); + } + + /// + /// The buffer belongs to one read line operation. A new operation starts with nothing to paste, + /// even when the same configuration object is reused. + /// + [Fact] + public void CutBuffer_DoesNotCarryOverToTheNextRead() + { + var config = ReadLineConfig.Basic.AddCtrlNavKeys(); + + var firstKeys = KeyBuilder.Create().Add("secret").Ctrl(ConsoleKey.U).Enter().Keys; + new ConsoleReadLine(new TestConsole(10, 80, firstKeys)).ReadLine(config); + + var secondKeys = KeyBuilder.Create().Add("fresh").Ctrl(ConsoleKey.Y).Enter().Keys; + var second = new ConsoleReadLine(new TestConsole(10, 80, secondKeys)).ReadLine(config); + + Assert.Equal("fresh", second); + } + + [Fact] + public void AddCtrlNavKeys_BindsPasteToCtrlY() + { + var config = ReadLineConfig.Empty.AddCtrlNavKeys(); + + Assert.True(config.KeyBehaviors.ContainsKey(new KeyId(ConsoleKey.Y, true, false, false))); + } + + private static string Read(ConsoleKeyInfo[] keys) + { + var config = ReadLineConfig.Basic.AddCtrlNavKeys(); + return new ConsoleReadLine(new TestConsole(10, 80, keys)).ReadLine(config); + } + } +} diff --git a/InteractiveReadLine.Tests/FakeConsoleValidationTests.cs b/InteractiveReadLine.Tests/FakeConsoleValidationTests.cs index 9db97c6..ff5844c 100644 --- a/InteractiveReadLine.Tests/FakeConsoleValidationTests.cs +++ b/InteractiveReadLine.Tests/FakeConsoleValidationTests.cs @@ -1,101 +1,101 @@ -using System; -using InteractiveReadLine.Tests.Fakes; -using Xunit; - -namespace InteractiveReadLine.Tests -{ - /// - /// These tests validate that the TestConsole fake works the way it's expected to - /// - public class FakeConsoleValidationTests - { - [Fact] - public void Buffer_StartsEmpty() - { - var height = 5; - var test = new TestConsole(height, 10); - - for (int i = 0; i < height; i++) - { - Assert.Equal(string.Empty, test.GetRow(i)); - } - } - - [Fact] - public void SimpleWriteOneLine_MatchesExpected() - { - var test = new TestConsole(5, 10); - test.Write("hello"); - - Assert.Equal("hello", test.GetRow(0)); - } - - [Fact] - public void WriteWithOverflow_MatchesExpected() - { - var test = new TestConsole(5, 10); - test.Write("0123456789abcdefg"); - - Assert.Equal("0123456789", test.GetRow(0)); - Assert.Equal("abcdefg", test.GetRow(1)); - } - - [Fact] - public void WriteLineWithOverflow_MatchesExpected() - { - var test = new TestConsole(5, 10); - test.WriteLine("0123456789abcdefg"); - test.Write("hello"); - - Assert.Equal("0123456789", test.GetRow(0)); - Assert.Equal("abcdefg", test.GetRow(1)); - Assert.Equal("hello", test.GetRow(2)); - } - - [Fact] - public void WriteManyLines_WithHeightOverflow_ShiftsRows() - { - var test = new TestConsole(5, 30); - test.WriteLine("this is the first row"); - test.WriteLine("And this is the second"); - test.WriteLine("here is the third"); - test.WriteLine("and the fourth"); - test.WriteLine("but this is the last row"); - - Assert.Equal("And this is the second", test.GetRow(0)); - Assert.Equal("here is the third", test.GetRow(1)); - Assert.Equal("and the fourth", test.GetRow(2)); - Assert.Equal("but this is the last row", test.GetRow(3)); - Assert.Equal(string.Empty, test.GetRow(4)); - } - - [Fact] - public void FakeKeyBuilder_BuildsFromText_Simple() - { - var keys = KeyBuilder.Create().Add("aA3 _").Keys; - - Assert.Equal(new ConsoleKeyInfo('a', ConsoleKey.A, false, false, false), keys[0]); - Assert.Equal(new ConsoleKeyInfo('A', ConsoleKey.A, true, false, false), keys[1]); - Assert.Equal(new ConsoleKeyInfo('3', ConsoleKey.D3, false, false, false), keys[2]); - Assert.Equal(new ConsoleKeyInfo(' ', ConsoleKey.Spacebar, false, false, false), keys[3]); - Assert.Equal(new ConsoleKeyInfo('_', ConsoleKey.Sleep, false, false, false), keys[4]); - } - - [Fact] - public void FakeKeyBuilder_BuildsFromText_WithSpecial() - { - var keys = KeyBuilder.Create() - .Add("aA") - .Add(ConsoleKey.W, false, false, true) - .Add(ConsoleKey.Enter, false, true, false) - .Keys; - - Assert.Equal(new ConsoleKeyInfo('a', ConsoleKey.A, false, false, false), keys[0]); - Assert.Equal(new ConsoleKeyInfo('A', ConsoleKey.A, true, false, false), keys[1]); - Assert.Equal(new ConsoleKeyInfo(char.MinValue, ConsoleKey.W, false, false, true), keys[2]); - Assert.Equal(new ConsoleKeyInfo(char.MinValue, ConsoleKey.Enter, false, true, false), keys[3]); - } - - - } -} +using System; +using InteractiveReadLine.Tests.Fakes; +using Xunit; + +namespace InteractiveReadLine.Tests +{ + /// + /// These tests validate that the TestConsole fake works the way it's expected to + /// + public class FakeConsoleValidationTests + { + [Fact] + public void Buffer_StartsEmpty() + { + var height = 5; + var test = new TestConsole(height, 10); + + for (int i = 0; i < height; i++) + { + Assert.Equal(string.Empty, test.GetRow(i)); + } + } + + [Fact] + public void SimpleWriteOneLine_MatchesExpected() + { + var test = new TestConsole(5, 10); + test.Write("hello"); + + Assert.Equal("hello", test.GetRow(0)); + } + + [Fact] + public void WriteWithOverflow_MatchesExpected() + { + var test = new TestConsole(5, 10); + test.Write("0123456789abcdefg"); + + Assert.Equal("0123456789", test.GetRow(0)); + Assert.Equal("abcdefg", test.GetRow(1)); + } + + [Fact] + public void WriteLineWithOverflow_MatchesExpected() + { + var test = new TestConsole(5, 10); + test.WriteLine("0123456789abcdefg"); + test.Write("hello"); + + Assert.Equal("0123456789", test.GetRow(0)); + Assert.Equal("abcdefg", test.GetRow(1)); + Assert.Equal("hello", test.GetRow(2)); + } + + [Fact] + public void WriteManyLines_WithHeightOverflow_ShiftsRows() + { + var test = new TestConsole(5, 30); + test.WriteLine("this is the first row"); + test.WriteLine("And this is the second"); + test.WriteLine("here is the third"); + test.WriteLine("and the fourth"); + test.WriteLine("but this is the last row"); + + Assert.Equal("And this is the second", test.GetRow(0)); + Assert.Equal("here is the third", test.GetRow(1)); + Assert.Equal("and the fourth", test.GetRow(2)); + Assert.Equal("but this is the last row", test.GetRow(3)); + Assert.Equal(string.Empty, test.GetRow(4)); + } + + [Fact] + public void FakeKeyBuilder_BuildsFromText_Simple() + { + var keys = KeyBuilder.Create().Add("aA3 _").Keys; + + Assert.Equal(new ConsoleKeyInfo('a', ConsoleKey.A, false, false, false), keys[0]); + Assert.Equal(new ConsoleKeyInfo('A', ConsoleKey.A, true, false, false), keys[1]); + Assert.Equal(new ConsoleKeyInfo('3', ConsoleKey.D3, false, false, false), keys[2]); + Assert.Equal(new ConsoleKeyInfo(' ', ConsoleKey.Spacebar, false, false, false), keys[3]); + Assert.Equal(new ConsoleKeyInfo('_', ConsoleKey.Sleep, false, false, false), keys[4]); + } + + [Fact] + public void FakeKeyBuilder_BuildsFromText_WithSpecial() + { + var keys = KeyBuilder.Create() + .Add("aA") + .Add(ConsoleKey.W, false, false, true) + .Add(ConsoleKey.Enter, false, true, false) + .Keys; + + Assert.Equal(new ConsoleKeyInfo('a', ConsoleKey.A, false, false, false), keys[0]); + Assert.Equal(new ConsoleKeyInfo('A', ConsoleKey.A, true, false, false), keys[1]); + Assert.Equal(new ConsoleKeyInfo(char.MinValue, ConsoleKey.W, false, false, true), keys[2]); + Assert.Equal(new ConsoleKeyInfo(char.MinValue, ConsoleKey.Enter, false, true, false), keys[3]); + } + + + } +} diff --git a/InteractiveReadLine.Tests/Fakes/KeyBuilder.cs b/InteractiveReadLine.Tests/Fakes/KeyBuilder.cs index 1e328b0..49f52c5 100644 --- a/InteractiveReadLine.Tests/Fakes/KeyBuilder.cs +++ b/InteractiveReadLine.Tests/Fakes/KeyBuilder.cs @@ -1,85 +1,122 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Text; - -namespace InteractiveReadLine.Tests.Fakes -{ - public class KeyBuilder - { - private readonly List _keys; - - private KeyBuilder() - { - _keys = new List(); - } - - public KeyBuilder Add(string text) - { - foreach (var c in text) - { - var cstr = c.ToString(); - var code = (int) cstr.ToUpper()[0]; - ConsoleKey key = ConsoleKey.Oem1; // Something benign - try - { - key = (ConsoleKey) code; - } - catch - { - ; - } - bool shift = cstr != cstr.ToLower(); - var keyInfo = new ConsoleKeyInfo(c, key, shift, false, false); - _keys.Add(keyInfo); - } - - return this; - } - - public KeyBuilder Add(ConsoleKey key, bool shift, bool alt, bool control, int count=1) - { - for (int i = 0; i < count; i++) - { - _keys.Add(new ConsoleKeyInfo(char.MinValue, key, shift, alt, control)); - } - - return this; - } - - public KeyBuilder Enter(int count=1) - { - return this.Add(ConsoleKey.Enter, false, false, false, count); - } - - public KeyBuilder LeftArrow(int count=1) - { - return this.Add(ConsoleKey.LeftArrow, false, false, false, count); - } - - public KeyBuilder RightArrow(int count=1) - { - return this.Add(ConsoleKey.RightArrow, false, false, false, count); - } - - public KeyBuilder DownArrow(int count=1) - { - return this.Add(ConsoleKey.DownArrow, false, false, false, count); - } - - public KeyBuilder UpArrow(int count=1) - { - return this.Add(ConsoleKey.UpArrow, false, false, false, count); - } - - public KeyBuilder Escape(int count=1) - { - return this.Add(ConsoleKey.Escape, false, false, false, count); - } - - - public ConsoleKeyInfo[] Keys => _keys.ToArray(); - - public static KeyBuilder Create() => new KeyBuilder(); - } -} \ No newline at end of file +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Text; + +namespace InteractiveReadLine.Tests.Fakes +{ + public class KeyBuilder + { + private readonly List _keys; + + private KeyBuilder() + { + _keys = new List(); + } + + public KeyBuilder Add(string text) + { + foreach (var c in text) + { + var cstr = c.ToString(); + var code = (int) cstr.ToUpper()[0]; + ConsoleKey key = ConsoleKey.Oem1; // Something benign + try + { + key = (ConsoleKey) code; + } + catch + { + ; + } + bool shift = cstr != cstr.ToLower(); + var keyInfo = new ConsoleKeyInfo(c, key, shift, false, false); + _keys.Add(keyInfo); + } + + return this; + } + + public KeyBuilder Add(ConsoleKey key, bool shift, bool alt, bool control, int count=1) + { + for (int i = 0; i < count; i++) + { + _keys.Add(new ConsoleKeyInfo(char.MinValue, key, shift, alt, control)); + } + + return this; + } + + public KeyBuilder Enter(int count=1) + { + return this.Add(ConsoleKey.Enter, false, false, false, count); + } + + public KeyBuilder LeftArrow(int count=1) + { + return this.Add(ConsoleKey.LeftArrow, false, false, false, count); + } + + public KeyBuilder RightArrow(int count=1) + { + return this.Add(ConsoleKey.RightArrow, false, false, false, count); + } + + public KeyBuilder DownArrow(int count=1) + { + return this.Add(ConsoleKey.DownArrow, false, false, false, count); + } + + public KeyBuilder UpArrow(int count=1) + { + return this.Add(ConsoleKey.UpArrow, false, false, false, count); + } + + public KeyBuilder Escape(int count=1) + { + return this.Add(ConsoleKey.Escape, false, false, false, count); + } + + /// + /// Adds a Ctrl+C keypress as the console delivers it when TreatControlCAsInput is set. The keypress + /// carries the end-of-text control character instead of a 'c'. + /// + public KeyBuilder CtrlC(int count=1) + { + return this.AddControlChar(ConsoleKey.C, '\u0003', count); + } + + /// + /// Adds a Ctrl+D keypress, which carries the end-of-transmission control character. + /// + public KeyBuilder CtrlD(int count=1) + { + return this.AddControlChar(ConsoleKey.D, '\u0004', count); + } + + /// + /// Adds a Ctrl+letter keypress as the console delivers it. The keypress carries the matching control + /// character instead of the letter. Use this method only with letter keys A through Z. + /// + public KeyBuilder Ctrl(ConsoleKey key, int count=1) + { + var character = (char) (key - ConsoleKey.A + 1); + return this.AddControlChar(key, character, count); + } + + private KeyBuilder AddControlChar(ConsoleKey key, char character, int count) + { + for (int i = 0; i < count; i++) + { + _keys.Add(new ConsoleKeyInfo(character, key, false, false, true)); + } + + return this; + } + + + public ConsoleKeyInfo[] Keys => _keys.ToArray(); + + public static KeyBuilder Create() => new KeyBuilder(); + } +} diff --git a/InteractiveReadLine.Tests/Fakes/TestConsole.cs b/InteractiveReadLine.Tests/Fakes/TestConsole.cs index 12c6f0d..78633d4 100644 --- a/InteractiveReadLine.Tests/Fakes/TestConsole.cs +++ b/InteractiveReadLine.Tests/Fakes/TestConsole.cs @@ -1,149 +1,177 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using InteractiveReadLine.Abstractions; -using InteractiveReadLine.Formatting; - -namespace InteractiveReadLine.Tests.Fakes -{ - /// - /// Class to simulate a System.Console text buffer - /// - public class TestConsole : IConsole - { - private readonly char[,] _buffer; - private readonly int _height; - private readonly int _width; - private readonly Queue _keys; - - public TestConsole(int height, int width, IEnumerable keys) - { - _height = height; - _width = width; - _buffer = new char[_height, _width]; - - for (int i = 0; i < _height; i++) - { - for (int j = 0; j < _width; j++) - { - _buffer[i, j] = char.MinValue; - } - } - - _keys = new Queue(keys); - } - - public TestConsole(int height, int width) - : this(height, width, Enumerable.Empty()) - { - } - - public int CursorLeft { get; set; } - - public int CursorTop { get; set; } - - public int BufferHeight => _height; - - public int BufferWidth => _width; - public void Write(FormattedText text) - { - this.Write(text.Text); - } - - public void WriteLine(FormattedText text) - { - this.WriteLine(text.Text); - } - - public void Write(FormattedChar c) - { - this.WriteChar(c.Char); - } - - public void Write(string text) - { - foreach (var c in text) - this.WriteChar(c); - } - - public void WriteLine(string text) - { - this.Write(text); - this.WriteChar('\n'); - } - - public void Write(char c) - { - this.WriteChar(c); - } - - public ConsoleKeyInfo ReadKey() - { - return _keys.Dequeue(); - } - - public string GetRow(int row) - { - var rowText = new StringBuilder(); - for (int j = 0; j < _width; j++) - { - rowText.Append(_buffer[row, j]); - } - - return rowText.ToString().TrimEnd(char.MinValue); - } - - public string BufferToString() - { - var output = new List(); - for (int i = 0; i < _height; i++) - { - output.Add(this.GetRow(i)); - } - - return string.Join("\n", output); - } - - /// - /// Writes the character at the current cursor position, then advances the cursor forward. If the cursor - /// advances beyond the end of the buffer width, or gets a carriage return, it moves down to the next line. - /// - /// - private void WriteChar(char c) - { - if (c != '\n') - _buffer[CursorTop, CursorLeft] = c; - - CursorLeft++; - if (CursorLeft == _width || c == '\n') - { - // Move down to the next line - CursorLeft = 0; - CursorTop++; - - if (CursorTop == _height) - { - // Copy the entire buffer up one so that the last row is empty - for (int i = 0; i < _height - 1; i++) - { - for (int j = 0; j < _width; j++) - { - _buffer[i, j] = _buffer[i + 1, j]; - } - } - - for (int j = 0; j < _width; j++) - { - _buffer[_height - 1, j] = char.MinValue; - } - - // bring the top cursor back - CursorTop--; - } - } - } - - - } -} \ No newline at end of file +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using InteractiveReadLine.Abstractions; +using InteractiveReadLine.Formatting; + +namespace InteractiveReadLine.Tests.Fakes +{ + /// + /// Class to simulate a System.Console text buffer + /// + public class TestConsole : IConsole + { + private readonly char[,] _buffer; + private readonly int _height; + private readonly int _width; + private readonly Queue _keys; + + public TestConsole(int height, int width, IEnumerable keys) + { + _height = height; + _width = width; + _buffer = new char[_height, _width]; + + for (int i = 0; i < _height; i++) + { + for (int j = 0; j < _width; j++) + { + _buffer[i, j] = char.MinValue; + } + } + + _keys = new Queue(keys); + } + + public TestConsole(int height, int width) + : this(height, width, Enumerable.Empty()) + { + } + + public int CursorLeft { get; set; } + + public int CursorTop { get; set; } + + public int BufferHeight => _height; + + public int BufferWidth => _width; + + public bool TreatControlCAsInput { get; set; } + + /// + /// Gets or sets whether this console reports that its input is redirected. A ConsoleReadLine provider + /// cannot operate when this value is true. + /// + public bool InputIsRedirected { get; set; } + + /// + /// Gets or sets the number of times KeyAvailable reports false before it starts reporting whether a key + /// is queued. Tests use this property to exercise the polling path of a cancelable read. + /// + public int PollsBeforeKeyAvailable { get; set; } + + public bool KeyAvailable + { + get + { + if (this.PollsBeforeKeyAvailable > 0) + { + this.PollsBeforeKeyAvailable--; + return false; + } + + return _keys.Count > 0; + } + } + public void Write(FormattedText text) + { + this.Write(text.Text); + } + + public void WriteLine(FormattedText text) + { + this.WriteLine(text.Text); + } + + public void Write(FormattedChar c) + { + this.WriteChar(c.Char); + } + + public void Write(string text) + { + foreach (var c in text) + this.WriteChar(c); + } + + public void WriteLine(string text) + { + this.Write(text); + this.WriteChar('\n'); + } + + public void Write(char c) + { + this.WriteChar(c); + } + + public ConsoleKeyInfo ReadKey() + { + return _keys.Dequeue(); + } + + public string GetRow(int row) + { + var rowText = new StringBuilder(); + for (int j = 0; j < _width; j++) + { + rowText.Append(_buffer[row, j]); + } + + return rowText.ToString().TrimEnd(char.MinValue); + } + + public string BufferToString() + { + var output = new List(); + for (int i = 0; i < _height; i++) + { + output.Add(this.GetRow(i)); + } + + return string.Join("\n", output); + } + + /// + /// Writes the character at the current cursor position, then advances the cursor forward. If the cursor + /// advances beyond the end of the buffer width, or gets a carriage return, it moves down to the next line. + /// + /// + private void WriteChar(char c) + { + if (c != '\n') + _buffer[CursorTop, CursorLeft] = c; + + CursorLeft++; + if (CursorLeft == _width || c == '\n') + { + // Move down to the next line + CursorLeft = 0; + CursorTop++; + + if (CursorTop == _height) + { + // Copy the entire buffer up one so that the last row is empty + for (int i = 0; i < _height - 1; i++) + { + for (int j = 0; j < _width; j++) + { + _buffer[i, j] = _buffer[i + 1, j]; + } + } + + for (int j = 0; j < _width; j++) + { + _buffer[_height - 1, j] = char.MinValue; + } + + // bring the top cursor back + CursorTop--; + } + } + } + + + } +} diff --git a/InteractiveReadLine.Tests/FormattedTextTests.cs b/InteractiveReadLine.Tests/FormattedTextTests.cs index 59c74b8..e63b883 100644 --- a/InteractiveReadLine.Tests/FormattedTextTests.cs +++ b/InteractiveReadLine.Tests/FormattedTextTests.cs @@ -1,195 +1,266 @@ -using System; -using System.Linq; -using InteractiveReadLine.Formatting; -using Xunit; - -namespace InteractiveReadLine.Tests -{ - public class FormattedTextTests - { - [Fact] - public void FormattedTextConstructor_InstantiatesText_Correctly() - { - string t = "this is some text"; - var test = new FormattedText(t); - - Assert.Equal(t, test.Text); - } - - [Fact] - public void FormattedTextConstructor_InstantiatesWithNullColors() - { - string t = "this is some text"; - var test = new FormattedText(t); - - Assert.All(test.Foreground, color => Assert.Null(color)); - Assert.All(test.Background, color => Assert.Null(color)); - } - - [Fact] - public void FormattedText_SetForegroundColors_Works() - { - string t = "this is some text"; - var test = new FormattedText(t); - test.SetForeground(ConsoleColor.Blue); - - Assert.All(test.Foreground, color => Assert.Equal(ConsoleColor.Blue, color)); - } - - [Fact] - public void FormattedText_SetBackgroundColors_Works() - { - string t = "this is some text"; - var test = new FormattedText(t); - test.SetBackground(ConsoleColor.Blue); - - Assert.All(test.Background, color => Assert.Equal(ConsoleColor.Blue, color)); - } - - [Fact] - public void FormattedText_ImplictToString_Works() - { - string t = "this is some text"; - var converter = new Func(s => s); - var test = converter(t); - - Assert.Equal(typeof(FormattedText), test.GetType()); - Assert.Equal(t, test.Text); - Assert.All(test.Foreground, color => Assert.Null(color)); - Assert.All(test.Background, color => Assert.Null(color)); - } - - [Fact] - public void FormattedText_Concat_HandlesColorsCorrectly() - { - var t1 = new FormattedText("first"); - var t2 = new FormattedText("second"); - t1.SetForeground(ConsoleColor.Red); - t1.SetBackground(ConsoleColor.Black); - t2.SetForeground(ConsoleColor.Blue); - t2.SetBackground(ConsoleColor.White); - - var test = t1 + t2; - - for (int i = 0; i < 5; i++) - { - Assert.Equal(ConsoleColor.Red, test.Foreground[i]); - Assert.Equal(ConsoleColor.Black, test.Background[i]); - } - - for (int i = 5; i < 10; i++) - { - Assert.Equal(ConsoleColor.Blue, test.Foreground[i]); - Assert.Equal(ConsoleColor.White, test.Background[i]); - } - } - - [Fact] - public void Equality_FalseOnNullOther() - { - var t = new FormattedText("test"); - - Assert.False(t.Equals(null)); - } - - [Fact] - public void Equality_FalseOnMismatchedText() - { - var t0 = new FormattedText("test"); - var t1 = new FormattedText("t"); - - Assert.NotEqual(t0, t1); - } - - [Fact] - public void Equality_FalseOnMismatchedForeground() - { - var t0 = new FormattedText("te", ConsoleColor.Black, ConsoleColor.White) + - new FormattedText("s", null, ConsoleColor.White) + - new FormattedText("t", ConsoleColor.Black, ConsoleColor.White); - var t1 = new FormattedText("test", ConsoleColor.Black, ConsoleColor.White); - - Assert.NotEqual(t0, t1); - } - - [Fact] - public void Equality_FalseOnMismatchedBackground() - { - var t0 = new FormattedText("te", ConsoleColor.Black, ConsoleColor.White) + - new FormattedText("s", ConsoleColor.Black, null) + - new FormattedText("t", ConsoleColor.Black, ConsoleColor.White); - var t1 = new FormattedText("test", ConsoleColor.Black, ConsoleColor.White); - - Assert.NotEqual(t0, t1); - } - - [Fact] - public void Equality_TrueOnMatch() - { - var t0 = new FormattedText("te", ConsoleColor.Black, ConsoleColor.White) + - new FormattedText("s", ConsoleColor.Black, ConsoleColor.White) + - new FormattedText("t", ConsoleColor.Black, ConsoleColor.White); - var t1 = new FormattedText("test", ConsoleColor.Black, ConsoleColor.White); - - Assert.Equal(t0, t1); - } - - [Fact] - public void SplitByFormatting_HandlesEmptyString() - { - var t = new FormattedText(string.Empty); - - var split = t.SplitByFormatting(); - - Assert.Empty(split); - } - - [Fact] - public void SplitByFormatting_HandlesSingleCharacterString() - { - var t = new FormattedText("t"); - - var split = t.SplitByFormatting(); - - Assert.Single(split); - Assert.Equal("t", split.First().Text); - } - - [Theory] - [InlineData(null, null)] - [InlineData(ConsoleColor.Red, null)] - [InlineData(null, ConsoleColor.Black)] - [InlineData(ConsoleColor.Blue, ConsoleColor.Black)] - public void SplitByFormatting_HandlesSingleGroup(ConsoleColor? fore, ConsoleColor? back) - { - var t = new FormattedText("this is some test text", fore, back); - - var split = t.SplitByFormatting(); - - Assert.Single(split); - Assert.Equal(fore, split.First()[0].Foreground); - Assert.Equal(back, split.First()[0].Background); - Assert.Equal(t.Text, split.First().Text); - } - - [Fact] - public void SplitByFormatting_SplitsCorrectly() - { - var t0 = new FormattedText("this ", ConsoleColor.Black, ConsoleColor.White); - var t1 = new FormattedText("is "); - var t2 = new FormattedText("some ", ConsoleColor.Black, ConsoleColor.White); - var t3 = new FormattedText("test ", ConsoleColor.Red, ConsoleColor.White); - var t4 = new FormattedText("text", ConsoleColor.Red, null); - var t = t0 + t1 + t2 + t3 + t4; - - var split = t.SplitByFormatting(); - - Assert.Equal(5, split.Length); - Assert.Equal(t0, split[0]); - Assert.Equal(t1, split[1]); - Assert.Equal(t2, split[2]); - Assert.Equal(t3, split[3]); - Assert.Equal(t4, split[4]); - } - } -} \ No newline at end of file +using System; +using System.Collections.Generic; +using System.Linq; +using InteractiveReadLine.Formatting; +using Xunit; + +namespace InteractiveReadLine.Tests +{ + public class FormattedTextTests + { + [Fact] + public void FormattedTextConstructor_InstantiatesText_Correctly() + { + string t = "this is some text"; + var test = new FormattedText(t); + + Assert.Equal(t, test.Text); + } + + [Fact] + public void FormattedTextConstructor_InstantiatesWithNullColors() + { + string t = "this is some text"; + var test = new FormattedText(t); + + Assert.All(test.Foreground, color => Assert.Null(color)); + Assert.All(test.Background, color => Assert.Null(color)); + } + + [Fact] + public void FormattedText_SetForegroundColors_Works() + { + string t = "this is some text"; + var test = new FormattedText(t); + test.SetForeground(ConsoleColor.Blue); + + Assert.All(test.Foreground, color => Assert.Equal(ConsoleColor.Blue, color)); + } + + [Fact] + public void FormattedText_SetBackgroundColors_Works() + { + string t = "this is some text"; + var test = new FormattedText(t); + test.SetBackground(ConsoleColor.Blue); + + Assert.All(test.Background, color => Assert.Equal(ConsoleColor.Blue, color)); + } + + [Fact] + public void FormattedText_ImplictToString_Works() + { + string t = "this is some text"; + var converter = new Func(s => s); + var test = converter(t); + + Assert.Equal(typeof(FormattedText), test.GetType()); + Assert.Equal(t, test.Text); + Assert.All(test.Foreground, color => Assert.Null(color)); + Assert.All(test.Background, color => Assert.Null(color)); + } + + [Fact] + public void FormattedText_Concat_HandlesColorsCorrectly() + { + var t1 = new FormattedText("first"); + var t2 = new FormattedText("second"); + t1.SetForeground(ConsoleColor.Red); + t1.SetBackground(ConsoleColor.Black); + t2.SetForeground(ConsoleColor.Blue); + t2.SetBackground(ConsoleColor.White); + + var test = t1 + t2; + + for (int i = 0; i < 5; i++) + { + Assert.Equal(ConsoleColor.Red, test.Foreground[i]); + Assert.Equal(ConsoleColor.Black, test.Background[i]); + } + + for (int i = 5; i < 10; i++) + { + Assert.Equal(ConsoleColor.Blue, test.Foreground[i]); + Assert.Equal(ConsoleColor.White, test.Background[i]); + } + } + + [Fact] + public void Equality_FalseOnNullOther() + { + var t = new FormattedText("test"); + + Assert.False(t.Equals(null)); + } + + [Fact] + public void Constructor_WithNullText_Throws() + { + Assert.Throws(() => new FormattedText(null)); + } + + [Fact] + public void ObjectEquality_MatchesTypedEquality() + { + object t0 = new FormattedText("test", ConsoleColor.Red, ConsoleColor.Black); + object t1 = new FormattedText("test", ConsoleColor.Red, ConsoleColor.Black); + + Assert.True(t0.Equals(t1)); + } + + [Fact] + public void ObjectEquality_FalseOnDifferentColors() + { + object t0 = new FormattedText("test", ConsoleColor.Red, ConsoleColor.Black); + object t1 = new FormattedText("test", ConsoleColor.Blue, ConsoleColor.Black); + + Assert.False(t0.Equals(t1)); + } + + [Fact] + public void ObjectEquality_FalseOnUnrelatedType() + { + object t = new FormattedText("test"); + + Assert.False(t.Equals("test")); + } + + [Fact] + public void HashCode_MatchesForEqualInstances() + { + var t0 = new FormattedText("test", ConsoleColor.Red, ConsoleColor.Black); + var t1 = new FormattedText("test", ConsoleColor.Red, ConsoleColor.Black); + + Assert.Equal(t0, t1); + Assert.Equal(t0.GetHashCode(), t1.GetHashCode()); + } + + /// + /// The color arrays are mutable and publicly accessible, so the hash code deliberately ignores them. + /// It therefore remains stable while the instance is in a hash-based collection. + /// + [Fact] + public void HashCode_IsUnaffectedByColorChanges() + { + var text = new FormattedText("test", ConsoleColor.Red, ConsoleColor.Black); + var before = text.GetHashCode(); + + text.SetForeground(ConsoleColor.Green); + + Assert.Equal(before, text.GetHashCode()); + } + + [Fact] + public void CanBeUsedInAHashSet() + { + var set = new HashSet + { + new FormattedText("test", ConsoleColor.Red, ConsoleColor.Black), + new FormattedText("test", ConsoleColor.Red, ConsoleColor.Black) + }; + + Assert.Single(set); + Assert.Contains(new FormattedText("test", ConsoleColor.Red, ConsoleColor.Black), set); + } + + [Fact] + public void Equality_FalseOnMismatchedText() + { + var t0 = new FormattedText("test"); + var t1 = new FormattedText("t"); + + Assert.NotEqual(t0, t1); + } + + [Fact] + public void Equality_FalseOnMismatchedForeground() + { + var t0 = new FormattedText("te", ConsoleColor.Black, ConsoleColor.White) + + new FormattedText("s", null, ConsoleColor.White) + + new FormattedText("t", ConsoleColor.Black, ConsoleColor.White); + var t1 = new FormattedText("test", ConsoleColor.Black, ConsoleColor.White); + + Assert.NotEqual(t0, t1); + } + + [Fact] + public void Equality_FalseOnMismatchedBackground() + { + var t0 = new FormattedText("te", ConsoleColor.Black, ConsoleColor.White) + + new FormattedText("s", ConsoleColor.Black, null) + + new FormattedText("t", ConsoleColor.Black, ConsoleColor.White); + var t1 = new FormattedText("test", ConsoleColor.Black, ConsoleColor.White); + + Assert.NotEqual(t0, t1); + } + + [Fact] + public void Equality_TrueOnMatch() + { + var t0 = new FormattedText("te", ConsoleColor.Black, ConsoleColor.White) + + new FormattedText("s", ConsoleColor.Black, ConsoleColor.White) + + new FormattedText("t", ConsoleColor.Black, ConsoleColor.White); + var t1 = new FormattedText("test", ConsoleColor.Black, ConsoleColor.White); + + Assert.Equal(t0, t1); + } + + [Fact] + public void SplitByFormatting_HandlesEmptyString() + { + var t = new FormattedText(string.Empty); + + var split = t.SplitByFormatting(); + + Assert.Empty(split); + } + + [Fact] + public void SplitByFormatting_HandlesSingleCharacterString() + { + var t = new FormattedText("t"); + + var split = t.SplitByFormatting(); + + Assert.Single(split); + Assert.Equal("t", split.First().Text); + } + + [Theory] + [InlineData(null, null)] + [InlineData(ConsoleColor.Red, null)] + [InlineData(null, ConsoleColor.Black)] + [InlineData(ConsoleColor.Blue, ConsoleColor.Black)] + public void SplitByFormatting_HandlesSingleGroup(ConsoleColor? fore, ConsoleColor? back) + { + var t = new FormattedText("this is some test text", fore, back); + + var split = t.SplitByFormatting(); + + Assert.Single(split); + Assert.Equal(fore, split.First()[0].Foreground); + Assert.Equal(back, split.First()[0].Background); + Assert.Equal(t.Text, split.First().Text); + } + + [Fact] + public void SplitByFormatting_SplitsCorrectly() + { + var t0 = new FormattedText("this ", ConsoleColor.Black, ConsoleColor.White); + var t1 = new FormattedText("is "); + var t2 = new FormattedText("some ", ConsoleColor.Black, ConsoleColor.White); + var t3 = new FormattedText("test ", ConsoleColor.Red, ConsoleColor.White); + var t4 = new FormattedText("text", ConsoleColor.Red, null); + var t = t0 + t1 + t2 + t3 + t4; + + var split = t.SplitByFormatting(); + + Assert.Equal(5, split.Length); + Assert.Equal(t0, split[0]); + Assert.Equal(t1, split[1]); + Assert.Equal(t2, split[2]); + Assert.Equal(t3, split[3]); + Assert.Equal(t4, split[4]); + } + } +} diff --git a/InteractiveReadLine.Tests/HistoryTests.cs b/InteractiveReadLine.Tests/HistoryTests.cs index 747ec3b..ee60e1b 100644 --- a/InteractiveReadLine.Tests/HistoryTests.cs +++ b/InteractiveReadLine.Tests/HistoryTests.cs @@ -1,190 +1,331 @@ -using System; -using System.Collections.Generic; -using InteractiveReadLine.KeyBehaviors; -using InteractiveReadLine.Tests.Fakes; -using Xunit; - -namespace InteractiveReadLine.Tests -{ - public class HistoryTests - { - [Fact] - public void NullHistory_DoesntCrash_OnNext() - { - var keys = KeyBuilder.Create().DownArrow().Enter().Keys; - var result = Fixture(keys, null).ReadLine(); - } - - [Fact] - public void NullHistory_DoesntCrash_OnPrevious() - { - var keys = KeyBuilder.Create().UpArrow().Enter().Keys; - var result = Fixture(keys, null).ReadLine(); - } - - [Fact] - public void EmptyHistory_DoesntCrash_OnNext() - { - var keys = KeyBuilder.Create().DownArrow().Enter().Keys; - var result = Fixture(keys, new List()).ReadLine(); - } - - [Fact] - public void EmptyHistory_DoesntCrash_OnPrevious() - { - var keys = KeyBuilder.Create().UpArrow().Enter().Keys; - var result = Fixture(keys, new List()).ReadLine(); - } - - [Fact] - public void NonUpdatingHistory_DoesntUpdate() - { - var items = new string[] {"item one", "item two", "item three"}; - var history = new List(items); - var keys = KeyBuilder.Create() - .Add("item four") - .Enter().Keys; - var result = this.Fixture(keys, history, false).ReadLine(); - - Assert.Equal(3, history.Count); - foreach (var item in items) - { - Assert.Contains(history, x => x.Contains(item)); - } - } - - [Fact] - public void UpdatingHistory_Updates() - { - var items = new string[] {"item one", "item two", "item three"}; - var history = new List(items); - var keys = KeyBuilder.Create() - .Add("item four") - .Enter().Keys; - var result = this.Fixture(keys, history, true).ReadLine(); - - Assert.Equal(4, history.Count); - Assert.Contains(history, x => x.Contains("item four")); - foreach (var item in items) - { - Assert.Contains(history, x => x.Contains(item)); - } - } - - [Theory] - [InlineData(1, "hist3")] - [InlineData(2, "histo2")] - [InlineData(3, "histor1")] - [InlineData(4, "history0")] - public void MovesPrevious_Correctly(int count, string expected) - { - var keys = KeyBuilder.Create().UpArrow(count).Enter().Keys; - var handler = FixtureWithHistory(keys); - var result = handler.ReadLine(); - - Assert.Equal(expected, handler.LineState.Text); - Assert.Equal(expected.Length, handler.LineState.Cursor); - } - - [Fact] - public void MovesPrevious_AtLimit_Correctly() - { - var keys = KeyBuilder.Create().UpArrow(7).Enter().Keys; - var handler = FixtureWithHistory(keys); - var result = handler.ReadLine(); - - Assert.Equal("history0", handler.LineState.Text); - } - - [Theory] - [InlineData(3, "hist3")] - [InlineData(2, "histo2")] - [InlineData(1, "histor1")] - public void MovesNext_Correctly(int count, string expected) - { - var keys = KeyBuilder.Create() - .Add("this is a test") // 'Type' the text into the readline buffer - .LeftArrow(3) // move the cursor back three positions - .UpArrow(7) // move all the way to the first history entry - .DownArrow(count) // Then forward in the history - .Enter().Keys; - var handler = FixtureWithHistory(keys); - var result = handler.ReadLine(); - - Assert.Equal(expected, handler.LineState.Text); - Assert.Equal(expected.Length, handler.LineState.Cursor); - } - - - [Theory] - [InlineData(1)] - [InlineData(2)] - [InlineData(3)] - [InlineData(7)] - public void MovesBackAndForward_Correctly_IncludingLimit(int steps) - { - var keys = KeyBuilder.Create() - .Add("this is a test") // 'Type' the text into the readline buffer - .LeftArrow(3) // move the cursor back three positions - .UpArrow(steps) // move back in the history a set number of steps - .DownArrow(steps) // then forward again the same number of steps - .Enter().Keys; - var handler = FixtureWithHistory(keys); - var result = handler.ReadLine(); - - Assert.Equal("this is a test", handler.LineState.Text); - Assert.Equal(11, handler.LineState.Cursor); - } - - [Theory] - [InlineData(1)] - [InlineData(2)] - [InlineData(3)] - [InlineData(7)] - public void MovesBackAndForward_Correctly_WithSecondEdit(int steps) - { - var keys = KeyBuilder.Create() - .Add("this is a test") // 'Type' the text into the readline buffer - .LeftArrow(4) // move the cursor back four positions - .UpArrow(steps) // move all the way to the first history entry - .DownArrow(steps) // then all the way back to the entered buffer - .Add("modified ") - .UpArrow(steps) // move all the way to the first history entry - .DownArrow(steps) // then all the way back to the entered buffer - .Enter().Keys; - var handler = FixtureWithHistory(keys); - var result = handler.ReadLine(); - - Assert.Equal("this is a modified test", handler.LineState.Text); - Assert.Equal(19, handler.LineState.Cursor); - } - - private ReadLineHandler FixtureWithHistory(ConsoleKeyInfo[] keys, bool update = false) - { - var history = new List {"history0", "histor1", "histo2", "hist3"}; - return this.Fixture(keys, history, update); - } - - private ReadLineHandler Fixture(ConsoleKeyInfo[] keys, List history, bool update=false) - { - var console = new TestConsole(500, 200, keys); - var config = ReadLineConfig.Empty - .SetDefaultKeyBehavior(CommonKeyBehaviors.InsertCharacter) - .AddEnterToFinish() - .AddKeyBehavior(ConsoleKey.LeftArrow, CommonKeyBehaviors.MoveCursorLeft) - .AddKeyBehavior(ConsoleKey.RightArrow, CommonKeyBehaviors.MoveCursorRight) - .AddKeyBehavior(ConsoleKey.DownArrow, CommonKeyBehaviors.HistoryNext) - .AddKeyBehavior(ConsoleKey.UpArrow, CommonKeyBehaviors.HistoryPrevious); - - if (history != null) - { - if (update) - config.SetUpdatingHistorySource(history); - else - config.SetHistorySource(history); - } - - return new ReadLineHandler(new ConsoleReadLine(console), config); - } - } -} \ No newline at end of file +using System; +using System.Collections.Generic; +using InteractiveReadLine.KeyBehaviors; +using InteractiveReadLine.Tests.Fakes; +using Xunit; + +namespace InteractiveReadLine.Tests +{ + public class HistoryTests + { + [Fact] + public void NullHistory_DoesntCrash_OnNext() + { + var keys = KeyBuilder.Create().DownArrow().Enter().Keys; + var result = Fixture(keys, null).ReadLine(); + } + + [Fact] + public void NullHistory_DoesntCrash_OnPrevious() + { + var keys = KeyBuilder.Create().UpArrow().Enter().Keys; + var result = Fixture(keys, null).ReadLine(); + } + + [Fact] + public void EmptyHistory_DoesntCrash_OnNext() + { + var keys = KeyBuilder.Create().DownArrow().Enter().Keys; + var result = Fixture(keys, new List()).ReadLine(); + } + + [Fact] + public void EmptyHistory_DoesntCrash_OnPrevious() + { + var keys = KeyBuilder.Create().UpArrow().Enter().Keys; + var result = Fixture(keys, new List()).ReadLine(); + } + + [Fact] + public void NonUpdatingHistory_DoesntUpdate() + { + var items = new string[] {"item one", "item two", "item three"}; + var history = new List(items); + var keys = KeyBuilder.Create() + .Add("item four") + .Enter().Keys; + var result = this.Fixture(keys, history, false).ReadLine(); + + Assert.Equal(3, history.Count); + foreach (var item in items) + { + Assert.Contains(history, x => x.Contains(item)); + } + } + + [Fact] + public void UpdatingHistory_Updates() + { + var items = new string[] {"item one", "item two", "item three"}; + var history = new List(items); + var keys = KeyBuilder.Create() + .Add("item four") + .Enter().Keys; + var result = this.Fixture(keys, history, true).ReadLine(); + + Assert.Equal(4, history.Count); + Assert.Contains(history, x => x.Contains("item four")); + foreach (var item in items) + { + Assert.Contains(history, x => x.Contains(item)); + } + } + + [Theory] + [InlineData(1, "hist3")] + [InlineData(2, "histo2")] + [InlineData(3, "histor1")] + [InlineData(4, "history0")] + public void MovesPrevious_Correctly(int count, string expected) + { + var keys = KeyBuilder.Create().UpArrow(count).Enter().Keys; + var handler = FixtureWithHistory(keys); + var result = handler.ReadLine(); + + Assert.Equal(expected, handler.LineState.Text); + Assert.Equal(expected.Length, handler.LineState.Cursor); + } + + [Fact] + public void MovesPrevious_AtLimit_Correctly() + { + var keys = KeyBuilder.Create().UpArrow(7).Enter().Keys; + var handler = FixtureWithHistory(keys); + var result = handler.ReadLine(); + + Assert.Equal("history0", handler.LineState.Text); + } + + [Theory] + [InlineData(3, "hist3")] + [InlineData(2, "histo2")] + [InlineData(1, "histor1")] + public void MovesNext_Correctly(int count, string expected) + { + var keys = KeyBuilder.Create() + .Add("this is a test") // 'Type' the text into the readline buffer + .LeftArrow(3) // move the cursor back three positions + .UpArrow(7) // move all the way to the first history entry + .DownArrow(count) // Then forward in the history + .Enter().Keys; + var handler = FixtureWithHistory(keys); + var result = handler.ReadLine(); + + Assert.Equal(expected, handler.LineState.Text); + Assert.Equal(expected.Length, handler.LineState.Cursor); + } + + + [Theory] + [InlineData(1)] + [InlineData(2)] + [InlineData(3)] + [InlineData(7)] + public void MovesBackAndForward_Correctly_IncludingLimit(int steps) + { + var keys = KeyBuilder.Create() + .Add("this is a test") // 'Type' the text into the readline buffer + .LeftArrow(3) // move the cursor back three positions + .UpArrow(steps) // move back in the history a set number of steps + .DownArrow(steps) // then forward again the same number of steps + .Enter().Keys; + var handler = FixtureWithHistory(keys); + var result = handler.ReadLine(); + + Assert.Equal("this is a test", handler.LineState.Text); + Assert.Equal(11, handler.LineState.Cursor); + } + + [Theory] + [InlineData(1)] + [InlineData(2)] + [InlineData(3)] + [InlineData(7)] + public void MovesBackAndForward_Correctly_WithSecondEdit(int steps) + { + var keys = KeyBuilder.Create() + .Add("this is a test") // 'Type' the text into the readline buffer + .LeftArrow(4) // move the cursor back four positions + .UpArrow(steps) // move all the way to the first history entry + .DownArrow(steps) // then all the way back to the entered buffer + .Add("modified ") + .UpArrow(steps) // move all the way to the first history entry + .DownArrow(steps) // then all the way back to the entered buffer + .Enter().Keys; + var handler = FixtureWithHistory(keys); + var result = handler.ReadLine(); + + Assert.Equal("this is a modified test", handler.LineState.Text); + Assert.Equal(19, handler.LineState.Cursor); + } + + [Fact] + public void UpdatingHistory_SkipsEmptyLine() + { + var history = new List {"existing entry"}; + var keys = KeyBuilder.Create().Enter().Keys; + this.Fixture(keys, history, true).ReadLine(); + + Assert.Single(history); + } + + [Fact] + public void UpdatingHistory_SkipsWhitespaceOnlyLine() + { + var history = new List {"existing entry"}; + var keys = KeyBuilder.Create().Add(" ").Enter().Keys; + this.Fixture(keys, history, true).ReadLine(); + + Assert.Single(history); + } + + [Fact] + public void UpdatingHistory_SkipsLineMatchingMostRecentEntry() + { + var history = new List {"item one", "repeated"}; + var keys = KeyBuilder.Create().Add("repeated").Enter().Keys; + this.Fixture(keys, history, true).ReadLine(); + + Assert.Equal(2, history.Count); + } + + /// + /// Only an immediately repeated line is skipped. A line that appears earlier in the history is still + /// recorded, which moves it to the most recent position. + /// + [Fact] + public void UpdatingHistory_KeepsLineMatchingAnOlderEntry() + { + var history = new List {"repeated", "something else"}; + var keys = KeyBuilder.Create().Add("repeated").Enter().Keys; + this.Fixture(keys, history, true).ReadLine(); + + Assert.Equal(3, history.Count); + Assert.Equal("repeated", history[2]); + } + + /// + /// SetUpdatingHistorySource performs the filtering. The handler does not, so a directly supplied + /// update action still receives every finalized line, including empty lines. + /// + [Fact] + public void CustomHistoryUpdateAction_ReceivesEveryFinalizedLine() + { + var recorded = new List(); + var console = new TestConsole(500, 200, KeyBuilder.Create().Enter().Keys); + var config = ReadLineConfig.Empty + .SetDefaultKeyBehavior(CommonKeyBehaviors.InsertCharacter) + .AddEnterToFinish() + .SetHistoryUpdateAction(recorded.Add); + + new ReadLineHandler(new ConsoleReadLine(console), config).ReadLine(); + + Assert.Single(recorded); + Assert.Equal(string.Empty, recorded[0]); + } + + [Fact] + public void SetUpdatingHistorySource_WithNullList_Throws() + { + Assert.Throws(() => ReadLineConfig.Empty.SetUpdatingHistorySource(null)); + } + + /// + /// The configuration holds a live reference to the history, so the collection can grow after the + /// handler is constructed and before the user navigates. HistoryNext then steps forward to the + /// pre-history state, which remains empty because HistoryPrevious was never called to populate it. + /// + [Fact] + public void HistoryNext_WhenHistoryGrewAfterConstruction_DoesNotThrow() + { + var handler = HandlerOverLiveHistory(out var history); + history.Add("four"); + + var exception = Record.Exception(() => handler.HistoryNext()); + + Assert.Null(exception); + Assert.Equal(string.Empty, handler.LineState.Text); + } + + /// + /// The live reference also allows the history to shrink, which can leave the index past the end of the + /// collection. Both navigation directions would index out of range without clamping. + /// + [Fact] + public void HistoryNext_WhenHistoryShrankAfterConstruction_DoesNotThrow() + { + var handler = HandlerOverLiveHistory(out var history); + history.RemoveRange(1, 2); + + var exception = Record.Exception(() => handler.HistoryNext()); + + Assert.Null(exception); + Assert.Equal(string.Empty, handler.LineState.Text); + } + + [Fact] + public void HistoryPrevious_WhenHistoryShrankAfterConstruction_ShowsMostRecentRemainingEntry() + { + var handler = HandlerOverLiveHistory(out var history); + history.RemoveRange(1, 2); + + var exception = Record.Exception(() => handler.HistoryPrevious()); + + Assert.Null(exception); + Assert.Equal("one", handler.LineState.Text); + } + + /// + /// After the history shrinks, navigating backward and forward again must still restore the text that + /// the user entered instead of leaving the index stranded. + /// + [Fact] + public void HistoryNavigation_AfterHistoryShrank_StillRestoresEnteredText() + { + var history = new List {"one", "two", "three"}; + var keys = KeyBuilder.Create().Add("typed").UpArrow().DownArrow().Enter().Keys; + var handler = this.Fixture(keys, history); + + history.RemoveRange(1, 2); + handler.ReadLine(); + + Assert.Equal("typed", handler.LineState.Text); + } + + private ReadLineHandler HandlerOverLiveHistory(out List history) + { + history = new List {"one", "two", "three"}; + var console = new TestConsole(500, 200, new ConsoleKeyInfo[0]); + var config = ReadLineConfig.Empty.SetHistorySource(history); + return new ReadLineHandler(new ConsoleReadLine(console), config); + } + + private ReadLineHandler FixtureWithHistory(ConsoleKeyInfo[] keys, bool update = false) + { + var history = new List {"history0", "histor1", "histo2", "hist3"}; + return this.Fixture(keys, history, update); + } + + private ReadLineHandler Fixture(ConsoleKeyInfo[] keys, List history, bool update=false) + { + var console = new TestConsole(500, 200, keys); + var config = ReadLineConfig.Empty + .SetDefaultKeyBehavior(CommonKeyBehaviors.InsertCharacter) + .AddEnterToFinish() + .AddKeyBehavior(ConsoleKey.LeftArrow, CommonKeyBehaviors.MoveCursorLeft) + .AddKeyBehavior(ConsoleKey.RightArrow, CommonKeyBehaviors.MoveCursorRight) + .AddKeyBehavior(ConsoleKey.DownArrow, CommonKeyBehaviors.HistoryNext) + .AddKeyBehavior(ConsoleKey.UpArrow, CommonKeyBehaviors.HistoryPrevious); + + if (history != null) + { + if (update) + config.SetUpdatingHistorySource(history); + else + config.SetHistorySource(history); + } + + return new ReadLineHandler(new ConsoleReadLine(console), config); + } + } +} diff --git a/InteractiveReadLine.Tests/InteractiveReadLine.Tests.csproj b/InteractiveReadLine.Tests/InteractiveReadLine.Tests.csproj index b23e4ab..4058853 100644 --- a/InteractiveReadLine.Tests/InteractiveReadLine.Tests.csproj +++ b/InteractiveReadLine.Tests/InteractiveReadLine.Tests.csproj @@ -1,25 +1,24 @@ - - - - netcoreapp3.0 - - false - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - + + + + net10.0 + + false + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + diff --git a/InteractiveReadLine.Tests/LineStateEqualityTests.cs b/InteractiveReadLine.Tests/LineStateEqualityTests.cs index 12edede..7c7a39e 100644 --- a/InteractiveReadLine.Tests/LineStateEqualityTests.cs +++ b/InteractiveReadLine.Tests/LineStateEqualityTests.cs @@ -70,8 +70,8 @@ public void LineState_ReferenceEquals() public void LineState_ReferenceEquals_FalseAgainstNull() { var s1 = new LineState("this is some text", 5); - - Assert.NotEqual(null, s1); + + Assert.False(s1.Equals(null)); } [Fact] diff --git a/InteractiveReadLine.Tests/RegexLexerTests.cs b/InteractiveReadLine.Tests/RegexLexerTests.cs index 2088563..44e9a59 100644 --- a/InteractiveReadLine.Tests/RegexLexerTests.cs +++ b/InteractiveReadLine.Tests/RegexLexerTests.cs @@ -1,89 +1,89 @@ -using System; -using System.Linq; -using InteractiveReadLine.Tokenizing; -using Xunit; - -namespace InteractiveReadLine.Tests -{ - public class RegexLexerTests - { - [Fact] - public void EmptyRegex_ToLexer_ThrowsArgException() - { - Assert.Throws(() => - { - var lexer = CommonLexers.Regex.ToLexer(); - }); - } - - [Fact] - public void AddTokenType_WithoutStartChar_ThrowsArgException() - { - Assert.Throws(() => - { - var lexer = CommonLexers.Regex.AddTokenType(@"\d+"); - }); - } - - [Fact] - public void SingleRegex_ToLexer_Functions() - { - // Create a lexer that only considers digits valid - var lexer = CommonLexers.Regex.AddTokenType(@"^\d+", 1).ToLexer(); - - var test = new LineState("this is 2031 a test", 0); - var tokenized = lexer(test); - - Assert.Equal("2031", tokenized.FirstNonHidden.Text); - Assert.Equal(1, tokenized.FirstNonHidden.TypeCode); - } - - [Fact] - public void TwoRegex_ToLexer_Functions() - { - // Since the integer literal will match the beginning of a floating point value, - // it is important that they are put so that the more specific regex comes before - // the more general one - var lexer = CommonLexers.Regex - .AddTokenType(@"^-?[0-9]*\.[0-9]*", 1) // floating point literal - .AddTokenType(@"^-?\d+", 2) // integer literal - .ToLexer(); - - var test = new LineState("this 58.34 is 2031 a test", 0); - var tokenized = lexer(test); - - var nonHidden = tokenized.Where(x => !x.IsHidden).ToArray(); - - Assert.Equal(2, nonHidden.Length); - Assert.Equal("58.34", nonHidden[0].Text); - Assert.Equal(1, nonHidden[0].TypeCode); - - Assert.Equal("2031", nonHidden[1].Text); - Assert.Equal(2, nonHidden[1].TypeCode); - } - - [Fact] - public void TwoRegexWrongOrder_ToLexer_FunctionsWrong() - { - var lexer = CommonLexers.Regex - .AddTokenType(@"^-?\d+", 2) // integer literal - .AddTokenType(@"^-?[0-9]*\.[0-9]*", 1) // floating point literal - .ToLexer(); - - var test = new LineState("this 58.34 is 2031 a test", 0); - var tokenized = lexer(test); - - var nonHidden = tokenized.Where(x => !x.IsHidden).ToArray(); - - Assert.Equal(3, nonHidden.Length); - Assert.Equal("58", nonHidden[0].Text); - Assert.Equal(2, nonHidden[0].TypeCode); - - Assert.Equal(".34", nonHidden[1].Text); - Assert.Equal(1, nonHidden[1].TypeCode); - - Assert.Equal("2031", nonHidden[2].Text); - Assert.Equal(2, nonHidden[2].TypeCode); - } - } +using System; +using System.Linq; +using InteractiveReadLine.Tokenizing; +using Xunit; + +namespace InteractiveReadLine.Tests +{ + public class RegexLexerTests + { + [Fact] + public void EmptyRegex_ToLexer_ThrowsArgException() + { + Assert.Throws(() => + { + var lexer = CommonLexers.Regex.ToLexer(); + }); + } + + [Fact] + public void AddTokenType_WithoutStartChar_ThrowsArgException() + { + Assert.Throws(() => + { + var lexer = CommonLexers.Regex.AddTokenType(@"\d+"); + }); + } + + [Fact] + public void SingleRegex_ToLexer_Functions() + { + // Create a lexer that only considers digits valid + var lexer = CommonLexers.Regex.AddTokenType(@"^\d+", 1).ToLexer(); + + var test = new LineState("this is 2031 a test", 0); + var tokenized = lexer(test); + + Assert.Equal("2031", tokenized.FirstNonHidden.Text); + Assert.Equal(1, tokenized.FirstNonHidden.TypeCode); + } + + [Fact] + public void TwoRegex_ToLexer_Functions() + { + // Since the integer literal will match the beginning of a floating point value, + // it is important that they are put so that the more specific regex comes before + // the more general one + var lexer = CommonLexers.Regex + .AddTokenType(@"^-?[0-9]*\.[0-9]*", 1) // floating point literal + .AddTokenType(@"^-?\d+", 2) // integer literal + .ToLexer(); + + var test = new LineState("this 58.34 is 2031 a test", 0); + var tokenized = lexer(test); + + var nonHidden = tokenized.Where(x => !x.IsHidden).ToArray(); + + Assert.Equal(2, nonHidden.Length); + Assert.Equal("58.34", nonHidden[0].Text); + Assert.Equal(1, nonHidden[0].TypeCode); + + Assert.Equal("2031", nonHidden[1].Text); + Assert.Equal(2, nonHidden[1].TypeCode); + } + + [Fact] + public void TwoRegexWrongOrder_ToLexer_FunctionsWrong() + { + var lexer = CommonLexers.Regex + .AddTokenType(@"^-?\d+", 2) // integer literal + .AddTokenType(@"^-?[0-9]*\.[0-9]*", 1) // floating point literal + .ToLexer(); + + var test = new LineState("this 58.34 is 2031 a test", 0); + var tokenized = lexer(test); + + var nonHidden = tokenized.Where(x => !x.IsHidden).ToArray(); + + Assert.Equal(3, nonHidden.Length); + Assert.Equal("58", nonHidden[0].Text); + Assert.Equal(2, nonHidden[0].TypeCode); + + Assert.Equal(".34", nonHidden[1].Text); + Assert.Equal(1, nonHidden[1].TypeCode); + + Assert.Equal("2031", nonHidden[2].Text); + Assert.Equal(2, nonHidden[2].TypeCode); + } + } } \ No newline at end of file diff --git a/InteractiveReadLine.Tests/TokenDistanceTests.cs b/InteractiveReadLine.Tests/TokenDistanceTests.cs index 9d603fa..ceac2e2 100644 --- a/InteractiveReadLine.Tests/TokenDistanceTests.cs +++ b/InteractiveReadLine.Tests/TokenDistanceTests.cs @@ -1,53 +1,53 @@ -using System.Linq; -using InteractiveReadLine.Tokenizing; -using Xunit; - -namespace InteractiveReadLine.Tests -{ - public class TokenDistanceTests - { - [Fact] - public void FirstNonEmpty_IdentifiesCorrectly() - { - var line = SimpleLine(); - - Assert.Equal("this", line.FirstNonHidden.Text); - } - - [Fact] - public void ForwardDistance_WorksCorrectly() - { - var line = SimpleLine(); - var start = line.FirstNonHidden; - var end = line.FirstOrDefault(x => x.Text == "testing"); - - var distance = start.DistanceTo(end); - Assert.Equal(4, distance); - } - - [Fact] - public void ForwardDistance_WorksCorrectly_WhileIgnoringHidden() - { - var line = SimpleLine(); - var start = line.FirstNonHidden; - var end = line.FirstOrDefault(x => x.Text == "testing"); - - var distance = start.DistanceTo(end, true); - Assert.Equal(2, distance); - } - - private TokenizedLine SimpleLine() - { - var line = new TokenizedLine(); - line.Add(" ", true); - line.Add("this", false); - line.Add(" ", true); - line.Add("is", false); - line.Add(" ", true); - line.Add("testing", false); - line.Add(" ", true); - line.Add("driven", true); - return line; - } - } +using System.Linq; +using InteractiveReadLine.Tokenizing; +using Xunit; + +namespace InteractiveReadLine.Tests +{ + public class TokenDistanceTests + { + [Fact] + public void FirstNonEmpty_IdentifiesCorrectly() + { + var line = SimpleLine(); + + Assert.Equal("this", line.FirstNonHidden.Text); + } + + [Fact] + public void ForwardDistance_WorksCorrectly() + { + var line = SimpleLine(); + var start = line.FirstNonHidden; + var end = line.FirstOrDefault(x => x.Text == "testing"); + + var distance = start.DistanceTo(end); + Assert.Equal(4, distance); + } + + [Fact] + public void ForwardDistance_WorksCorrectly_WhileIgnoringHidden() + { + var line = SimpleLine(); + var start = line.FirstNonHidden; + var end = line.FirstOrDefault(x => x.Text == "testing"); + + var distance = start.DistanceTo(end, true); + Assert.Equal(2, distance); + } + + private TokenizedLine SimpleLine() + { + var line = new TokenizedLine(); + line.Add(" ", true); + line.Add("this", false); + line.Add(" ", true); + line.Add("is", false); + line.Add(" ", true); + line.Add("testing", false); + line.Add(" ", true); + line.Add("driven", true); + return line; + } + } } \ No newline at end of file diff --git a/InteractiveReadLine.Tests/TokenRecombineTests.cs b/InteractiveReadLine.Tests/TokenRecombineTests.cs index ce87b8f..c4793b4 100644 --- a/InteractiveReadLine.Tests/TokenRecombineTests.cs +++ b/InteractiveReadLine.Tests/TokenRecombineTests.cs @@ -1,28 +1,28 @@ -using InteractiveReadLine.Tokenizing; -using Xunit; - -namespace InteractiveReadLine.Tests -{ - public class TokenRecombineTests - { - [Theory] - [InlineData("this is a test")] - [InlineData(" this is a test")] - [InlineData("this is a test ")] - [InlineData("this is a test")] - [InlineData(" ")] - [InlineData("test")] - public void Tokens_RoundTrip_CombineToExpected(string text) - { - // Check that the cursor is reset correctly for each position in the text - for (int i = 0; i < text.Length + 1; i++) - { - var tokenize = new LineState(text, i); - var result = CommonLexers.SplitOnWhitespace(tokenize); - - Assert.Equal(text, result.Text); - Assert.Equal(i, result.Cursor); - } - } - } +using InteractiveReadLine.Tokenizing; +using Xunit; + +namespace InteractiveReadLine.Tests +{ + public class TokenRecombineTests + { + [Theory] + [InlineData("this is a test")] + [InlineData(" this is a test")] + [InlineData("this is a test ")] + [InlineData("this is a test")] + [InlineData(" ")] + [InlineData("test")] + public void Tokens_RoundTrip_CombineToExpected(string text) + { + // Check that the cursor is reset correctly for each position in the text + for (int i = 0; i < text.Length + 1; i++) + { + var tokenize = new LineState(text, i); + var result = CommonLexers.SplitOnWhitespace(tokenize); + + Assert.Equal(text, result.Text); + Assert.Equal(i, result.Cursor); + } + } + } } \ No newline at end of file diff --git a/InteractiveReadLine.Tests/TokenizeCursorTests.cs b/InteractiveReadLine.Tests/TokenizeCursorTests.cs index 9f11cef..991935e 100644 --- a/InteractiveReadLine.Tests/TokenizeCursorTests.cs +++ b/InteractiveReadLine.Tests/TokenizeCursorTests.cs @@ -1,143 +1,143 @@ -using InteractiveReadLine.Tokenizing; -using Xunit; - -namespace InteractiveReadLine.Tests -{ - public class TokenizeCursorTests - { - [Fact] - public void CursorTestFixture_IdentifiesCursorPosition_Start() - { - var tokenize = FromTestText( - "this is a test", - "^"); - - Assert.Equal(0, tokenize.Cursor); - } - - [Fact] - public void CursorTestFixture_IdentifiesCursorPosition_End() - { - var tokenize = FromTestText( - "this is a test", - " ^"); - - Assert.Equal(14, tokenize.Cursor); - } - - [Fact] - public void CursorTestFixture_IdentifiesCursorPosition_Middle() - { - var tokenize = FromTestText( - "this is a test", - " ^"); - - Assert.Equal(6, tokenize.Cursor); - } - - [Fact] - public void CursorInSeparatorText_IdentifiesCorrectly() - { - var tokenize = FromTestText( - "this is a test", - " ^ "); - var tokens = CommonLexers.SplitOnWhitespace(tokenize); - Assert.Equal(1, tokens.CursorTokenIndex); - Assert.Equal(2, tokens.CursorToken.Cursor); - - } - - [Theory] - // 43210 - // " " - [InlineData("^ ", 0)] - [InlineData(" ^ ", 2)] - [InlineData(" ^", 3)] - public void CursorInSeparatorText_PrefixOnly_IdentifiesCorrectly(string cursorText, int position) - { - var tokenize = FromTestText(" ", cursorText); - var tokens = CommonLexers.SplitOnWhitespace(tokenize); - - Assert.Equal(0, tokens.CursorTokenIndex); - Assert.Equal(position, tokens.CursorToken.Cursor); - } - - [Fact] - public void CursorInSeparatorText_MidLine_IdentifiesCorrectly() - { - var tokenize = FromTestText( - "this is a test", - " ^ "); - var tokens = CommonLexers.SplitOnWhitespace(tokenize); - Assert.Equal(3, tokens.CursorTokenIndex); - Assert.Equal(1, tokens.CursorToken.Cursor); - } - - [Theory] - // 0 2 4 6 8 10 12 - // 0123 01 0 0123 01 012 012345 - // "this is a test of the cursor" - [InlineData("^ ", 0, 0)] - [InlineData(" ^ ", 0, 1)] - [InlineData(" ^ ", 0, 4)] - [InlineData(" ^ ", 6, 0)] - [InlineData(" ^ ", 6, 1)] - [InlineData(" ^ ", 6, 4)] - [InlineData(" ^ ", 12, 0)] - [InlineData(" ^ ", 12, 5)] - [InlineData(" ^", 12, 6)] - public void TokenizedCursor_SimpleCase_IdentifiesCorrectToken(string cursorText, int token, int position) - { - var tokenize = FromTestText("this is a test of the cursor", cursorText); - var tokens = CommonLexers.SplitOnWhitespace(tokenize); - - Assert.Equal(token, tokens.CursorTokenIndex); - Assert.Equal(position, tokens.CursorToken.Cursor); - } - - [Theory] - // 1 3 5 7 9 11 13 - // 0123 01 0 0123 01 012 012345 - // " this is a test of the cursor" - [InlineData(" ^ ", 1, 0)] - [InlineData(" ^ ", 1, 1)] - [InlineData(" ^ ", 1, 4)] - [InlineData(" ^ ", 7, 0)] - [InlineData(" ^ ", 7, 1)] - [InlineData(" ^ ", 7, 4)] - [InlineData(" ^ ", 13, 0)] - [InlineData(" ^ ", 13, 5)] - [InlineData(" ^", 13, 6)] - public void TokenizedCursor_WithLeadingSpace_IdentifiesCorrectToken(string cursorText, int token, int position) - { - var tokenize = FromTestText(" this is a test of the cursor", cursorText); - var tokens = CommonLexers.SplitOnWhitespace(tokenize); - - Assert.Equal(token, tokens.CursorTokenIndex); - Assert.Equal(position, tokens.CursorToken.Cursor); - } - - [Theory] - // 0 2 4 6 8 10 12 - // 0123 01 0 0123 01 012 012345 - // "this is a test of the cursor " - [InlineData(" ^ ", 12, 0)] - [InlineData(" ^ ", 12, 5)] - [InlineData(" ^ ", 12, 6)] - [InlineData(" ^", 14, 0)] - public void TokenizedCursor_TrailingSpace_IdentifiesCorrectToken(string cursorText, int token, int position) - { - var tokenize = FromTestText("this is a test of the cursor ", cursorText); - var tokens = CommonLexers.SplitOnWhitespace(tokenize); - - Assert.Equal(token, tokens.CursorTokenIndex); - Assert.Equal(position, tokens.CursorToken.Cursor); - } - - public LineState FromTestText(string text, string curs) - { - int cpos = curs.IndexOf('^'); - return new LineState(text, cpos); - } - } +using InteractiveReadLine.Tokenizing; +using Xunit; + +namespace InteractiveReadLine.Tests +{ + public class TokenizeCursorTests + { + [Fact] + public void CursorTestFixture_IdentifiesCursorPosition_Start() + { + var tokenize = FromTestText( + "this is a test", + "^"); + + Assert.Equal(0, tokenize.Cursor); + } + + [Fact] + public void CursorTestFixture_IdentifiesCursorPosition_End() + { + var tokenize = FromTestText( + "this is a test", + " ^"); + + Assert.Equal(14, tokenize.Cursor); + } + + [Fact] + public void CursorTestFixture_IdentifiesCursorPosition_Middle() + { + var tokenize = FromTestText( + "this is a test", + " ^"); + + Assert.Equal(6, tokenize.Cursor); + } + + [Fact] + public void CursorInSeparatorText_IdentifiesCorrectly() + { + var tokenize = FromTestText( + "this is a test", + " ^ "); + var tokens = CommonLexers.SplitOnWhitespace(tokenize); + Assert.Equal(1, tokens.CursorTokenIndex); + Assert.Equal(2, tokens.CursorToken.Cursor); + + } + + [Theory] + // 43210 + // " " + [InlineData("^ ", 0)] + [InlineData(" ^ ", 2)] + [InlineData(" ^", 3)] + public void CursorInSeparatorText_PrefixOnly_IdentifiesCorrectly(string cursorText, int position) + { + var tokenize = FromTestText(" ", cursorText); + var tokens = CommonLexers.SplitOnWhitespace(tokenize); + + Assert.Equal(0, tokens.CursorTokenIndex); + Assert.Equal(position, tokens.CursorToken.Cursor); + } + + [Fact] + public void CursorInSeparatorText_MidLine_IdentifiesCorrectly() + { + var tokenize = FromTestText( + "this is a test", + " ^ "); + var tokens = CommonLexers.SplitOnWhitespace(tokenize); + Assert.Equal(3, tokens.CursorTokenIndex); + Assert.Equal(1, tokens.CursorToken.Cursor); + } + + [Theory] + // 0 2 4 6 8 10 12 + // 0123 01 0 0123 01 012 012345 + // "this is a test of the cursor" + [InlineData("^ ", 0, 0)] + [InlineData(" ^ ", 0, 1)] + [InlineData(" ^ ", 0, 4)] + [InlineData(" ^ ", 6, 0)] + [InlineData(" ^ ", 6, 1)] + [InlineData(" ^ ", 6, 4)] + [InlineData(" ^ ", 12, 0)] + [InlineData(" ^ ", 12, 5)] + [InlineData(" ^", 12, 6)] + public void TokenizedCursor_SimpleCase_IdentifiesCorrectToken(string cursorText, int token, int position) + { + var tokenize = FromTestText("this is a test of the cursor", cursorText); + var tokens = CommonLexers.SplitOnWhitespace(tokenize); + + Assert.Equal(token, tokens.CursorTokenIndex); + Assert.Equal(position, tokens.CursorToken.Cursor); + } + + [Theory] + // 1 3 5 7 9 11 13 + // 0123 01 0 0123 01 012 012345 + // " this is a test of the cursor" + [InlineData(" ^ ", 1, 0)] + [InlineData(" ^ ", 1, 1)] + [InlineData(" ^ ", 1, 4)] + [InlineData(" ^ ", 7, 0)] + [InlineData(" ^ ", 7, 1)] + [InlineData(" ^ ", 7, 4)] + [InlineData(" ^ ", 13, 0)] + [InlineData(" ^ ", 13, 5)] + [InlineData(" ^", 13, 6)] + public void TokenizedCursor_WithLeadingSpace_IdentifiesCorrectToken(string cursorText, int token, int position) + { + var tokenize = FromTestText(" this is a test of the cursor", cursorText); + var tokens = CommonLexers.SplitOnWhitespace(tokenize); + + Assert.Equal(token, tokens.CursorTokenIndex); + Assert.Equal(position, tokens.CursorToken.Cursor); + } + + [Theory] + // 0 2 4 6 8 10 12 + // 0123 01 0 0123 01 012 012345 + // "this is a test of the cursor " + [InlineData(" ^ ", 12, 0)] + [InlineData(" ^ ", 12, 5)] + [InlineData(" ^ ", 12, 6)] + [InlineData(" ^", 14, 0)] + public void TokenizedCursor_TrailingSpace_IdentifiesCorrectToken(string cursorText, int token, int position) + { + var tokenize = FromTestText("this is a test of the cursor ", cursorText); + var tokens = CommonLexers.SplitOnWhitespace(tokenize); + + Assert.Equal(token, tokens.CursorTokenIndex); + Assert.Equal(position, tokens.CursorToken.Cursor); + } + + public LineState FromTestText(string text, string curs) + { + int cpos = curs.IndexOf('^'); + return new LineState(text, cpos); + } + } } \ No newline at end of file diff --git a/InteractiveReadLine.Tests/TokenizeSegmentationTest.cs b/InteractiveReadLine.Tests/TokenizeSegmentationTest.cs index 39cc69b..90e1416 100644 --- a/InteractiveReadLine.Tests/TokenizeSegmentationTest.cs +++ b/InteractiveReadLine.Tests/TokenizeSegmentationTest.cs @@ -1,159 +1,159 @@ -using System.Linq; -using InteractiveReadLine.Tokenizing; -using Xunit; - -namespace InteractiveReadLine.Tests -{ - public class TokenizeSegmentationTest - { - [Fact] - public void Tokenizer_HandlesEmptyString_Gracefully() - { - var test = new LineState("", 0); - var tokenized = CommonLexers.SplitOnWhitespace(test); - - Assert.Single(tokenized); - Assert.Equal("", tokenized.First.Text); - } - - [Fact] - public void Tokenizer_SplitOnSpaces_WorksCorrectly() - { - var test = new LineState("this is a test", 0); - var tokenized = CommonLexers.SplitOnWhitespace(test); - var tokens = tokenized.Where(x => !x.IsHidden).ToArray(); - - Assert.Equal("this", tokens[0].Text); - Assert.Equal("is", tokens[1].Text); - Assert.Equal("a", tokens[2].Text); - Assert.Equal("test", tokens[3].Text); - } - - [Fact] - public void Tokenizer_SplitOnUnequalSpaces_WithCursor_WorksCorrectly() - { - var test = new LineState("this is a test", 15); - var tokenized = CommonLexers.SplitOnWhitespace(test); - var tokens = tokenized.Where(x => !x.IsHidden).ToArray(); - - Assert.Equal("this", tokens[0].Text); - Assert.Equal("is", tokens[1].Text); - Assert.Equal("a", tokens[2].Text); - Assert.Equal("test", tokens[3].Text); - - Assert.Equal(1, tokens[3].Cursor); - } - - [Fact] - public void Tokenizer_PreviousAndNext_Separators_Correct() - { - var test = new LineState("this is a test", 15); - var tokenized = CommonLexers.SplitOnWhitespace(test); - var tokens = tokenized.Where(x => x.IsHidden).ToArray(); - - Assert.Equal(" ", tokens[0].Text); - Assert.Equal(" ", tokens[1].Text); - Assert.Equal(" ", tokens[2].Text); - } - - [Fact] - public void Tokenizer_SplitOnUnequalSpaces_Linking_WorksCorrectly() - { - var test = new LineState("this is a test", 15); - var tokenized = CommonLexers.SplitOnWhitespace(test); - var tokens = tokenized.Where(x => !x.IsHidden).ToArray(); - - Assert.Equal("this", tokens[0].Text); - Assert.Equal(" ", tokens[0].Next.Text); - - Assert.Equal(" ", tokens[1].Previous.Text); - Assert.Equal("is", tokens[1].Text); - Assert.Equal(" ", tokens[1].Next.Text); - - Assert.Equal(" ", tokens[2].Previous.Text); - Assert.Equal("a", tokens[2].Text); - Assert.Equal(" ", tokens[2].Next.Text); - - Assert.Equal(" ", tokens[3].Previous.Text); - } - - [Fact] - public void Tokens_Linked_Correctly_Backwards() - { - var test = new LineState("this is a test", 15); - var tokenized = CommonLexers.SplitOnWhitespace(test); - var tokens = tokenized.Where(x => !x.IsHidden).ToArray(); - - var last = tokens.Last(); - - Assert.Equal("this", last.PreviousNotHidden.PreviousNotHidden.PreviousNotHidden.Text); - Assert.Equal("is", last.PreviousNotHidden.PreviousNotHidden.Text); - Assert.Equal("a", last.PreviousNotHidden.Text); - Assert.Equal("test", last.Text); - } - - [Fact] - public void Tokens_Linked_Correctly_Forward() - { - var test = new LineState("this is a test", 15); - var tokenized = CommonLexers.SplitOnWhitespace(test); - var tokens = tokenized.Where(x => !x.IsHidden).ToArray(); - - var first = tokens.First(); - - Assert.Equal("this", first.Text); - Assert.Equal("is", first.NextNotHidden.Text); - Assert.Equal("a", first.NextNotHidden.NextNotHidden.Text); - Assert.Equal("test", first.NextNotHidden.NextNotHidden.NextNotHidden.Text); - } - - [Fact] - public void Tokenizer_CursorAtEndWithEmptySep_CreatesNoEmptyToken() - { - var test = new LineState("this is a test", 14); - var tokenized = CommonLexers.SplitOnWhitespace(test); - var tokens = tokenized.Where(x => !x.IsHidden).ToArray(); - - Assert.Equal(4, tokens.Length); - Assert.Equal("test", tokenized.Last.Text); - } - - [Fact] - public void Tokenizer_CursorAtEndWithNonEmptySep_CreatesEmptyToken() - { - var test = new LineState("this is a test ", 15); - var tokenized = CommonLexers.SplitOnWhitespace(test); - - Assert.Equal(5, tokenized.Count(x => !x.IsHidden)); - Assert.Equal("", tokenized.Last.Text); - } - - [Fact] - public void Tokenizer_CursorOnSecondToken_Start_Correct() - { - var test = new LineState("this is a test", 5); - var tokenized = CommonLexers.SplitOnWhitespace(test); - - Assert.Equal(0, tokenized[2].Cursor); - } - - [Fact] - public void Tokenizer_CursorOnSecondToken_End_Correctly() - { - var test = new LineState("this is a test", 6); - var tokenized = CommonLexers.SplitOnWhitespace(test); - - Assert.Equal(1, tokenized[2].Cursor); - } - - [Fact] - public void Tokenizer_InitialSeparator_WithCursor_WorksCorrectly() - { - var test = new LineState(" this is a test ", 13); - var tokenized = CommonLexers.SplitOnWhitespace(test); - - Assert.Equal(" ", tokenized.First.Text); - Assert.Equal(0, tokenized.Last(x => !x.IsHidden).Cursor); - } - } +using System.Linq; +using InteractiveReadLine.Tokenizing; +using Xunit; + +namespace InteractiveReadLine.Tests +{ + public class TokenizeSegmentationTest + { + [Fact] + public void Tokenizer_HandlesEmptyString_Gracefully() + { + var test = new LineState("", 0); + var tokenized = CommonLexers.SplitOnWhitespace(test); + + Assert.Single(tokenized); + Assert.Equal("", tokenized.First.Text); + } + + [Fact] + public void Tokenizer_SplitOnSpaces_WorksCorrectly() + { + var test = new LineState("this is a test", 0); + var tokenized = CommonLexers.SplitOnWhitespace(test); + var tokens = tokenized.Where(x => !x.IsHidden).ToArray(); + + Assert.Equal("this", tokens[0].Text); + Assert.Equal("is", tokens[1].Text); + Assert.Equal("a", tokens[2].Text); + Assert.Equal("test", tokens[3].Text); + } + + [Fact] + public void Tokenizer_SplitOnUnequalSpaces_WithCursor_WorksCorrectly() + { + var test = new LineState("this is a test", 15); + var tokenized = CommonLexers.SplitOnWhitespace(test); + var tokens = tokenized.Where(x => !x.IsHidden).ToArray(); + + Assert.Equal("this", tokens[0].Text); + Assert.Equal("is", tokens[1].Text); + Assert.Equal("a", tokens[2].Text); + Assert.Equal("test", tokens[3].Text); + + Assert.Equal(1, tokens[3].Cursor); + } + + [Fact] + public void Tokenizer_PreviousAndNext_Separators_Correct() + { + var test = new LineState("this is a test", 15); + var tokenized = CommonLexers.SplitOnWhitespace(test); + var tokens = tokenized.Where(x => x.IsHidden).ToArray(); + + Assert.Equal(" ", tokens[0].Text); + Assert.Equal(" ", tokens[1].Text); + Assert.Equal(" ", tokens[2].Text); + } + + [Fact] + public void Tokenizer_SplitOnUnequalSpaces_Linking_WorksCorrectly() + { + var test = new LineState("this is a test", 15); + var tokenized = CommonLexers.SplitOnWhitespace(test); + var tokens = tokenized.Where(x => !x.IsHidden).ToArray(); + + Assert.Equal("this", tokens[0].Text); + Assert.Equal(" ", tokens[0].Next.Text); + + Assert.Equal(" ", tokens[1].Previous.Text); + Assert.Equal("is", tokens[1].Text); + Assert.Equal(" ", tokens[1].Next.Text); + + Assert.Equal(" ", tokens[2].Previous.Text); + Assert.Equal("a", tokens[2].Text); + Assert.Equal(" ", tokens[2].Next.Text); + + Assert.Equal(" ", tokens[3].Previous.Text); + } + + [Fact] + public void Tokens_Linked_Correctly_Backwards() + { + var test = new LineState("this is a test", 15); + var tokenized = CommonLexers.SplitOnWhitespace(test); + var tokens = tokenized.Where(x => !x.IsHidden).ToArray(); + + var last = tokens.Last(); + + Assert.Equal("this", last.PreviousNotHidden.PreviousNotHidden.PreviousNotHidden.Text); + Assert.Equal("is", last.PreviousNotHidden.PreviousNotHidden.Text); + Assert.Equal("a", last.PreviousNotHidden.Text); + Assert.Equal("test", last.Text); + } + + [Fact] + public void Tokens_Linked_Correctly_Forward() + { + var test = new LineState("this is a test", 15); + var tokenized = CommonLexers.SplitOnWhitespace(test); + var tokens = tokenized.Where(x => !x.IsHidden).ToArray(); + + var first = tokens.First(); + + Assert.Equal("this", first.Text); + Assert.Equal("is", first.NextNotHidden.Text); + Assert.Equal("a", first.NextNotHidden.NextNotHidden.Text); + Assert.Equal("test", first.NextNotHidden.NextNotHidden.NextNotHidden.Text); + } + + [Fact] + public void Tokenizer_CursorAtEndWithEmptySep_CreatesNoEmptyToken() + { + var test = new LineState("this is a test", 14); + var tokenized = CommonLexers.SplitOnWhitespace(test); + var tokens = tokenized.Where(x => !x.IsHidden).ToArray(); + + Assert.Equal(4, tokens.Length); + Assert.Equal("test", tokenized.Last.Text); + } + + [Fact] + public void Tokenizer_CursorAtEndWithNonEmptySep_CreatesEmptyToken() + { + var test = new LineState("this is a test ", 15); + var tokenized = CommonLexers.SplitOnWhitespace(test); + + Assert.Equal(5, tokenized.Count(x => !x.IsHidden)); + Assert.Equal("", tokenized.Last.Text); + } + + [Fact] + public void Tokenizer_CursorOnSecondToken_Start_Correct() + { + var test = new LineState("this is a test", 5); + var tokenized = CommonLexers.SplitOnWhitespace(test); + + Assert.Equal(0, tokenized[2].Cursor); + } + + [Fact] + public void Tokenizer_CursorOnSecondToken_End_Correctly() + { + var test = new LineState("this is a test", 6); + var tokenized = CommonLexers.SplitOnWhitespace(test); + + Assert.Equal(1, tokenized[2].Cursor); + } + + [Fact] + public void Tokenizer_InitialSeparator_WithCursor_WorksCorrectly() + { + var test = new LineState(" this is a test ", 13); + var tokenized = CommonLexers.SplitOnWhitespace(test); + + Assert.Equal(" ", tokenized.First.Text); + Assert.Equal(0, tokenized.Last(x => !x.IsHidden).Cursor); + } + } } \ No newline at end of file diff --git a/InteractiveReadLine.Tests/TokenizedLineEditingTests.cs b/InteractiveReadLine.Tests/TokenizedLineEditingTests.cs index 46e0f02..972c205 100644 --- a/InteractiveReadLine.Tests/TokenizedLineEditingTests.cs +++ b/InteractiveReadLine.Tests/TokenizedLineEditingTests.cs @@ -1,84 +1,84 @@ -using InteractiveReadLine.Tokenizing; -using Xunit; - -namespace InteractiveReadLine.Tests -{ - public class TokenizedLineEditingTests - { - [Fact] - public void SetCursorToEnd_AssignsCorrectToken() - { - var line = SimpleLine(); - line.Last.Cursor = line.Last.Text.Length; - - Assert.Equal(line.Last, line.CursorToken); - } - - [Fact] - public void ReplacingTokenText_ShorterText_DoesntLoseCursor() - { - var line = SimpleLine(); - line.Last.Cursor = line.Last.Text.Length; - line.Last.Text = "a"; - - Assert.Equal(line.Last, line.CursorToken); - } - - [Fact] - public void ShrinkTokenBeforeCursor_OneBefore_MovesCursorCorrectly() - { - // This tests for an issue discovered when shrinking a token right before - // the cursor - var line = SimpleLine(); - line[2].Cursor = 0; - var edit = line[2].Previous; - - Assert.Equal(5, line.Cursor); - edit.Text = ""; - - Assert.Equal(4, line.Cursor); - } - - [Fact] - public void ShrinkTokenBeforeCursor_MovesCursorCorrectly() - { - var line = SimpleLine(); - line.Last.Cursor = 4; - var edit = line.Last.PreviousNotHidden; - Assert.Equal("driven", line.CursorToken.Text); - Assert.Equal("testing", edit.Text); - - edit.Text = "a"; - - Assert.Equal(4, line.Last.Cursor); - } - - [Fact] - public void ExpandTokenBeforeCursor_MovesCursorCorrectly() - { - var line = SimpleLine(); - line.Last.Cursor = 4; - var edit = line.Last.PreviousNotHidden; - Assert.Equal("driven", line.CursorToken.Text); - Assert.Equal("testing", edit.Text); - - edit.Text = "supercalifragalisticexpialadocious"; - - Assert.Equal(4, line.Last.Cursor); - } - - - private TokenizedLine SimpleLine() - { - var line = new TokenizedLine(); - line.Add("this", false); - line.Add(" ", true); - line.Add("is", false); - line.Add(" ", true); - line.Add("testing", false); - line.Add(" ", true); - line.Add("driven", true); - return line; - } - } +using InteractiveReadLine.Tokenizing; +using Xunit; + +namespace InteractiveReadLine.Tests +{ + public class TokenizedLineEditingTests + { + [Fact] + public void SetCursorToEnd_AssignsCorrectToken() + { + var line = SimpleLine(); + line.Last.Cursor = line.Last.Text.Length; + + Assert.Equal(line.Last, line.CursorToken); + } + + [Fact] + public void ReplacingTokenText_ShorterText_DoesntLoseCursor() + { + var line = SimpleLine(); + line.Last.Cursor = line.Last.Text.Length; + line.Last.Text = "a"; + + Assert.Equal(line.Last, line.CursorToken); + } + + [Fact] + public void ShrinkTokenBeforeCursor_OneBefore_MovesCursorCorrectly() + { + // This tests for an issue discovered when shrinking a token right before + // the cursor + var line = SimpleLine(); + line[2].Cursor = 0; + var edit = line[2].Previous; + + Assert.Equal(5, line.Cursor); + edit.Text = ""; + + Assert.Equal(4, line.Cursor); + } + + [Fact] + public void ShrinkTokenBeforeCursor_MovesCursorCorrectly() + { + var line = SimpleLine(); + line.Last.Cursor = 4; + var edit = line.Last.PreviousNotHidden; + Assert.Equal("driven", line.CursorToken.Text); + Assert.Equal("testing", edit.Text); + + edit.Text = "a"; + + Assert.Equal(4, line.Last.Cursor); + } + + [Fact] + public void ExpandTokenBeforeCursor_MovesCursorCorrectly() + { + var line = SimpleLine(); + line.Last.Cursor = 4; + var edit = line.Last.PreviousNotHidden; + Assert.Equal("driven", line.CursorToken.Text); + Assert.Equal("testing", edit.Text); + + edit.Text = "supercalifragalisticexpialadocious"; + + Assert.Equal(4, line.Last.Cursor); + } + + + private TokenizedLine SimpleLine() + { + var line = new TokenizedLine(); + line.Add("this", false); + line.Add(" ", true); + line.Add("is", false); + line.Add(" ", true); + line.Add("testing", false); + line.Add(" ", true); + line.Add("driven", true); + return line; + } + } } \ No newline at end of file diff --git a/InteractiveReadLine.sln b/InteractiveReadLine.sln index 20a8959..1a194d3 100644 --- a/InteractiveReadLine.sln +++ b/InteractiveReadLine.sln @@ -1,37 +1,37 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29409.12 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "InteractiveReadLine", "InteractiveReadLine\InteractiveReadLine.csproj", "{8546DDCA-6845-471C-8AFB-5FCF8BA0ED94}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "InteractiveReadLine.Demo", "InteractiveReadLine.Demo\InteractiveReadLine.Demo.csproj", "{F526E382-8480-4F2C-884A-F806760F7509}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InteractiveReadLine.Tests", "InteractiveReadLine.Tests\InteractiveReadLine.Tests.csproj", "{1D176FC0-C600-4A57-B793-F6B0EA1EEC95}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {8546DDCA-6845-471C-8AFB-5FCF8BA0ED94}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8546DDCA-6845-471C-8AFB-5FCF8BA0ED94}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8546DDCA-6845-471C-8AFB-5FCF8BA0ED94}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8546DDCA-6845-471C-8AFB-5FCF8BA0ED94}.Release|Any CPU.Build.0 = Release|Any CPU - {F526E382-8480-4F2C-884A-F806760F7509}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F526E382-8480-4F2C-884A-F806760F7509}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F526E382-8480-4F2C-884A-F806760F7509}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F526E382-8480-4F2C-884A-F806760F7509}.Release|Any CPU.Build.0 = Release|Any CPU - {1D176FC0-C600-4A57-B793-F6B0EA1EEC95}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1D176FC0-C600-4A57-B793-F6B0EA1EEC95}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1D176FC0-C600-4A57-B793-F6B0EA1EEC95}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1D176FC0-C600-4A57-B793-F6B0EA1EEC95}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {CABE4E9B-B1ED-4959-A514-8FC4BBD45FAE} - EndGlobalSection -EndGlobal + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29409.12 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "InteractiveReadLine", "InteractiveReadLine\InteractiveReadLine.csproj", "{8546DDCA-6845-471C-8AFB-5FCF8BA0ED94}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "InteractiveReadLine.Demo", "InteractiveReadLine.Demo\InteractiveReadLine.Demo.csproj", "{F526E382-8480-4F2C-884A-F806760F7509}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InteractiveReadLine.Tests", "InteractiveReadLine.Tests\InteractiveReadLine.Tests.csproj", "{1D176FC0-C600-4A57-B793-F6B0EA1EEC95}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {8546DDCA-6845-471C-8AFB-5FCF8BA0ED94}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8546DDCA-6845-471C-8AFB-5FCF8BA0ED94}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8546DDCA-6845-471C-8AFB-5FCF8BA0ED94}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8546DDCA-6845-471C-8AFB-5FCF8BA0ED94}.Release|Any CPU.Build.0 = Release|Any CPU + {F526E382-8480-4F2C-884A-F806760F7509}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F526E382-8480-4F2C-884A-F806760F7509}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F526E382-8480-4F2C-884A-F806760F7509}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F526E382-8480-4F2C-884A-F806760F7509}.Release|Any CPU.Build.0 = Release|Any CPU + {1D176FC0-C600-4A57-B793-F6B0EA1EEC95}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1D176FC0-C600-4A57-B793-F6B0EA1EEC95}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1D176FC0-C600-4A57-B793-F6B0EA1EEC95}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1D176FC0-C600-4A57-B793-F6B0EA1EEC95}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {CABE4E9B-B1ED-4959-A514-8FC4BBD45FAE} + EndGlobalSection +EndGlobal diff --git a/InteractiveReadLine/Abstractions/IConsole.cs b/InteractiveReadLine/Abstractions/IConsole.cs index 2e6d218..ea36703 100644 --- a/InteractiveReadLine/Abstractions/IConsole.cs +++ b/InteractiveReadLine/Abstractions/IConsole.cs @@ -1,39 +1,81 @@ -using System; -using InteractiveReadLine.Formatting; - -namespace InteractiveReadLine.Abstractions -{ - /// - /// Defines a provider for a buffer backed, console-like interface. Intended to create a seam between - /// the actual System.Console instance and the higher level behaviors, it can also be used to wrap - /// any character buffer interface with a moving cursor. - /// - public interface IConsole - { - /// - /// Gets or sets the cursor's position from the left edge of the buffer - /// - int CursorLeft { get; set; } - - /// - /// Gets or sets the cursor's position from the top of the buffer - /// - int CursorTop { get; set; } - - /// - /// Gets the height of the provider's buffer, measured in rows - /// - int BufferHeight { get; } - - /// - /// Gets the width of the provider's buffer, measured in columns - /// - int BufferWidth { get; } - - void Write(FormattedText text); - void WriteLine(FormattedText text); - void Write(FormattedChar c); - - ConsoleKeyInfo ReadKey(); - } -} \ No newline at end of file +using System; +using InteractiveReadLine.Formatting; + +namespace InteractiveReadLine.Abstractions +{ + /// + /// Defines a provider for a buffer backed, console-like interface. Intended to create a seam between + /// the actual System.Console instance and the higher level behaviors, it can also be used to wrap + /// any character buffer interface with a moving cursor. + /// + public interface IConsole + { + /// + /// Gets or sets the cursor's position from the left edge of the buffer + /// + int CursorLeft { get; set; } + + /// + /// Gets or sets the cursor's position from the top of the buffer + /// + int CursorTop { get; set; } + + /// + /// Gets the height of the provider's buffer, measured in rows + /// + int BufferHeight { get; } + + /// + /// Gets the width of the provider's buffer, measured in columns + /// + int BufferWidth { get; } + + /// + /// Gets or sets whether Ctrl+C is delivered as an ordinary keypress rather than being treated as a + /// signal to terminate the program. + /// + /// + /// A read line operation enables this property so that a Ctrl+C key behavior can abandon the line, then + /// restores the previous value when the operation finishes. Implementations without a system console + /// can store the value without acting on it. + /// + bool TreatControlCAsInput { get; set; } + + /// + /// Gets whether a keypress is waiting, which lets callers wait for input without blocking on ReadKey. + /// + bool KeyAvailable { get; } + + /// + /// Gets whether input comes from a redirected stream instead of an interactive console. Individual + /// keypresses cannot be read from a redirected stream. + /// + bool InputIsRedirected { get; } + + /// + /// Writes formatted text at the cursor, applies each character's colors, and leaves the cursor after + /// the written text. + /// + /// The text to write. + void Write(FormattedText text); + + /// + /// Writes formatted text at the cursor followed by a newline, leaving the cursor at the start of the + /// following row. + /// + /// The text to write. + void WriteLine(FormattedText text); + + /// + /// Writes a single formatted character at the cursor, applying its colors. + /// + /// The character to write. + void Write(FormattedChar c); + + /// + /// Waits for a keypress and returns it without echoing it to the display. + /// + /// Information about the pressed key. + ConsoleKeyInfo ReadKey(); + } +} diff --git a/InteractiveReadLine/Abstractions/SystemConsoleWrapper.cs b/InteractiveReadLine/Abstractions/SystemConsoleWrapper.cs index 0685216..5e74956 100644 --- a/InteractiveReadLine/Abstractions/SystemConsoleWrapper.cs +++ b/InteractiveReadLine/Abstractions/SystemConsoleWrapper.cs @@ -1,77 +1,125 @@ -using System; -using System.Text; -using InteractiveReadLine.Formatting; - -namespace InteractiveReadLine.Abstractions -{ - /// - /// A wrapper around the System.Console object. This currently only exists to allow unit testing. - /// - internal class SystemConsoleWrapper : IConsole - { - public int CursorLeft - { - get => Console.CursorLeft; - set => Console.CursorLeft = value; - } - - public int CursorTop - { - get => Console.CursorTop; - set => Console.CursorTop = value; - } - - public int BufferHeight => Console.BufferHeight; - - public int BufferWidth => Console.BufferWidth; - - public void Write(FormattedText text) - { - // Break the text into pieces which have the same foreground and background colors, then write them - // to the Console object - var pieces = text.SplitByFormatting(); - - foreach (var piece in pieces) - { - if (piece.Length <= 0) - continue; - - if (piece[0].Foreground == null || piece[0].Background == null) - Console.ResetColor(); - - if (piece[0].Foreground != null) - Console.ForegroundColor = (ConsoleColor) piece[0].Foreground; - - if (piece[0].Background != null) - Console.BackgroundColor = (ConsoleColor) piece[0].Background; - - Console.Write(piece.Text); - } - } - - public void WriteLine(FormattedText text) - { - this.Write(text); - this.Write("\n"); - } - - public void Write(FormattedChar c) - { - // TODO: Is there a more efficient way of dealing with this? - Console.ResetColor(); - - if (c.Foreground != null) - Console.ForegroundColor = (ConsoleColor) c.Foreground; - - if (c.Background != null) - Console.BackgroundColor = (ConsoleColor) c.Background; - - Console.Write(c.Char); - } - - public ConsoleKeyInfo ReadKey() - { - return Console.ReadKey(true); - } - } -} \ No newline at end of file +using System; +using System.IO; +using InteractiveReadLine.Formatting; + +namespace InteractiveReadLine.Abstractions +{ + /// + /// Presents System.Console through the IConsole interface. This default implementation originally existed + /// to support unit testing. It is public so that callers can decorate or compose it to intercept output + /// that read line operations write to the system console. + /// + public class SystemConsoleWrapper : IConsole + { + /// + public int CursorLeft + { + get => Console.CursorLeft; + set => Console.CursorLeft = value; + } + + /// + public int CursorTop + { + get => Console.CursorTop; + set => Console.CursorTop = value; + } + + /// + public int BufferHeight => Console.BufferHeight; + + /// + public int BufferWidth => Console.BufferWidth; + + /// + public bool KeyAvailable => Console.KeyAvailable; + + /// + public bool InputIsRedirected => Console.IsInputRedirected; + + /// + public bool TreatControlCAsInput + { + // Some platforms and processes without an attached console do not support reading or writing this + // property. Because Ctrl+C handling is optional, both accessors suppress the related exceptions. + get + { + try + { + return Console.TreatControlCAsInput; + } + catch (IOException) + { + return false; + } + catch (PlatformNotSupportedException) + { + return false; + } + } + set + { + try + { + Console.TreatControlCAsInput = value; + } + catch (IOException) + { + } + catch (PlatformNotSupportedException) + { + } + } + } + + /// + public void Write(FormattedText text) + { + // Break the text into pieces which have the same foreground and background colors, then write them + // to the Console object + var pieces = text.SplitByFormatting(); + + foreach (var piece in pieces) + { + if (piece.Length <= 0) + continue; + + var foreground = piece[0].Foreground; + var background = piece[0].Background; + + if (foreground == null || background == null) + Console.ResetColor(); + + if (foreground != null) + Console.ForegroundColor = foreground.Value; + + if (background != null) + Console.BackgroundColor = background.Value; + + Console.Write(piece.Text); + } + } + + /// + public void WriteLine(FormattedText text) + { + this.Write(text); + this.Write("\n"); + } + + /// + public void Write(FormattedChar c) + { + // A single character is a one-character run of formatted text, so defer to the text overload to + // reuse its color handling. When the character specifies foreground and background colors, this + // also avoids resetting the console colors immediately before setting both of them. + this.Write(new FormattedText(c)); + } + + /// + public ConsoleKeyInfo ReadKey() + { + return Console.ReadKey(true); + } + } +} diff --git a/InteractiveReadLine/ConsoleReadLine.cs b/InteractiveReadLine/ConsoleReadLine.cs index e2bdc1c..88986d8 100644 --- a/InteractiveReadLine/ConsoleReadLine.cs +++ b/InteractiveReadLine/ConsoleReadLine.cs @@ -1,191 +1,308 @@ -using System; -using System.Collections.Generic; -using InteractiveReadLine.Abstractions; -using InteractiveReadLine.Formatting; - -namespace InteractiveReadLine -{ - /// - /// Exposes a IReadLineProvider that's wrapping a IConsole object, which by default is a wrapper around the System.Console. - /// This class is the standard implementation of a ReadLine provider, intended for use with console applications. - /// - public class ConsoleReadLine : IReadLineProvider - { - private readonly IConsole _console; - private FormattedText _lastWrittenText; - private int _lastWrittenCursor; - private int _startingRow; - - public ConsoleReadLine(IConsole console=null) - { - _console = console ?? new SystemConsoleWrapper(); - this.Start(); - } - - /// - /// Reads a console key from the underlying provider. This method blocks until a key is received. - /// - /// - public ConsoleKeyInfo ReadKey() - { - return _console.ReadKey(); - } - - /// - /// Sets the display state on the underlying console, consisting of a prefix, body, suffix, and cursor - /// position. - /// - /// - public void SetDisplay(LineDisplayState state) - { - var totalText = state.Prefix + state.LineBody + state.Suffix; - var cursor = state.Prefix.Length + state.Cursor; - this.SetText(totalText, cursor); - } - - /// - /// Sets the read line to contain the specified text and cursor position. - /// - /// - /// - private void SetText(FormattedText totalText, int cursorPos) - { - // The process of setting the input text requires us to find the difference between - // the last written text and the new text, then perform the minimum amount of character - // writes necessary to make the two identical - - // First, we should determine what the new line needs to look like. If the new line is - // longer than the old line, we will write the new line exactly. If it's shorter, we'll - // need to pad it out with empty characters - var writeText = (totalText.Length >= _lastWrittenText.Length) - ? totalText - : totalText + new string(' ', _lastWrittenText.Length - totalText.Length); - - // Sweep through each character in the text to write and determine if an edit needs to be - // made (or does the FormattedChar match what was last written at this position?) - // Cluster the edits into contiguous FormattedText objects, each with a cursor start position. - var edits = new List>(); - - Tuple edit = null; - - for (int i = 0; i < writeText.Length; i++) - { - if (i < _lastWrittenText.Length && writeText[i].Equals(_lastWrittenText[i])) - { - if (edit != null) - { - edits.Add(edit); - edit = null; - } - - continue; - } - - if (edit == null) - { - edit = new Tuple(i, writeText[i]); - } - else - { - edit = new Tuple(edit.Item1, edit.Item2 + writeText[i]); - } - - /* - int left = this.ColOffset(i); - int top = this.RowOffset(i) + _startingRow; - - if (left != _console.CursorLeft) - _console.CursorLeft = left; - if (top != _console.CursorTop) - _console.CursorTop = top; - - _console.Write(writeText[i]); - */ - } - if (edit != null) - edits.Add(edit); - - foreach (var e in edits) - { - - int left = this.ColOffset(e.Item1); - int top = this.RowOffset(e.Item1) + _startingRow; - - if (left != _console.CursorLeft) - _console.CursorLeft = left; - if (top != _console.CursorTop) - _console.CursorTop = top; - - _console.Write(e.Item2); - } - - _lastWrittenText = totalText; - - // Check if we shifted down the buffer. In certain cases, if we reach the end of the buffer - // height and we skip a line, the System.Console shifts everything up, and our starting row - // will effectively be less than where we started. It will never move down. - var writtenRowOffset = this.RowOffset(_lastWrittenText.Length); - if (writtenRowOffset + _startingRow >= _console.BufferHeight) - { - _startingRow = _console.BufferHeight - writtenRowOffset - 1; - } - - _console.CursorTop = _startingRow + this.RowOffset(cursorPos); - _console.CursorLeft = this.ColOffset(cursorPos); - _lastWrittenCursor = cursorPos; - } - - /// - /// Writes a message out to the console out in the spot where the current read line input is, then - /// immediately re-displays the line input on the next row. - /// - /// The text to write to the console, a newline char will be added automatically - public void InsertText(FormattedText text) - { - var currentText = _lastWrittenText; - var currentCursor = _lastWrittenCursor; - - SetText(text, text.Length); - _console.WriteLine(""); - - _startingRow = _console.CursorTop; - _lastWrittenText = ""; - _lastWrittenCursor = 0; - SetText(currentText, currentCursor); - - } - - public void Dispose() - { - this.Finish(); - } - - private void Start() - { - // _console.WriteLine(string.Empty); - _startingRow = _console.CursorTop; - _console.CursorLeft = 0; - _lastWrittenText = string.Empty; - } - - private void Finish() - { - _console.WriteLine(string.Empty); - } - - private int ColOffset(int length) => length % _console.BufferWidth; - - private int RowOffset(int length) => (length - this.ColOffset(length)) / _console.BufferWidth; - - /// - /// Provides a convenient static method of calling the ReadLine method on the System.Console - /// - /// - /// - public static string ReadLine(ReadLineConfig config=null) - { - var provider = new ConsoleReadLine(); - return provider.ReadLine(config ?? ReadLineConfig.Basic); - } - } -} \ No newline at end of file +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using InteractiveReadLine.Abstractions; +using InteractiveReadLine.Formatting; + +namespace InteractiveReadLine +{ + /// + /// Exposes a IReadLineProvider that's wrapping a IConsole object, which by default is a wrapper around the System.Console. + /// This class is the standard implementation of a ReadLine provider, intended for use with console applications. + /// + public class ConsoleReadLine : IReadLineProvider + { + /// + /// The delay, in milliseconds, between keypress checks during a cancelable read. + /// + private const int PollIntervalMilliseconds = 15; + + private readonly IConsole _console; + private FormattedText _lastWrittenText = string.Empty; + private int _lastWrittenCursor; + private int _startingRow; + private bool _disposed; + private bool _previousTreatControlCAsInput; + + /// + /// Creates a read-line provider over the specified console, or System.Console when no console is given. + /// + /// The console to use, or null to use System.Console. + /// The selected console reports redirected input. + public ConsoleReadLine(IConsole? console=null) + { + _console = console ?? new SystemConsoleWrapper(); + this.Start(); + } + + /// + /// Reads a console key from the underlying provider, waiting until one is received. + /// + /// A token that cancels the wait. + /// The next keypress. + /// The token was canceled before a key arrived. + public ConsoleKeyInfo ReadKey(CancellationToken cancellationToken = default) + { + // A console read cannot be interrupted after it blocks. When a token can be canceled, wait for a + // key to become available and check the token between polls. Then perform the nonblocking read. + if (!cancellationToken.CanBeCanceled) + return _console.ReadKey(); + + cancellationToken.ThrowIfCancellationRequested(); + + while (!_console.KeyAvailable) + { + Thread.Sleep(PollIntervalMilliseconds); + cancellationToken.ThrowIfCancellationRequested(); + } + + return _console.ReadKey(); + } + + /// + /// Reads a console key from the underlying provider, waiting asynchronously until one is received. + /// + /// + /// No asynchronous console input API is available. This method therefore polls until a key is available + /// and then reads it without blocking. It polls even when the token cannot be canceled because an + /// asynchronous read must not block. No thread is occupied between polls. + /// + /// A token that cancels the wait. + /// A task producing the next keypress. + /// The token was canceled before a key arrived. + public async Task ReadKeyAsync(CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + while (!_console.KeyAvailable) + { + await Task.Delay(PollIntervalMilliseconds, cancellationToken).ConfigureAwait(false); + } + + return _console.ReadKey(); + } + + /// + /// Sets the display state on the underlying console, consisting of a prefix, body, suffix, and cursor + /// position. + /// + /// + public void SetDisplay(LineDisplayState state) + { + var totalText = state.Prefix + state.LineBody + state.Suffix; + var cursor = state.Prefix.Length + state.Cursor; + this.SetText(totalText, cursor); + } + + /// + /// Sets the read line to contain the specified text and cursor position. + /// + /// + /// + private void SetText(FormattedText totalText, int cursorPos) + { + // The process of setting the input text requires us to find the difference between + // the last written text and the new text, then perform the minimum amount of character + // writes necessary to make the two identical + + // First, we should determine what the new line needs to look like. If the new line is + // longer than the old line, we will write the new line exactly. If it's shorter, we'll + // need to pad it out with empty characters + var writeText = (totalText.Length >= _lastWrittenText.Length) + ? totalText + : totalText + new string(' ', _lastWrittenText.Length - totalText.Length); + + // Sweep through each character in the text to write and determine if an edit needs to be + // made (or does the FormattedChar match what was last written at this position?) + // Cluster the edits into contiguous FormattedText objects, each with a cursor start position. + var edits = new List>(); + + Tuple? edit = null; + + for (int i = 0; i < writeText.Length; i++) + { + if (i < _lastWrittenText.Length && writeText[i].Equals(_lastWrittenText[i])) + { + if (edit != null) + { + edits.Add(edit); + edit = null; + } + + continue; + } + + if (edit == null) + { + edit = new Tuple(i, writeText[i]); + } + else + { + edit = new Tuple(edit.Item1, edit.Item2 + writeText[i]); + } + } + if (edit != null) + edits.Add(edit); + + foreach (var e in edits) + { + int left = this.ColOffset(e.Item1); + int top = this.RowOffset(e.Item1) + _startingRow; + + if (left != _console.CursorLeft) + _console.CursorLeft = left; + if (top != _console.CursorTop) + _console.CursorTop = top; + + _console.Write(e.Item2); + } + + _lastWrittenText = totalText; + + // Check if we shifted down the buffer. In certain cases, if we reach the end of the buffer + // height and we skip a line, the System.Console shifts everything up, and our starting row + // will effectively be less than where we started. It will never move down. + var writtenRowOffset = this.RowOffset(_lastWrittenText.Length); + if (writtenRowOffset + _startingRow >= _console.BufferHeight) + { + _startingRow = _console.BufferHeight - writtenRowOffset - 1; + } + + _console.CursorTop = _startingRow + this.RowOffset(cursorPos); + _console.CursorLeft = this.ColOffset(cursorPos); + _lastWrittenCursor = cursorPos; + } + + /// + /// Writes a message out to the console out in the spot where the current read line input is, then + /// immediately re-displays the line input on the next row. + /// + /// The text to write to the console, a newline char will be added automatically + public void InsertText(FormattedText text) + { + var currentText = _lastWrittenText; + var currentCursor = _lastWrittenCursor; + + SetText(text, text.Length); + _console.WriteLine(""); + + _startingRow = _console.CursorTop; + _lastWrittenText = ""; + _lastWrittenCursor = 0; + SetText(currentText, currentCursor); + + } + + /// + /// Finishes the read line operation and moves the console cursor to the following row. Additional calls + /// have no effect. + /// + public void Dispose() + { + if (_disposed) + return; + + _disposed = true; + this.Finish(); + } + + private void Start() + { + // Reading individual keypresses is impossible when input comes from a pipe or a file, and the + // underlying console throws an unhelpful error deep inside the first read. Failing here instead + // says what is actually wrong. + if (_console.InputIsRedirected) + throw new InvalidOperationException( + "ConsoleReadLine requires an interactive console, but standard input has been redirected. " + + "Individual keypresses cannot be read from a redirected stream. Read the input with " + + "Console.ReadLine, or supply a custom IReadLineProvider for this scenario."); + + // _console.WriteLine(string.Empty); + _startingRow = _console.CursorTop; + _console.CursorLeft = 0; + _lastWrittenText = string.Empty; + + // Ctrl+C would otherwise terminate the process instead of reaching a key behavior. The previous + // setting is captured so that it can be restored when the operation finishes. + _previousTreatControlCAsInput = _console.TreatControlCAsInput; + _console.TreatControlCAsInput = true; + } + + private void Finish() + { + _console.TreatControlCAsInput = _previousTreatControlCAsInput; + _console.WriteLine(string.Empty); + } + + private int ColOffset(int length) => length % _console.BufferWidth; + + private int RowOffset(int length) => (length - this.ColOffset(length)) / _console.BufferWidth; + + /// + /// Provides a convenient static method of calling the ReadLine method on the System.Console + /// + /// The configuration to use, or null to use ReadLineConfig.Basic. + /// A token that cancels the read. + /// + /// The finished text; null if the user signaled the end of input with Ctrl+D; or an empty string if the + /// user abandoned the line with Ctrl+C. Use Read to distinguish these outcomes. + /// + /// The token was canceled before input completed. + /// Standard input is redirected. + public static string? ReadLine(ReadLineConfig? config=null, CancellationToken cancellationToken=default) + { + var provider = new ConsoleReadLine(); + return provider.ReadLine(config ?? ReadLineConfig.Basic, cancellationToken); + } + + /// + /// Reads a line from System.Console and returns a result that describes the text and how the + /// user ended the interaction. + /// + /// The configuration to use, or null to use ReadLineConfig.Basic. + /// A token that cancels the read. + /// The completed interaction result. + /// The token was canceled before input completed. + /// Standard input is redirected. + public static ReadLineResult Read(ReadLineConfig? config=null, CancellationToken cancellationToken=default) + { + var provider = new ConsoleReadLine(); + return provider.Read(config ?? ReadLineConfig.Basic, cancellationToken); + } + + /// + /// Reads a line from System.Console without blocking a thread while waiting for keys. + /// + /// The configuration to use, or null to use ReadLineConfig.Basic. + /// A token that cancels the read. + /// + /// The finished text; null if the user signaled the end of input with Ctrl+D; or an empty string if the + /// user abandoned the line with Ctrl+C. Use ReadAsync to distinguish these outcomes. + /// + /// The token was canceled before input completed. + /// Standard input is redirected. + public static Task ReadLineAsync(ReadLineConfig? config=null, + CancellationToken cancellationToken=default) + { + var provider = new ConsoleReadLine(); + return provider.ReadLineAsync(config ?? ReadLineConfig.Basic, cancellationToken); + } + + /// + /// Reads a line from System.Console without blocking a thread while waiting for keys, returning a + /// result that describes the text and how the user ended the interaction. + /// + /// The configuration to use, or null to use ReadLineConfig.Basic. + /// A token that cancels the read. + /// A task producing the completed interaction result. + /// The token was canceled before input completed. + /// Standard input is redirected. + public static Task ReadAsync(ReadLineConfig? config=null, + CancellationToken cancellationToken=default) + { + var provider = new ConsoleReadLine(); + return provider.ReadAsync(config ?? ReadLineConfig.Basic, cancellationToken); + } + } +} diff --git a/InteractiveReadLine/ExtensionMethods.cs b/InteractiveReadLine/ExtensionMethods.cs index 32a3650..4ba3b6b 100644 --- a/InteractiveReadLine/ExtensionMethods.cs +++ b/InteractiveReadLine/ExtensionMethods.cs @@ -1,25 +1,106 @@ -using System.Runtime.CompilerServices; - -namespace InteractiveReadLine -{ - public static class ExtensionMethods - { - /// - /// Interactively read a line of text from the provider, using a specified configuration if one is - /// given as an optional argument. - /// - /// the IReadLineProvider provider which will perform the interaction with the user (for - /// example, the ConsoleReadLine object which wraps System.Console) - /// The configuration to use for this specific interaction - /// the text read from the user - public static string ReadLine(this IReadLineProvider provider, ReadLineConfig config=null) - { - using (provider) - { - var handler = new ReadLineHandler(provider, config); - return handler.ReadLine(); - } - } - - } -} \ No newline at end of file +using System.Threading; +using System.Threading.Tasks; + +namespace InteractiveReadLine +{ + /// + /// Provides methods that drive a provider through one line of input. Each method runs the interaction + /// through a handler and disposes the provider before returning. + /// + public static class ExtensionMethods + { + /// + /// Interactively read a line of text from the provider, using a specified configuration if one is + /// given as an optional argument. + /// + /// the IReadLineProvider provider which will perform the interaction with the user (for + /// example, the ConsoleReadLine object which wraps System.Console) + /// The configuration to use for this specific interaction + /// A token that cancels the read. + /// + /// The text read from the user; null if the user signaled the end of input; or an empty string if the + /// user abandoned the line. Use Read to distinguish an abandoned line from an entered empty line. + /// + /// + /// The token was canceled before input completed. + /// + public static string? ReadLine(this IReadLineProvider provider, ReadLineConfig? config=null, + CancellationToken cancellationToken=default) + { + return provider.Read(config, cancellationToken).ToText(); + } + + /// + /// Interactively reads a line of text from the provider and returns a result that describes the text + /// and how the user ended the interaction. The method disposes the provider before returning. + /// + /// the IReadLineProvider provider which will perform the interaction with the user (for + /// example, the ConsoleReadLine object which wraps System.Console) + /// The configuration to use for this specific interaction + /// + /// A token that cancels the read. The provider is still disposed if the read is canceled, so the + /// console is left in the state it would have been after an ordinary read. + /// + /// The completed interaction result. + /// + /// The token was canceled before input completed. + /// + public static ReadLineResult Read(this IReadLineProvider provider, ReadLineConfig? config=null, + CancellationToken cancellationToken=default) + { + using (provider) + { + var handler = new ReadLineHandler(provider, config); + return handler.Read(cancellationToken); + } + } + + /// + /// Interactively reads a line of text from the provider without blocking a thread while waiting for + /// keys. The method disposes the provider before returning. + /// + /// the IReadLineProvider provider which will perform the interaction with the user (for + /// example, the ConsoleReadLine object which wraps System.Console) + /// The configuration to use for this specific interaction + /// A token that cancels the read. + /// + /// The text read from the user; null if the user signaled the end of input; or an empty string if the + /// user abandoned the line. Use ReadAsync to distinguish an abandoned line from an entered empty line. + /// + /// + /// The token was canceled before input completed. + /// + public static async Task ReadLineAsync(this IReadLineProvider provider, ReadLineConfig? config=null, + CancellationToken cancellationToken=default) + { + var result = await provider.ReadAsync(config, cancellationToken).ConfigureAwait(false); + return result.ToText(); + } + + /// + /// Interactively reads a line of text from the provider without blocking a thread while waiting for + /// keys, returning a result that describes the text and how the user ended the interaction. The method + /// disposes the provider before returning. + /// + /// the IReadLineProvider provider which will perform the interaction with the user (for + /// example, the ConsoleReadLine object which wraps System.Console) + /// The configuration to use for this specific interaction + /// + /// A token that cancels the read. The provider is still disposed if the read is canceled, so the + /// console is left in the state it would have been after an ordinary read. + /// + /// The completed interaction result. + /// + /// The token was canceled before input completed. + /// + public static async Task ReadAsync(this IReadLineProvider provider, ReadLineConfig? config=null, + CancellationToken cancellationToken=default) + { + using (provider) + { + var handler = new ReadLineHandler(provider, config); + return await handler.ReadAsync(cancellationToken).ConfigureAwait(false); + } + } + } +} diff --git a/InteractiveReadLine/Formatting/CommonFormatters.cs b/InteractiveReadLine/Formatting/CommonFormatters.cs index 606e10d..eb9ab73 100644 --- a/InteractiveReadLine/Formatting/CommonFormatters.cs +++ b/InteractiveReadLine/Formatting/CommonFormatters.cs @@ -1,72 +1,80 @@ -using System; -using System.Security.Cryptography; -using System.Text; -using LineFormatter = System.Func; -using TokenFormatter = System.Func; - -namespace InteractiveReadLine.Formatting -{ - public static class CommonFormatters - { - /// - /// Provides a formatter that displays a fixed prompt in front of the input line, or wraps another - /// formatter overwriting its prefix with the supplied prompt - /// - /// the prompt text to display - /// - public static LineFormatter FixedPrompt(FormattedText prompt, LineFormatter formatter = null) - { - return state => - { - if (formatter == null) - return new LineDisplayState(prompt, state.Text, string.Empty, state.Cursor); - var result = formatter.Invoke(state); - return new LineDisplayState(prompt, result.LineBody, result.Suffix, result.Cursor); - }; - } - - /// - /// A formatter that blanks out the entered characters, and has no prefix or suffix - /// - public static LineFormatter PasswordBlank => - state => new LineDisplayState(string.Empty, string.Empty, string.Empty, 0); - - /// - /// A formatter that puts out a variable length bar based on the 1st and 10th bytes in a SHA256 hash - /// of the entered password. Provides repeatable visual feedback without revealing anything about the - /// password itself - /// - public static LineFormatter PasswordBar => - state => - { - var hash = SHA256.Create(); - var result = hash.ComputeHash(Encoding.ASCII.GetBytes(state.Text)); - var l1 = (int) Math.Round(20.0 * result[0] / 255.0); - var l2 = (int) Math.Round(20.0 * result[10] / 255.0); - var builder = new StringBuilder("["); - for (var i = 0; i < 20; i++) - if (i < l1 && i < l2 || i > l1 && i > l2) - builder.Append(' '); - else - builder.Append('='); - - builder.Append(']'); - - return new LineDisplayState(string.Empty, builder.ToString(), string.Empty, builder.Length); - }; - - - /// - /// A formatter that converts the password characters to stars - /// - public static LineFormatter PasswordStars => - state => new LineDisplayState(string.Empty, new string('*', state.Text.Length), string.Empty, state.Cursor); - - - /// - /// Adds a fixed prompt to the given formatter, overwriting the prefix - /// - public static LineFormatter WithFixedPrompt(this LineFormatter formatter, FormattedText prompt) => FixedPrompt(prompt, formatter); - - } -} \ No newline at end of file +using System; +using System.Security.Cryptography; +using System.Text; +using LineFormatter = System.Func; +using TokenFormatter = System.Func; + +namespace InteractiveReadLine.Formatting +{ + /// + /// Provides ready-made formatters that add a prompt, hide text, or apply colors before displaying a line. + /// A formatter does not alter the text that the user is editing. + /// + public static class CommonFormatters + { + /// + /// Provides a formatter that displays a fixed prompt in front of the input line, or wraps another + /// formatter overwriting its prefix with the supplied prompt + /// + /// the prompt text to display + /// + public static LineFormatter FixedPrompt(FormattedText prompt, LineFormatter? formatter = null) + { + return state => + { + if (formatter == null) + return new LineDisplayState(prompt, state.Text, string.Empty, state.Cursor); + var result = formatter.Invoke(state); + return new LineDisplayState(prompt, result.LineBody, result.Suffix, result.Cursor); + }; + } + + /// + /// A formatter that blanks out the entered characters, and has no prefix or suffix + /// + public static LineFormatter PasswordBlank => + state => new LineDisplayState(string.Empty, string.Empty, string.Empty, 0); + + /// + /// A formatter that displays a variable-length bar based on the first and tenth bytes of a SHA256 hash + /// of the entered password's UTF-8 bytes. The bar provides repeatable visual feedback without revealing + /// the password itself. + /// + public static LineFormatter PasswordBar => + state => + { + byte[] result; + using (var hash = SHA256.Create()) + { + result = hash.ComputeHash(Encoding.UTF8.GetBytes(state.Text)); + } + + var l1 = (int) Math.Round(20.0 * result[0] / 255.0); + var l2 = (int) Math.Round(20.0 * result[10] / 255.0); + var builder = new StringBuilder("["); + for (var i = 0; i < 20; i++) + if (i < l1 && i < l2 || i > l1 && i > l2) + builder.Append(' '); + else + builder.Append('='); + + builder.Append(']'); + + return new LineDisplayState(string.Empty, builder.ToString(), string.Empty, builder.Length); + }; + + + /// + /// A formatter that converts the password characters to stars + /// + public static LineFormatter PasswordStars => + state => new LineDisplayState(string.Empty, new string('*', state.Text.Length), string.Empty, state.Cursor); + + + /// + /// Adds a fixed prompt to the given formatter, overwriting the prefix + /// + public static LineFormatter WithFixedPrompt(this LineFormatter formatter, FormattedText prompt) => FixedPrompt(prompt, formatter); + + } +} diff --git a/InteractiveReadLine/Formatting/FormattedChar.cs b/InteractiveReadLine/Formatting/FormattedChar.cs index ada61f3..da9d31c 100644 --- a/InteractiveReadLine/Formatting/FormattedChar.cs +++ b/InteractiveReadLine/Formatting/FormattedChar.cs @@ -8,6 +8,13 @@ namespace InteractiveReadLine.Formatting /// public struct FormattedChar : IEquatable { + /// + /// Creates a character with the specified foreground and background colors. Either color can be null + /// to use the display default. + /// + /// The character. + /// The foreground color, or null to use the display default. + /// The background color, or null to use the display default. public FormattedChar(char c, ConsoleColor? foreground, ConsoleColor? background) { Char = c; @@ -15,20 +22,34 @@ public FormattedChar(char c, ConsoleColor? foreground, ConsoleColor? background) Background = background; } + /// + /// Gets the character without its formatting. + /// public char Char { get; } + /// + /// Gets the foreground color, or null when the display default should be used. + /// public ConsoleColor? Foreground { get; } + /// + /// Gets the background color, or null when the display default should be used. + /// public ConsoleColor? Background { get; } + /// + /// Determines whether this instance and another formatted character have the same character and colors. + /// public bool Equals(FormattedChar other) { return Char == other.Char && Foreground == other.Foreground && Background == other.Background; } - public override bool Equals(object obj) + /// + public override bool Equals(object? obj) { return obj is FormattedChar other && Equals(other); } + /// public override int GetHashCode() { unchecked @@ -40,4 +61,4 @@ public override int GetHashCode() } } } -} \ No newline at end of file +} diff --git a/InteractiveReadLine/Formatting/FormattedText.cs b/InteractiveReadLine/Formatting/FormattedText.cs index e522609..2f1ed22 100644 --- a/InteractiveReadLine/Formatting/FormattedText.cs +++ b/InteractiveReadLine/Formatting/FormattedText.cs @@ -1,169 +1,203 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data.Common; -using System.Linq; -using System.Net.Mime; -using System.Runtime.InteropServices.ComTypes; -using System.Text; - -namespace InteractiveReadLine.Formatting -{ - /// - /// Represents a formatted string, where each character has a potentially unique foreground and background - /// color assigned to it. - /// - public class FormattedText : IEquatable - { - public FormattedText(string text, ConsoleColor? foreground = null, ConsoleColor? background = null) - { - this.Text = text; - this.Foreground = new ConsoleColor?[this.Text.Length]; - this.Background = new ConsoleColor?[this.Text.Length]; - - for (int i = 0; i < this.Text.Length; i++) - { - this.Foreground[i] = foreground; - this.Background[i] = background; - } - } - - public FormattedText(FormattedChar c) - : this(c.Char.ToString(), c.Foreground, c.Background) - { - } - - /// - /// Gets the characters in the text as a string without any formatting - /// - public string Text { get; } - - /// - /// Gets the length of the text - /// - public int Length => Text.Length; - - /// - /// Gets the character and its formatting at position i in the text - /// - /// - public FormattedChar this[int index] => new FormattedChar(this.Text[index], this.Foreground[index], this.Background[index]); - - /// - /// Gets the foreground color array of the text - /// - public ConsoleColor?[] Foreground { get; } - - /// - /// Gets the background color array of the text - /// - public ConsoleColor?[] Background { get; } - - /// - /// Sets the foreground color for every character in the text - /// - /// - public void SetForeground(ConsoleColor? color) - { - for (int i = 0; i < this.Text.Length; i++) - { - Foreground[i] = color; - } - } - - /// - /// Sets the background color for every character in the text - /// - /// - public void SetBackground(ConsoleColor? color) - { - for (int i = 0; i < this.Text.Length; i++) - { - Background[i] = color; - } - } - - /// - /// Splits the formatted text object into an array of FormattedText objects, in which each element of the array - /// consists of text where every character has the same foreground and background colors. - /// - /// - public FormattedText[] SplitByFormatting() - { - if (this.Text == string.Empty) - { - return Array.Empty(); - } - - var result = new List(); - - var buffer = new StringBuilder(); - ConsoleColor? fore = null; - ConsoleColor? back = null; - - buffer.Append(this.Text[0]); - fore = this.Foreground[0]; - back = this.Background[0]; - - for (int i = 1; i < this.Text.Length; i++) - { - if (fore != this.Foreground[i] || back != this.Background[i]) - { - // Either the foreground or the background has changed, so we need to - // finish the existing buffer and start a new one - result.Add(new FormattedText(buffer.ToString(), fore, back)); - - buffer.Clear(); - fore = this.Foreground[i]; - back = this.Background[i]; - } - - buffer.Append(this.Text[i]); - } - - // Add the final buffer - result.Add(new FormattedText(buffer.ToString(), fore, back)); - - return result.ToArray(); - } - - public static implicit operator FormattedText(string s) => new FormattedText(s); - - public static implicit operator FormattedText(FormattedChar c) => new FormattedText(c); - - public static FormattedText operator +(FormattedText lhs, FormattedText rhs) - { - var product = new FormattedText(lhs.Text + rhs.Text); - for (int i = 0; i < lhs.Text.Length; i++) - { - product.Foreground[i] = lhs.Foreground[i]; - product.Background[i] = lhs.Background[i]; - } - - for (int i = 0; i < rhs.Text.Length; i++) - { - product.Foreground[i + lhs.Text.Length] = rhs.Foreground[i]; - product.Background[i + lhs.Text.Length] = rhs.Background[i]; - } - - return product; - } - - public bool Equals(FormattedText other) - { - if (other == null || this.Text != other.Text) - return false; - - for (int i = 0; i < this.Length; i++) - { - if (this.Foreground[i] != other.Foreground[i]) - return false; - - if (this.Background[i] != other.Background[i]) - return false; - } - - return true; - } - } -} \ No newline at end of file +using System; +using System.Collections.Generic; +using System.Text; + +namespace InteractiveReadLine.Formatting +{ + /// + /// Represents a formatted string, where each character has a potentially unique foreground and background + /// color assigned to it. + /// + public class FormattedText : IEquatable + { + /// + /// Creates formatted text whose characters all have the specified foreground and background colors. + /// Either color can be null to use the display default. + /// + /// The text. + /// The foreground color, or null to use the display default. + /// The background color, or null to use the display default. + /// The text is null. + public FormattedText(string text, ConsoleColor? foreground = null, ConsoleColor? background = null) + { + this.Text = text ?? throw new ArgumentNullException(nameof(text)); + this.Foreground = new ConsoleColor?[this.Text.Length]; + this.Background = new ConsoleColor?[this.Text.Length]; + + for (int i = 0; i < this.Text.Length; i++) + { + this.Foreground[i] = foreground; + this.Background[i] = background; + } + } + + /// + /// Creates formatted text containing one character and its colors. + /// + /// The character used to create the text. + public FormattedText(FormattedChar c) + : this(c.Char.ToString(), c.Foreground, c.Background) + { + } + + /// + /// Gets the characters in the text as a string without any formatting + /// + public string Text { get; } + + /// + /// Gets the length of the text + /// + public int Length => Text.Length; + + /// + /// Gets the character and its formatting at position i in the text + /// + /// + public FormattedChar this[int index] => new FormattedChar(this.Text[index], this.Foreground[index], this.Background[index]); + + /// + /// Gets the foreground color array of the text + /// + public ConsoleColor?[] Foreground { get; } + + /// + /// Gets the background color array of the text + /// + public ConsoleColor?[] Background { get; } + + /// + /// Sets the foreground color for every character in the text + /// + /// + public void SetForeground(ConsoleColor? color) + { + for (int i = 0; i < this.Text.Length; i++) + { + Foreground[i] = color; + } + } + + /// + /// Sets the background color for every character in the text + /// + /// + public void SetBackground(ConsoleColor? color) + { + for (int i = 0; i < this.Text.Length; i++) + { + Background[i] = color; + } + } + + /// + /// Splits the formatted text object into an array of FormattedText objects, in which each element of the array + /// consists of text where every character has the same foreground and background colors. + /// + /// + public FormattedText[] SplitByFormatting() + { + if (this.Text == string.Empty) + { + return Array.Empty(); + } + + var result = new List(); + + var buffer = new StringBuilder(); + ConsoleColor? fore = null; + ConsoleColor? back = null; + + buffer.Append(this.Text[0]); + fore = this.Foreground[0]; + back = this.Background[0]; + + for (int i = 1; i < this.Text.Length; i++) + { + if (fore != this.Foreground[i] || back != this.Background[i]) + { + // Either the foreground or the background has changed, so we need to + // finish the existing buffer and start a new one + result.Add(new FormattedText(buffer.ToString(), fore, back)); + + buffer.Clear(); + fore = this.Foreground[i]; + back = this.Background[i]; + } + + buffer.Append(this.Text[i]); + } + + // Add the final buffer + result.Add(new FormattedText(buffer.ToString(), fore, back)); + + return result.ToArray(); + } + + /// + /// Converts a plain string to formatted text which uses the display's default colors. + /// + public static implicit operator FormattedText(string s) => new FormattedText(s); + + /// + /// Converts a single formatted character to formatted text of length one. + /// + public static implicit operator FormattedText(FormattedChar c) => new FormattedText(c); + + /// + /// Joins two pieces of formatted text, preserving the colors each character already carried. + /// + public static FormattedText operator +(FormattedText lhs, FormattedText rhs) + { + var product = new FormattedText(lhs.Text + rhs.Text); + for (int i = 0; i < lhs.Text.Length; i++) + { + product.Foreground[i] = lhs.Foreground[i]; + product.Background[i] = lhs.Background[i]; + } + + for (int i = 0; i < rhs.Text.Length; i++) + { + product.Foreground[i + lhs.Text.Length] = rhs.Foreground[i]; + product.Background[i + lhs.Text.Length] = rhs.Background[i]; + } + + return product; + } + + /// + /// Determines whether this instance and another FormattedText instance contain identical characters + /// and identical per-character foreground and background colors. + /// + public bool Equals(FormattedText? other) + { + if (other == null || this.Text != other.Text) + return false; + + for (int i = 0; i < this.Length; i++) + { + if (this.Foreground[i] != other.Foreground[i]) + return false; + + if (this.Background[i] != other.Background[i]) + return false; + } + + return true; + } + + /// + public override bool Equals(object? obj) => this.Equals(obj as FormattedText); + + /// + /// Gets a hash code derived from the characters of the text, ignoring the colors. + /// + /// + /// The color arrays are mutable and publicly accessible, so including them would let an instance's hash + /// code change while the instance is in a hash-based collection. Hashing only the text keeps the hash + /// code stable for the lifetime of the instance and satisfies the contract because equal instances + /// contain the same text. Instances that differ only by color can have the same hash code. + /// + public override int GetHashCode() => this.Text.GetHashCode(); + } +} diff --git a/InteractiveReadLine/Formatting/LineDisplayState.cs b/InteractiveReadLine/Formatting/LineDisplayState.cs index c53c753..d88e0e8 100644 --- a/InteractiveReadLine/Formatting/LineDisplayState.cs +++ b/InteractiveReadLine/Formatting/LineDisplayState.cs @@ -1,50 +1,58 @@ -namespace InteractiveReadLine.Formatting -{ - /// - /// Holds all of the information to present to the user through the view. The LineDisplayState is typically - /// the output of a formatter, and is intended to be written directly to an IReadLineProvider - /// - /// - /// The LineDisplayState is the output of a formatter, which is a function which receives either a LineState or - /// a TokenizedLine object and returns a LineDisplayState. - /// - /// A LineDisplayState consists of three pieces of formatted text in addition to a cursor position. The - /// actual presentation of the LineDisplayState is the responsibility of the IReadLineProvider, but it is - /// typically intended that the prefix be written first (like a prompt), the line body in the middle, and - /// the suffix at the end. The cursor should be located as an offset of the first character of the line - /// body in order to visually align with how the ReadLineHandler will perform character inserts. - /// - /// Text and word wrapping is left up to the provider. - /// - public class LineDisplayState - { - public LineDisplayState(FormattedText prefix, FormattedText lineBody, FormattedText suffix, int cursor) - { - Prefix = prefix; - LineBody = lineBody; - Suffix = suffix; - Cursor = cursor; - } - - /// - /// Gets the prefix, which is displayed before the line body - /// - public FormattedText Prefix { get; } - - /// - /// Gets the line's body text, which is typically the text entered by the user or some representation of - /// what they've entered - /// - public FormattedText LineBody { get; } - - /// - /// Gets the position of the cursor as an integer offset from the beginning of the LineBody - /// - public int Cursor { get; } - - /// - /// Gets the suffix, which is displayed after the line body - /// - public FormattedText Suffix { get; } - } -} \ No newline at end of file +namespace InteractiveReadLine.Formatting +{ + /// + /// Holds all of the information to present to the user through the view. The LineDisplayState is typically + /// the output of a formatter, and is intended to be written directly to an IReadLineProvider + /// + /// + /// The LineDisplayState is the output of a formatter, which is a function which receives either a LineState or + /// a TokenizedLine object and returns a LineDisplayState. + /// + /// A LineDisplayState consists of three pieces of formatted text in addition to a cursor position. The + /// actual presentation of the LineDisplayState is the responsibility of the IReadLineProvider, but it is + /// typically intended that the prefix be written first (like a prompt), the line body in the middle, and + /// the suffix at the end. The cursor should be located as an offset of the first character of the line + /// body in order to visually align with how the ReadLineHandler will perform character inserts. + /// + /// Text and word wrapping is left up to the provider. + /// + public class LineDisplayState + { + /// + /// Creates a display state from the line body, its surrounding text, and the cursor position within + /// the body. + /// + /// Text displayed before the line, such as a prompt. + /// The displayed form of the line being edited. + /// Text displayed after the line, such as a hint. + /// The cursor position, measured from the start of the body. + public LineDisplayState(FormattedText prefix, FormattedText lineBody, FormattedText suffix, int cursor) + { + Prefix = prefix; + LineBody = lineBody; + Suffix = suffix; + Cursor = cursor; + } + + /// + /// Gets the prefix, which is displayed before the line body + /// + public FormattedText Prefix { get; } + + /// + /// Gets the line's body text, which is typically the text entered by the user or some representation of + /// what they've entered + /// + public FormattedText LineBody { get; } + + /// + /// Gets the position of the cursor as an integer offset from the beginning of the LineBody + /// + public int Cursor { get; } + + /// + /// Gets the suffix, which is displayed after the line body + /// + public FormattedText Suffix { get; } + } +} diff --git a/InteractiveReadLine/IReadLineProvider.cs b/InteractiveReadLine/IReadLineProvider.cs index b953b30..508399d 100644 --- a/InteractiveReadLine/IReadLineProvider.cs +++ b/InteractiveReadLine/IReadLineProvider.cs @@ -1,42 +1,63 @@ -using System; -using InteractiveReadLine.Formatting; - -namespace InteractiveReadLine -{ - /// - /// The underlying contract for any object which is to provide ReadLine functionality to the input handler. - /// - /// - /// Any object which is to provide a functioning backend on which the ReadLineHandler can act must implement these - /// three features: synchronously returning a single ConsoleKeyInfo when asked, writing out text and a cursor - /// position on the currently active line (clearing whatever was there before), and inserting text to some - /// output without interfering with the active display line. - /// - /// Finally, the provider must implement IDisposable; as it will be disposed by the handler when the input of - /// a line has been completed. The provider must then clean up the view in some fashion (on a standard System.Console - /// provider this involves writing a newline to the console) - /// - public interface IReadLineProvider : IDisposable - { - /// - /// Waits synchronously for a ConsoleKeyInfo to be returned from some underlying input source. - /// - /// The information of the key which was just read/pressed - ConsoleKeyInfo ReadKey(); - - /// - /// Displays the LineDisplayState to the visual output, including the cursor position - /// - /// The line display state (prefix, suffix, text, and cursor position) to be displayed - void SetDisplay(LineDisplayState state); - - /// - /// Inserts text to the console out in the spot where the current read line input is, then - /// immediately re-displays the line input on the next row. This is used to interrupt the user with a message or - /// information while the ReadLine is still active - /// - /// The text to write to the console, a newline char will be added automatically - void InsertText(FormattedText text); - - } -} \ No newline at end of file +using System; +using System.Threading; +using System.Threading.Tasks; +using InteractiveReadLine.Formatting; + +namespace InteractiveReadLine +{ + /// + /// The underlying contract for any object which is to provide ReadLine functionality to the input handler. + /// + /// + /// Any object which is to provide a functioning backend on which the ReadLineHandler can act must implement these + /// features: returning a single ConsoleKeyInfo when asked, both synchronously and asynchronously, writing out + /// text and a cursor position on the currently active line (clearing whatever was there before), and inserting + /// text to some output without interfering with the active display line. + /// + /// Finally, the provider must implement IDisposable; as it will be disposed by the handler when the input of + /// a line has been completed. The provider must then clean up the view in some fashion (on a standard System.Console + /// provider this involves writing a newline to the console) + /// + public interface IReadLineProvider : IDisposable + { + /// + /// Waits synchronously for a ConsoleKeyInfo to be returned from some underlying input source. + /// + /// + /// A token that cancels the wait. An implementation whose underlying wait cannot be interrupted + /// should poll for input becoming available rather than blocking, so that the token can be observed. + /// + /// Information about the key that was read. + /// The token was canceled before a key arrived. + ConsoleKeyInfo ReadKey(CancellationToken cancellationToken = default); + + /// + /// Waits asynchronously for a ConsoleKeyInfo to be returned from some underlying input source. + /// + /// + /// A backend whose input arrives through an event or an already asynchronous API should implement this + /// natively. A backend whose ReadKey does not block, such as one reading from an already populated + /// queue, may return Task.FromResult(ReadKey(cancellationToken)). Avoid wrapping a blocking read in + /// Task.Run because it occupies a thread until the user presses a key, and the token cannot interrupt it. + /// + /// A token that cancels the wait. + /// A task producing information about the key that was read. + /// The token was canceled before a key arrived. + Task ReadKeyAsync(CancellationToken cancellationToken = default); + + /// + /// Displays the LineDisplayState to the visual output, including the cursor position + /// + /// The line display state (prefix, suffix, text, and cursor position) to be displayed + void SetDisplay(LineDisplayState state); + + /// + /// Inserts text to the console out in the spot where the current read line input is, then + /// immediately re-displays the line input on the next row. This is used to interrupt the user with a message or + /// information while the ReadLine is still active + /// + /// The text to write to the console, a newline char will be added automatically + void InsertText(FormattedText text); + + } +} diff --git a/InteractiveReadLine/InteractiveReadLine.csproj b/InteractiveReadLine/InteractiveReadLine.csproj index 939a2ed..96987a6 100644 --- a/InteractiveReadLine/InteractiveReadLine.csproj +++ b/InteractiveReadLine/InteractiveReadLine.csproj @@ -1,7 +1,48 @@ - - - - netstandard2.0 - - - + + + + netstandard2.0;net10.0 + latest + enable + true + + + + InteractiveReadLine + Matt Jarvis + An extensible, composable GNU Readline-style line editor for interactive .NET console applications. Provides customizable key behaviors, colored formatting, lexers, tab auto-complete, and navigable history with no external runtime dependencies. + readline;console;cli;repl;interactive;autocomplete;history;prompt;terminal + MIT + https://github.com/mattj23/InteractiveReadLine + https://github.com/mattj23/InteractiveReadLine + git + README.md + Copyright (c) Matt Jarvis + + + + + true + true + true + snupkg + + + + + v + + + + + + + + + + + + diff --git a/InteractiveReadLine/KeyBehaviors/BehaviorExtensionMethods.cs b/InteractiveReadLine/KeyBehaviors/BehaviorExtensionMethods.cs index ee5c1d3..086ac32 100644 --- a/InteractiveReadLine/KeyBehaviors/BehaviorExtensionMethods.cs +++ b/InteractiveReadLine/KeyBehaviors/BehaviorExtensionMethods.cs @@ -1,108 +1,213 @@ -using System; - -namespace InteractiveReadLine.KeyBehaviors -{ - public static class BehaviorExtensionMethods - { - public static ReadLineConfig AddKeyBehavior(this ReadLineConfig config, KeyId key, Action action) - { - config.KeyBehaviors.Add(key, action); - return config; - } - - public static ReadLineConfig AddKeyBehavior(this ReadLineConfig config, ConsoleKey key, - bool control, bool alt, bool shift, Action action) - { - return config.AddKeyBehavior(new KeyId(key, false, false, false), action); - } - - public static ReadLineConfig AddKeyBehavior(this ReadLineConfig config, char key, - Action action) - { - return config.AddKeyBehavior(new KeyId(key), action); - } - - public static ReadLineConfig AddKeyBehavior(this ReadLineConfig config, ConsoleKey key, - Action action) - { - return config.AddKeyBehavior(new KeyId(key, false, false, false), action); - } - - public static ReadLineConfig AddCtrlKeyBehavior(this ReadLineConfig config, ConsoleKey key, - Action action) - { - return config.AddKeyBehavior(new KeyId(key, true, false, false), action); - } - - public static ReadLineConfig AddDeleteBackspace(this ReadLineConfig config) - { - return config.AddKeyBehavior(ConsoleKey.Delete, CommonKeyBehaviors.Delete) - .AddKeyBehavior(ConsoleKey.Backspace, CommonKeyBehaviors.Backspace); - } - - public static ReadLineConfig AddEnterToFinish(this ReadLineConfig config) - { - return config.AddKeyBehavior(ConsoleKey.Enter, CommonKeyBehaviors.Finish); - } - - public static ReadLineConfig AddHomeAndEndKeys(this ReadLineConfig config) - { - return config - .AddKeyBehavior(ConsoleKey.Home, CommonKeyBehaviors.MoveCursorToStart) - .AddKeyBehavior(ConsoleKey.End, CommonKeyBehaviors.MoveCursorToEnd); - } - - public static ReadLineConfig AddArrowMovesCursor(this ReadLineConfig config) - { - return config - .AddKeyBehavior(ConsoleKey.LeftArrow, CommonKeyBehaviors.MoveCursorLeft) - .AddKeyBehavior(ConsoleKey.RightArrow, CommonKeyBehaviors.MoveCursorRight); - } - public static ReadLineConfig AddUpDownHistoryNavigation(this ReadLineConfig config) - { - return config - .AddKeyBehavior(ConsoleKey.UpArrow, CommonKeyBehaviors.HistoryPrevious) - .AddKeyBehavior(ConsoleKey.DownArrow, CommonKeyBehaviors.HistoryNext); - } - - public static ReadLineConfig AddCtrlNavKeys(this ReadLineConfig config) - { - return config - .AddCtrlKeyBehavior(ConsoleKey.A, CommonKeyBehaviors.MoveCursorToStart) - .AddCtrlKeyBehavior(ConsoleKey.B, CommonKeyBehaviors.MoveCursorLeft) - .AddCtrlKeyBehavior(ConsoleKey.E, CommonKeyBehaviors.MoveCursorToEnd) - .AddCtrlKeyBehavior(ConsoleKey.F, CommonKeyBehaviors.MoveCursorRight) - .AddCtrlKeyBehavior(ConsoleKey.H, CommonKeyBehaviors.Backspace) - .AddCtrlKeyBehavior(ConsoleKey.K, CommonKeyBehaviors.CutToEnd) - .AddCtrlKeyBehavior(ConsoleKey.U, CommonKeyBehaviors.CutToStart) - .AddCtrlKeyBehavior(ConsoleKey.L, CommonKeyBehaviors.ClearAll) - .AddCtrlKeyBehavior(ConsoleKey.M, CommonKeyBehaviors.Finish) - .AddCtrlKeyBehavior(ConsoleKey.N, CommonKeyBehaviors.HistoryNext) - .AddCtrlKeyBehavior(ConsoleKey.P, CommonKeyBehaviors.HistoryPrevious) - .AddCtrlKeyBehavior(ConsoleKey.D, CommonKeyBehaviors.Delete) - .AddCtrlKeyBehavior(ConsoleKey.W, CommonKeyBehaviors.CutPreviousWord); - } - - /// - /// Adds a set of standard keys to the configuration, including the default of inserting printable - /// characters, enter to finish the line, delete, backspace, and the left and right arrow keys. - /// - public static ReadLineConfig AddStandardKeys(this ReadLineConfig config) - { - return config - .SetDefaultKeyBehavior(CommonKeyBehaviors.InsertCharacter) - .AddEnterToFinish() - .AddDeleteBackspace() - .AddHomeAndEndKeys() - .AddUpDownHistoryNavigation() - .AddArrowMovesCursor(); - } - - public static ReadLineConfig AddTabAutoComplete(this ReadLineConfig config) - { - return config - .AddKeyBehavior(ConsoleKey.Tab, CommonKeyBehaviors.AutoCompleteNext) - .AddKeyBehavior(new KeyId(ConsoleKey.Tab, false, false, true), CommonKeyBehaviors.AutoCompletePrevious); - } - } -} \ No newline at end of file +using System; + +namespace InteractiveReadLine.KeyBehaviors +{ + /// + /// Provides extension methods that register key behaviors on a configuration. Each method returns the + /// supplied configuration for chaining and replaces any existing binding for the same key. + /// + public static class BehaviorExtensionMethods + { + /// + /// Binds a behavior to a key identified by a KeyId that contains the key and its modifiers. + /// + /// The configuration to add the binding to + /// The key which invokes the behavior + /// The behavior to run when the key is pressed + /// The same configuration, for chaining + public static ReadLineConfig AddKeyBehavior(this ReadLineConfig config, KeyId key, Action action) + { + // Use assignment so that a binding registered later replaces an earlier binding without throwing. + // This lets callers start with a pre-built configuration and override individual keys. + config.KeyBehaviors[key] = action; + return config; + } + + /// + /// Binds a behavior to a key pressed together with the given modifiers. + /// + /// The configuration to add the binding to + /// The key which invokes the behavior + /// Whether the control key must be held + /// Whether the alt key must be held + /// Whether the shift key must be held + /// The behavior to run when the key is pressed + /// The same configuration, for chaining + public static ReadLineConfig AddKeyBehavior(this ReadLineConfig config, ConsoleKey key, + bool control, bool alt, bool shift, Action action) + { + return config.AddKeyBehavior(new KeyId(key, control, alt, shift), action); + } + + /// + /// Binds a behavior to a character, whichever combination of keys produced it. A character binding is + /// matched before the key and modifier bindings are considered. + /// + /// The configuration to add the binding to + /// The character which invokes the behavior + /// The behavior to run when the character is typed + /// The same configuration, for chaining + public static ReadLineConfig AddKeyBehavior(this ReadLineConfig config, char key, + Action action) + { + return config.AddKeyBehavior(new KeyId(key), action); + } + + /// + /// Binds a behavior to a key pressed with no modifiers. + /// + /// The configuration to add the binding to + /// The key which invokes the behavior + /// The behavior to run when the key is pressed + /// The same configuration, for chaining + public static ReadLineConfig AddKeyBehavior(this ReadLineConfig config, ConsoleKey key, + Action action) + { + return config.AddKeyBehavior(new KeyId(key, false, false, false), action); + } + + /// + /// Binds a behavior to a key pressed together with the control key. + /// + /// The configuration to add the binding to + /// The key which invokes the behavior when control is held + /// The behavior to run when the key is pressed + /// The same configuration, for chaining + public static ReadLineConfig AddCtrlKeyBehavior(this ReadLineConfig config, ConsoleKey key, + Action action) + { + return config.AddKeyBehavior(new KeyId(key, true, false, false), action); + } + + /// + /// Binds the delete key to removing the character under the cursor, and the backspace key to removing + /// the character before it. + /// + /// The configuration to add the bindings to + /// The same configuration, for chaining + public static ReadLineConfig AddDeleteBackspace(this ReadLineConfig config) + { + return config.AddKeyBehavior(ConsoleKey.Delete, CommonKeyBehaviors.Delete) + .AddKeyBehavior(ConsoleKey.Backspace, CommonKeyBehaviors.Backspace); + } + + /// + /// Binds the Enter key to finish the line and return from the read line operation. + /// + /// The configuration to add the binding to + /// The same configuration, for chaining + public static ReadLineConfig AddEnterToFinish(this ReadLineConfig config) + { + return config.AddKeyBehavior(ConsoleKey.Enter, CommonKeyBehaviors.Finish); + } + + /// + /// Binds Ctrl+C to abandon the current line, matching conventional shell behavior. + /// + /// + /// The ConsoleReadLine provider puts the console into a mode where Ctrl+C arrives as an ordinary + /// keypress rather than terminating the process, and restores the previous mode when it is disposed. + /// Without this binding, Ctrl+C has no effect while a line is being read. + /// + public static ReadLineConfig AddCancelKeys(this ReadLineConfig config) + { + return config.AddCtrlKeyBehavior(ConsoleKey.C, CommonKeyBehaviors.Cancel); + } + + /// + /// Binds the home and end keys to moving the cursor to the start and end of the line. + /// + /// The configuration to add the bindings to + /// The same configuration, for chaining + public static ReadLineConfig AddHomeAndEndKeys(this ReadLineConfig config) + { + return config + .AddKeyBehavior(ConsoleKey.Home, CommonKeyBehaviors.MoveCursorToStart) + .AddKeyBehavior(ConsoleKey.End, CommonKeyBehaviors.MoveCursorToEnd); + } + + /// + /// Binds the left and right arrow keys to moving the cursor one character in their direction. + /// + /// The configuration to add the bindings to + /// The same configuration, for chaining + public static ReadLineConfig AddArrowMovesCursor(this ReadLineConfig config) + { + return config + .AddKeyBehavior(ConsoleKey.LeftArrow, CommonKeyBehaviors.MoveCursorLeft) + .AddKeyBehavior(ConsoleKey.RightArrow, CommonKeyBehaviors.MoveCursorRight); + } + /// + /// Binds the up and down arrow keys to step backward and forward through history. The + /// bindings do nothing unless the configuration also has a history source. + /// + /// The configuration to add the bindings to + /// The same configuration, for chaining + public static ReadLineConfig AddUpDownHistoryNavigation(this ReadLineConfig config) + { + return config + .AddKeyBehavior(ConsoleKey.UpArrow, CommonKeyBehaviors.HistoryPrevious) + .AddKeyBehavior(ConsoleKey.DownArrow, CommonKeyBehaviors.HistoryNext); + } + + /// + /// Binds the control key navigation and editing commands familiar from Bash: cursor movement with + /// Ctrl+A, B, E and F, backspace with Ctrl+H, cutting with Ctrl+K, U and W, pasting with Ctrl+Y, + /// clearing with Ctrl+L, finishing with Ctrl+M, history with Ctrl+N and P, and Ctrl+D to delete + /// forward or signal the end of input on an empty line. + /// + /// The configuration to add the bindings to + /// The same configuration, for chaining + public static ReadLineConfig AddCtrlNavKeys(this ReadLineConfig config) + { + return config + .AddCtrlKeyBehavior(ConsoleKey.A, CommonKeyBehaviors.MoveCursorToStart) + .AddCtrlKeyBehavior(ConsoleKey.B, CommonKeyBehaviors.MoveCursorLeft) + .AddCtrlKeyBehavior(ConsoleKey.E, CommonKeyBehaviors.MoveCursorToEnd) + .AddCtrlKeyBehavior(ConsoleKey.F, CommonKeyBehaviors.MoveCursorRight) + .AddCtrlKeyBehavior(ConsoleKey.H, CommonKeyBehaviors.Backspace) + .AddCtrlKeyBehavior(ConsoleKey.K, CommonKeyBehaviors.CutToEnd) + .AddCtrlKeyBehavior(ConsoleKey.U, CommonKeyBehaviors.CutToStart) + .AddCtrlKeyBehavior(ConsoleKey.L, CommonKeyBehaviors.ClearAll) + .AddCtrlKeyBehavior(ConsoleKey.M, CommonKeyBehaviors.Finish) + .AddCtrlKeyBehavior(ConsoleKey.N, CommonKeyBehaviors.HistoryNext) + .AddCtrlKeyBehavior(ConsoleKey.P, CommonKeyBehaviors.HistoryPrevious) + .AddCtrlKeyBehavior(ConsoleKey.D, CommonKeyBehaviors.DeleteOrEndOfInput) + .AddCtrlKeyBehavior(ConsoleKey.W, CommonKeyBehaviors.CutPreviousWord) + // GNU Readline and many terminal applications conventionally use Ctrl+Y for pasting. Ctrl+V + // conventionally inserts the next character literally, and many terminals intercept it. + .AddCtrlKeyBehavior(ConsoleKey.Y, CommonKeyBehaviors.Paste); + } + + /// + /// Adds a set of standard keys to the configuration, including the default of inserting printable + /// characters, enter to finish the line, delete, backspace, the left and right arrow keys, and + /// Ctrl+C to abandon the line. + /// + public static ReadLineConfig AddStandardKeys(this ReadLineConfig config) + { + return config + .SetDefaultKeyBehavior(CommonKeyBehaviors.InsertCharacter) + .AddEnterToFinish() + .AddDeleteBackspace() + .AddHomeAndEndKeys() + .AddUpDownHistoryNavigation() + .AddArrowMovesCursor() + .AddCancelKeys(); + } + + /// + /// Binds Tab to cycle forward through auto-complete suggestions and Shift+Tab to cycle backward. The + /// bindings do nothing unless the configuration also has a lexer and a suggestion + /// provider. + /// + /// The configuration to add the bindings to + /// The same configuration, for chaining + public static ReadLineConfig AddTabAutoComplete(this ReadLineConfig config) + { + return config + .AddKeyBehavior(ConsoleKey.Tab, CommonKeyBehaviors.AutoCompleteNext) + .AddKeyBehavior(new KeyId(ConsoleKey.Tab, false, false, true), CommonKeyBehaviors.AutoCompletePrevious); + } + } +} diff --git a/InteractiveReadLine/KeyBehaviors/CommonKeyBehaviors.cs b/InteractiveReadLine/KeyBehaviors/CommonKeyBehaviors.cs index f386f97..abe9f0f 100644 --- a/InteractiveReadLine/KeyBehaviors/CommonKeyBehaviors.cs +++ b/InteractiveReadLine/KeyBehaviors/CommonKeyBehaviors.cs @@ -1,215 +1,276 @@ -using System; -using System.Runtime.CompilerServices; -using InteractiveReadLine.Tokenizing; - -namespace InteractiveReadLine.KeyBehaviors -{ - /// - /// These are common "behaviors" which are invoked by keys being pressed, and can be added to the handler - /// either as the default behavior or to be invoked when a special key or character is pressed. They are given - /// to the handler in the form of Action delegates which receive an IKeyBehaviorTarget, which they can operate - /// on in order to affect some change on the line of text being written. - /// - /// The behaviors provided in this static class are all simple ones, they can be used directly or they can be - /// composed together or wrapped in other methods which allow access to external state, or any other use - /// case that can be imagined. - /// - public static class CommonKeyBehaviors - { - /// - /// Deletes the character after the cursor - /// - /// - public static void Delete(IKeyBehaviorTarget target) - { - if (target.CursorPosition < target.TextBuffer.Length) - target.TextBuffer.Remove(target.CursorPosition, 1); - } - - /// - /// Deletes the character before the cursor - /// - public static void Backspace(IKeyBehaviorTarget target) - { - if (target.CursorPosition > 0) - { - target.TextBuffer.Remove(target.CursorPosition - 1, 1); - target.CursorPosition--; - } - } - - /// - /// Immediately moves the cursor to the end of the line - /// - public static void MoveCursorToEnd(IKeyBehaviorTarget target) - { - target.CursorPosition = target.TextBuffer.Length; - } - - /// - /// Immediately moves the cursor to the beginning of the line - /// - public static void MoveCursorToStart(IKeyBehaviorTarget target) - { - target.CursorPosition = 0; - } - - /// - /// Moves the cursor left (towards the start) of the line, but will not move it past the first character - /// - public static void MoveCursorLeft(IKeyBehaviorTarget target) - { - if (target.CursorPosition > 0) - target.CursorPosition--; - } - - /// - /// Moves the cursor right (towards the end) of the line, but will not move it beyond the end of the line - /// - public static void MoveCursorRight(IKeyBehaviorTarget target) - { - if (target.CursorPosition < target.TextBuffer.Length) - target.CursorPosition++; - } - - /// - /// Clears the entire contents of the text buffer - /// - public static void ClearAll(IKeyBehaviorTarget target) - { - target.TextBuffer.Clear(); - target.CursorPosition = 0; - } - - /// - /// Uses a function to create a key behavior that uses the provider's "InsertText" method to insert - /// a message to the user. The handler will provide your function with the tokenized version of the - /// current text, which will be null if the configuration doesn't have a tokenizer. - /// - /// A function which receives a Tokens object and uses it to create a string - /// message, this is typically useful for providing help or hints to the user - /// A key behavior action which can be registered with the read line configuration - public static Action WriteMessageFromTokens(Func message) - { - return new Action(t => t.InsertText(message(t.GetTextTokens()))); - } - - /// - /// Invokes the target's auto-complete next behavior, which substitutes in the next suggestion - /// at the token where the cursor is currently residing - /// - public static void AutoCompleteNext(IKeyBehaviorTarget target) => target.AutoCompleteNext(); - - /// - /// Invokes the target's auto-complete previous behavior, which substitutes in the previous suggestion - /// at the token where the cursor is currently residing - /// - public static void AutoCompletePrevious(IKeyBehaviorTarget target) => target.AutoCompletePrevious(); - - /// - /// Invokes the target's next history behavior, which replaces the line with the next element - /// in the history collection. Will do nothing if no history has been provided, or replace the line - /// with the last entered line state if the end of the history has been reached. - /// - /// - public static void HistoryNext(IKeyBehaviorTarget target) => target.HistoryNext(); - - /// - /// Invokes the target's previous history behavior, which replaces the entire line with the previous - /// element in the history collection. Will do nothing if no history has been provided, or if the oldest - /// element in the collection has been reached. - /// - /// - public static void HistoryPrevious(IKeyBehaviorTarget target) => target.HistoryPrevious(); - - /// - /// Finishes the ReadLine input, instructing the handler to return the text as it is - /// - public static void Finish(IKeyBehaviorTarget target) => target.Finish(); - - /// - /// Removes all of the text between the cursor and the end of the line - /// - /// - public static void CutToEnd(IKeyBehaviorTarget target) - { - var cursor = target.CursorPosition; - var captured = target.TextBuffer.ToString().Substring(0, cursor); - target.TextBuffer.Clear(); - target.TextBuffer.Append(captured); - target.CursorPosition = cursor; - } - - /// - /// Removes all of the text between the cursor and the start of the line - /// - /// - public static void CutToStart(IKeyBehaviorTarget target) - { - var cursor = target.CursorPosition; - var captured = target.TextBuffer.ToString() - .Substring(cursor, target.TextBuffer.Length - cursor); - target.TextBuffer.Clear(); - target.TextBuffer.Append(captured); - target.CursorPosition = 0; - } - - /// - /// Using a basic split on whitespace strategy, this removes all of the text between the cursor - /// and the end of the previous word - /// - /// - public static void CutPreviousWord(IKeyBehaviorTarget target) - { - var tokens = - CommonLexers.SplitOnWhitespace(new LineState(target.TextBuffer.ToString(), target.CursorPosition)); - int cursor = (int) tokens.CursorToken.Cursor; - - var token = tokens.CursorToken; - var previous = tokens.CursorToken.Previous; - - if (cursor == 0 && previous?.IsHidden == true) - { - // Example for "test data here", which should delete back to the beginning - // ↑ - - previous.Text = ""; - if (previous.Previous != null) - { - previous.Previous.Text = ""; - } - } - else - { - var captured = token.Text.Substring(cursor, token.Text.Length - cursor); - token.Cursor = 0; - token.Text = captured; - - if (token.IsHidden && previous != null) - { - previous.Text = ""; - } - } - - target.TextBuffer.Clear(); - target.TextBuffer.Append(tokens.Text); - target.CursorPosition = tokens.Cursor; - } - - /// - /// Inserts the received character at the cursor position if the character is a letter, digit, whitespace, - /// punctuation, or symbol. Advances the cursor by one. - /// - public static void InsertCharacter(IKeyBehaviorTarget target) - { - if (char.IsLetterOrDigit(target.ReceivedKey.KeyChar) || - char.IsWhiteSpace(target.ReceivedKey.KeyChar) || - char.IsPunctuation(target.ReceivedKey.KeyChar) || - char.IsSymbol(target.ReceivedKey.KeyChar)) - { - target.TextBuffer.Insert(target.CursorPosition, target.ReceivedKey.KeyChar); - target.CursorPosition++; - } - } - } -} \ No newline at end of file +using System; +using InteractiveReadLine.Tokenizing; + +namespace InteractiveReadLine.KeyBehaviors +{ + /// + /// These are common "behaviors" which are invoked by keys being pressed, and can be added to the handler + /// either as the default behavior or to be invoked when a special key or character is pressed. They are given + /// to the handler in the form of Action delegates which receive an IKeyBehaviorTarget, which they can operate + /// on in order to affect some change on the line of text being written. + /// + /// The behaviors provided in this static class are all simple ones, they can be used directly or they can be + /// composed together or wrapped in other methods which allow access to external state, or any other use + /// case that can be imagined. + /// + public static class CommonKeyBehaviors + { + /// + /// Deletes the character after the cursor + /// + /// + public static void Delete(IKeyBehaviorTarget target) + { + if (target.CursorPosition < target.TextBuffer.Length) + target.TextBuffer.Remove(target.CursorPosition, 1); + } + + /// + /// Deletes the character before the cursor + /// + public static void Backspace(IKeyBehaviorTarget target) + { + if (target.CursorPosition > 0) + { + target.TextBuffer.Remove(target.CursorPosition - 1, 1); + target.CursorPosition--; + } + } + + /// + /// Immediately moves the cursor to the end of the line + /// + public static void MoveCursorToEnd(IKeyBehaviorTarget target) + { + target.CursorPosition = target.TextBuffer.Length; + } + + /// + /// Immediately moves the cursor to the beginning of the line + /// + public static void MoveCursorToStart(IKeyBehaviorTarget target) + { + target.CursorPosition = 0; + } + + /// + /// Moves the cursor left (towards the start) of the line, but will not move it past the first character + /// + public static void MoveCursorLeft(IKeyBehaviorTarget target) + { + if (target.CursorPosition > 0) + target.CursorPosition--; + } + + /// + /// Moves the cursor right (towards the end) of the line, but will not move it beyond the end of the line + /// + public static void MoveCursorRight(IKeyBehaviorTarget target) + { + if (target.CursorPosition < target.TextBuffer.Length) + target.CursorPosition++; + } + + /// + /// Clears the entire contents of the text buffer + /// + public static void ClearAll(IKeyBehaviorTarget target) + { + target.TextBuffer.Clear(); + target.CursorPosition = 0; + } + + /// + /// Uses a function to create a key behavior that uses the provider's "InsertText" method to insert + /// a message to the user. The handler will provide your function with the tokenized version of the + /// current text, which will be null if the configuration doesn't have a tokenizer. + /// + /// A function which receives a Tokens object and uses it to create a string + /// message, this is typically useful for providing help or hints to the user + /// A key behavior action which can be registered with the read line configuration + public static Action WriteMessageFromTokens(Func message) + { + return new Action(t => t.InsertText(message(t.GetTextTokens()))); + } + + /// + /// Invokes the target's auto-complete next behavior, which substitutes in the next suggestion + /// at the token where the cursor is currently residing + /// + public static void AutoCompleteNext(IKeyBehaviorTarget target) => target.AutoCompleteNext(); + + /// + /// Invokes the target's auto-complete previous behavior, which substitutes in the previous suggestion + /// at the token where the cursor is currently residing + /// + public static void AutoCompletePrevious(IKeyBehaviorTarget target) => target.AutoCompletePrevious(); + + /// + /// Invokes the target's next history behavior, which replaces the line with the next element + /// in the history collection. Will do nothing if no history has been provided, or replace the line + /// with the last entered line state if the end of the history has been reached. + /// + /// + public static void HistoryNext(IKeyBehaviorTarget target) => target.HistoryNext(); + + /// + /// Invokes the target's previous history behavior, which replaces the entire line with the previous + /// element in the history collection. Will do nothing if no history has been provided, or if the oldest + /// element in the collection has been reached. + /// + /// + public static void HistoryPrevious(IKeyBehaviorTarget target) => target.HistoryPrevious(); + + /// + /// Finishes the ReadLine input, instructing the handler to return the text as it is + /// + public static void Finish(IKeyBehaviorTarget target) => target.Finish(); + + /// + /// Abandons the ReadLine input and discards the entered text. This behavior is conventionally + /// bound to Ctrl+C. + /// + public static void Cancel(IKeyBehaviorTarget target) => target.Cancel(); + + /// + /// Signals that the user has no more input and discards the entered text. This behavior is conventionally + /// behavior conventionally bound to Ctrl+D on an empty line. + /// + public static void EndOfInput(IKeyBehaviorTarget target) => target.EndOfInput(); + + /// + /// Deletes the character under the cursor, or signals the end of input if the line is empty. This + /// matches shell behavior for Ctrl+D: it deletes forward when a character is available and otherwise + /// ends the session. + /// + public static void DeleteOrEndOfInput(IKeyBehaviorTarget target) + { + if (target.TextBuffer.Length == 0) + target.EndOfInput(); + else + Delete(target); + } + + /// + /// Removes all of the text between the cursor and the end of the line + /// + /// + public static void CutToEnd(IKeyBehaviorTarget target) + { + var cursor = target.CursorPosition; + var text = target.TextBuffer.ToString(); + var captured = text.Substring(0, cursor); + + target.TextBuffer.Clear(); + target.TextBuffer.Append(captured); + target.CursorPosition = cursor; + + target.CutForward(text.Substring(cursor)); + } + + /// + /// Removes all of the text between the cursor and the start of the line + /// + /// + public static void CutToStart(IKeyBehaviorTarget target) + { + var cursor = target.CursorPosition; + var text = target.TextBuffer.ToString(); + var captured = text.Substring(cursor, target.TextBuffer.Length - cursor); + + target.TextBuffer.Clear(); + target.TextBuffer.Append(captured); + target.CursorPosition = 0; + + target.CutBackward(text.Substring(0, cursor)); + } + + /// + /// Using a basic split on whitespace strategy, this removes all of the text between the cursor + /// and the end of the previous word + /// + /// + public static void CutPreviousWord(IKeyBehaviorTarget target) + { + var textBefore = target.TextBuffer.ToString(); + var cursorBefore = target.CursorPosition; + + var tokens = + CommonLexers.SplitOnWhitespace(new LineState(target.TextBuffer.ToString(), target.CursorPosition)); + var token = tokens.CursorToken; + if (token?.Cursor == null) + return; + + int cursor = token.Cursor.Value; + var previous = token.Previous; + + if (cursor == 0 && previous?.IsHidden == true) + { + // Example for "test data here", which should delete back to the beginning + // ↑ + + previous.Text = ""; + if (previous.Previous != null) + { + previous.Previous.Text = ""; + } + } + else + { + var captured = token.Text.Substring(cursor, token.Text.Length - cursor); + token.Cursor = 0; + token.Text = captured; + + if (token.IsHidden && previous != null) + { + previous.Text = ""; + } + } + + target.TextBuffer.Clear(); + target.TextBuffer.Append(tokens.Text); + target.CursorPosition = tokens.Cursor; + + // This behavior rebuilds the line from its tokens. Recover the removed text from the span crossed + // when the cursor moved backward. + var removedLength = cursorBefore - target.CursorPosition; + if (removedLength > 0 && cursorBefore <= textBefore.Length) + target.CutBackward(textBefore.Substring(target.CursorPosition, removedLength)); + else + target.CutBackward(string.Empty); + } + + /// + /// Inserts the text in the cut buffer at the cursor position and leaves the cursor at the end of + /// the inserted text. Does nothing when nothing has been cut. + /// + /// + /// The buffer is not emptied by pasting, so the same text can be pasted repeatedly. + /// + public static void Paste(IKeyBehaviorTarget target) + { + var text = target.CutBuffer; + if (string.IsNullOrEmpty(text)) + return; + + target.TextBuffer.Insert(target.CursorPosition, text); + target.CursorPosition += text.Length; + } + + /// + /// Inserts the received character at the cursor position if the character is a letter, digit, whitespace, + /// punctuation, or symbol. Advances the cursor by one. + /// + public static void InsertCharacter(IKeyBehaviorTarget target) + { + if (char.IsLetterOrDigit(target.ReceivedKey.KeyChar) || + char.IsWhiteSpace(target.ReceivedKey.KeyChar) || + char.IsPunctuation(target.ReceivedKey.KeyChar) || + char.IsSymbol(target.ReceivedKey.KeyChar)) + { + target.TextBuffer.Insert(target.CursorPosition, target.ReceivedKey.KeyChar); + target.CursorPosition++; + } + } + } +} diff --git a/InteractiveReadLine/KeyBehaviors/IKeyBehaviorTarget.cs b/InteractiveReadLine/KeyBehaviors/IKeyBehaviorTarget.cs index 4bab965..ff60358 100644 --- a/InteractiveReadLine/KeyBehaviors/IKeyBehaviorTarget.cs +++ b/InteractiveReadLine/KeyBehaviors/IKeyBehaviorTarget.cs @@ -1,73 +1,118 @@ -using System; -using System.Text; -using InteractiveReadLine.Formatting; -using InteractiveReadLine.Tokenizing; - -namespace InteractiveReadLine.KeyBehaviors -{ - /// - /// Provides the unified target of key behaviors, exposing a standard amount of state which the - /// behavior method can act upon - /// - public interface IKeyBehaviorTarget - { - /// - /// Gets the ConsoleKey which was received for the current request - /// - ConsoleKeyInfo ReceivedKey { get; } - - /// - /// Gets the string buffer which holds the current readline text which is being edited by the user - /// - StringBuilder TextBuffer { get; } - - /// - /// Gets or sets the integer position of the cursor. Cannot be set before the beginning or after the end - /// of the TextBuffer. - /// - int CursorPosition { get; set; } - - /// - /// Invokes the auto-complete's "next" functionality, which substitutes in the next suggestion - /// - void AutoCompleteNext(); - - /// - /// Invokes the auto-complete's "previous" functionality, which substitutes in the previous suggestion - /// - void AutoCompletePrevious(); - - /// - /// Inserts text to the console out in the spot where the current read line input is, then - /// immediately re-displays the line input on the next row. Use this to interrupt the user with a message or - /// information while the ReadLine is still being used - /// - /// The text to write to the console, a newline char will be added automatically - void InsertText(FormattedText text); - - /// - /// If the handler configuration has a tokenizer, this will get the tokenization result of the text - /// buffer - /// - /// Returns null if there is no tokenizer, otherwise a Tokens result - TokenizedLine GetTextTokens(); - - /// - /// Invokes the history's "next" functionality, which replaces the entire line with the next element - /// in the history collection. If the last history element has been reached, the previously entered - /// LineState will be reverted. - /// - void HistoryNext(); - - /// - /// Invokes the history's "previous" functionality, which replaces the entire line with the previous - /// element in the history collection. - /// - void HistoryPrevious(); - - /// - /// Tells the readline handler to finish this line of input and return it - /// - void Finish(); - } -} \ No newline at end of file +using System; +using System.Text; +using InteractiveReadLine.Formatting; +using InteractiveReadLine.Tokenizing; + +namespace InteractiveReadLine.KeyBehaviors +{ + /// + /// Provides the unified target of key behaviors, exposing a standard amount of state which the + /// behavior method can act upon + /// + public interface IKeyBehaviorTarget + { + /// + /// Gets the ConsoleKey which was received for the current request + /// + ConsoleKeyInfo ReceivedKey { get; } + + /// + /// Gets the string buffer which holds the current readline text which is being edited by the user + /// + StringBuilder TextBuffer { get; } + + /// + /// Gets or sets the integer position of the cursor. Cannot be set before the beginning or after the end + /// of the TextBuffer. + /// + int CursorPosition { get; set; } + + /// + /// Invokes the auto-complete's "next" functionality, which substitutes in the next suggestion + /// + void AutoCompleteNext(); + + /// + /// Invokes the auto-complete's "previous" functionality, which substitutes in the previous suggestion + /// + void AutoCompletePrevious(); + + /// + /// Inserts text to the console out in the spot where the current read line input is, then + /// immediately re-displays the line input on the next row. Use this to interrupt the user with a message or + /// information while the ReadLine is still being used + /// + /// The text to write to the console, a newline char will be added automatically + void InsertText(FormattedText text); + + /// + /// Gets the tokenized text buffer when the handler configuration has a lexer. + /// + /// The tokenized line, or null when the configuration has no lexer. + TokenizedLine? GetTextTokens(); + + /// + /// Invokes the history's "next" functionality, which replaces the entire line with the next element + /// in the history collection. If the last history element has been reached, the previously entered + /// LineState will be reverted. + /// + void HistoryNext(); + + /// + /// Invokes the history's "previous" functionality, which replaces the entire line with the previous + /// element in the history collection. + /// + void HistoryPrevious(); + + /// + /// Gets the text accumulated by the most recent run of cut operations. The paste behavior inserts this + /// text at the cursor. The value is empty when nothing has been cut. + /// + /// + /// The buffer belongs to a single read line operation and does not carry over to the next one. It is + /// populated through CutForward and CutBackward, which accumulate consecutive cuts into one piece of + /// text that can be pasted. + /// + string CutBuffer { get; } + + /// + /// Records text removed from in front of the cursor, placing it at the end of the cut buffer. + /// + /// + /// Cut text is stored in its original order on the line, so a run of cuts can be pasted back as the + /// original text. A behavior that removes text in front of the cursor, such as cutting to the end of + /// the line, should report it here. + /// + /// The text that was removed from the line. + void CutForward(string text); + + /// + /// Records text removed from behind the cursor, placing it at the front of the cut buffer. + /// + /// + /// A behavior that removes text from behind the cursor, such as cutting to the start of the line or + /// cutting the previous word, should report it here. Cutting three words backward one after + /// another therefore leaves the three words in the buffer in their original order. + /// + /// The text that was removed from the line. + void CutBackward(string text); + + /// + /// Tells the readline handler to finish this line of input and return it + /// + void Finish(); + + /// + /// Tells the ReadLine handler to abandon the current line and discard the entered text. This matches + /// conventional Ctrl+C behavior: the handler records nothing in history and completes without an error. + /// + void Cancel(); + + /// + /// Tells the ReadLine handler that the user has signaled the end of input, which is what Ctrl+D on an + /// empty line means to a shell. The line is discarded, and the caller is told that no + /// further input is coming. + /// + void EndOfInput(); + } +} diff --git a/InteractiveReadLine/KeyBehaviors/KeyId.cs b/InteractiveReadLine/KeyBehaviors/KeyId.cs index 575a8e0..21811cc 100644 --- a/InteractiveReadLine/KeyBehaviors/KeyId.cs +++ b/InteractiveReadLine/KeyBehaviors/KeyId.cs @@ -1,76 +1,112 @@ -using System; -using System.Collections.Generic; - -namespace InteractiveReadLine.KeyBehaviors -{ - /// - /// An identity for a key, is equatable so that it can be used in a dictionary - /// - public struct KeyId : IEquatable - { - public KeyId(char c) - { - this.Char = c; - this.Key = null; - this.HasAlt = false; - this.HasCtrl = false; - this.HasShift = false; - } - - public KeyId(ConsoleKey key, bool ctrl, bool alt, bool shift) - { - this.Char = null; - this.Key = key; - this.HasCtrl = ctrl; - this.HasAlt = alt; - this.HasShift = shift; - } - - public char? Char { get; set; } - public ConsoleKey? Key { get; set; } - - public bool HasCtrl { get; set; } - public bool HasAlt { get; set; } - public bool HasShift { get; set; } - - public override string ToString() - { - var repr = new List(); - if (HasCtrl) - repr.Add("Ctrl"); - if (HasAlt) - repr.Add("Alt"); - if (HasShift) - repr.Add("Shift"); - if (Key != null) - repr.Add(Key.ToString()); - else - repr.Add("'" + Char + "'"); - - return string.Join("+", repr); - } - - public bool Equals(KeyId other) - { - return Char == other.Char && Key == other.Key && HasCtrl == other.HasCtrl && HasAlt == other.HasAlt && HasShift == other.HasShift; - } - - public override bool Equals(object obj) - { - return obj is KeyId other && Equals(other); - } - - public override int GetHashCode() - { - unchecked - { - var hashCode = Char.GetHashCode(); - hashCode = (hashCode * 397) ^ Key.GetHashCode(); - hashCode = (hashCode * 397) ^ HasCtrl.GetHashCode(); - hashCode = (hashCode * 397) ^ HasAlt.GetHashCode(); - hashCode = (hashCode * 397) ^ HasShift.GetHashCode(); - return hashCode; - } - } - } -} \ No newline at end of file +using System; +using System.Collections.Generic; + +namespace InteractiveReadLine.KeyBehaviors +{ + /// + /// An identity for a key, is equatable so that it can be used in a dictionary + /// + public struct KeyId : IEquatable + { + /// + /// Creates an identity that matches a character, regardless of the keys that produced it. + /// + /// The character to match. + public KeyId(char c) + { + this.Char = c; + this.Key = null; + this.HasAlt = false; + this.HasCtrl = false; + this.HasShift = false; + } + + /// + /// Creates an identity matching a key pressed together with a particular set of modifiers. + /// + /// The key to match. + /// Whether the Control key must be held. + /// Whether the Alt key must be held. + /// Whether the Shift key must be held. + public KeyId(ConsoleKey key, bool ctrl, bool alt, bool shift) + { + this.Char = null; + this.Key = key; + this.HasCtrl = ctrl; + this.HasAlt = alt; + this.HasShift = shift; + } + + // These properties are deliberately get-only. KeyId values serve as dictionary keys, and mutating a + // value after using it to store a behavior would make the entry unreachable through that value. + /// + /// Gets the character this identity matches, or null when it matches a key rather than a character. + /// + public char? Char { get; } + /// + /// Gets the key this identity matches, or null when it matches a character rather than a key. + /// + public ConsoleKey? Key { get; } + + /// + /// Gets whether the Control key must be held for this identity to match. + /// + public bool HasCtrl { get; } + /// + /// Gets whether the Alt key must be held for this identity to match. + /// + public bool HasAlt { get; } + /// + /// Gets whether the Shift key must be held for this identity to match. + /// + public bool HasShift { get; } + + /// + /// Returns a readable description of the keypress, such as "Ctrl+Shift+Tab". + /// + public override string ToString() + { + var repr = new List(); + if (HasCtrl) + repr.Add("Ctrl"); + if (HasAlt) + repr.Add("Alt"); + if (HasShift) + repr.Add("Shift"); + if (Key != null) + repr.Add(Key.Value.ToString()); + else + repr.Add("'" + Char + "'"); + + return string.Join("+", repr); + } + + /// + /// Determines whether this identity matches the same keypress as another. + /// + public bool Equals(KeyId other) + { + return Char == other.Char && Key == other.Key && HasCtrl == other.HasCtrl && HasAlt == other.HasAlt && HasShift == other.HasShift; + } + + /// + public override bool Equals(object? obj) + { + return obj is KeyId other && Equals(other); + } + + /// + public override int GetHashCode() + { + unchecked + { + var hashCode = Char.GetHashCode(); + hashCode = (hashCode * 397) ^ Key.GetHashCode(); + hashCode = (hashCode * 397) ^ HasCtrl.GetHashCode(); + hashCode = (hashCode * 397) ^ HasAlt.GetHashCode(); + hashCode = (hashCode * 397) ^ HasShift.GetHashCode(); + return hashCode; + } + } + } +} diff --git a/InteractiveReadLine/LineState.cs b/InteractiveReadLine/LineState.cs index 690beca..856f3e2 100644 --- a/InteractiveReadLine/LineState.cs +++ b/InteractiveReadLine/LineState.cs @@ -1,54 +1,64 @@ -using System; - -namespace InteractiveReadLine -{ - /// - /// Contains the text and cursor position data produced by a user's interaction with the IReadLineProvider. - /// - public class LineState : IEquatable - { - /// - /// A string can implicitly be converted to a LineState, however the cursor position will be 0 by default. - /// - public static implicit operator LineState(string s) => new LineState(s, 0); - - public LineState(string text, int cursor) - { - Text = text; - Cursor = cursor; - } - - /// - /// Gets the cursor position as an integer offset from the first character - /// - public int Cursor { get; } - - /// - /// Gets the string contents of the line of text - /// - public string Text { get; } - - public bool Equals(LineState other) - { - if (ReferenceEquals(null, other)) return false; - if (ReferenceEquals(this, other)) return true; - return Cursor == other.Cursor && Text == other.Text; - } - - public override bool Equals(object obj) - { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != this.GetType()) return false; - return Equals((LineState) obj); - } - - public override int GetHashCode() - { - unchecked - { - return (Cursor * 397) ^ (Text != null ? Text.GetHashCode() : 0); - } - } - } +using System; + +namespace InteractiveReadLine +{ + /// + /// Contains the text and cursor position data produced by a user's interaction with the IReadLineProvider. + /// + public class LineState : IEquatable + { + /// + /// A string can implicitly be converted to a LineState, however the cursor position will be 0 by default. + /// + public static implicit operator LineState(string s) => new LineState(s, 0); + + /// + /// Creates a line state from the text of a line and a cursor position within it. + /// + /// The contents of the line + /// The cursor position, as an offset from the first character + public LineState(string text, int cursor) + { + Text = text; + Cursor = cursor; + } + + /// + /// Gets the cursor position as an integer offset from the first character + /// + public int Cursor { get; } + + /// + /// Gets the string contents of the line of text + /// + public string Text { get; } + + /// + /// Determines whether this line state holds the same text and cursor position as another. + /// + public bool Equals(LineState? other) + { + if (ReferenceEquals(null, other)) return false; + if (ReferenceEquals(this, other)) return true; + return Cursor == other.Cursor && Text == other.Text; + } + + /// + public override bool Equals(object? obj) + { + if (ReferenceEquals(null, obj)) return false; + if (ReferenceEquals(this, obj)) return true; + if (obj.GetType() != this.GetType()) return false; + return Equals((LineState) obj); + } + + /// + public override int GetHashCode() + { + unchecked + { + return (Cursor * 397) ^ (Text != null ? Text.GetHashCode() : 0); + } + } + } } \ No newline at end of file diff --git a/InteractiveReadLine/ReadLineConfig.cs b/InteractiveReadLine/ReadLineConfig.cs index ae5df80..56b9ea9 100644 --- a/InteractiveReadLine/ReadLineConfig.cs +++ b/InteractiveReadLine/ReadLineConfig.cs @@ -1,181 +1,201 @@ -using System; -using System.Collections.Generic; -using System.Text; -using InteractiveReadLine.Formatting; -using InteractiveReadLine.KeyBehaviors; -using InteractiveReadLine.Tokenizing; - -namespace InteractiveReadLine -{ - /// - /// The main configuration object for the ReadLineHandler, instances of this class carry all of the objects - /// which customize and control every aspect of the ReadLineHandler's behavior. Many standard behaviors are - /// provided through the CommonFormatters/CommonKeyBehaviors/CommonLexers tools, but custom behaviors can - /// be attached to this object instead. - /// - public class ReadLineConfig - { - private ReadLineConfig() - { - this.KeyBehaviors = new Dictionary>(); - } - - /// - /// Gets an Action which can be used to update the history. This is automatically set when the - /// - /// - public Action UpdateHistory { get; private set; } - - /// - /// Gets a list which contains the history of entered text, used for any behaviors which interact - /// with the entered history. - /// - public IReadOnlyList History { get; private set; } - - /// - /// Gets a providing function used to format the line to display based on a tokenization of the - /// readline content just before display. Requires a Lexer to work. - /// - public Func FormatterFromTokens { get; private set; } - - /// - /// Gets a format providing method which should format the line based on the raw LineState - /// - public Func FormatterFromLine { get; private set; } - - /// - /// Gets a dictionary which maps key press information to key behavior methods - /// - public Dictionary> KeyBehaviors { get; } - - /// - /// Gets the default key behavior, which is applied if no other key behavior is first located by - /// the KeyBehaviors dictionary - /// - public Action DefaultKeyBehavior { get; private set; } - - /// - /// Gets the lexer for the readline handler to use, which tokenizes a LineState object. - /// A non-null lexer is a critical component of auto-completion and certain token-based key behaviors - /// - public Func Lexer { get; private set; } - - /// - /// Gets the auto-completion provider, which is a method that takes a TokenizedLine object - /// and returns a list of suggestions for the token under the cursor. The TokenizedLine can - /// also be modified by the auto-completion method. - /// - public Func AutoCompletion { get; private set; } - - /// - /// Gets whether the configuration is capable of auto-completion, which requires both a Lexer - /// and an auto-completion handler. - /// - public bool CanAutoComplete => this.Lexer != null && this.AutoCompletion != null; - - /// - /// Sets the auto-completion handler for the configuration - /// - public ReadLineConfig SetAutoCompletion(Func handler) - { - this.AutoCompletion = handler; - return this; - } - - /// - /// Sets the lexer for the configuration - /// - public ReadLineConfig SetLexer(Func lexer) - { - this.Lexer = lexer; - return this; - } - - /// - /// Sets the formatter for the configuration using a formatter based on a tokenized line. This will - /// require that a lexer be provided for the configuration. - /// - /// - /// - public ReadLineConfig SetFormatter(Func formatter) - { - this.FormatterFromLine = null; - this.FormatterFromTokens = formatter; - return this; - } - - /// - /// Sets the formatter for the configuration using a formatter which only needs a simple LineState. - /// - /// - /// - public ReadLineConfig SetFormatter(Func formatter) - { - this.FormatterFromLine = formatter; - this.FormatterFromTokens = null; - return this; - } - - /// - /// Sets the collection of previously entered lines to be used as the command history. Use this setter - /// if you do not want the history to be automatically updated. Also, make sure to set some key behavior - /// which will make use of the history. - /// - /// - /// - public ReadLineConfig SetHistorySource(IReadOnlyList history) - { - this.History = history; - return this; - } - - /// - /// Sets the collection of previously entered lines to be used as the command history. This setter will - /// cause the history list to be automatically updated. Also, make sure to set some key behavior which - /// will make use of the history. - /// - /// - /// - public ReadLineConfig SetUpdatingHistorySource(List history) - { - this.SetHistoryUpdateAction(history.Add); - return this.SetHistorySource(history); - } - - /// - /// Sets the action delegate which will get call when the readline is finalized and the history would otherwise - /// update itself. Use this to provide a custom update action. - /// - /// - /// - public ReadLineConfig SetHistoryUpdateAction(Action action) - { - this.UpdateHistory = action; - return this; - } - - /// - /// Set the default KeyBehavior which is called when no other special action for a key has been registered - /// in the configuration. Typically this will be used to insert the key character into the input line. - /// - /// - /// - public ReadLineConfig SetDefaultKeyBehavior(Action defaultBehavior) - { - this.DefaultKeyBehavior = defaultBehavior; - return this; - } - - - /// - /// Gets an empty configuration with absolutely nothing set - /// - public static ReadLineConfig Empty => new ReadLineConfig(); - - /// - /// Gets a configuration that has the standard key behaviors added to it - /// - public static ReadLineConfig Basic => new ReadLineConfig().AddStandardKeys(); - - } -} \ No newline at end of file +using System; +using System.Collections.Generic; +using System.Text; +using InteractiveReadLine.Formatting; +using InteractiveReadLine.KeyBehaviors; +using InteractiveReadLine.Tokenizing; + +namespace InteractiveReadLine +{ + /// + /// The main configuration object for the ReadLineHandler, instances of this class carry all of the objects + /// which customize and control every aspect of the ReadLineHandler's behavior. Many standard behaviors are + /// provided through the CommonFormatters/CommonKeyBehaviors/CommonLexers tools, but custom behaviors can + /// be attached to this object instead. + /// + public class ReadLineConfig + { + private ReadLineConfig() + { + this.KeyBehaviors = new Dictionary>(); + } + + /// + /// Gets an Action that is invoked with the finalized line when a ReadLine operation completes. The + /// action is responsible for recording the line in the history. SetUpdatingHistorySource configures + /// this action automatically, or callers can configure it directly with SetHistoryUpdateAction. It is + /// null when history updates are disabled, in which case no line is recorded. + /// + public Action? UpdateHistory { get; private set; } + + /// + /// Gets the history of entered text, or null when no history source is configured. + /// + public IReadOnlyList? History { get; private set; } + + /// + /// Gets the formatter that processes a tokenized line before display, or null when no token-based + /// formatter is configured. The formatter requires a Lexer. + /// + public Func? FormatterFromTokens { get; private set; } + + /// + /// Gets the formatter that processes the raw LineState, or null when no line-based formatter is + /// configured. + /// + public Func? FormatterFromLine { get; private set; } + + /// + /// Gets a dictionary which maps key press information to key behavior methods + /// + public Dictionary> KeyBehaviors { get; } + + /// + /// Gets the default key behavior applied when KeyBehaviors contains no behavior for the pressed key. + /// The value is null when no default behavior is configured. + /// + public Action? DefaultKeyBehavior { get; private set; } + + /// + /// Gets the lexer that tokenizes a LineState, or null when no lexer is configured. A lexer is required + /// for auto-completion and certain token-based key behaviors. + /// + public Func? Lexer { get; private set; } + + /// + /// Gets the auto-completion provider, or null when none is configured. The provider receives a + /// TokenizedLine and returns suggestions for the token under the cursor. It can also modify the + /// TokenizedLine. + /// + public Func? AutoCompletion { get; private set; } + + /// + /// Gets whether the configuration is capable of auto-completion, which requires both a Lexer + /// and an auto-completion handler. + /// + public bool CanAutoComplete => this.Lexer != null && this.AutoCompletion != null; + + /// + /// Sets the auto-completion handler for the configuration + /// + public ReadLineConfig SetAutoCompletion(Func handler) + { + this.AutoCompletion = handler; + return this; + } + + /// + /// Sets the lexer for the configuration + /// + public ReadLineConfig SetLexer(Func lexer) + { + this.Lexer = lexer; + return this; + } + + /// + /// Sets the formatter for the configuration using a formatter based on a tokenized line. This will + /// require that a lexer be provided for the configuration. + /// + /// + /// + public ReadLineConfig SetFormatter(Func formatter) + { + this.FormatterFromLine = null; + this.FormatterFromTokens = formatter; + return this; + } + + /// + /// Sets the formatter for the configuration using a formatter which only needs a simple LineState. + /// + /// + /// + public ReadLineConfig SetFormatter(Func formatter) + { + this.FormatterFromLine = formatter; + this.FormatterFromTokens = null; + return this; + } + + /// + /// Sets the collection of previously entered lines to be used as the command history. Use this setter + /// if you do not want the history to be automatically updated. Also, make sure to set some key behavior + /// which will make use of the history. + /// + /// + /// + public ReadLineConfig SetHistorySource(IReadOnlyList history) + { + this.History = history; + return this; + } + + /// + /// Sets the collection of previously entered lines to be used as the command history. This setter will + /// cause the history list to be automatically updated. Also, make sure to set some key behavior which + /// will make use of the history. + /// + /// + /// The update action created here skips lines that are empty or contain only whitespace. It also skips + /// a line that is identical to the most recent entry. These entries therefore do not crowd out useful + /// history. To record every finalized line, provide your own action through SetHistoryUpdateAction. + /// + /// + /// + public ReadLineConfig SetUpdatingHistorySource(List history) + { + if (history == null) + throw new ArgumentNullException(nameof(history)); + + this.SetHistoryUpdateAction(text => + { + if (string.IsNullOrWhiteSpace(text)) + return; + + if (history.Count > 0 && history[history.Count - 1] == text) + return; + + history.Add(text); + }); + + return this.SetHistorySource(history); + } + + /// + /// Sets the action delegate which will get call when the readline is finalized and the history would otherwise + /// update itself. Use this to provide a custom update action. + /// + /// + /// + public ReadLineConfig SetHistoryUpdateAction(Action action) + { + this.UpdateHistory = action; + return this; + } + + /// + /// Set the default KeyBehavior which is called when no other special action for a key has been registered + /// in the configuration. Typically this will be used to insert the key character into the input line. + /// + /// + /// + public ReadLineConfig SetDefaultKeyBehavior(Action defaultBehavior) + { + this.DefaultKeyBehavior = defaultBehavior; + return this; + } + + + /// + /// Gets an empty configuration with absolutely nothing set + /// + public static ReadLineConfig Empty => new ReadLineConfig(); + + /// + /// Gets a configuration that has the standard key behaviors added to it + /// + public static ReadLineConfig Basic => new ReadLineConfig().AddStandardKeys(); + + } +} diff --git a/InteractiveReadLine/ReadLineHandler.cs b/InteractiveReadLine/ReadLineHandler.cs index da7ea99..442e84c 100644 --- a/InteractiveReadLine/ReadLineHandler.cs +++ b/InteractiveReadLine/ReadLineHandler.cs @@ -1,324 +1,518 @@ -using System; -using System.Diagnostics; -using System.Linq; -using System.Runtime.InteropServices; -using System.Text; -using InteractiveReadLine.Formatting; -using InteractiveReadLine.KeyBehaviors; -using InteractiveReadLine.Tokenizing; - -namespace InteractiveReadLine -{ - /// - /// This class handles getting a single line of input from the underlying IReadLineProvider. It reads keys from the - /// provider, determines what the current line of text being edited should be and where the cursor should be positioned. - /// It pushes out the text to the provider, which also serves as the view. - /// - public class ReadLineHandler : IKeyBehaviorTarget - { - private readonly IReadLineProvider _provider; - private readonly ReadLineConfig _config; - private int _cursorPos; - private int _autoCompleteIndex; - private TokenizedLine _autoCompleteTokens; - private bool _autoCompleteCalled = false; - private string[] _autoCompleteSuggestions; - - private int _historyIndex; - private LineState _preHistoryState; - - private bool _finishTrigger = false; - - public ReadLineHandler(IReadLineProvider provider, ReadLineConfig config=null) - { - _config = config ?? ReadLineConfig.Basic; - _provider = provider; - TextBuffer = new StringBuilder(); - _cursorPos = 0; - - _autoCompleteIndex = int.MinValue; - _autoCompleteSuggestions = null; - - // The history index should start one element past the length of the current history - _historyIndex = config?.History?.Any() == true ? config.History.Count : 0; - } - - /// - /// Gets the current LineState representation of the text and the cursor position - /// - public LineState LineState => new LineState(TextBuffer.ToString(), _cursorPos); - - /// - public StringBuilder TextBuffer { get; } - - /// - public int CursorPosition - { - get => _cursorPos; - set - { - _cursorPos = value; - if (_cursorPos > TextBuffer.Length) - _cursorPos = TextBuffer.Length; - if (_cursorPos < 0) - _cursorPos = 0; - } - } - - /// - public ConsoleKeyInfo ReceivedKey { get; private set; } - - /// - public void AutoCompleteNext() - { - if (_autoCompleteIndex >= 0) - { - // Next index - _autoCompleteIndex++; - if (_autoCompleteIndex >= _autoCompleteSuggestions.Length) - _autoCompleteIndex = 0; - - this.SetAutoCompleteText(); - } - else - this.StartAutoComplete(); - } - - /// - public void AutoCompletePrevious() - { - if (_autoCompleteIndex >= 0) - { - // Previous index - _autoCompleteIndex--; - if (_autoCompleteIndex < 0) - _autoCompleteIndex = _autoCompleteSuggestions.Length - 1; - - this.SetAutoCompleteText(); - } - else - this.StartAutoComplete(); - - } - - /// - public void InsertText(FormattedText text) - { - _provider.InsertText(text); - } - - /// - public TokenizedLine GetTextTokens() - { - return _config.Lexer?.Invoke(this.LineState); - } - - public void HistoryNext() - { - // If there is no history, we don't need to do anything - if (_config.History?.Any() != true) - return; - - // If we're at the end of the history (including the entered text) we do nothing - if (_historyIndex == _config.History.Count) - return; - - // Otherwise we increment the history index and set the current text buffer based - // on whether or not we still have another history element - _historyIndex++; - this.TextBuffer.Clear(); - if (_historyIndex == _config.History.Count) - { - this.TextBuffer.Append(_preHistoryState.Text); - this.CursorPosition = _preHistoryState.Cursor; - } - else - { - this.TextBuffer.Append(_config.History[_historyIndex]); - this.CursorPosition = this.TextBuffer.Length; - } - } - - public void HistoryPrevious() - { - // If there is no history, we don't need to do anything - if (_config.History?.Any() != true) - return; - - if (_historyIndex == 0) - return; - - // Check if we're about to leave entered text to go backwards in the history. If so - // we want to store it first. - if (_historyIndex == _config.History.Count) - { - _preHistoryState = new LineState(this.LineState.Text, this.LineState.Cursor); - } - - _historyIndex--; - this.TextBuffer.Clear(); - this.TextBuffer.Append(_config.History[_historyIndex]); - this.CursorPosition = this.TextBuffer.Length; - } - - /// - /// Interactively manage the user input of a line of text at the console, returning the contents - /// of the text when finished. - /// - public string ReadLine() - { - // The display must be updated at the beginning if any prompts or other prefix/suffix text - // is to be displayed - this.UpdateDisplay(); - - // The main processing loop of the handler, this loop will block until it receives a single key from the - // console. It will then attempt to look up a key behavior for that key, and if it finds one it will - // invoke it, otherwise it will invoke the default behavior if there is one. After that it will check - // if the condition to finish the input has been set, and if not it will update the display and wait - // for the next key. - while (true) - { - this.ReceivedKey = _provider.ReadKey(); - - // We will need to check if the line state (text & cursor position) is altered by the - // key behavior which will be run, so we store the current state now - var previousState = this.LineState; - _autoCompleteCalled = false; - - // See if there's a specific behavior which should be mapped to this key, - // and if so, run it instead of checking the insert/enter behaviors - var behavior = this.GetKeyAction(ReceivedKey); - if (behavior != null) - { - behavior.Invoke(this); - } - else - { - _config.DefaultKeyBehavior?.Invoke(this); - } - - // Check if the Finish behavior was called, indicating that we can exit this method - // and return the contents of the text buffer to the caller - if (_finishTrigger) - break; - - // If the text contents or the cursor have changed at all, and we weren't currently - // doing autocomplete, we need to invalidate the auto-completion information - if ((!previousState.Equals(this.LineState)) && !_autoCompleteCalled) - this.InvalidateAutoComplete(); - - this.UpdateDisplay(); - } - - // If there is a delegate to update the history, invoke it now - _config.UpdateHistory?.Invoke(TextBuffer.ToString()); - - return TextBuffer.ToString(); - } - - /// - /// Updates the display on the underlying provider. This is where any formatter is called, immediately - /// prior to the display being set. - /// - private void UpdateDisplay() - { - // Finally, if we have an available formatter, we can get a display format from here - var display = new LineDisplayState(string.Empty, TextBuffer.ToString(), string.Empty, _cursorPos); - - if (_config.FormatterFromLine != null) - display = _config.FormatterFromLine.Invoke(LineState); - else if (_config.FormatterFromTokens != null && _config.Lexer != null) - display = _config.FormatterFromTokens(GetTextTokens()); - - _provider.SetDisplay(display); - } - - /// - /// Check a ConsoleKeyInfo to see if the configuration object has a behavior registered - /// for that key. The character is checked first, and if that fails, the ConsoleKey and the modifier keys - /// are checked. If that fails, null is returned - /// - private Action GetKeyAction(ConsoleKeyInfo info) - { - var charKey = new KeyId(info.KeyChar); - if (_config.KeyBehaviors.ContainsKey(charKey)) - return _config.KeyBehaviors[charKey]; - - var key = new KeyId(info.Key, (info.Modifiers & ConsoleModifiers.Control) != 0, - (info.Modifiers & ConsoleModifiers.Alt) != 0, (info.Modifiers & ConsoleModifiers.Shift) != 0); - if (_config.KeyBehaviors.ContainsKey(key)) - return _config.KeyBehaviors[key]; - - return null; - } - - /// - /// Initializes and begins the AutoComplete functionality. AutoComplete is its own special state of interaction, - /// and must be initialized before the next/previous functions will work. It then can continue until an action - /// other than next/previous occurs, after which it will have to be reinitialized to be used again. The - /// initialization process involves fetching the valid suggestions for the currently entered text and cursor - /// position. - /// - private void StartAutoComplete() - { - if (!_config.CanAutoComplete) - return; - - _autoCompleteTokens = _config.Lexer(new LineState(TextBuffer.ToString(), _cursorPos)); - if (_autoCompleteTokens.CursorToken == null) - return; - - _autoCompleteSuggestions = _config.AutoCompletion(_autoCompleteTokens) ?? Array.Empty(); - - if (_autoCompleteTokens.Text != TextBuffer.ToString()) - { - TextBuffer.Clear(); - TextBuffer.Append(_autoCompleteTokens.Text); - CursorPosition = _autoCompleteTokens.Cursor; - } - - if (_autoCompleteSuggestions.Any()) - { - _autoCompleteIndex = 0; - SetAutoCompleteText(); - } - - } - - /// - /// If AutoComplete is currently active, the only allowable actions are next/previous. If any other - /// modification is made to the line, the current AutoComplete suggestions are invalidated and any attempt - /// to use the next/previous functionality will require a reinitialization of the AutoComplete mechanism. - /// - private void InvalidateAutoComplete() - { - _autoCompleteIndex = Int32.MinValue; - _autoCompleteTokens = null; - _autoCompleteSuggestions = null; - } - - /// - /// Inserts the text from the currently selected auto complete suggestion into the token under the cursor. Only - /// works if the system is currently in autocomplete mode. - /// - private void SetAutoCompleteText() - { - if (!_config.CanAutoComplete || _autoCompleteTokens == null || _autoCompleteIndex < 0) - return; - - _autoCompleteCalled = true; - _autoCompleteTokens.CursorToken.Text = _autoCompleteSuggestions[_autoCompleteIndex]; - _autoCompleteTokens.CursorToken.Cursor = _autoCompleteTokens.CursorToken.Text.Length; - - TextBuffer.Clear(); - TextBuffer.Append(_autoCompleteTokens.Text); - CursorPosition = _autoCompleteTokens.Cursor; - - } - - /// - /// Causes the ReadLine handler to finish, returning the contents of the text buffer - /// - public void Finish() => _finishTrigger = true; - } -} \ No newline at end of file +using System; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using InteractiveReadLine.Formatting; +using InteractiveReadLine.KeyBehaviors; +using InteractiveReadLine.Tokenizing; + +namespace InteractiveReadLine +{ + /// + /// This class handles getting a single line of input from the underlying IReadLineProvider. It reads keys from the + /// provider, determines what the current line of text being edited should be and where the cursor should be positioned. + /// It pushes out the text to the provider, which also serves as the view. + /// + public class ReadLineHandler : IKeyBehaviorTarget + { + private readonly IReadLineProvider _provider; + private readonly ReadLineConfig _config; + private int _cursorPos; + private int _autoCompleteIndex; + private TokenizedLine? _autoCompleteTokens; + private bool _autoCompleteCalled = false; + private string[]? _autoCompleteSuggestions; + + private int _historyIndex; + private LineState _preHistoryState; + + // Null while the user is still editing; set by Finish, Cancel or EndOfInput to the kind of result the + // read line operation should produce, which also ends the processing loop. + private ReadLineResultKind? _resultKind; + + // The text accumulated by consecutive cuts and two flags that determine where a run starts and ends. + // A run continues while each key performs a cut, allowing one paste to restore text from several cuts. + private string _cutBuffer = string.Empty; + private bool _cutOnThisKey; + private bool _cutOnPreviousKey; + + /// + /// Creates a handler which will read a single line of input through the given provider. + /// + /// The backend which reads keys and displays the line + /// + /// The configuration controlling key behaviors, formatting, lexing, auto-completion and history, or + /// null to use ReadLineConfig.Basic. + /// + public ReadLineHandler(IReadLineProvider provider, ReadLineConfig? config=null) + { + _config = config ?? ReadLineConfig.Basic; + _provider = provider; + TextBuffer = new StringBuilder(); + _cursorPos = 0; + + _autoCompleteIndex = int.MinValue; + _autoCompleteSuggestions = null; + + // This is the state to restore when the user navigates forward out of the history. HistoryNext can + // run before HistoryPrevious stores a state here, so initialize it to an empty state. + _preHistoryState = new LineState(string.Empty, 0); + + // The history index should start one element past the length of the current history + _historyIndex = _config.History?.Any() == true ? _config.History.Count : 0; + } + + /// + /// Gets the current LineState representation of the text and the cursor position + /// + public LineState LineState => new LineState(TextBuffer.ToString(), _cursorPos); + + /// + public StringBuilder TextBuffer { get; } + + /// + public int CursorPosition + { + get => _cursorPos; + set + { + _cursorPos = value; + if (_cursorPos > TextBuffer.Length) + _cursorPos = TextBuffer.Length; + if (_cursorPos < 0) + _cursorPos = 0; + } + } + + /// + public ConsoleKeyInfo ReceivedKey { get; private set; } + + /// + public void AutoCompleteNext() + { + if (_autoCompleteIndex >= 0 && _autoCompleteSuggestions != null) + { + // Next index + _autoCompleteIndex++; + if (_autoCompleteIndex >= _autoCompleteSuggestions.Length) + _autoCompleteIndex = 0; + + this.SetAutoCompleteText(); + } + else + this.StartAutoComplete(); + } + + /// + public void AutoCompletePrevious() + { + if (_autoCompleteIndex >= 0 && _autoCompleteSuggestions != null) + { + // Previous index + _autoCompleteIndex--; + if (_autoCompleteIndex < 0) + _autoCompleteIndex = _autoCompleteSuggestions.Length - 1; + + this.SetAutoCompleteText(); + } + else + this.StartAutoComplete(); + + } + + /// + public void InsertText(FormattedText text) + { + _provider.InsertText(text); + } + + /// + public TokenizedLine? GetTextTokens() + { + return _config.Lexer?.Invoke(this.LineState); + } + + /// + public string CutBuffer => _cutBuffer; + + /// + public void CutForward(string text) => this.RecordCut(text, true); + + /// + public void CutBackward(string text) => this.RecordCut(text, false); + + /// + /// Adds text to the cut buffer, starting a new buffer unless this key is continuing a run of cuts. + /// + /// The text that was removed from the line. + /// + /// True when the text was in front of the cursor and belongs at the end of the buffer, false when it + /// was behind the cursor and belongs at the front. + /// + private void RecordCut(string text, bool fromInFrontOfCursor) + { + // The first cut after anything else discards whatever an earlier run had accumulated. + if (!_cutOnPreviousKey && !_cutOnThisKey) + _cutBuffer = string.Empty; + + // Mark the key as a cut even when it removes nothing, so cutting at the end of a line does not end + // the current run. + _cutOnThisKey = true; + + if (string.IsNullOrEmpty(text)) + return; + + _cutBuffer = fromInFrontOfCursor + ? _cutBuffer + text + : text + _cutBuffer; + } + + /// + /// Brings the history index into the inclusive range from zero through the length of the history. The + /// final position represents the text that the user entered before navigating backward into history. + /// + /// + /// The configuration holds a live reference to the history collection, so entries can be removed after + /// this handler is constructed and before the user navigates. Without clamping, the index could point + /// past the end of the collection and cause an exception when used. The lower bound does not require + /// clamping because the index starts at zero or above and is decremented only after a check for zero. + /// + private void ClampHistoryIndex() + { + var history = _config.History; + if (history != null && _historyIndex > history.Count) + _historyIndex = history.Count; + } + + /// + public void HistoryNext() + { + // If there is no history, we don't need to do anything + if (_config.History?.Any() != true) + return; + + this.ClampHistoryIndex(); + + // If we're at the end of the history (including the entered text) we do nothing + if (_historyIndex == _config.History.Count) + return; + + // Otherwise we increment the history index and set the current text buffer based + // on whether or not we still have another history element + _historyIndex++; + this.TextBuffer.Clear(); + if (_historyIndex == _config.History.Count) + { + this.TextBuffer.Append(_preHistoryState.Text); + this.CursorPosition = _preHistoryState.Cursor; + } + else + { + this.TextBuffer.Append(_config.History[_historyIndex]); + this.CursorPosition = this.TextBuffer.Length; + } + } + + /// + public void HistoryPrevious() + { + // If there is no history, we don't need to do anything + if (_config.History?.Any() != true) + return; + + this.ClampHistoryIndex(); + + if (_historyIndex == 0) + return; + + // Check if we're about to leave entered text to go backwards in the history. If so + // we want to store it first. + if (_historyIndex == _config.History.Count) + { + _preHistoryState = new LineState(this.LineState.Text, this.LineState.Cursor); + } + + _historyIndex--; + this.TextBuffer.Clear(); + this.TextBuffer.Append(_config.History[_historyIndex]); + this.CursorPosition = this.TextBuffer.Length; + } + + /// + /// Interactively manage the user input of a line of text at the console, returning the contents + /// of the text when finished. + /// + /// A token that cancels the read. + /// + /// The finished text; null if the user signaled the end of input; or an empty string if the user + /// abandoned the line. Use Read to distinguish an abandoned line from an entered empty line. + /// + /// The token was canceled before input completed. + public string? ReadLine(CancellationToken cancellationToken = default) => + this.Read(cancellationToken).ToText(); + + /// + /// Interactively manages a line of console input and returns a result that describes the text and how + /// the interaction ended. + /// + /// + /// A token that cancels the read. Cancellation raises an OperationCanceledException instead of + /// producing a result, which is what distinguishes it from the user abandoning the line with Ctrl+C. + /// + /// The token was canceled before input completed. + public ReadLineResult Read(CancellationToken cancellationToken = default) + { + // The display must be updated at the beginning if any prompts or other prefix/suffix text + // is to be displayed + this.UpdateDisplay(); + + // The main processing loop of the handler, this loop will block until it receives a single key from the + // console. It will then attempt to look up a key behavior for that key, and if it finds one it will + // invoke it, otherwise it will invoke the default behavior if there is one. After that it will check + // if the condition to finish the input has been set, and if not it will update the display and wait + // for the next key. + while (true) + { + this.ReceivedKey = _provider.ReadKey(cancellationToken); + + if (this.ProcessKey()) + break; + + this.UpdateDisplay(); + } + + return this.BuildResult(); + } + + /// + /// Interactively manages a line of console input without blocking a thread while waiting for keys, + /// returning the contents of the text when finished. + /// + /// A token that cancels the read. + /// + /// The finished text; null if the user signaled the end of input; or an empty string if the user + /// abandoned the line. Use ReadAsync to distinguish an abandoned line from an entered empty line. + /// + /// The token was canceled before input completed. + public async Task ReadLineAsync(CancellationToken cancellationToken = default) + { + var result = await this.ReadAsync(cancellationToken).ConfigureAwait(false); + return result.ToText(); + } + + /// + /// Interactively manages a line of console input without blocking a thread while waiting for keys, and + /// returns a result that describes the text and how the interaction ended. + /// + /// + /// This method performs the same interaction as Read and differs only in how it waits for each key. Each + /// key behavior, auto-completion operation, and history operation runs synchronously on the thread that + /// resumes the wait. + /// + /// + /// A token that cancels the read. Cancellation raises an OperationCanceledException instead of + /// producing a result, which is what distinguishes it from the user abandoning the line with Ctrl+C. + /// + /// A task that produces the completed interaction result. + /// The token was canceled before input completed. + public async Task ReadAsync(CancellationToken cancellationToken = default) + { + this.UpdateDisplay(); + + while (true) + { + this.ReceivedKey = await _provider.ReadKeyAsync(cancellationToken).ConfigureAwait(false); + + if (this.ProcessKey()) + break; + + this.UpdateDisplay(); + } + + return this.BuildResult(); + } + + /// + /// Runs the behavior registered for the key currently in ReceivedKey, then reports whether the + /// interaction is over. + /// + /// True if a behavior ended the interaction; otherwise, false. + private bool ProcessKey() + { + // We will need to check if the line state (text & cursor position) is altered by the + // key behavior which will be run, so we store the current state now + var previousState = this.LineState; + _autoCompleteCalled = false; + _cutOnThisKey = false; + + // See if there's a specific behavior which should be mapped to this key, + // and if so, run it instead of checking the insert/enter behaviors + var behavior = this.GetKeyAction(ReceivedKey); + if (behavior != null) + { + behavior.Invoke(this); + } + else + { + _config.DefaultKeyBehavior?.Invoke(this); + } + + // A cut run continues only while every key performs a cut. Any other key ends the run, so the next + // cut clears the buffer. Custom cut behaviors participate by calling CutForward or CutBackward. + _cutOnPreviousKey = _cutOnThisKey; + + // Check if a behavior ended the interaction, in which case we can stop reading keys + if (_resultKind != null) + return true; + + // If the text contents or the cursor have changed at all, and we weren't currently + // doing autocomplete, we need to invalidate the auto-completion information + if ((!previousState.Equals(this.LineState)) && !_autoCompleteCalled) + this.InvalidateAutoComplete(); + + return false; + } + + /// + /// Produces the interaction result and updates history only when the user finishes a line. + /// + private ReadLineResult BuildResult() + { + // A canceled or ended interaction discards its text. Pass only a finished line to the history + // update action. + if (_resultKind != ReadLineResultKind.Line) + return _resultKind == ReadLineResultKind.Cancelled + ? ReadLineResult.Cancelled + : ReadLineResult.EndOfInput; + + var text = TextBuffer.ToString(); + _config.UpdateHistory?.Invoke(text); + + return ReadLineResult.ForLine(text); + } + + /// + /// Updates the display on the underlying provider. This is where any formatter is called, immediately + /// prior to the display being set. + /// + private void UpdateDisplay() + { + // Finally, if we have an available formatter, we can get a display format from here + var display = new LineDisplayState(string.Empty, TextBuffer.ToString(), string.Empty, _cursorPos); + + if (_config.FormatterFromLine != null) + display = _config.FormatterFromLine.Invoke(LineState); + else if (_config.FormatterFromTokens != null && _config.Lexer != null) + { + var tokens = this.GetTextTokens(); + if (tokens != null) + display = _config.FormatterFromTokens(tokens); + } + + _provider.SetDisplay(display); + } + + /// + /// Check a ConsoleKeyInfo to see if the configuration object has a behavior registered + /// for that key. The character is checked first, and if that fails, the ConsoleKey and the modifier keys + /// are checked. If that fails, null is returned + /// + private Action? GetKeyAction(ConsoleKeyInfo info) + { + var charKey = new KeyId(info.KeyChar); + if (_config.KeyBehaviors.ContainsKey(charKey)) + return _config.KeyBehaviors[charKey]; + + var key = new KeyId(info.Key, (info.Modifiers & ConsoleModifiers.Control) != 0, + (info.Modifiers & ConsoleModifiers.Alt) != 0, (info.Modifiers & ConsoleModifiers.Shift) != 0); + if (_config.KeyBehaviors.ContainsKey(key)) + return _config.KeyBehaviors[key]; + + return null; + } + + /// + /// Initializes and begins the AutoComplete functionality. AutoComplete is its own special state of interaction, + /// and must be initialized before the next/previous functions will work. It then can continue until an action + /// other than next/previous occurs, after which it will have to be reinitialized to be used again. The + /// initialization process involves fetching the valid suggestions for the currently entered text and cursor + /// position. + /// + private void StartAutoComplete() + { + // CanAutoComplete tests whether both values are present. Store them in local variables so nullable + // analysis can preserve that relationship throughout the method. + var lexer = _config.Lexer; + var autoCompletion = _config.AutoCompletion; + if (lexer == null || autoCompletion == null) + return; + + _autoCompleteTokens = lexer(new LineState(TextBuffer.ToString(), _cursorPos)); + if (_autoCompleteTokens?.CursorToken == null) + return; + + _autoCompleteSuggestions = autoCompletion(_autoCompleteTokens) ?? Array.Empty(); + + if (_autoCompleteTokens.Text != TextBuffer.ToString()) + { + TextBuffer.Clear(); + TextBuffer.Append(_autoCompleteTokens.Text); + CursorPosition = _autoCompleteTokens.Cursor; + } + + if (_autoCompleteSuggestions.Any()) + { + _autoCompleteIndex = 0; + SetAutoCompleteText(); + } + + } + + /// + /// If AutoComplete is currently active, the only allowable actions are next/previous. If any other + /// modification is made to the line, the current AutoComplete suggestions are invalidated and any attempt + /// to use the next/previous functionality will require a reinitialization of the AutoComplete mechanism. + /// + private void InvalidateAutoComplete() + { + _autoCompleteIndex = Int32.MinValue; + _autoCompleteTokens = null; + _autoCompleteSuggestions = null; + } + + /// + /// Inserts the text from the currently selected auto complete suggestion into the token under the cursor. Only + /// works if the system is currently in autocomplete mode. + /// + private void SetAutoCompleteText() + { + var tokens = _autoCompleteTokens; + var suggestions = _autoCompleteSuggestions; + var cursorToken = tokens?.CursorToken; + + if (tokens == null || suggestions == null || cursorToken == null || _autoCompleteIndex < 0) + return; + + _autoCompleteCalled = true; + cursorToken.Text = suggestions[_autoCompleteIndex]; + cursorToken.Cursor = cursorToken.Text.Length; + + TextBuffer.Clear(); + TextBuffer.Append(tokens.Text); + CursorPosition = tokens.Cursor; + + } + + /// + /// Causes the ReadLine handler to finish, returning the contents of the text buffer + /// + public void Finish() => _resultKind = ReadLineResultKind.Line; + + /// + public void Cancel() => _resultKind = ReadLineResultKind.Cancelled; + + /// + public void EndOfInput() => _resultKind = ReadLineResultKind.EndOfInput; + } +} diff --git a/InteractiveReadLine/ReadLineResult.cs b/InteractiveReadLine/ReadLineResult.cs new file mode 100644 index 0000000..1471b21 --- /dev/null +++ b/InteractiveReadLine/ReadLineResult.cs @@ -0,0 +1,115 @@ +using System; + +namespace InteractiveReadLine +{ + /// + /// Describes how a read line operation came to an end. + /// + public enum ReadLineResultKind + { + /// + /// The user finished a line of input, typically by pressing enter. The text is available on the result. + /// + Line, + + /// + /// The user abandoned the line, typically by pressing Ctrl+C. Whatever had been typed is discarded. + /// + Cancelled, + + /// + /// The user signaled that there is no more input, typically by pressing Ctrl+D on an empty line. + /// + EndOfInput + } + + /// + /// Represents the outcome of a read line operation: a completed line or one of two outcomes that do not + /// produce a line. + /// + /// + /// The simpler ReadLine methods flatten this to a string, returning null for EndOfInput and an empty + /// string for Cancelled. Use the Read methods and this type when the difference matters, for example to + /// tell an abandoned line apart from a genuinely empty one. + /// + public readonly struct ReadLineResult : IEquatable + { + private ReadLineResult(ReadLineResultKind kind, string? text) + { + this.Kind = kind; + this.Text = text; + } + + /// + /// Gets how the read line operation ended. + /// + public ReadLineResultKind Kind { get; } + + /// + /// Gets the text that the user entered. This value is non-null when Kind is Line and null otherwise. + /// + public string? Text { get; } + + /// + /// Gets whether the operation produced a line of text. + /// + public bool IsLine => this.Kind == ReadLineResultKind.Line; + + /// + /// Creates a result carrying a finished line of text. + /// + public static ReadLineResult ForLine(string text) + { + if (text == null) + throw new ArgumentNullException(nameof(text)); + + return new ReadLineResult(ReadLineResultKind.Line, text); + } + + /// + /// Gets a result representing a line the user abandoned. + /// + public static ReadLineResult Cancelled => new ReadLineResult(ReadLineResultKind.Cancelled, null); + + /// + /// Gets a result representing the end of the user's input. + /// + public static ReadLineResult EndOfInput => new ReadLineResult(ReadLineResultKind.EndOfInput, null); + + /// + /// Flattens this result to a string, returning the text for a finished line, null for the end of + /// input, and an empty string for a line the user abandoned. + /// + public string? ToText() + { + switch (this.Kind) + { + case ReadLineResultKind.Line: + return this.Text; + case ReadLineResultKind.Cancelled: + return string.Empty; + default: + return null; + } + } + + /// + public bool Equals(ReadLineResult other) => this.Kind == other.Kind && this.Text == other.Text; + + /// + public override bool Equals(object? obj) => obj is ReadLineResult other && this.Equals(other); + + /// + public override int GetHashCode() + { + unchecked + { + return ((int) this.Kind * 397) ^ (this.Text?.GetHashCode() ?? 0); + } + } + + /// + public override string ToString() => + this.IsLine ? $"{this.Kind}: \"{this.Text}\"" : this.Kind.ToString(); + } +} diff --git a/InteractiveReadLine/Tokenizing/CommonLexers.cs b/InteractiveReadLine/Tokenizing/CommonLexers.cs index bcc031e..3b34338 100644 --- a/InteractiveReadLine/Tokenizing/CommonLexers.cs +++ b/InteractiveReadLine/Tokenizing/CommonLexers.cs @@ -1,111 +1,143 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using Lexer = System.Func; -using RegexList = System.Collections.Generic.List; - -namespace InteractiveReadLine.Tokenizing -{ - public static class CommonLexers - { - public static RegexList Regex => new RegexList(); - - /// - /// Adds a new token type to the end of the regular expression token list. The token must begin with - /// the regular expression start of text character (^) or an ArgumentException will be thrown - /// - /// - /// The regular expression pattern which identifies the token, must start with ^ - /// An optional type code, such that any token matched by this definition will have - /// this value in the .TypeCode property of the IToken interface - /// - public static RegexList AddTokenType(this RegexList list, string pattern, int typeCode = 0) - { - if (!pattern.StartsWith("^")) - throw new ArgumentException($"Regex token definitions must start with the ^ character, which was not present in the pattern '{pattern}'"); - - list.Add(new RegexTokenDef(pattern, typeCode)); - return list; - } - - public static RegexList AddAnyNonWhitespace(this RegexList list, int typeCode = 0) => - list.AddTokenType(@"^\S+", typeCode); - - public static RegexList AddDoubleQuoteStringLiterals(this RegexList list, int typeCode = 0) => - list.AddTokenType(@"^""(?:[^""\\]|\\.)*""", typeCode); - - public static RegexList AddSingleQuoteStringLiterals(this RegexList list, int typeCode = 0) => - list.AddTokenType(@"^'(?:[^'\\]|\\.)*'", typeCode); - - /// - /// From a list of RegexTokenDefs, produce a function that will tokenize a LineState according to - /// the specified token definitions in the order they were provided. Effectively this renders a list - /// of regular expression token definitions into a functioning lexer. - /// - /// - /// - public static Lexer ToLexer(this RegexList list) - { - if (!list.Any()) - throw new ArgumentException("The RegexTokenDefs list must not be empty"); - - return lineState => - { - - var tokenized = new TokenizedLine(); - - var ignored = new StringBuilder(); - for (int i = 0; i < lineState.Text.Length; i++) - { - var substring = lineState.Text.Substring(i); - - bool hasMatch = false; - - foreach (var tokenDef in list) - { - var match = tokenDef.Regex.Match(substring); - if (match.Success) - { - if (ignored.Length > 0) - { - tokenized.Add(ignored.ToString(), true, null); - ignored.Clear(); - } - - tokenized.Add(match.Value, false, null, tokenDef.TypeCode); - i += match.Value.Length - 1; - hasMatch = true; - break; - } - - } - if (!hasMatch) - { - ignored.Append(lineState.Text[i]); - } - } - - if (ignored.Length > 0) - { - tokenized.Add(ignored.ToString(), true); - ignored.Clear(); - } - - tokenized.Cursor = lineState.Cursor; - - if (!tokenized.Any() || - (tokenized.Last.IsHidden && tokenized.Last.Cursor == tokenized.Last.Text.Length)) - { - tokenized.Add(string.Empty, false, 0); - } - - return tokenized; - }; - } - - public static Lexer SplitOnWhitespace => Regex.AddAnyNonWhitespace().ToLexer(); - - } -} \ No newline at end of file +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using Lexer = System.Func; +using RegexList = System.Collections.Generic.List; + +namespace InteractiveReadLine.Tokenizing +{ + /// + /// Provides ready-made lexers and components for creating custom lexers. A lexer splits a line into tokens + /// used by auto-completion and token-based formatters. + /// + public static class CommonLexers + { + /// + /// Creates an empty list of regular-expression token types. Add token patterns to the list, then convert + /// it to a lexer with ToLexer. + /// + public static RegexList Regex => new RegexList(); + + /// + /// Adds a new token type to the end of the regular expression token list. The token must begin with + /// the regular expression start of text character (^) or an ArgumentException will be thrown + /// + /// + /// The regular expression pattern which identifies the token, must start with ^ + /// An optional type code, such that any token matched by this definition will have + /// this value in the .TypeCode property of the IToken interface + /// + public static RegexList AddTokenType(this RegexList list, string pattern, int typeCode = 0) + { + if (!pattern.StartsWith("^")) + throw new ArgumentException($"Regex token definitions must start with the ^ character, which was not present in the pattern '{pattern}'"); + + list.Add(new RegexTokenDef(pattern, typeCode)); + return list; + } + + /// + /// Adds a token type that matches a sequence of non-whitespace characters, which commonly represents + /// one word. + /// + /// The token type list to add to + /// A code identifying this token type in the resulting tokens + /// The same list, for chaining + public static RegexList AddAnyNonWhitespace(this RegexList list, int typeCode = 0) => + list.AddTokenType(@"^\S+", typeCode); + + /// + /// Adds a token type that matches a double-quoted string and honors backslash escapes, so a quoted + /// phrase is treated as one token rather than split on its spaces. + /// + /// The token type list to add to + /// A code identifying this token type in the resulting tokens + /// The same list, for chaining + public static RegexList AddDoubleQuoteStringLiterals(this RegexList list, int typeCode = 0) => + list.AddTokenType(@"^""(?:[^""\\]|\\.)*""", typeCode); + + /// + /// Adds a token type that matches a single-quoted string and honors backslash escapes. + /// + /// The token type list to add to + /// A code identifying this token type in the resulting tokens + /// The same list, for chaining + public static RegexList AddSingleQuoteStringLiterals(this RegexList list, int typeCode = 0) => + list.AddTokenType(@"^'(?:[^'\\]|\\.)*'", typeCode); + + /// + /// From a list of RegexTokenDefs, produce a function that will tokenize a LineState according to + /// the specified token definitions in the order they were provided. Effectively this renders a list + /// of regular expression token definitions into a functioning lexer. + /// + /// + /// + public static Lexer ToLexer(this RegexList list) + { + if (!list.Any()) + throw new ArgumentException("The RegexTokenDefs list must not be empty"); + + return lineState => + { + + var tokenized = new TokenizedLine(); + + var ignored = new StringBuilder(); + for (int i = 0; i < lineState.Text.Length; i++) + { + var substring = lineState.Text.Substring(i); + + bool hasMatch = false; + + foreach (var tokenDef in list) + { + var match = tokenDef.Regex.Match(substring); + if (match.Success) + { + if (ignored.Length > 0) + { + tokenized.Add(ignored.ToString(), true, null); + ignored.Clear(); + } + + tokenized.Add(match.Value, false, null, tokenDef.TypeCode); + i += match.Value.Length - 1; + hasMatch = true; + break; + } + + } + if (!hasMatch) + { + ignored.Append(lineState.Text[i]); + } + } + + if (ignored.Length > 0) + { + tokenized.Add(ignored.ToString(), true); + ignored.Clear(); + } + + tokenized.Cursor = lineState.Cursor; + + var last = tokenized.Last; + if (last == null || + (last.IsHidden && last.Cursor == last.Text.Length)) + { + tokenized.Add(string.Empty, false, 0); + } + + return tokenized; + }; + } + + /// + /// Gets a lexer that splits a line into words at whitespace boundaries for use with auto-completion. + /// + public static Lexer SplitOnWhitespace => Regex.AddAnyNonWhitespace().ToLexer(); + + } +} diff --git a/InteractiveReadLine/Tokenizing/IToken.cs b/InteractiveReadLine/Tokenizing/IToken.cs index 9ba2bed..6b50c95 100644 --- a/InteractiveReadLine/Tokenizing/IToken.cs +++ b/InteractiveReadLine/Tokenizing/IToken.cs @@ -1,81 +1,81 @@ -namespace InteractiveReadLine.Tokenizing -{ - /// - /// A contract for a single token produced from a line of text by a lexer. - /// - /// - /// - /// A lexer takes a string and splits it into a sequence of tokens. In order for the autocomplete - /// mechanism to work, there are additional constraints placed on lexers and tokens in the InteractiveReadLine - /// codebase that might not be necessary for other applications. - /// - /// Any implementation of IToken must make sure to properly implement the four different Previous/Next - /// links, meaning that the lexer itself must connect the token objects such that the entire sequence - /// of tokens can be walked by following these links from beginning to end and back again. - /// - /// Additionally, the Cursor property setter must ensure that setting the cursor on one token - /// will remove it from the previous token in the sequence on which it resided. - /// - /// - public interface IToken - { - /// - /// Gets or sets the text of this particular token. If the cursor is currently on this token, the cursor - /// will be adjusted if necessary if the length of the text changes. - /// - string Text { get; set; } - - /// - /// Gets or sets the cursor position as an offset from the first character in the the Text property. Setting - /// the cursor on this token will remove it from any other token in the sequence. - /// - int? Cursor { get; set; } - - /// - /// Gets the next token in the sequence, regardless of whether the next token is hidden or not. Returns null - /// if this is the last token in the sequence. - /// - IToken Next { get; } - - /// - /// Gets the previous token in the sequence, regardless of whether the previous token is hidden or not. Returns - /// null if this is the first token in the sequence. - /// - IToken Previous { get; } - - /// - /// Gets the next token in the sequence, ignoring hidden tokens. Returns null if this is the last non-hidden - /// token in the sequence. - /// - IToken NextNotHidden { get; } - - /// - /// Gets the previous token in the sequence, ignoring hidden tokens. Returns null if this is the first non-hidden - /// token in the sequence. - /// - IToken PreviousNotHidden { get; } - - /// - /// Gets a value indicating whether or not this token is considered a hidden (grammatically meaningless) token. An - /// example of a typical hidden token in most grammars is whitespace. - /// - bool IsHidden { get; } - - /// - /// Determines the distance between two tokens as the number of links that must be followed to get from this token - /// to the other. Adjacent tokens, for example, have a distance of 1. Returns null if the two tokens are not in - /// the same sequence. - /// - /// Another token in the same sequence to measure the distance to - /// Specifies whether or not hidden tokens count as part of the distance - /// The distance between tokens, or null if the distance cannot be found - int? DistanceTo(IToken other, bool ignoreHidden=false); - - /// - /// Gets the integer type code associated with this token. The lexer has the option of assigning an integer type code - /// to tokens, typically with some semantic meaning known by the lexer as it processed the text. If so, that value - /// it assigned is available here. - /// - int TypeCode { get; } - } +namespace InteractiveReadLine.Tokenizing +{ + /// + /// A contract for a single token produced from a line of text by a lexer. + /// + /// + /// + /// A lexer takes a string and splits it into a sequence of tokens. In order for the autocomplete + /// mechanism to work, there are additional constraints placed on lexers and tokens in the InteractiveReadLine + /// codebase that might not be necessary for other applications. + /// + /// Any implementation of IToken must make sure to properly implement the four different Previous/Next + /// links, meaning that the lexer itself must connect the token objects such that the entire sequence + /// of tokens can be walked by following these links from beginning to end and back again. + /// + /// Additionally, the Cursor property setter must ensure that setting the cursor on one token + /// will remove it from the previous token in the sequence on which it resided. + /// + /// + public interface IToken + { + /// + /// Gets or sets the text of this particular token. If the cursor is currently on this token, the cursor + /// will be adjusted if necessary if the length of the text changes. + /// + string Text { get; set; } + + /// + /// Gets or sets the cursor position as an offset from the first character in the the Text property. Setting + /// the cursor on this token will remove it from any other token in the sequence. + /// + int? Cursor { get; set; } + + /// + /// Gets the next token in the sequence, regardless of whether the next token is hidden or not. Returns null + /// if this is the last token in the sequence. + /// + IToken? Next { get; } + + /// + /// Gets the previous token in the sequence, regardless of whether the previous token is hidden or not. Returns + /// null if this is the first token in the sequence. + /// + IToken? Previous { get; } + + /// + /// Gets the next token in the sequence, ignoring hidden tokens. Returns null if this is the last non-hidden + /// token in the sequence. + /// + IToken? NextNotHidden { get; } + + /// + /// Gets the previous token in the sequence, ignoring hidden tokens. Returns null if this is the first non-hidden + /// token in the sequence. + /// + IToken? PreviousNotHidden { get; } + + /// + /// Gets a value indicating whether or not this token is considered a hidden (grammatically meaningless) token. An + /// example of a typical hidden token in most grammars is whitespace. + /// + bool IsHidden { get; } + + /// + /// Determines the distance between two tokens as the number of links that must be followed to get from this token + /// to the other. Adjacent tokens, for example, have a distance of 1. Returns null if the two tokens are not in + /// the same sequence. + /// + /// Another token in the same sequence to measure the distance to + /// Specifies whether or not hidden tokens count as part of the distance + /// The distance between tokens, or null if the distance cannot be found + int? DistanceTo(IToken other, bool ignoreHidden=false); + + /// + /// Gets the integer type code associated with this token. The lexer has the option of assigning an integer type code + /// to tokens, typically with some semantic meaning known by the lexer as it processed the text. If so, that value + /// it assigned is available here. + /// + int TypeCode { get; } + } } \ No newline at end of file diff --git a/InteractiveReadLine/Tokenizing/RegexTokenDef.cs b/InteractiveReadLine/Tokenizing/RegexTokenDef.cs index ab7deda..d7a38f6 100644 --- a/InteractiveReadLine/Tokenizing/RegexTokenDef.cs +++ b/InteractiveReadLine/Tokenizing/RegexTokenDef.cs @@ -1,37 +1,45 @@ -using System.Text.RegularExpressions; - -namespace InteractiveReadLine.Tokenizing -{ - /// - /// A definition of a token type for a regex based parser. Contains a matching pattern which must begin with - /// the start character ^ and an optional type code to assign to tokens matched by the regex. - /// - public class RegexTokenDef - { - public RegexTokenDef(string pattern, int typeCode=0) - { - this.Pattern = pattern; - this.TypeCode = typeCode; - - if (!this.Pattern.StartsWith("^")) - this.Pattern = "^" + this.Pattern; - - this.Regex = new Regex(this.Pattern); - } - - /// - /// Gets the string version of the regex pattern defined to match tokens of this type - /// - public string Pattern { get; } - - /// - /// Gets the optional type code to assign to tokens matched by the Pattern property - /// - public int TypeCode { get; } - - /// - /// Gets the compiled regex for the Pattern property - /// - public Regex Regex { get; } - } -} \ No newline at end of file +using System.Text.RegularExpressions; + +namespace InteractiveReadLine.Tokenizing +{ + /// + /// Defines a token type for a regular-expression parser. The definition contains a matching pattern, + /// automatically anchored with ^ when necessary, and an optional type code for matching tokens. + /// + public class RegexTokenDef + { + /// + /// Creates a token definition from a regular expression pattern. + /// + /// + /// The pattern that identifies the token. The constructor adds a leading ^ when the pattern does not + /// already have one. + /// + /// A code that identifies this token type in the resulting tokens. + public RegexTokenDef(string pattern, int typeCode=0) + { + this.Pattern = pattern; + this.TypeCode = typeCode; + + if (!this.Pattern.StartsWith("^")) + this.Pattern = "^" + this.Pattern; + + this.Regex = new Regex(this.Pattern); + } + + /// + /// Gets the string version of the regex pattern defined to match tokens of this type + /// + public string Pattern { get; } + + /// + /// Gets the optional type code to assign to tokens matched by the Pattern property + /// + public int TypeCode { get; } + + /// + /// Gets the regular expression created from the Pattern property. + /// + public Regex Regex { get; } + } +} diff --git a/InteractiveReadLine/Tokenizing/TokenizedLine.cs b/InteractiveReadLine/Tokenizing/TokenizedLine.cs index b6692a4..0d8b222 100644 --- a/InteractiveReadLine/Tokenizing/TokenizedLine.cs +++ b/InteractiveReadLine/Tokenizing/TokenizedLine.cs @@ -1,296 +1,297 @@ -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Net.Mime; -using System.Runtime.CompilerServices; -using System.Text; - -namespace InteractiveReadLine.Tokenizing -{ - /// - /// The TokenizedLine class represents a line of text processed by a lexer and split into a sequence of - /// tokens. - /// - /// - /// These tokens in order contain every character of text in the original line, such that combining - /// them in sequence would recreate the original string. Additionally, the line's original cursor position - /// is preserved and contained by one of the tokens. The tokens can be walked in its entirety in either - /// direction by navigation properties on the tokens themselves, or iterated through in the line. - /// - public class TokenizedLine : IReadOnlyList - { - private readonly List _tokens; - private int _cursor; - - public TokenizedLine() - { - _tokens = new List(); - } - - /// - /// Gets the first token in the sequence, or null if the sequence is empty - /// - public IToken First => _tokens.FirstOrDefault(); - - /// - /// Gets the last token in the sequence, or null if the sequence is empty - /// - public IToken Last => _tokens.LastOrDefault(); - - /// - /// Gets the first non-hidden token in the sequence, or null if none exist - /// - public IToken FirstNonHidden => _tokens.FirstOrDefault()?.FirstNonHidden; - - /// - /// Gets the combined text of all of the tokens in the sequence, which will match the original line of text - /// before it was split apart by the lexer - /// - public string Text => Token.BuildText(_tokens); - - /// - /// Gets an enumerator which can be used to iterate through the tokens - /// - /// - public IEnumerator GetEnumerator() => _tokens.GetEnumerator(); - - /// - /// Gets an enumerator which can be used to iterate through the tokens - /// - /// - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - - /// - /// Gets the number of tokens in the sequence - /// - public int Count => _tokens.Count; - - /// - /// Gets the token at the specified index in the sequence - /// - /// Index in the token sequence - /// - public IToken this[int index] => _tokens[index]; - - /// - /// Gets the token which currently contains the cursor - /// - public IToken CursorToken => _tokens.FirstOrDefault(x => x.Cursor != null); - - /// - /// Gets the index number of the token which currently contains the cursor - /// - public int CursorTokenIndex => _tokens.IndexOf(_tokens.FirstOrDefault(x => x.Cursor != null)); - - /// - /// Gets the overall index of the cursor in the combined text - /// - public int Cursor - { - get => _cursor; - set - { - _cursor = value; - - int textLen = this.Text.Length; - if (value > textLen) - _cursor = textLen; - } - } - - /// - /// Add a token to the sequence, making all of the necessary links - /// - /// The text contained by the token - /// Whether or not this is a hidden token - /// Null if the token does not contain the cursor, otherwise the index of the cursor as an offset from the first character in the token text - /// An optional type code which can be accessed by a consumer of the token - public void Add(string text, bool isHidden, int? cursor=null, int typeCode=0) - { - var newToken = new Token(text, isHidden, this, typeCode); - - if (_tokens.Any()) - { - _tokens.Last().Next = newToken; - newToken.Previous = _tokens.Last(); - } - - _tokens.Add(newToken); - - if (cursor != null) - newToken.Cursor = cursor; - } - - /// - /// Internal implementation of the token - /// - /// - /// - /// Tokens and the TokenizedLine require a lot of internal plumbing to work correctly, and don't necessarily - /// have a meaning or purpose except in conjunction with each other. To make sure that the TokenizedLine.Add - /// method is the obvious way of producing tokens and connecting them, and that tokens are not created - /// independent from a TokenizedLine, this class is hidden from consumers and exposed only through the - /// IToken interface. - /// - private class Token : IToken - { - private readonly TokenizedLine _parent; - private string _text; - - public Token(string text, bool isHidden, TokenizedLine parent, int typeCode) - { - _parent = parent; - TypeCode = typeCode; - _text = text; - this.IsHidden = isHidden; - } - - public int TypeCode { get; } - - public string Text - { - get => _text; - set - { - int? cursorMove = null; - - // Adjust the cursor if the cursor lies in this token - if (Cursor != null && Cursor > value.Length) - { - Cursor = value.Length; - } - else - { - // Check if the cursor is after this token, and if so adjust it accordingly - var beforeLen = TextBefore().Length; - if (beforeLen + _text.Length - 1 < _parent.Cursor) - { - var delta = value.Length - _text.Length; - cursorMove = _parent.Cursor + delta; - } - } - - _text = value; - if (cursorMove != null) - _parent.Cursor = (int) cursorMove; - } - } - - public int? Cursor - { - get - { - int lengthBefore = this.TextBefore().Length; - if (_parent.Cursor < lengthBefore) - return null; - - int offset = _parent.Cursor - lengthBefore; - - if (offset == Text.Length && Next?.IsHidden == false) - { - return null; - } - - if (offset <= Text.Length) - return offset; - return null; - } - set - { - if (value == null || value < 0 || value > Text.Length) - return; - - _parent.Cursor = this.TextBefore().Length + (int) value; - } - } - - public Token Next { get; set; } - public Token Previous { get; set; } - - public IToken PreviousNotHidden => this.Previous?.ThisOrPrevIfHidden(); - public IToken NextNotHidden => this.Next?.ThisOrNextIfHidden(); - - IToken IToken.Next => this.Next; - - IToken IToken.Previous => this.Previous; - - public Token First => this.Previous == null ? this : this.Previous.First; - - public Token FirstNonHidden => this.First.ThisOrNextIfHidden(); - - public bool IsHidden { get; set; } - - public int? DistanceTo(IToken other, bool ignoreHidden = false) - { - var token = other as Token; - if (token == null) - return null; - - var gap = Next?.ForwardTo(token, new List()); - if (ignoreHidden) - return gap?.Where(x => !x.IsHidden).Count(); - else - return gap?.Count; - } - - private List ForwardTo(Token other, List gap) - { - gap.Add(this); - - if (other == this) - return gap; - else - { - return this.Next?.ForwardTo(other, gap); - } - } - - private Token[] TokensBefore() - { - var tokens = new List(); - var first = this.First; - - var pointer = first; - while (pointer != this) - { - tokens.Add(pointer); - pointer = pointer.Next; - } - - return tokens.ToArray(); - } - - private string TextBefore() - { - return BuildText(this.TokensBefore()); - } - - private Token ThisOrNextIfHidden() - { - if (this.IsHidden) - return this.Next?.ThisOrNextIfHidden(); - else - return this; - } - - private Token ThisOrPrevIfHidden() - { - if (this.IsHidden) - return this.Previous?.ThisOrPrevIfHidden(); - else - return this; - } - - public static string BuildText(IEnumerable tokens) - { - var builder = new StringBuilder(); - foreach (var token in tokens) - { - builder.Append(token.Text); - } - - return builder.ToString(); - } - } - } -} \ No newline at end of file +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace InteractiveReadLine.Tokenizing +{ + /// + /// The TokenizedLine class represents a line of text processed by a lexer and split into a sequence of + /// tokens. + /// + /// + /// These tokens in order contain every character of text in the original line, such that combining + /// them in sequence would recreate the original string. Additionally, the line's original cursor position + /// is preserved and contained by one of the tokens. The tokens can be walked in its entirety in either + /// direction by navigation properties on the tokens themselves, or iterated through in the line. + /// + public class TokenizedLine : IReadOnlyList + { + private readonly List _tokens; + private int _cursor; + + /// + /// Creates an empty sequence to which a lexer can add tokens. + /// + public TokenizedLine() + { + _tokens = new List(); + } + + /// + /// Gets the first token in the sequence, or null when the sequence is empty. + /// + public IToken? First => _tokens.FirstOrDefault(); + + /// + /// Gets the last token in the sequence, or null when the sequence is empty. + /// + public IToken? Last => _tokens.LastOrDefault(); + + /// + /// Gets the first non-hidden token in the sequence, or null when none exists. + /// + public IToken? FirstNonHidden => _tokens.FirstOrDefault()?.FirstNonHidden; + + /// + /// Gets the combined text of all of the tokens in the sequence, which will match the original line of text + /// before it was split apart by the lexer + /// + public string Text => Token.BuildText(_tokens); + + /// + /// Gets an enumerator which can be used to iterate through the tokens + /// + /// + public IEnumerator GetEnumerator() => _tokens.GetEnumerator(); + + /// + /// Gets an enumerator which can be used to iterate through the tokens + /// + /// + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + /// + /// Gets the number of tokens in the sequence + /// + public int Count => _tokens.Count; + + /// + /// Gets the token at the specified index in the sequence + /// + /// Index in the token sequence + /// + public IToken this[int index] => _tokens[index]; + + /// + /// Gets the token that contains the cursor, or null when no token contains it. + /// + public IToken? CursorToken => _tokens.FirstOrDefault(x => x.Cursor != null); + + /// + /// Gets the index of the token that contains the cursor, or -1 when no token contains it. + /// + public int CursorTokenIndex => _tokens.FindIndex(x => x.Cursor != null); + + /// + /// Gets the overall index of the cursor in the combined text + /// + public int Cursor + { + get => _cursor; + set + { + _cursor = value; + + int textLen = this.Text.Length; + if (value > textLen) + _cursor = textLen; + } + } + + /// + /// Add a token to the sequence, making all of the necessary links + /// + /// The text contained by the token + /// Whether or not this is a hidden token + /// Null if the token does not contain the cursor, otherwise the index of the cursor as an offset from the first character in the token text + /// An optional type code which can be accessed by a consumer of the token + public void Add(string text, bool isHidden, int? cursor=null, int typeCode=0) + { + var newToken = new Token(text, isHidden, this, typeCode); + + if (_tokens.Any()) + { + _tokens.Last().Next = newToken; + newToken.Previous = _tokens.Last(); + } + + _tokens.Add(newToken); + + if (cursor != null) + newToken.Cursor = cursor; + } + + /// + /// Internal implementation of the token + /// + /// + /// + /// Tokens and the TokenizedLine require a lot of internal plumbing to work correctly, and don't necessarily + /// have a meaning or purpose except in conjunction with each other. To make sure that the TokenizedLine.Add + /// method is the obvious way of producing tokens and connecting them, and that tokens are not created + /// independent from a TokenizedLine, this class is hidden from consumers and exposed only through the + /// IToken interface. + /// + private class Token : IToken + { + private readonly TokenizedLine _parent; + private string _text; + + public Token(string text, bool isHidden, TokenizedLine parent, int typeCode) + { + _parent = parent; + TypeCode = typeCode; + _text = text; + this.IsHidden = isHidden; + } + + public int TypeCode { get; } + + public string Text + { + get => _text; + set + { + int? cursorMove = null; + + // Adjust the cursor if the cursor lies in this token + if (Cursor != null && Cursor > value.Length) + { + Cursor = value.Length; + } + else + { + // Check if the cursor is after this token, and if so adjust it accordingly + var beforeLen = TextBefore().Length; + if (beforeLen + _text.Length - 1 < _parent.Cursor) + { + var delta = value.Length - _text.Length; + cursorMove = _parent.Cursor + delta; + } + } + + _text = value; + if (cursorMove != null) + _parent.Cursor = (int) cursorMove; + } + } + + public int? Cursor + { + get + { + int lengthBefore = this.TextBefore().Length; + if (_parent.Cursor < lengthBefore) + return null; + + int offset = _parent.Cursor - lengthBefore; + + if (offset == Text.Length && Next?.IsHidden == false) + { + return null; + } + + if (offset <= Text.Length) + return offset; + return null; + } + set + { + if (value == null || value < 0 || value > Text.Length) + return; + + _parent.Cursor = this.TextBefore().Length + (int) value; + } + } + + public Token? Next { get; set; } + public Token? Previous { get; set; } + + public IToken? PreviousNotHidden => this.Previous?.ThisOrPrevIfHidden(); + public IToken? NextNotHidden => this.Next?.ThisOrNextIfHidden(); + + IToken? IToken.Next => this.Next; + + IToken? IToken.Previous => this.Previous; + + public Token First => this.Previous == null ? this : this.Previous.First; + + public Token? FirstNonHidden => this.First.ThisOrNextIfHidden(); + + public bool IsHidden { get; set; } + + public int? DistanceTo(IToken other, bool ignoreHidden = false) + { + var token = other as Token; + if (token == null) + return null; + + var gap = Next?.ForwardTo(token, new List()); + if (ignoreHidden) + return gap?.Where(x => !x.IsHidden).Count(); + else + return gap?.Count; + } + + private List? ForwardTo(Token other, List gap) + { + gap.Add(this); + + if (other == this) + return gap; + else + { + return this.Next?.ForwardTo(other, gap); + } + } + + private Token[] TokensBefore() + { + var tokens = new List(); + var first = this.First; + + Token? pointer = first; + while (pointer != null && pointer != this) + { + tokens.Add(pointer); + pointer = pointer.Next; + } + + return tokens.ToArray(); + } + + private string TextBefore() + { + return BuildText(this.TokensBefore()); + } + + private Token? ThisOrNextIfHidden() + { + if (this.IsHidden) + return this.Next?.ThisOrNextIfHidden(); + else + return this; + } + + private Token? ThisOrPrevIfHidden() + { + if (this.IsHidden) + return this.Previous?.ThisOrPrevIfHidden(); + else + return this; + } + + public static string BuildText(IEnumerable tokens) + { + var builder = new StringBuilder(); + foreach (var token in tokens) + { + builder.Append(token.Text); + } + + return builder.ToString(); + } + } + } +} diff --git a/README.md b/README.md index d5ab860..2a4fd11 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,6 @@ -![](https://github.com/mattj23/InteractiveReadLine/workflows/CI%20netcore/badge.svg) -[![Coverage](https://codecov.io/gh/mattj23/InteractiveReadLine/branch/master/graph/badge.svg)](https://codecov.io/gh/mattj23/InteractiveReadLine) +[![CI](https://github.com/mattj23/InteractiveReadLine/actions/workflows/ci.yml/badge.svg)](https://github.com/mattj23/InteractiveReadLine/actions/workflows/ci.yml) +[![NuGet](https://img.shields.io/nuget/v/InteractiveReadLine.svg)](https://www.nuget.org/packages/InteractiveReadLine/) +[![Coverage](https://codecov.io/gh/mattj23/InteractiveReadLine/branch/main/graph/badge.svg)](https://codecov.io/gh/mattj23/InteractiveReadLine) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) # Interactive ReadLine @@ -31,7 +32,7 @@ However, practically every aspect of the system's behavior is configurable. Con All of these above configurations are done by providing `Action<..>` and `Func<..>` style delegates to a configuration object, rather than use a zoo of custom interfaces. -Below is a more complex example, the full code for which can be seen at [Demos/ComplexConfig.cs](https://github.com/mattj23/InteractiveReadLine/tree/master/InteractiveReadLine.Demo/Demos/ComplexConfig.cs) +Below is a more complex example, the full code for which can be seen at [Demos/ComplexConfig.cs](https://github.com/mattj23/InteractiveReadLine/tree/main/InteractiveReadLine.Demo/Demos/ComplexConfig.cs) ```csharp @@ -43,7 +44,7 @@ var config = ReadLineConfig.Empty .SetAutoCompletion(AutoComplete) .SetLexer(lexer); -string result = ConsoleReadline.ReadLine(config); +string result = ConsoleReadLine.ReadLine(config); ``` ![Example](./docs/animations/complex_config.svg) @@ -55,7 +56,7 @@ Within the github repository there is a demo project which contains many example ![Example](./docs/animations/demo.svg) --- -## Design Philosopy +## Design Philosophy ### Obviousness and Correctness The design of this library's API was based on an attempt to do two things: @@ -81,7 +82,7 @@ In conjunction with documentation, unit testing is a priority to ensure that the --- ## Code Documentation -> Currently, the library only works with a provider written to wrap the `System.Console` object. However, a provider only needs to implement three methods which consist of displaying text and reading keyboard input 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. +> 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 @@ -130,10 +131,11 @@ There are many pre-made bindings as well. These exist in `BehaviorExtensionMeth * **`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 -* **`ArrowMovesCursor()`** binds the left and right arrows to move the cursor one character in their respective directions -* **`AddUpDownHistoryNavation()`** binds the up and down arrows to history navigation, which will require the history mechanism to be set up for it to work -* **`AddCtrlNavKeys()`** this adds a series of many naviation and edit commands familiar to bash users, such as cut word, cut to begining/end, jump to beginning/end, etc -* **`AddStandardKeys()`** is a shortcut to add a complete and basic set of bindings (this is what a `ReadLineConfig.Basic` config uses), which will add the default insert character behavior, enter to complete the line, delete, backspace, home/end, left/right arrows, and the up/down arrow history navigation +* **`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: @@ -164,6 +166,15 @@ var config = ReadLineConfig.Empty .AddKeyBehavior(new KeyId(ConsoleKey.S, false, true, false), CommonKeyBehaviors.CutToStart) .[...] ``` + +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: + +```csharp +var config = ReadLineConfig.Empty + .AddKeyBehavior(ConsoleKey.S, false, true, false, CommonKeyBehaviors.CutToStart) + .[...] +``` Or, to bind the `'?'` character to end the input: ```csharp @@ -172,6 +183,15 @@ var config = ReadLineConfig.Empty .[...] ``` +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: + +```csharp +// 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. @@ -208,6 +228,136 @@ var config = ReadLineConfig.Empty --- +### 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: + +```csharp +// 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: + +```csharp +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: + +```csharp +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`: + +```csharp +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: + +```csharp +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.* @@ -277,7 +427,7 @@ var text = ConsoleReadLine.ReadLine(config); #### TokenizedLine Formatters As has been mentioned, a formatter can be either a function which recieves a `LineState` object, or a function which recieves a `TokenizedLine` object. The `TokenizedLine` will be covered in more detail in the section on lexers, but this simple example shows how the lexer can be used to split the input text into tokens and a formatter can take advantage of that. -The following code example can be seen in further detail in [this demo](https://github.com/mattj23/InteractiveReadLine/tree/master/InteractiveReadLine.Demo/Demos/Formatters/TokenCustomFormatter.cs), but effectively it searches for tokens which match a valid hexidecimal number (digits 0 to 9 and letters a through f) and simultaneously displays it as capitalized and cyan. All other tokens are displayed exactly as they have been entered. +The following code example can be seen in further detail in [this demo](https://github.com/mattj23/InteractiveReadLine/tree/main/InteractiveReadLine.Demo/Demos/Formatters/TokenCustomFormatter.cs), but effectively it searches for tokens which match a valid hexidecimal number (digits 0 to 9 and letters a through f) and simultaneously displays it as capitalized and cyan. All other tokens are displayed exactly as they have been entered. ```csharp var pattern = new Regex(@"^[0-9a-fA-F]+$"); @@ -311,4 +461,4 @@ var result = ConsoleReadLine.ReadLine(config); ### Auto-Complete -### History \ No newline at end of file +### History diff --git a/docs/docfx.json b/docs/docfx.json new file mode 100644 index 0000000..7570882 --- /dev/null +++ b/docs/docfx.json @@ -0,0 +1,50 @@ +{ + "metadata": [ + { + "src": [ + { + "files": [ "InteractiveReadLine/InteractiveReadLine.csproj" ], + "src": ".." + } + ], + "dest": "api", + "properties": { + "TargetFramework": "net10.0", + "Configuration": "Release" + }, + "disableGitFeatures": false, + "disableDefaultFilter": false + } + ], + "build": { + "content": [ + { + "files": [ "api/**.yml", "api/index.md" ] + }, + { + "files": [ "*.md", "toc.yml" ], + "exclude": [ "nuget-readme.md" ] + } + ], + "resource": [ + { + "files": [ "animations/**" ] + } + ], + "output": "_site", + "template": [ "default", "modern" ], + "globalMetadata": { + "_appName": "InteractiveReadLine", + "_appTitle": "InteractiveReadLine", + "_enableSearch": true, + "_gitContribute": { + "repo": "https://github.com/mattj23/InteractiveReadLine", + "branch": "main" + }, + "pdf": false + }, + "postProcessors": [ "ExtractSearchIndex" ], + "keepFileLink": false, + "disableGitFeatures": false + } +} diff --git a/docs/history.md b/docs/history.md index e740a0b..675c951 100644 --- a/docs/history.md +++ b/docs/history.md @@ -1,129 +1,145 @@ -# The History Feature - -The history feature is meant to emulate a simple version of the typical history behavior of most shells, in which two keys (typically the up and down arrows) cycle through the list of previously entered commands. - -Accomplishing this requires three things: a collection of previously entered commands, a mechanism for cycling through these commands during the read line operation, and a means of updating the collection when a new command is entered. - -## Trivial Code Example -```csharp -var history = new List {"these are", "past entries"}; - -// The ReadLineConfig.Basic defaults with the up and down arrows set to navigate -// forward and backwards through the history. They will simply be disabled -// if no history source is set in the configuration -var config = ReadLineConfig.Basic - .SetUpdatingHistorySource(history); - -var result = ConsoleReadLine.ReadLine(config); - -// If the ConsoleReadLine.ReadLine method is now called again with the same config -// object, the last entered line will be the most recent element in the history -``` - -## Configuring ReadLine to use a History - -Like all other configuration, setting up the `ReadLine()` method to use a collection of past commands is done through the `ReadLineConfig` object. In accordance with the three ingredients mentioned above, you will need to decide three things: - -1. What values should be provided to the input handler for it to use when navigating the history? - -2. What should trigger the input handler to cycle forwards and backwards through the history? - -3. Should the input handler automatically update the historical collection when the current line of input is finalized? - -### Setting Key Behaviors -#### How History Navigation Works -Navigating through the history is performed by two methods of the input handler, and thus to the `IKeyBehaviorTarget` given to key behaviors. They are, simply, `HistoryPrevious()` and `HistoryNext()`. They are wrapped for convenience by `CommonKeyBehaviors.HistoryPrevious` and `CommonKeyBehaviors.HistoryNext`, respectively. - -When the input handler starts, it has an empty 'original' text buffer. This can be thought of as the last entry in the history, and the user can navigate back to it no matter how they step through the history. - -When showing the starting text buffer, `HistoryNext` will do nothing, but `HistoryPrevious` will change the contents of the visible text buffer to the last entry in the history. Further `HistoryPrevious` actions will iterate backwards through the list until stalling at the beginning, while `HistoryNext` actions will iterate forward through the list until the last entry is reached. After the last entry, the contents of the 'original' text buffer will be displayed in whatever state they were the last time the user navigated into the history. - -#### Setting History Navigation Behaviors - -##### Basic Config Case - -In the simplest case, simply using `ReadLineConfig.Basic` will come with the next and previous history behaviors mapped to the down and up arrows, respectively. - -##### Adding Arrow Key Navigation - -Starting with an empty or custom configuration that does not have the up and down arrow keys mapped to the history navigation, they can be added with the following extension method: - -```csharp -var config = ReadLineConfig.Empty - .AddUpDownHistoryNavigation(); -``` - -##### Adding Custom Keys - -Starting from a configuration that doesn't have navigation mapped, the next/previous history navigation behaviors can be mapped using the wrappers in `CommonKeyBehaviors`. -For example, the following code maps `HistoryNext` to Ctrl+Shift+Tab, and `HistoryPrevious` to the minus character. - -```csharp -var config = ReadLineConfig.Empty - .AddKeyBehavior(ConsoleKey.Tab, true, true, false, CommonKeyBehaviors.HistoryNext) - .AddKeyBehavior('-', CommonKeyBehaviors.HistoryPrevious); -``` - -### Providing History Values - -The history is provided to the configuration object as any object which implements `IReadOnlyList`. The sequence of the history is assumed to be oldest values at the beginning of the list, newest values at the end of the list. The entries are plain text, as any lexing or formatting will only be done when a particular value is loaded to the input handler's text buffer. - -**For a non-updating history:** -```csharp -// For a history that is not actively updated by the input handler, any object which -// provides IReadOnlyList can be used -var history = new string[] {"history entry 0", "history entry 1", "history entry 2"}; - -// Set the source of the history values with SetHistorySource() -var config = ReadLineConfig.Basic.SetHistorySource(history); - -var result = ConsoleReadLine.ReadLine(config); -``` - -The input handler can take care of the task of updating the history values when its input is finalized (typically when the enter key is pressed) just before the value is returned from the method. However, this will obviously not be possible with an `IReadOnlyList`, so under the covers the update is performed by an `Action` delegate provided to the configuration. - -> The decision to split the history into a read-only component and an `Action` to update was to allow for the user to supply more complex update behavior than simply appending an entry onto the end of a list, such as the cleaning and max size behavior demonstrated in the later tutorial. - -In the case of using a simple `List` to store command history, there is a shortcut method which will set the update action delegate automatically (it will point directly at the list's `.Add()` method). New entries will simply be added to the end of the list with no regard for content or history size. - -**For a simple self-updating history:** -```csharp -var history = new List {"history entry 0", "history entry 1", "history entry 2"}; - -// In this case, the history must be a List, and you will use SetUpdatingHistorySource, -// which will create the update action automatically -var config = ReadLineConfig.Basic - .SetUpdatingHistorySource(history); - -var result = ConsoleReadLine.ReadLine(config); - -// If the ConsoleReadLine.ReadLine method is now called again with the same config -// object, the last entered line will be the most recent element in the history -``` - -## Extra Code Recipes - -### A Duplicate-Removing, Max Sized, Updating History -As an example of the usefulness of splitting the history into a component that is only used for reading, and an action delegate for updating, the following configuration stores its history in a generic list, but on update will first remove duplicates of the new entry before re-adding it to the end of the list. Additionally, the history is capped at ten values, so the oldest value is removed if the list is full. - -Notice in this case there's no need to use the `SetUpdatingHistorySource()` shortcut. - -Instead, the history list is added through the `SetHistorySource()` method, which will only ever read values. The update action is defined as a lambda which encloses `history` in its scope and performs the duplicate removal and size capping before adding the new value. - -```csharp -var history = new List(); - -var config = ReadLineConfig.Basic - // ... other configuration here ... - .SetHistorySource(history) - .SetHistoryUpdateAction(s => - { - // Remove all previous entries of the text - history.RemoveAll(x => x == s); - if (history.Count >= 10) - history.RemoveAt(0); - history.Add(s); - }); - -var result = ConsoleReadLine.ReadLine(config); -``` \ No newline at end of file +# The History Feature + +The history feature is meant to emulate a simple version of the typical history behavior of most shells, in which two keys (typically the up and down arrows) cycle through the list of previously entered commands. + +Accomplishing this requires three things: a collection of previously entered commands, a mechanism for cycling through these commands during the read line operation, and a means of updating the collection when a new command is entered. + +## Trivial Code Example +```csharp +var history = new List {"these are", "past entries"}; + +// The ReadLineConfig.Basic defaults with the up and down arrows set to navigate +// forward and backwards through the history. They will simply be disabled +// if no history source is set in the configuration +var config = ReadLineConfig.Basic + .SetUpdatingHistorySource(history); + +var result = ConsoleReadLine.ReadLine(config); + +// If the ConsoleReadLine.ReadLine method is now called again with the same config +// object, the last entered line will be the most recent element in the history +``` + +## Configuring ReadLine to use a History + +Like all other configuration, setting up the `ReadLine()` method to use a collection of past commands is done through the `ReadLineConfig` object. In accordance with the three ingredients mentioned above, you will need to decide three things: + +1. What values should be provided to the input handler for it to use when navigating the history? + +2. What should trigger the input handler to cycle forwards and backwards through the history? + +3. Should the input handler automatically update the historical collection when the current line of input is finalized? + +### Setting Key Behaviors +#### How History Navigation Works +Navigating through the history is performed by two methods of the input handler, and thus to the `IKeyBehaviorTarget` given to key behaviors. They are, simply, `HistoryPrevious()` and `HistoryNext()`. They are wrapped for convenience by `CommonKeyBehaviors.HistoryPrevious` and `CommonKeyBehaviors.HistoryNext`, respectively. + +When the input handler starts, it has an empty 'original' text buffer. This can be thought of as the last entry in the history, and the user can navigate back to it no matter how they step through the history. + +When showing the starting text buffer, `HistoryNext` will do nothing, but `HistoryPrevious` will change the contents of the visible text buffer to the last entry in the history. Further `HistoryPrevious` actions will iterate backwards through the list until stalling at the beginning, while `HistoryNext` actions will iterate forward through the list until the last entry is reached. After the last entry, the contents of the 'original' text buffer will be displayed in whatever state they were the last time the user navigated into the history. + +#### Setting History Navigation Behaviors + +##### Basic Config Case + +In the simplest case, simply using `ReadLineConfig.Basic` will come with the next and previous history behaviors mapped to the down and up arrows, respectively. + +##### Adding Arrow Key Navigation + +Starting with an empty or custom configuration that does not have the up and down arrow keys mapped to the history navigation, they can be added with the following extension method: + +```csharp +var config = ReadLineConfig.Empty + .AddUpDownHistoryNavigation(); +``` + +##### Adding Custom Keys + +Starting from a configuration that doesn't have navigation mapped, the next/previous history navigation behaviors can be mapped using the wrappers in `CommonKeyBehaviors`. +For example, the following code maps `HistoryNext` to Ctrl+Shift+Tab, and `HistoryPrevious` to the minus character. + +```csharp +var config = ReadLineConfig.Empty + .AddKeyBehavior(ConsoleKey.Tab, true, false, true, CommonKeyBehaviors.HistoryNext) + .AddKeyBehavior('-', CommonKeyBehaviors.HistoryPrevious); +``` + +The three booleans represent modifier keys in the order **control, alt, shift**, which matches the +`KeyId` constructor. Therefore, Ctrl+Shift+Tab is `true, false, true`. + +### Providing History Values + +The history is provided to the configuration object as any object which implements `IReadOnlyList`. The sequence of the history is assumed to be oldest values at the beginning of the list, newest values at the end of the list. The entries are plain text, as any lexing or formatting will only be done when a particular value is loaded to the input handler's text buffer. + +The configuration keeps a live reference to the collection you provide, so collection changes are visible without reconfiguration. If the collection shrinks during a read line operation, the input handler clamps its navigation position to the new end of the collection. The user can then navigate backward to the most recent remaining entry or forward to the text entered before history navigation began. + +**For a non-updating history:** +```csharp +// For a history that is not actively updated by the input handler, any object which +// provides IReadOnlyList can be used +var history = new string[] {"history entry 0", "history entry 1", "history entry 2"}; + +// Set the source of the history values with SetHistorySource() +var config = ReadLineConfig.Basic.SetHistorySource(history); + +var result = ConsoleReadLine.ReadLine(config); +``` + +The input handler can take care of the task of updating the history values when its input is finalized (typically when the enter key is pressed) just before the value is returned from the method. However, this will obviously not be possible with an `IReadOnlyList`, so under the covers the update is performed by an `Action` delegate provided to the configuration. + +> The decision to split the history into a read-only component and an `Action` to update was to allow for the user to supply more complex update behavior than simply appending an entry onto the end of a list, such as the cleaning and max size behavior demonstrated in the later tutorial. + +When you use a simple `List` to store command history, a shortcut method configures the update action automatically. The generated action appends the finalized line to the end of the list, except in two cases that would otherwise crowd out useful entries: + +* Lines that are empty or contain only whitespace +* A line that is identical to the entry already at the end of the list + +Only an *immediately* repeated line is skipped. Entering a command that appears earlier in the history still appends it, which moves the command to the most recent position. The history has no size limit. + +To record every finalized line as entered, including blank lines, supply your own delegate through `SetHistoryUpdateAction()`. The input handler performs no filtering and passes the finalized line to the update action in the configuration. + +The update action runs only when the user finishes a line. If the user abandons the line with Ctrl+C or signals the end of input with Ctrl+D, the text is discarded and the update action is not called. + +**For a simple self-updating history:** +```csharp +var history = new List {"history entry 0", "history entry 1", "history entry 2"}; + +// In this case, the history must be a List, and you will use SetUpdatingHistorySource, +// which will create the update action automatically +var config = ReadLineConfig.Basic + .SetUpdatingHistorySource(history); + +var result = ConsoleReadLine.ReadLine(config); + +// If the ConsoleReadLine.ReadLine method is now called again with the same config +// object, the last entered line will be the most recent element in the history +``` + +## Extra Code Recipes + +### A Duplicate-Removing, Max Sized, Updating History +As an example of the usefulness of splitting the history into a component that is only used for reading, and an action delegate for updating, the following configuration stores its history in a generic list, but on update will first remove duplicates of the new entry before re-adding it to the end of the list. Additionally, the history is capped at ten values, so the oldest value is removed if the list is full. + +Notice in this case there's no need to use the `SetUpdatingHistorySource()` shortcut. + +Instead, the history list is added through the `SetHistorySource()` method, which will only ever read values. The update action is defined as a lambda which encloses `history` in its scope and performs the duplicate removal and size capping before adding the new value. + +Because this replaces the update action entirely, the skipping behavior described above does not apply. The lambda receives every finalized line and decides what to record. To discard blank lines here too, add an `if (string.IsNullOrWhiteSpace(s)) return;` guard at the beginning. + +```csharp +var history = new List(); + +var config = ReadLineConfig.Basic + // ... other configuration here ... + .SetHistorySource(history) + .SetHistoryUpdateAction(s => + { + // Remove all previous entries of the text + history.RemoveAll(x => x == s); + if (history.Count >= 10) + history.RemoveAt(0); + history.Add(s); + }); + +var result = ConsoleReadLine.ReadLine(config); +``` diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..7d02102 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,40 @@ +# InteractiveReadLine + +An extensible, composable readline library written in pure C# for creating interactive text-based +interfaces with `System.Console` and other console-like UI components. + +Targets .NET Standard 2.0 and .NET 10 and has no external runtime dependencies. + +```csharp +var text = ConsoleReadLine.ReadLine(); +``` + +## Documentation + +* The **[API Reference](api/InteractiveReadLine.yml)** documents the public API directly from the + source. +* The **[History](history.md)** article explains the history feature, from basic setup through custom + update behavior. +* The [repository README](https://github.com/mattj23/InteractiveReadLine) has the full guide, + including animated examples of each feature. +* Run the repository's [demo program](https://github.com/mattj23/InteractiveReadLine/tree/main/InteractiveReadLine.Demo) + to try each feature interactively. + +## Starting points in the API + +| Type | Purpose | +| --- | --- | +| @InteractiveReadLine.ConsoleReadLine | Reads lines from `System.Console` and provides the usual entry point | +| @InteractiveReadLine.ReadLineConfig | Configures keys, formatting, lexing, auto-complete, and history | +| @InteractiveReadLine.ReadLineResult | Distinguishes a finished line from an abandoned line or the end of input | +| @InteractiveReadLine.KeyBehaviors.CommonKeyBehaviors | The ready-made editing behaviors | +| @InteractiveReadLine.KeyBehaviors.BehaviorExtensionMethods | The ready-made key bindings | +| @InteractiveReadLine.Formatting.CommonFormatters | The ready-made display formatters | +| @InteractiveReadLine.Tokenizing.CommonLexers | Ready-made lexers and components for building custom lexers | +| @InteractiveReadLine.IReadLineProvider | Defines a backend for input sources other than the console | + +## Installing + +``` +dotnet add package InteractiveReadLine +``` diff --git a/docs/nuget-readme.md b/docs/nuget-readme.md new file mode 100644 index 0000000..f388997 --- /dev/null +++ b/docs/nuget-readme.md @@ -0,0 +1,87 @@ +# Interactive ReadLine + +An extensible, composable readline library written in pure C# for creating interactive text-based +interfaces with `System.Console` and other console-like UI components. Includes customizable key +behaviors, formatting, auto-complete, navigable history, and many composable ready-made components. + +Targets .NET Standard 2.0 and .NET 10 and has no external runtime dependencies. + +> The [project page on GitHub](https://github.com/mattj23/InteractiveReadLine) has the full +> documentation, including animated examples of each feature and a runnable demo program. + +## Getting Started + +The simplest way to read a line of input is: + +```csharp +var text = ConsoleReadLine.ReadLine(); +``` + +This creates a promptless input with typing, Delete, Backspace, the arrow keys, and Ctrl+C to abandon +the line. Practically every aspect of the behavior is configurable through a `ReadLineConfig`: + +```csharp +var config = ReadLineConfig.Empty + .AddStandardKeys() + .AddCtrlNavKeys() + .AddTabAutoComplete() + .SetLexer(CommonLexers.SplitOnWhitespace) + .SetAutoCompletion(tokens => Suggestions(tokens)) + .SetFormatter(CommonFormatters.FixedPrompt("> ")); + +var text = ConsoleReadLine.ReadLine(config); +``` + +Configuration uses delegates such as `Action` and `Func` and falls into five categories: + +* **Key behaviors** determine what happens when a key is pressed, covering both the standard editing + commands and any custom behavior you bind. +* **Formatters** intercept the text on its way to the display so it can be given a prompt, a suffix, + and per-character colors. They never alter the text the user is editing. +* **Lexers** split the line into tokens used by auto-complete and token-based formatters. A composable + regular-expression lexer is included. +* **Auto-complete** provides suggestions for the token under the cursor. The user cycles through the + suggestions with Tab. +* **History** supplies previously entered lines for the user to navigate with the arrow keys. + +## Ending a Line + +A user can finish a line with Enter, abandon it with Ctrl+C, or signal that there is no more input +with Ctrl+D on an empty line. `ReadLine()` converts these outcomes to the entered text, an empty +string, and `null`, respectively. An ordinary read loop therefore terminates on Ctrl+D: + +```csharp +string? line; +while ((line = ConsoleReadLine.ReadLine(config)) != null) +{ + Execute(line); +} +``` + +Use `Read()` when you must distinguish an abandoned line from an entered empty line. It returns a +`ReadLineResult` containing the text and information about how the interaction ended. + +Note that while a line is being read, Ctrl+C abandons the line rather than terminating the process. +The previous console behavior is restored when the read finishes. + +## Canceling and Async + +Every read method accepts a `CancellationToken` and has an asynchronous counterpart: + +```csharp +var line = await ConsoleReadLine.ReadLineAsync(config, cancellationToken); +``` + +Canceling through the token raises an `OperationCanceledException`. A user abandoning a line is +ordinary input and produces a result. The asynchronous versions wait for a keypress without +occupying a thread, allowing other work to continue while the prompt remains open. + +## Requirements + +Reading individual keypresses requires an interactive console. The `ConsoleReadLine` constructor +throws an `InvalidOperationException` when standard input is redirected from a pipe or file. Use +`Console.ReadLine()` for redirected input or supply your own `IReadLineProvider`. + +## License + +MIT. See the [repository](https://github.com/mattj23/InteractiveReadLine) for the full text. diff --git a/docs/toc.yml b/docs/toc.yml new file mode 100644 index 0000000..595c733 --- /dev/null +++ b/docs/toc.yml @@ -0,0 +1,6 @@ +- name: Home + href: index.md +- name: History + href: history.md +- name: API Reference + href: api/