Revert commits related to modernization of code

* Revert f6e1368: "Fixes problems with extension blocks and params keyword"
* Revert 7965168: "Add modernization commit to .git-blame-ignore-revs"
* Revert 3f57df5: "Modernization of the code base"
This commit is contained in:
Patrik Svensson
2026-01-08 10:17:53 +01:00
committed by Patrik Svensson
parent 4de45cc131
commit 9ac41ec876
201 changed files with 8439 additions and 7087 deletions

View File

@@ -1,8 +1,5 @@
# Use file scoped namespace declarations
7b2da0a4f63bf3ceab99d2c88535e74155f2b99c
# Fix line-endings
# fix line-endings
e2ad4b1ea5555e701cda4fd400bb6592e318e1ff
# Modernization of code base (extension blocks)
3f57df5af667beeaab128d865a8818c246af8ea1

View File

@@ -21,7 +21,10 @@ Task("Clean")
Task("Lint")
.Does(ctx =>
{
ctx.DotNetFormatStyle(solution);
ctx.DotNetFormatStyle(solution, new DotNetFormatSettings
{
VerifyNoChanges = true,
});
});
Task("Build")

View File

@@ -1,12 +1,6 @@
[*.cs]
# ========================================================
# Temporarily disable warnings related to extension blocks
# ========================================================
dotnet_diagnostic.RCS1139.severity = none
dotnet_diagnostic.RCS1263.severity = none
dotnet_diagnostic.CS1572.severity = none
dotnet_diagnostic.CA1510.severity = warning
root = false
[*.cs]
# Prefer file scoped namespace declarations
csharp_style_namespace_declarations = file_scoped:warning

View File

@@ -1,4 +1,4 @@
<Project>
<Project>
<PropertyGroup Label="Settings">
<Deterministic>true</Deterministic>
<LangVersion>14</LangVersion>
@@ -14,12 +14,6 @@
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>$(MSBuildThisFileDirectory)\..\resources\spectre.snk</AssemblyOriginatorKeyFile>
<PublicKey>00240000048000009400000006020000002400005253413100040000010001006146d3789d31477cf4a3b508dcf772ff9ccad8613f6bd6b17b9c4a960a7a7b551ecd22e4f4119ced70ee8bbdf3ca0a117c99fd6248c16255ea9033110c2233d42e74e81bf4f3f7eb09bfe8b53ad399d957514f427171a86f5fe9fe0014be121d571c80c4a0cfc3531bdbf5a2900d936d93f2c94171b9134f7644a1ac3612a0d0</PublicKey>
<PolyArgumentExceptions>true</PolyArgumentExceptions>
</PropertyGroup>
<!-- Earlier (<10.0.100) SDK throws on extension blocks -->
<PropertyGroup Condition="'$(TargetFramework)' != 'net10.0'">
<NoWarn>$(NoWarn);AD0001</NoWarn>
</PropertyGroup>
<!-- Disable nullability for netstandard2.0 since polyfills are not -->

View File

@@ -4,7 +4,7 @@
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="AngleSharp" Version="1.4.0" />
<PackageVersion Include="Humanizer.Core" Version="3.0.1" />
<PackageVersion Include="Humanizer.Core" Version="2.14.1" />
<PackageVersion Include="IsExternalInit" Version="1.0.3" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.0.1" />
<PackageVersion Include="Microsoft.SourceLink.GitHub" PrivateAssets="All" Version="8.0.0" />
@@ -18,12 +18,12 @@
<PackageVersion Include="System.Text.Json" Version="8.0.5" />
<PackageVersion Include="Shouldly" Version="4.3.0" />
<PackageVersion Include="SixLabors.ImageSharp" Version="3.1.12" />
<PackageVersion Include="Spectre.Console.Cli" Version="0.53.1" />
<PackageVersion Include="Spectre.Console.Cli" Version="0.53.0" />
<PackageVersion Include="Spectre.IO" Version="0.21.0" />
<PackageVersion Include="Spectre.Verify.Extensions" Version="28.16.0" />
<PackageVersion Include="System.Memory" Version="4.6.3" />
<PackageVersion Include="TunnelVisionLabs.ReferenceAssemblyAnnotator" Version="1.0.0-alpha.160" />
<PackageVersion Include="Verify.Xunit" Version="31.9.3" />
<PackageVersion Include="Verify.Xunit" Version="31.7.1" />
<PackageVersion Include="Wcwidth.Sources" Version="4.0.1" />
<PackageVersion Include="xunit" Version="2.9.3" />
<PackageVersion Include="xunit.runner.visualstudio" Version="3.1.5">

View File

@@ -8,100 +8,127 @@ namespace Spectre.Console;
/// </summary>
public static class CanvasImageExtensions
{
/// <summary>
/// Sets the maximum width of the rendered image.
/// </summary>
/// <param name="image">The canvas image.</param>
extension(CanvasImage image)
/// <param name="maxWidth">The maximum width.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static CanvasImage MaxWidth(this CanvasImage image, int? maxWidth)
{
/// <summary>
/// Sets the maximum width of the rendered image.
/// </summary>
/// <param name="maxWidth">The maximum width.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public CanvasImage MaxWidth(int? maxWidth)
if (image is null)
{
ArgumentNullException.ThrowIfNull(image);
image.MaxWidth = maxWidth;
return image;
throw new ArgumentNullException(nameof(image));
}
/// <summary>
/// Disables the maximum width of the rendered image.
/// </summary>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public CanvasImage NoMaxWidth()
{
ArgumentNullException.ThrowIfNull(image);
image.MaxWidth = maxWidth;
return image;
}
image.MaxWidth = null;
return image;
/// <summary>
/// Disables the maximum width of the rendered image.
/// </summary>
/// <param name="image">The canvas image.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static CanvasImage NoMaxWidth(this CanvasImage image)
{
if (image is null)
{
throw new ArgumentNullException(nameof(image));
}
/// <summary>
/// Sets the pixel width.
/// </summary>
/// <param name="width">The pixel width.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public CanvasImage PixelWidth(int width)
{
ArgumentNullException.ThrowIfNull(image);
image.MaxWidth = null;
return image;
}
image.PixelWidth = width;
return image;
/// <summary>
/// Sets the pixel width.
/// </summary>
/// <param name="image">The canvas image.</param>
/// <param name="width">The pixel width.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static CanvasImage PixelWidth(this CanvasImage image, int width)
{
if (image is null)
{
throw new ArgumentNullException(nameof(image));
}
/// <summary>
/// Mutates the underlying image.
/// </summary>
/// <param name="action">The action that mutates the underlying image.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public CanvasImage Mutate(Action<IImageProcessingContext> action)
image.PixelWidth = width;
return image;
}
/// <summary>
/// Mutates the underlying image.
/// </summary>
/// <param name="image">The canvas image.</param>
/// <param name="action">The action that mutates the underlying image.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static CanvasImage Mutate(this CanvasImage image, Action<IImageProcessingContext> action)
{
if (image is null)
{
ArgumentNullException.ThrowIfNull(image);
ArgumentNullException.ThrowIfNull(action);
image.Image.Mutate(action);
return image;
throw new ArgumentNullException(nameof(image));
}
/// <summary>
/// Uses a bicubic sampler that implements the bicubic kernel algorithm W(x).
/// </summary>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public CanvasImage BicubicResampler()
if (action is null)
{
ArgumentNullException.ThrowIfNull(image);
image.Resampler = KnownResamplers.Bicubic;
return image;
throw new ArgumentNullException(nameof(action));
}
/// <summary>
/// Uses a bilinear sampler. This interpolation algorithm
/// can be used where perfect image transformation with pixel matching is impossible,
/// so that one can calculate and assign appropriate intensity values to pixels.
/// </summary>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public CanvasImage BilinearResampler()
{
ArgumentNullException.ThrowIfNull(image);
image.Image.Mutate(action);
return image;
}
image.Resampler = KnownResamplers.Triangle;
return image;
/// <summary>
/// Uses a bicubic sampler that implements the bicubic kernel algorithm W(x).
/// </summary>
/// <param name="image">The canvas image.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static CanvasImage BicubicResampler(this CanvasImage image)
{
if (image is null)
{
throw new ArgumentNullException(nameof(image));
}
/// <summary>
/// Uses a Nearest-Neighbour sampler that implements the nearest neighbor algorithm.
/// This uses a very fast, unscaled filter which will select the closest pixel to
/// the new pixels position.
/// </summary>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public CanvasImage NearestNeighborResampler()
{
ArgumentNullException.ThrowIfNull(image);
image.Resampler = KnownResamplers.Bicubic;
return image;
}
image.Resampler = KnownResamplers.NearestNeighbor;
return image;
/// <summary>
/// Uses a bilinear sampler. This interpolation algorithm
/// can be used where perfect image transformation with pixel matching is impossible,
/// so that one can calculate and assign appropriate intensity values to pixels.
/// </summary>
/// <param name="image">The canvas image.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static CanvasImage BilinearResampler(this CanvasImage image)
{
if (image is null)
{
throw new ArgumentNullException(nameof(image));
}
image.Resampler = KnownResamplers.Triangle;
return image;
}
/// <summary>
/// Uses a Nearest-Neighbour sampler that implements the nearest neighbor algorithm.
/// This uses a very fast, unscaled filter which will select the closest pixel to
/// the new pixels position.
/// </summary>
/// <param name="image">The canvas image.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static CanvasImage NearestNeighborResampler(this CanvasImage image)
{
if (image is null)
{
throw new ArgumentNullException(nameof(image));
}
image.Resampler = KnownResamplers.NearestNeighbor;
return image;
}
}

View File

@@ -5,241 +5,309 @@ namespace Spectre.Console.Json;
/// </summary>
public static class JsonTextExtensions
{
/// <summary>
/// Sets the style used for braces.
/// </summary>
/// <param name="text">The JSON text instance.</param>
extension(JsonText text)
/// <param name="style">The style to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static JsonText BracesStyle(this JsonText text, Style? style)
{
/// <summary>
/// Sets the style used for braces.
/// </summary>
/// <param name="style">The style to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public JsonText BracesStyle(Style style)
if (text == null)
{
ArgumentNullException.ThrowIfNull(text);
text.BracesStyle = style;
return text;
throw new ArgumentNullException(nameof(text));
}
/// <summary>
/// Sets the style used for brackets.
/// </summary>
/// <param name="style">The style to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public JsonText BracketStyle(Style? style)
{
ArgumentNullException.ThrowIfNull(text);
text.BracesStyle = style;
return text;
}
text.BracketsStyle = style;
return text;
/// <summary>
/// Sets the style used for brackets.
/// </summary>
/// <param name="text">The JSON text instance.</param>
/// <param name="style">The style to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static JsonText BracketStyle(this JsonText text, Style? style)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
/// <summary>
/// Sets the style used for member names.
/// </summary>
/// <param name="style">The style to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public JsonText MemberStyle(Style? style)
{
ArgumentNullException.ThrowIfNull(text);
text.BracketsStyle = style;
return text;
}
text.MemberStyle = style;
return text;
/// <summary>
/// Sets the style used for member names.
/// </summary>
/// <param name="text">The JSON text instance.</param>
/// <param name="style">The style to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static JsonText MemberStyle(this JsonText text, Style? style)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
/// <summary>
/// Sets the style used for colons.
/// </summary>
/// <param name="style">The style to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public JsonText ColonStyle(Style? style)
{
ArgumentNullException.ThrowIfNull(text);
text.MemberStyle = style;
return text;
}
text.ColonStyle = style;
return text;
/// <summary>
/// Sets the style used for colons.
/// </summary>
/// <param name="text">The JSON text instance.</param>
/// <param name="style">The style to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static JsonText ColonStyle(this JsonText text, Style? style)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
/// <summary>
/// Sets the style used for commas.
/// </summary>
/// <param name="style">The style to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public JsonText CommaStyle(Style? style)
{
ArgumentNullException.ThrowIfNull(text);
text.ColonStyle = style;
return text;
}
text.CommaStyle = style;
return text;
/// <summary>
/// Sets the style used for commas.
/// </summary>
/// <param name="text">The JSON text instance.</param>
/// <param name="style">The style to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static JsonText CommaStyle(this JsonText text, Style? style)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
/// <summary>
/// Sets the style used for string literals.
/// </summary>
/// <param name="style">The style to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public JsonText StringStyle(Style? style)
{
ArgumentNullException.ThrowIfNull(text);
text.CommaStyle = style;
return text;
}
text.StringStyle = style;
return text;
/// <summary>
/// Sets the style used for string literals.
/// </summary>
/// <param name="text">The JSON text instance.</param>
/// <param name="style">The style to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static JsonText StringStyle(this JsonText text, Style? style)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
/// <summary>
/// Sets the style used for number literals.
/// </summary>
/// <param name="style">The style to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public JsonText NumberStyle(Style? style)
{
ArgumentNullException.ThrowIfNull(text);
text.StringStyle = style;
return text;
}
text.NumberStyle = style;
return text;
/// <summary>
/// Sets the style used for number literals.
/// </summary>
/// <param name="text">The JSON text instance.</param>
/// <param name="style">The style to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static JsonText NumberStyle(this JsonText text, Style? style)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
/// <summary>
/// Sets the style used for boolean literals.
/// </summary>
/// <param name="style">The style to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public JsonText BooleanStyle(Style? style)
{
ArgumentNullException.ThrowIfNull(text);
text.NumberStyle = style;
return text;
}
text.BooleanStyle = style;
return text;
/// <summary>
/// Sets the style used for boolean literals.
/// </summary>
/// <param name="text">The JSON text instance.</param>
/// <param name="style">The style to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static JsonText BooleanStyle(this JsonText text, Style? style)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
/// <summary>
/// Sets the style used for <c>null</c> literals.
/// </summary>
/// <param name="style">The style to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public JsonText NullStyle(Style? style)
{
ArgumentNullException.ThrowIfNull(text);
text.BooleanStyle = style;
return text;
}
text.NullStyle = style;
return text;
/// <summary>
/// Sets the style used for <c>null</c> literals.
/// </summary>
/// <param name="text">The JSON text instance.</param>
/// <param name="style">The style to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static JsonText NullStyle(this JsonText text, Style? style)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
/// <summary>
/// Sets the color used for braces.
/// </summary>
/// <param name="color">The color to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public JsonText BracesColor(Color color)
{
ArgumentNullException.ThrowIfNull(text);
text.NullStyle = style;
return text;
}
text.BracesStyle = new Style(color);
return text;
/// <summary>
/// Sets the color used for braces.
/// </summary>
/// <param name="text">The JSON text instance.</param>
/// <param name="color">The color to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static JsonText BracesColor(this JsonText text, Color color)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
/// <summary>
/// Sets the color used for brackets.
/// </summary>
/// <param name="color">The color to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public JsonText BracketColor(Color color)
{
ArgumentNullException.ThrowIfNull(text);
text.BracesStyle = new Style(color);
return text;
}
text.BracketsStyle = new Style(color);
return text;
/// <summary>
/// Sets the color used for brackets.
/// </summary>
/// <param name="text">The JSON text instance.</param>
/// <param name="color">The color to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static JsonText BracketColor(this JsonText text, Color color)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
/// <summary>
/// Sets the color used for member names.
/// </summary>
/// <param name="color">The color to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public JsonText MemberColor(Color color)
{
ArgumentNullException.ThrowIfNull(text);
text.BracketsStyle = new Style(color);
return text;
}
text.MemberStyle = new Style(color);
return text;
/// <summary>
/// Sets the color used for member names.
/// </summary>
/// <param name="text">The JSON text instance.</param>
/// <param name="color">The color to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static JsonText MemberColor(this JsonText text, Color color)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
/// <summary>
/// Sets the color used for colons.
/// </summary>
/// <param name="color">The color to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public JsonText ColonColor(Color color)
{
ArgumentNullException.ThrowIfNull(text);
text.MemberStyle = new Style(color);
return text;
}
text.ColonStyle = new Style(color);
return text;
/// <summary>
/// Sets the color used for colons.
/// </summary>
/// <param name="text">The JSON text instance.</param>
/// <param name="color">The color to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static JsonText ColonColor(this JsonText text, Color color)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
/// <summary>
/// Sets the color used for commas.
/// </summary>
/// <param name="color">The color to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public JsonText CommaColor(Color color)
{
ArgumentNullException.ThrowIfNull(text);
text.ColonStyle = new Style(color);
return text;
}
text.CommaStyle = new Style(color);
return text;
/// <summary>
/// Sets the color used for commas.
/// </summary>
/// <param name="text">The JSON text instance.</param>
/// <param name="color">The color to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static JsonText CommaColor(this JsonText text, Color color)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
/// <summary>
/// Sets the color used for string literals.
/// </summary>
/// <param name="color">The color to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public JsonText StringColor(Color color)
{
ArgumentNullException.ThrowIfNull(text);
text.CommaStyle = new Style(color);
return text;
}
text.StringStyle = new Style(color);
return text;
/// <summary>
/// Sets the color used for string literals.
/// </summary>
/// <param name="text">The JSON text instance.</param>
/// <param name="color">The color to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static JsonText StringColor(this JsonText text, Color color)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
/// <summary>
/// Sets the color used for number literals.
/// </summary>
/// <param name="color">The color to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public JsonText NumberColor(Color color)
{
ArgumentNullException.ThrowIfNull(text);
text.StringStyle = new Style(color);
return text;
}
text.NumberStyle = new Style(color);
return text;
/// <summary>
/// Sets the color used for number literals.
/// </summary>
/// <param name="text">The JSON text instance.</param>
/// <param name="color">The color to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static JsonText NumberColor(this JsonText text, Color color)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
/// <summary>
/// Sets the color used for boolean literals.
/// </summary>
/// <param name="color">The color to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public JsonText BooleanColor(Color color)
{
ArgumentNullException.ThrowIfNull(text);
text.NumberStyle = new Style(color);
return text;
}
text.BooleanStyle = new Style(color);
return text;
/// <summary>
/// Sets the color used for boolean literals.
/// </summary>
/// <param name="text">The JSON text instance.</param>
/// <param name="color">The color to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static JsonText BooleanColor(this JsonText text, Color color)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
/// <summary>
/// Sets the color used for <c>null</c> literals.
/// </summary>
/// <param name="color">The color to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public JsonText NullColor(Color color)
{
ArgumentNullException.ThrowIfNull(text);
text.BooleanStyle = new Style(color);
return text;
}
text.NullStyle = new Style(color);
return text;
/// <summary>
/// Sets the color used for <c>null</c> literals.
/// </summary>
/// <param name="text">The JSON text instance.</param>
/// <param name="color">The color to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static JsonText NullColor(this JsonText text, Color color)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
text.NullStyle = new Style(color);
return text;
}
}

View File

@@ -1,3 +1,4 @@
global using System.Text;
global using Spectre.Console.Internal;
global using Spectre.Console.Json.Syntax;
global using Spectre.Console.Rendering;

View File

@@ -11,20 +11,13 @@
<PolySharpIncludeRuntimeSupportedAttributes>true</PolySharpIncludeRuntimeSupportedAttributes>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\Polyfills.cs">
<Link>Internal\Polyfills.cs</Link>
</Compile>
<Compile Include="..\..\Spectre.Console\Extensions\Bcl\CharExtensions.cs" Link="Internal\CharExtensions.cs" />
<Compile Include="..\..\Spectre.Console\Extensions\Bcl\EnumerableExtensions.cs" Link="Internal\EnumerableExtensions.cs" />
<Compile Include="..\..\Spectre.Console\Internal\Extensions\CharExtensions.cs" Link="Internal\CharExtensions.cs" />
<Compile Include="..\..\Spectre.Console\Internal\Extensions\EnumerableExtensions.cs" Link="Internal\EnumerableExtensions.cs" />
<Compile Include="..\..\Spectre.Console\Internal\Text\StringBuffer.cs" Link="Internal\StringBuffer.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Spectre.Console\Spectre.Console.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Polyfill" Condition="'$(TargetFramework)' == 'netstandard2.0'" PrivateAssets="all" />
</ItemGroup>
</Project>

View File

@@ -1,15 +0,0 @@
#if NETSTANDARD
namespace Spectre.Console;
internal static class Polyfills
{
extension(CancellationTokenSource cts)
{
public Task CancelAsync()
{
cts.Cancel();
return Task.CompletedTask;
}
}
}
#endif

View File

@@ -5,25 +5,25 @@ namespace Spectre.Console.Testing;
/// </summary>
public static class ShouldlyExtensions
{
/// <param name="item">The object to operate on.</param>
/// <summary>
/// Performs the specified action on the given object and then returns the object.
/// Useful for fluent testing patterns where additional assertions or operations
/// are chained together in a readable manner.
/// </summary>
/// <typeparam name="T">The type of the object.</typeparam>
extension<T>(T item)
/// <param name="item">The object to operate on.</param>
/// <param name="action">An action to perform on the object.</param>
/// <returns>The original object, to allow further chaining.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="action"/> is null.</exception>
[DebuggerStepThrough]
public static T And<T>(this T item, Action<T> action)
{
/// <summary>
/// Performs the specified action on the given object and then returns the object.
/// Useful for fluent testing patterns where additional assertions or operations
/// are chained together in a readable manner.
/// </summary>
/// <param name="action">An action to perform on the object.</param>
/// <returns>The original object, to allow further chaining.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="action"/> is null.</exception>
[DebuggerStepThrough]
public T And(Action<T> action)
if (action == null)
{
ArgumentNullException.ThrowIfNull(action);
action(item);
return item;
throw new ArgumentNullException(nameof(action));
}
action(item);
return item;
}
}

View File

@@ -5,42 +5,40 @@ namespace Spectre.Console.Testing;
/// </summary>
public static class StringExtensions
{
/// <summary>
/// Returns a new string with all lines trimmed of trailing whitespace.
/// </summary>
/// <param name="value">The string to trim.</param>
extension(string value)
/// <returns>A new string with all lines trimmed of trailing whitespace.</returns>
public static string TrimLines(this string value)
{
/// <summary>
/// Returns a new string with all lines trimmed of trailing whitespace.
/// </summary>
/// <returns>A new string with all lines trimmed of trailing whitespace.</returns>
public string TrimLines()
if (value is null)
{
if (value is null)
{
return string.Empty;
}
var result = new List<string>();
foreach (var line in value.NormalizeLineEndings().Split(new[] { '\n' }))
{
result.Add(line.TrimEnd());
}
return string.Join("\n", result);
}
/// <summary>
/// Returns a new string with normalized line endings.
/// </summary>
/// <returns>A new string with normalized line endings.</returns>
public string NormalizeLineEndings()
{
if (value != null)
{
value = value.Replace("\r\n", "\n");
return value.Replace("\r", string.Empty);
}
return string.Empty;
}
var result = new List<string>();
foreach (var line in value.NormalizeLineEndings().Split(new[] { '\n' }))
{
result.Add(line.TrimEnd());
}
return string.Join("\n", result);
}
/// <summary>
/// Returns a new string with normalized line endings.
/// </summary>
/// <param name="value">The string to normalize line endings for.</param>
/// <returns>A new string with normalized line endings.</returns>
public static string NormalizeLineEndings(this string value)
{
if (value != null)
{
value = value.Replace("\r\n", "\n");
return value.Replace("\r", string.Empty);
}
return string.Empty;
}
}

View File

@@ -5,23 +5,20 @@ namespace Spectre.Console.Testing;
/// </summary>
public static class StyleExtensions
{
/// <summary>
/// Sets the foreground or background color of the specified style.
/// </summary>
/// <param name="style">The style.</param>
extension(Style style)
/// <param name="color">The color.</param>
/// <param name="foreground">Whether or not to set the foreground color.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Style SetColor(this Style style, Color color, bool foreground)
{
/// <summary>
/// Sets the foreground or background color of the specified style.
/// </summary>
/// <param name="color">The color.</param>
/// <param name="foreground">Whether or not to set the foreground color.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public Style SetColor(Color color, bool foreground)
if (foreground)
{
if (foreground)
{
return style.Foreground(color);
}
return style.Background(color);
return style.Foreground(color);
}
return style.Background(color);
}
}

View File

@@ -5,84 +5,87 @@ namespace Spectre.Console.Testing;
/// </summary>
public static partial class TestConsoleExtensions
{
/// <summary>
/// Sets the console's color system.
/// </summary>
/// <param name="console">The console.</param>
extension(TestConsole console)
/// <param name="colors">The color system to use.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static TestConsole Colors(this TestConsole console, ColorSystem colors)
{
/// <summary>
/// Sets the console's color system.
/// </summary>
/// <param name="colors">The color system to use.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public TestConsole Colors(ColorSystem colors)
{
console.Profile.Capabilities.ColorSystem = colors;
return console;
}
console.Profile.Capabilities.ColorSystem = colors;
return console;
}
/// <summary>
/// Sets whether or not ANSI is supported.
/// </summary>
/// <param name="enable">Whether or not VT/ANSI control codes are supported.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public TestConsole SupportsAnsi(bool enable)
{
console.Profile.Capabilities.Ansi = enable;
return console;
}
/// <summary>
/// Sets whether or not ANSI is supported.
/// </summary>
/// <param name="console">The console.</param>
/// <param name="enable">Whether or not VT/ANSI control codes are supported.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static TestConsole SupportsAnsi(this TestConsole console, bool enable)
{
console.Profile.Capabilities.Ansi = enable;
return console;
}
/// <summary>
/// Makes the console interactive.
/// </summary>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public TestConsole Interactive()
{
console.Profile.Capabilities.Interactive = true;
return console;
}
/// <summary>
/// Makes the console interactive.
/// </summary>
/// <param name="console">The console.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static TestConsole Interactive(this TestConsole console)
{
console.Profile.Capabilities.Interactive = true;
return console;
}
/// <summary>
/// Sets the console width.
/// </summary>
/// <param name="width">The console width.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public TestConsole Width(int width)
{
console.Profile.Width = width;
return console;
}
/// <summary>
/// Sets the console width.
/// </summary>
/// <param name="console">The console.</param>
/// <param name="width">The console width.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static TestConsole Width(this TestConsole console, int width)
{
console.Profile.Width = width;
return console;
}
/// <summary>
/// Sets the console height.
/// </summary>
/// <param name="width">The console height.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public TestConsole Height(int width)
{
console.Profile.Height = width;
return console;
}
/// <summary>
/// Sets the console height.
/// </summary>
/// <param name="console">The console.</param>
/// <param name="width">The console height.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static TestConsole Height(this TestConsole console, int width)
{
console.Profile.Height = width;
return console;
}
/// <summary>
/// Sets the console size.
/// </summary>
/// <param name="size">The console size.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public TestConsole Size(Size size)
{
console.Profile.Width = size.Width;
console.Profile.Height = size.Height;
return console;
}
/// <summary>
/// Sets the console size.
/// </summary>
/// <param name="console">The console.</param>
/// <param name="size">The console size.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static TestConsole Size(this TestConsole console, Size size)
{
console.Profile.Width = size.Width;
console.Profile.Height = size.Height;
return console;
}
/// <summary>
/// Turns on emitting of VT/ANSI sequences.
/// </summary>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public TestConsole EmitAnsiSequences()
{
console.SetCursor(null);
console.EmitAnsiSequences = true;
return console;
}
/// <summary>
/// Turns on emitting of VT/ANSI sequences.
/// </summary>
/// <param name="console">The console.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static TestConsole EmitAnsiSequences(this TestConsole console)
{
console.SetCursor(null);
console.EmitAnsiSequences = true;
return console;
}
}

View File

@@ -10,15 +10,5 @@
<ItemGroup>
<ProjectReference Include="..\Spectre.Console\Spectre.Console.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Polyfill" Condition="'$(TargetFramework)' == 'netstandard2.0'" PrivateAssets="all" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\Polyfills.cs">
<Link>Extensions\Polyfills.cs</Link>
</Compile>
</ItemGroup>
</Project>

View File

@@ -33,7 +33,10 @@ public sealed class TestCapabilities : IReadOnlyCapabilities
/// <returns>A <see cref="RenderOptions"/> with the same capabilities as this instace.</returns>
public RenderOptions CreateRenderContext(IAnsiConsole console)
{
ArgumentNullException.ThrowIfNull(console);
if (console is null)
{
throw new ArgumentNullException(nameof(console));
}
return RenderOptions.Create(console, this);
}

View File

@@ -21,7 +21,10 @@ public sealed class TestConsoleInput : IAnsiConsoleInput
/// <param name="input">The input string.</param>
public void PushText(string input)
{
ArgumentNullException.ThrowIfNull(input);
if (input is null)
{
throw new ArgumentNullException(nameof(input));
}
foreach (var character in input)
{

View File

@@ -2,17 +2,14 @@ namespace Spectre.Console.Tests;
public static class ConsoleKeyExtensions
{
extension(ConsoleKey key)
public static ConsoleKeyInfo ToConsoleKeyInfo(this ConsoleKey key)
{
public ConsoleKeyInfo ToConsoleKeyInfo()
var ch = (char)key;
if (char.IsControl(ch))
{
var ch = (char)key;
if (char.IsControl(ch))
{
ch = '\0';
}
return new ConsoleKeyInfo(ch, key, false, false, false);
ch = '\0';
}
return new ConsoleKeyInfo(ch, key, false, false, false);
}
}

View File

@@ -2,16 +2,16 @@ namespace Spectre.Console.Tests;
public static class StreamExtensions
{
extension(Stream stream)
public static string ReadText(this Stream stream)
{
public string ReadText()
if (stream is null)
{
ArgumentNullException.ThrowIfNull(stream);
throw new ArgumentNullException(nameof(stream));
}
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}

View File

@@ -1,9 +1,3 @@
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Shouldly;
using Xunit;
namespace Spectre.Console.Tests.Unit;
/// <summary>

View File

@@ -1,3 +1,5 @@
using Spectre.Console.Extensions;
namespace Spectre.Console.Tests.Unit;
[ExpectationPath("Widgets/Align")]

View File

@@ -4,7 +4,10 @@ public static class EmbeddedResourceReader
{
public static Stream LoadResourceStream(string resourceName)
{
ArgumentNullException.ThrowIfNull(resourceName);
if (resourceName is null)
{
throw new ArgumentNullException(nameof(resourceName));
}
var assembly = Assembly.GetCallingAssembly();
resourceName = resourceName.Replace("/", ".");
@@ -20,9 +23,15 @@ public static class EmbeddedResourceReader
public static Stream LoadResourceStream(Assembly assembly, string resourceName)
{
ArgumentNullException.ThrowIfNull(assembly);
if (assembly is null)
{
throw new ArgumentNullException(nameof(assembly));
}
ArgumentNullException.ThrowIfNull(resourceName);
if (resourceName is null)
{
throw new ArgumentNullException(nameof(resourceName));
}
resourceName = resourceName.Replace("/", ".");
var stream = assembly.GetManifestResourceStream(resourceName);

View File

@@ -6,25 +6,22 @@ public static class TestConsoleExtensions
private static readonly Regex _filenameRegex = new Regex("\\sin\\s.*cs:nn", RegexOptions.Multiline);
private static readonly Regex _pathSeparatorRegex = new Regex(@"[/\\]+");
extension(TestConsole console)
public static string WriteNormalizedException(this TestConsole console, Exception ex, ExceptionFormats formats = ExceptionFormats.Default)
{
public string WriteNormalizedException(Exception ex, ExceptionFormats formats = ExceptionFormats.Default)
if (!string.IsNullOrWhiteSpace(console.Output))
{
if (!string.IsNullOrWhiteSpace(console.Output))
{
throw new InvalidOperationException("Output buffer is not empty.");
}
console.WriteException(ex, formats);
return string.Join("\n", NormalizeStackTrace(console.Output)
.NormalizeLineEndings()
.Split(['\n'])
.Select(line => line.TrimEnd()));
throw new InvalidOperationException("Output buffer is not empty.");
}
console.WriteException(ex, formats);
return string.Join("\n", NormalizeStackTrace(console.Output)
.NormalizeLineEndings()
.Split(['\n'])
.Select(line => line.TrimEnd()));
}
private static string NormalizeStackTrace(string text)
public static string NormalizeStackTrace(string text)
{
// First normalize line numbers
text = _lineNumberRegex.Replace(text, ":nn");

View File

@@ -0,0 +1,29 @@
namespace Spectre.Console;
/// <summary>
/// A console capable of writing ANSI escape sequences.
/// </summary>
public static partial class AnsiConsole
{
/// <summary>
/// Writes an exception to the console.
/// </summary>
/// <param name="exception">The exception to write to the console.</param>
/// <param name="format">The exception format options.</param>
[RequiresDynamicCode(ExceptionFormatter.AotWarning)]
public static void WriteException(Exception exception, ExceptionFormats format = ExceptionFormats.Default)
{
Console.WriteException(exception, format);
}
/// <summary>
/// Writes an exception to the console.
/// </summary>
/// <param name="exception">The exception to write to the console.</param>
/// <param name="settings">The exception settings.</param>
[RequiresDynamicCode(ExceptionFormatter.AotWarning)]
public static void WriteException(Exception exception, ExceptionSettings settings)
{
Console.WriteException(exception, settings);
}
}

View File

@@ -0,0 +1,17 @@
namespace Spectre.Console;
/// <summary>
/// A console capable of writing ANSI escape sequences.
/// </summary>
public static partial class AnsiConsole
{
/// <summary>
/// Creates a new <see cref="LiveDisplay"/> instance.
/// </summary>
/// <param name="target">The target renderable to update.</param>
/// <returns>A <see cref="LiveDisplay"/> instance.</returns>
public static LiveDisplay Live(IRenderable target)
{
return Console.Live(target);
}
}

View File

@@ -0,0 +1,141 @@
namespace Spectre.Console;
/// <summary>
/// A console capable of writing ANSI escape sequences.
/// </summary>
public static partial class AnsiConsole
{
/// <summary>
/// Writes the specified markup to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Markup(string value)
{
Console.Markup(value);
}
/// <summary>
/// Writes the specified markup to the console.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="args">An array of objects to write.</param>
public static void Markup(string format, params object[] args)
{
Console.Markup(format, args);
}
/// <summary>
/// Writes the specified markup to the console.
/// <para/>
/// All interpolation holes which contain a string are automatically escaped so you must not call <see cref="StringExtensions.EscapeMarkup"/>.
/// </summary>
/// <example>
/// <code>
/// string input = args[0];
/// string output = Process(input);
/// AnsiConsole.MarkupInterpolated($"[blue]{input}[/] -> [green]{output}[/]");
/// </code>
/// </example>
/// <param name="value">The interpolated string value to write.</param>
public static void MarkupInterpolated(FormattableString value)
{
Console.MarkupInterpolated(value);
}
/// <summary>
/// Writes the specified markup to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="format">A composite format string.</param>
/// <param name="args">An array of objects to write.</param>
public static void Markup(IFormatProvider provider, string format, params object[] args)
{
Console.Markup(provider, format, args);
}
/// <summary>
/// Writes the specified markup to the console.
/// <para/>
/// All interpolation holes which contain a string are automatically escaped so you must not call <see cref="StringExtensions.EscapeMarkup"/>.
/// </summary>
/// <example>
/// <code>
/// string input = args[0];
/// string output = Process(input);
/// AnsiConsole.MarkupInterpolated(CultureInfo.InvariantCulture, $"[blue]{input}[/] -> [green]{output}[/]");
/// </code>
/// </example>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The interpolated string value to write.</param>
public static void MarkupInterpolated(IFormatProvider provider, FormattableString value)
{
Console.MarkupInterpolated(provider, value);
}
/// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void MarkupLine(string value)
{
Console.MarkupLine(value);
}
/// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="args">An array of objects to write.</param>
public static void MarkupLine(string format, params object[] args)
{
Console.MarkupLine(format, args);
}
/// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console.
/// <para/>
/// All interpolation holes which contain a string are automatically escaped so you must not call <see cref="StringExtensions.EscapeMarkup"/>.
/// </summary>
/// <example>
/// <code>
/// string input = args[0];
/// string output = Process(input);
/// AnsiConsole.MarkupLineInterpolated($"[blue]{input}[/] -> [green]{output}[/]");
/// </code>
/// </example>
/// <param name="value">The interpolated string value to write.</param>
public static void MarkupLineInterpolated(FormattableString value)
{
Console.MarkupLineInterpolated(value);
}
/// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="format">A composite format string.</param>
/// <param name="args">An array of objects to write.</param>
public static void MarkupLine(IFormatProvider provider, string format, params object[] args)
{
Console.MarkupLine(provider, format, args);
}
/// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console.
/// <para/>
/// All interpolation holes which contain a string are automatically escaped so you must not call <see cref="StringExtensions.EscapeMarkup"/>.
/// </summary>
/// <example>
/// <code>
/// string input = args[0];
/// string output = Process(input);
/// AnsiConsole.MarkupLineInterpolated(CultureInfo.InvariantCulture, $"[blue]{input}[/] -> [green]{output}[/]");
/// </code>
/// </example>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The interpolated string value to write.</param>
public static void MarkupLineInterpolated(IFormatProvider provider, FormattableString value)
{
Console.MarkupLineInterpolated(provider, value);
}
}

View File

@@ -0,0 +1,25 @@
namespace Spectre.Console;
/// <summary>
/// A console capable of writing ANSI escape sequences.
/// </summary>
public static partial class AnsiConsole
{
/// <summary>
/// Creates a new <see cref="Progress"/> instance.
/// </summary>
/// <returns>A <see cref="Progress"/> instance.</returns>
public static Progress Progress()
{
return Console.Progress();
}
/// <summary>
/// Creates a new <see cref="Status"/> instance.
/// </summary>
/// <returns>A <see cref="Status"/> instance.</returns>
public static Status Status()
{
return Console.Status();
}
}

View File

@@ -0,0 +1,123 @@
namespace Spectre.Console;
/// <summary>
/// A console capable of writing ANSI escape sequences.
/// </summary>
public static partial class AnsiConsole
{
/// <summary>
/// Displays a prompt to the user.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="prompt">The prompt to display.</param>
/// <returns>The prompt input result.</returns>
public static T Prompt<T>(IPrompt<T> prompt)
{
if (prompt is null)
{
throw new ArgumentNullException(nameof(prompt));
}
return prompt.Show(Console);
}
/// <summary>
/// Displays a prompt to the user.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="prompt">The prompt to display.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>The prompt input result.</returns>
public static Task<T> PromptAsync<T>(IPrompt<T> prompt, CancellationToken cancellationToken = default)
{
if (prompt is null)
{
throw new ArgumentNullException(nameof(prompt));
}
return prompt.ShowAsync(Console, cancellationToken);
}
/// <summary>
/// Displays a prompt to the user.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="prompt">The prompt markup text.</param>
/// <returns>The prompt input result.</returns>
public static T Ask<T>(string prompt)
{
return new TextPrompt<T>(prompt).Show(Console);
}
/// <summary>
/// Displays a prompt to the user.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="prompt">The prompt markup text.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>The prompt input result.</returns>
public static Task<T> AskAsync<T>(string prompt, CancellationToken cancellationToken = default)
{
return new TextPrompt<T>(prompt).ShowAsync(Console, cancellationToken);
}
/// <summary>
/// Displays a prompt to the user with a given default.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="prompt">The prompt markup text.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The prompt input result.</returns>
public static T Ask<T>(string prompt, T defaultValue)
{
return new TextPrompt<T>(prompt)
.DefaultValue(defaultValue)
.Show(Console);
}
/// <summary>
/// Displays a prompt to the user with a given default.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="prompt">The prompt markup text.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>The prompt input result.</returns>
public static Task<T> AskAsync<T>(string prompt, T defaultValue, CancellationToken cancellationToken = default)
{
return new TextPrompt<T>(prompt)
.DefaultValue(defaultValue)
.ShowAsync(Console, cancellationToken);
}
/// <summary>
/// Displays a prompt with two choices, yes or no.
/// </summary>
/// <param name="prompt">The prompt markup text.</param>
/// <param name="defaultValue">Specifies the default answer.</param>
/// <returns><c>true</c> if the user selected "yes", otherwise <c>false</c>.</returns>
public static bool Confirm(string prompt, bool defaultValue = true)
{
return new ConfirmationPrompt(prompt)
{
DefaultValue = defaultValue,
}
.Show(Console);
}
/// <summary>
/// Displays a prompt with two choices, yes or no.
/// </summary>
/// <param name="prompt">The prompt markup text.</param>
/// <param name="defaultValue">Specifies the default answer.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns><c>true</c> if the user selected "yes", otherwise <c>false</c>.</returns>
public static Task<bool> ConfirmAsync(string prompt, bool defaultValue = true, CancellationToken cancellationToken = default)
{
return new ConfirmationPrompt(prompt)
{
DefaultValue = defaultValue,
}
.ShowAsync(Console, cancellationToken);
}
}

View File

@@ -0,0 +1,66 @@
namespace Spectre.Console;
/// <summary>
/// A console capable of writing ANSI escape sequences.
/// </summary>
public static partial class AnsiConsole
{
/// <summary>
/// Starts recording the console output.
/// </summary>
public static void Record()
{
if (_recorder == null)
{
_recorder = new Recorder(Console);
}
}
/// <summary>
/// Exports all recorded console output as text.
/// </summary>
/// <returns>The recorded output as text.</returns>
public static string ExportText()
{
if (_recorder == null)
{
throw new InvalidOperationException("Cannot export text since a recording hasn't been started.");
}
return _recorder.ExportText();
}
/// <summary>
/// Exports all recorded console output as HTML text.
/// </summary>
/// <returns>The recorded output as HTML text.</returns>
public static string ExportHtml()
{
if (_recorder == null)
{
throw new InvalidOperationException("Cannot export HTML since a recording hasn't been started.");
}
return _recorder.ExportHtml();
}
/// <summary>
/// Exports all recorded console output using a custom encoder.
/// </summary>
/// <param name="encoder">The encoder to use.</param>
/// <returns>The recorded output.</returns>
public static string ExportCustom(IAnsiConsoleEncoder encoder)
{
if (_recorder == null)
{
throw new InvalidOperationException("Cannot export HTML since a recording hasn't been started.");
}
if (encoder is null)
{
throw new ArgumentNullException(nameof(encoder));
}
return _recorder.Export(encoder);
}
}

View File

@@ -0,0 +1,31 @@
namespace Spectre.Console;
/// <summary>
/// A console capable of writing ANSI escape sequences.
/// </summary>
public static partial class AnsiConsole
{
/// <summary>
/// Renders the specified object to the console.
/// </summary>
/// <param name="renderable">The object to render.</param>
[Obsolete("Consider using AnsiConsole.Write instead.")]
public static void Render(IRenderable renderable)
{
Write(renderable);
}
/// <summary>
/// Renders the specified <see cref="IRenderable"/> to the console.
/// </summary>
/// <param name="renderable">The object to render.</param>
public static void Write(IRenderable renderable)
{
if (renderable is null)
{
throw new ArgumentNullException(nameof(renderable));
}
Console.Write(renderable);
}
}

View File

@@ -0,0 +1,16 @@
namespace Spectre.Console;
/// <summary>
/// A console capable of writing ANSI escape sequences.
/// </summary>
public static partial class AnsiConsole
{
/// <summary>
/// Switches to an alternate screen buffer if the terminal supports it.
/// </summary>
/// <param name="action">The action to execute within the alternate screen buffer.</param>
public static void AlternateScreen(Action action)
{
Console.AlternateScreen(action);
}
}

View File

@@ -0,0 +1,62 @@
namespace Spectre.Console;
/// <summary>
/// A console capable of writing ANSI escape sequences.
/// </summary>
public static partial class AnsiConsole
{
internal static Style CurrentStyle { get; private set; } = Style.Plain;
internal static bool Created { get; private set; }
/// <summary>
/// Gets or sets the foreground color.
/// </summary>
public static Color Foreground
{
get => CurrentStyle.Foreground;
set => CurrentStyle = CurrentStyle.Foreground(value);
}
/// <summary>
/// Gets or sets the background color.
/// </summary>
public static Color Background
{
get => CurrentStyle.Background;
set => CurrentStyle = CurrentStyle.Background(value);
}
/// <summary>
/// Gets or sets the text decoration.
/// </summary>
public static Decoration Decoration
{
get => CurrentStyle.Decoration;
set => CurrentStyle = CurrentStyle.Decoration(value);
}
/// <summary>
/// Resets colors and text decorations.
/// </summary>
public static void Reset()
{
ResetColors();
ResetDecoration();
}
/// <summary>
/// Resets the current applied text decorations.
/// </summary>
public static void ResetDecoration()
{
Decoration = Decoration.None;
}
/// <summary>
/// Resets the current applied foreground and background colors.
/// </summary>
public static void ResetColors()
{
CurrentStyle = Style.Plain;
}
}

View File

@@ -0,0 +1,249 @@
namespace Spectre.Console;
/// <summary>
/// A console capable of writing ANSI escape sequences.
/// </summary>
public static partial class AnsiConsole
{
/// <summary>
/// Writes the specified string value to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Write(string value)
{
Write(value, CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified 32-bit
/// signed integer value to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Write(int value)
{
Write(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified 32-bit
/// signed integer value to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void Write(IFormatProvider provider, int value)
{
Console.Write(value.ToString(provider), CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified 32-bit
/// unsigned integer value to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Write(uint value)
{
Write(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified 32-bit
/// unsigned integer value to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void Write(IFormatProvider provider, uint value)
{
Console.Write(value.ToString(provider), CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified 64-bit
/// signed integer value to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Write(long value)
{
Write(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified 64-bit
/// signed integer value to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void Write(IFormatProvider provider, long value)
{
Console.Write(value.ToString(provider), CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified 64-bit
/// unsigned integer value to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Write(ulong value)
{
Write(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified 64-bit
/// unsigned integer value to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void Write(IFormatProvider provider, ulong value)
{
Console.Write(value.ToString(provider), CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified single-precision
/// floating-point value to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Write(float value)
{
Write(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified single-precision
/// floating-point value to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void Write(IFormatProvider provider, float value)
{
Console.Write(value.ToString(provider), CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified double-precision
/// floating-point value to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Write(double value)
{
Write(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified double-precision
/// floating-point value to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void Write(IFormatProvider provider, double value)
{
Console.Write(value.ToString(provider), CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified decimal value, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Write(decimal value)
{
Write(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified decimal value, to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void Write(IFormatProvider provider, decimal value)
{
Console.Write(value.ToString(provider), CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified boolean value to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Write(bool value)
{
Write(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified boolean value to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void Write(IFormatProvider provider, bool value)
{
Console.Write(value.ToString(provider), CurrentStyle);
}
/// <summary>
/// Writes the specified Unicode character to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Write(char value)
{
Write(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the specified Unicode character to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void Write(IFormatProvider provider, char value)
{
Console.Write(value.ToString(provider), CurrentStyle);
}
/// <summary>
/// Writes the specified array of Unicode characters to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Write(char[] value)
{
Write(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the specified array of Unicode characters to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void Write(IFormatProvider provider, char[] value)
{
if (value is null)
{
throw new ArgumentNullException(nameof(value));
}
for (var index = 0; index < value.Length; index++)
{
Console.Write(value[index].ToString(provider), CurrentStyle);
}
}
/// <summary>
/// Writes the text representation of the specified array of objects,
/// to the console using the specified format information.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="args">An array of objects to write.</param>
public static void Write(string format, params object[] args)
{
Write(CultureInfo.CurrentCulture, format, args);
}
/// <summary>
/// Writes the text representation of the specified array of objects,
/// to the console using the specified format information.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="format">A composite format string.</param>
/// <param name="args">An array of objects to write.</param>
public static void Write(IFormatProvider provider, string format, params object[] args)
{
Console.Write(string.Format(provider, format, args), CurrentStyle);
}
}

View File

@@ -0,0 +1,269 @@
namespace Spectre.Console;
/// <summary>
/// A console capable of writing ANSI escape sequences.
/// </summary>
public static partial class AnsiConsole
{
/// <summary>
/// Writes an empty line to the console.
/// </summary>
public static void WriteLine()
{
Console.WriteLine();
}
/// <summary>
/// Writes the specified string value, followed by the current line terminator, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void WriteLine(string value)
{
Console.WriteLine(value, CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified 32-bit signed integer value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void WriteLine(int value)
{
WriteLine(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified 32-bit signed integer value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void WriteLine(IFormatProvider provider, int value)
{
Console.WriteLine(value.ToString(provider), CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified 32-bit unsigned integer value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void WriteLine(uint value)
{
WriteLine(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified 32-bit unsigned integer value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void WriteLine(IFormatProvider provider, uint value)
{
Console.WriteLine(value.ToString(provider), CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified 64-bit signed integer value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void WriteLine(long value)
{
WriteLine(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified 64-bit signed integer value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void WriteLine(IFormatProvider provider, long value)
{
Console.WriteLine(value.ToString(provider), CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified 64-bit unsigned integer value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void WriteLine(ulong value)
{
WriteLine(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified 64-bit unsigned integer value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void WriteLine(IFormatProvider provider, ulong value)
{
Console.WriteLine(value.ToString(provider), CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified single-precision floating-point
/// value, followed by the current line terminator, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void WriteLine(float value)
{
WriteLine(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified single-precision floating-point
/// value, followed by the current line terminator, to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void WriteLine(IFormatProvider provider, float value)
{
Console.WriteLine(value.ToString(provider), CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified double-precision floating-point
/// value, followed by the current line terminator, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void WriteLine(double value)
{
WriteLine(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified double-precision floating-point
/// value, followed by the current line terminator, to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void WriteLine(IFormatProvider provider, double value)
{
Console.WriteLine(value.ToString(provider), CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified decimal value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void WriteLine(decimal value)
{
WriteLine(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified decimal value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void WriteLine(IFormatProvider provider, decimal value)
{
Console.WriteLine(value.ToString(provider), CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified boolean value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void WriteLine(bool value)
{
WriteLine(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified boolean value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void WriteLine(IFormatProvider provider, bool value)
{
Console.WriteLine(value.ToString(provider), CurrentStyle);
}
/// <summary>
/// Writes the specified Unicode character, followed by the current
/// line terminator, value to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void WriteLine(char value)
{
WriteLine(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the specified Unicode character, followed by the current
/// line terminator, value to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void WriteLine(IFormatProvider provider, char value)
{
Console.WriteLine(value.ToString(provider), CurrentStyle);
}
/// <summary>
/// Writes the specified array of Unicode characters, followed by the current
/// line terminator, value to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void WriteLine(char[] value)
{
WriteLine(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the specified array of Unicode characters, followed by the current
/// line terminator, value to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void WriteLine(IFormatProvider provider, char[] value)
{
if (value is null)
{
throw new ArgumentNullException(nameof(value));
}
for (var index = 0; index < value.Length; index++)
{
Console.Write(value[index].ToString(provider), CurrentStyle);
}
Console.WriteLine();
}
/// <summary>
/// Writes the text representation of the specified array of objects,
/// followed by the current line terminator, to the console
/// using the specified format information.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="args">An array of objects to write.</param>
public static void WriteLine(string format, params object[] args)
{
WriteLine(CultureInfo.CurrentCulture, format, args);
}
/// <summary>
/// Writes the text representation of the specified array of objects,
/// followed by the current line terminator, to the console
/// using the specified format information.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="format">A composite format string.</param>
/// <param name="args">An array of objects to write.</param>
public static void WriteLine(IFormatProvider provider, string format, params object[] args)
{
Console.WriteLine(string.Format(provider, format, args), CurrentStyle);
}
}

View File

@@ -9,11 +9,7 @@ public static partial class AnsiConsole
private static readonly AnsiConsoleFactory _factory = new AnsiConsoleFactory();
#pragma warning restore CS0618
internal static Style CurrentStyle { get; set; } = Style.Plain;
internal static Recorder? Recorder { get; set; }
internal static bool Created { get; private set; }
private static Recorder? _recorder;
private static Lazy<IAnsiConsole> _console = new Lazy<IAnsiConsole>(
() =>
{
@@ -35,12 +31,18 @@ public static partial class AnsiConsole
{
get
{
return Recorder ?? _console.Value;
return _recorder ?? _console.Value;
}
set
{
_console = new Lazy<IAnsiConsole>(() => value);
Recorder = Recorder?.Clone(value); // Recreate the recorder
if (_recorder != null)
{
// Recreate the recorder
_recorder = _recorder.Clone(value);
}
Created = true;
}
}
@@ -48,7 +50,7 @@ public static partial class AnsiConsole
/// <summary>
/// Gets the <see cref="IAnsiConsoleCursor"/>.
/// </summary>
public static IAnsiConsoleCursor Cursor => Recorder?.Cursor ?? _console.Value.Cursor;
public static IAnsiConsoleCursor Cursor => _recorder?.Cursor ?? _console.Value.Cursor;
/// <summary>
/// Gets the console profile.
@@ -65,99 +67,12 @@ public static partial class AnsiConsole
{
return _factory.Create(settings);
}
}
// TODO: This is here temporary due to a bug in the .NET SDK
// See issue: https://github.com/dotnet/roslyn/issues/80024
public static partial class AnsiConsole
{
/// <summary>
/// Writes the text representation of the specified array of objects,
/// to the console using the specified format information.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="args">An array of objects to write.</param>
public static void Write(string format, params object[] args)
{
Write(CultureInfo.CurrentCulture, format, args);
}
/// <summary>
/// Writes the text representation of the specified array of objects,
/// to the console using the specified format information.
/// Clears the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="format">A composite format string.</param>
/// <param name="args">An array of objects to write.</param>
public static void Write(IFormatProvider provider, string format, params object[] args)
public static void Clear()
{
Console.Write(string.Format(provider, format, args), CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified array of objects,
/// followed by the current line terminator, to the console
/// using the specified format information.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="args">An array of objects to write.</param>
public static void WriteLine(string format, params object[] args)
{
WriteLine(CultureInfo.CurrentCulture, format, args);
}
/// <summary>
/// Writes the text representation of the specified array of objects,
/// followed by the current line terminator, to the console
/// using the specified format information.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="format">A composite format string.</param>
/// <param name="args">An array of objects to write.</param>
public static void WriteLine(IFormatProvider provider, string format, params object[] args)
{
Console.WriteLine(string.Format(provider, format, args), CurrentStyle);
}
/// <summary>
/// Writes the specified markup to the console.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="args">An array of objects to write.</param>
public static void Markup(string format, params object[] args)
{
Console.Markup(format, args);
}
/// <summary>
/// Writes the specified markup to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="format">A composite format string.</param>
/// <param name="args">An array of objects to write.</param>
public static void Markup(IFormatProvider provider, string format, params object[] args)
{
Console.Markup(provider, format, args);
}
/// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console.
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="args">An array of objects to write.</param>
public static void MarkupLine(string format, params object[] args)
{
Console.MarkupLine(format, args);
}
/// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="format">A composite format string.</param>
/// <param name="args">An array of objects to write.</param>
public static void MarkupLine(IFormatProvider provider, string format, params object[] args)
{
Console.MarkupLine(provider, format, args);
Console.Clear();
}
}

View File

@@ -13,7 +13,10 @@ public sealed class AnsiConsoleFactory
/// <returns>An implementation of <see cref="IAnsiConsole"/>.</returns>
public IAnsiConsole Create(AnsiConsoleSettings settings)
{
ArgumentNullException.ThrowIfNull(settings);
if (settings is null)
{
throw new ArgumentNullException(nameof(settings));
}
var output = settings.Out ?? new AnsiConsoleOutput(System.Console.Out);
if (output.Writer == null)

View File

@@ -16,31 +16,4 @@ public abstract partial class BoxBorder
/// <param name="part">The part to get the character representation for.</param>
/// <returns>A character representation of the specified border part.</returns>
public abstract string GetPart(BoxBorderPart part);
}
/// <summary>
/// Contains extension methods for <see cref="BoxBorder"/>.
/// </summary>
public static class BoxExtensions
{
/// <param name="border">The border to get the safe border for.</param>
extension(BoxBorder border)
{
/// <summary>
/// Gets the safe border for a border.
/// </summary>
/// <param name="safe">Whether or not to return the safe border.</param>
/// <returns>The safe border if one exist, otherwise the original border.</returns>
public BoxBorder GetSafeBorder(bool safe)
{
ArgumentNullException.ThrowIfNull(border);
if (safe && border.SafeBorder != null)
{
border = border.SafeBorder;
}
return border;
}
}
}

View File

@@ -220,7 +220,10 @@ public partial struct Color : IEquatable<Color>
/// <returns>The color created from the hexadecimal string.</returns>
public static Color FromHex(string hex)
{
ArgumentNullException.ThrowIfNull(hex);
if (hex is null)
{
throw new ArgumentNullException(nameof(hex));
}
if (hex.StartsWith("#"))
{

View File

@@ -19,9 +19,15 @@ public static partial class Emoji
/// <param name="emoji">The emoji.</param>
public static void Remap(string tag, string emoji)
{
ArgumentNullException.ThrowIfNull(tag);
if (tag is null)
{
throw new ArgumentNullException(nameof(tag));
}
ArgumentNullException.ThrowIfNull(emoji);
if (emoji is null)
{
throw new ArgumentNullException(nameof(emoji));
}
tag = tag.TrimStart(':').TrimEnd(':');
emoji = emoji.TrimStart(':').TrimEnd(':');
@@ -106,4 +112,16 @@ public static partial class Emoji
value = string.Empty;
return false;
}
private static int IndexOf(this ReadOnlySpan<char> span, char value, int startIndex)
{
var indexInSlice = span.Slice(startIndex).IndexOf(value);
if (indexInSlice == -1)
{
return -1;
}
return startIndex + indexInSlice;
}
}

View File

@@ -25,7 +25,10 @@ internal static class ProfileEnricher
ProfileEnrichment settings,
IDictionary<string, string>? environmentVariables)
{
ArgumentNullException.ThrowIfNull(profile);
if (profile is null)
{
throw new ArgumentNullException(nameof(profile));
}
settings ??= new ProfileEnrichment();

View File

@@ -3,36 +3,34 @@ namespace Spectre.Console.Advanced;
/// <summary>
/// Contains extension methods for <see cref="IAnsiConsole"/>.
/// </summary>
[Obsolete("Use methods on IAnsiConsole instead")]
public static class AnsiConsoleExtensions
{
/// <summary>
/// Writes a VT/Ansi control code sequence to the console (if supported).
/// </summary>
/// <param name="console">The console to write to.</param>
extension(IAnsiConsole console)
/// <param name="sequence">The VT/Ansi control code sequence to write.</param>
public static void WriteAnsi(this IAnsiConsole console, string sequence)
{
/// <summary>
/// Writes a VT/Ansi control code sequence to the console (if supported).
/// </summary>
/// <param name="sequence">The VT/Ansi control code sequence to write.</param>
[Obsolete("Use Spectre.Console.IAnsiConsole.WriteAnsi instead")]
public void WriteAnsi(string sequence)
if (console is null)
{
ArgumentNullException.ThrowIfNull(console);
if (console.Profile.Capabilities.Ansi)
{
console.Write(new ControlCode(sequence));
}
throw new ArgumentNullException(nameof(console));
}
/// <summary>
/// Gets the VT/ANSI control code sequence for a <see cref="IRenderable"/>.
/// </summary>
/// <param name="renderable">The renderable to the VT/ANSI control code sequence for.</param>
/// <returns>The VT/ANSI control code sequence.</returns>
[Obsolete("Use Spectre.Console.IAnsiConsole.ToAnsi instead")]
public string ToAnsi(IRenderable renderable)
if (console.Profile.Capabilities.Ansi)
{
return AnsiBuilder.Build(console, renderable);
console.Write(new ControlCode(sequence));
}
}
/// <summary>
/// Gets the VT/ANSI control code sequence for a <see cref="IRenderable"/>.
/// </summary>
/// <param name="console">The console.</param>
/// <param name="renderable">The renderable to the VT/ANSI control code sequence for.</param>
/// <returns>The VT/ANSI control code sequence.</returns>
public static string ToAnsi(this IAnsiConsole console, IRenderable renderable)
{
return AnsiBuilder.Build(console, renderable);
}
}

View File

@@ -0,0 +1,106 @@
namespace Spectre.Console.Extensions;
/// <summary>
/// Contains extension methods for <see cref="Align"/>.
/// </summary>
public static class AlignExtensions
{
/// <summary>
/// Sets the width.
/// </summary>
/// <param name="align">The <see cref="Align"/> object.</param>
/// <param name="width">The width, or <c>null</c> for no explicit width.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Align Width(this Align align, int? width)
{
if (align is null)
{
throw new ArgumentNullException(nameof(align));
}
align.Width = width;
return align;
}
/// <summary>
/// Sets the height.
/// </summary>
/// <param name="align">The <see cref="Align"/> object.</param>
/// <param name="height">The height, or <c>null</c> for no explicit height.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Align Height(this Align align, int? height)
{
if (align is null)
{
throw new ArgumentNullException(nameof(align));
}
align.Height = height;
return align;
}
/// <summary>
/// Sets the vertical alignment.
/// </summary>
/// <param name="align">The <see cref="Align"/> object.</param>
/// <param name="vertical">The vertical alignment, or <c>null</c> for no vertical alignment.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Align VerticalAlignment(this Align align, VerticalAlignment? vertical)
{
if (align is null)
{
throw new ArgumentNullException(nameof(align));
}
align.Vertical = vertical;
return align;
}
/// <summary>
/// Sets the <see cref="Align"/> object to be top aligned.
/// </summary>
/// <param name="align">The <see cref="Align"/> object.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Align TopAligned(this Align align)
{
if (align is null)
{
throw new ArgumentNullException(nameof(align));
}
align.Vertical = Console.VerticalAlignment.Top;
return align;
}
/// <summary>
/// Sets the <see cref="Align"/> object to be middle aligned.
/// </summary>
/// <param name="align">The <see cref="Align"/> object.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Align MiddleAligned(this Align align)
{
if (align is null)
{
throw new ArgumentNullException(nameof(align));
}
align.Vertical = Console.VerticalAlignment.Middle;
return align;
}
/// <summary>
/// Sets the <see cref="Align"/> object to be bottom aligned.
/// </summary>
/// <param name="align">The <see cref="Align"/> object.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Align BottomAligned(this Align align)
{
if (align is null)
{
throw new ArgumentNullException(nameof(align));
}
align.Vertical = Console.VerticalAlignment.Bottom;
return align;
}
}

View File

@@ -0,0 +1,80 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="IAlignable"/>.
/// </summary>
public static class AlignableExtensions
{
/// <summary>
/// Sets the alignment for an <see cref="IAlignable"/> object.
/// </summary>
/// <typeparam name="T">The alignable object type.</typeparam>
/// <param name="obj">The alignable object.</param>
/// <param name="alignment">The alignment.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T Alignment<T>(this T obj, Justify? alignment)
where T : class, IAlignable
{
if (obj is null)
{
throw new System.ArgumentNullException(nameof(obj));
}
obj.Alignment = alignment;
return obj;
}
/// <summary>
/// Sets the <see cref="IAlignable"/> object to be left aligned.
/// </summary>
/// <typeparam name="T">The alignable type.</typeparam>
/// <param name="obj">The alignable object.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T LeftAligned<T>(this T obj)
where T : class, IAlignable
{
if (obj is null)
{
throw new System.ArgumentNullException(nameof(obj));
}
obj.Alignment = Justify.Left;
return obj;
}
/// <summary>
/// Sets the <see cref="IAlignable"/> object to be centered.
/// </summary>
/// <typeparam name="T">The alignable type.</typeparam>
/// <param name="obj">The alignable object.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T Centered<T>(this T obj)
where T : class, IAlignable
{
if (obj is null)
{
throw new System.ArgumentNullException(nameof(obj));
}
obj.Alignment = Justify.Center;
return obj;
}
/// <summary>
/// Sets the <see cref="IAlignable"/> object to be right aligned.
/// </summary>
/// <typeparam name="T">The alignable type.</typeparam>
/// <param name="obj">The alignable object.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T RightAligned<T>(this T obj)
where T : class, IAlignable
{
if (obj is null)
{
throw new System.ArgumentNullException(nameof(obj));
}
obj.Alignment = Justify.Right;
return obj;
}
}

View File

@@ -1,53 +0,0 @@
namespace Spectre.Console;
public static partial class AnsiConsoleExtensions
{
extension(AnsiConsole)
{
/// <summary>
/// Writes a VT/Ansi control code sequence to the console (if supported).
/// </summary>
/// <param name="sequence">The VT/Ansi control code sequence to write.</param>
public static void WriteAnsi(string sequence)
{
AnsiConsole.Console.WriteAnsi(sequence);
}
/// <summary>
/// Gets the VT/ANSI control code sequence for a <see cref="IRenderable"/>.
/// </summary>
/// <param name="renderable">The renderable to the VT/ANSI control code sequence for.</param>
/// <returns>The VT/ANSI control code sequence.</returns>
public static string ToAnsi(IRenderable renderable)
{
return AnsiConsole.Console.ToAnsi(renderable);
}
}
extension(IAnsiConsole console)
{
/// <summary>
/// Writes a VT/Ansi control code sequence to the console (if supported).
/// </summary>
/// <param name="sequence">The VT/Ansi control code sequence to write.</param>
public void WriteAnsi(string sequence)
{
ArgumentNullException.ThrowIfNull(console);
if (console.Profile.Capabilities.Ansi)
{
console.Write(new ControlCode(sequence));
}
}
/// <summary>
/// Gets the VT/ANSI control code sequence for a <see cref="IRenderable"/>.
/// </summary>
/// <param name="renderable">The renderable to the VT/ANSI control code sequence for.</param>
/// <returns>The VT/ANSI control code sequence.</returns>
public string ToAnsi(IRenderable renderable)
{
return AnsiBuilder.Build(console, renderable);
}
}
}

View File

@@ -0,0 +1,92 @@
namespace Spectre.Console.Extensions;
/// <summary>
/// Provides extension methods for running tasks with a spinner animation.
/// </summary>
public static class SpinnerExtensions
{
/// <summary>
/// Runs a task with a spinner animation.
/// </summary>
/// <param name="task">The task to run.</param>
/// <param name="spinner">The spinner to use.</param>
/// <param name="style">The style to apply to the spinner.</param>
/// <param name="ansiConsole">The console to write to.</param>
/// <returns>The result of the task.</returns>
public static async Task Spinner(this Task task, Spinner? spinner = null, Style? style = null, IAnsiConsole? ansiConsole = null)
{
await SpinnerInternal<object>(task, spinner ?? Console.Spinner.Known.Default, style, ansiConsole);
}
/// <summary>
/// Runs a task with a spinner animation.
/// </summary>
/// <typeparam name="T">The type of the task result.</typeparam>
/// <param name="task">The task to run.</param>
/// <param name="spinner">The spinner to use.</param>
/// <param name="style">The style to apply to the spinner.</param>
/// <param name="ansiConsole">The console to write to.</param>
/// <returns>The result of the task.</returns>
public static async Task<T> Spinner<T>(this Task<T> task, Spinner? spinner = null, Style? style = null, IAnsiConsole? ansiConsole = null)
{
return (await SpinnerInternal<T>(task, spinner ?? Console.Spinner.Known.Default, style, ansiConsole))!;
}
private static async Task<T?> SpinnerInternal<T>(Task task, Spinner spinner, Style? style = null, IAnsiConsole? ansiConsole = null)
{
ansiConsole ??= AnsiConsole.Console;
style ??= Style.Plain;
var currentFrame = 0;
var cancellationTokenSource = new CancellationTokenSource();
// Start spinner animation in background
var spinnerTask = Task.Run(
async () =>
{
while (!cancellationTokenSource.Token.IsCancellationRequested)
{
ansiConsole.Cursor.Show(false);
var spinnerFrame = spinner.Frames[currentFrame];
// Write the spinner frame
ansiConsole.Write(new Text(spinnerFrame, style));
ansiConsole.Write(new ControlCode(AnsiSequences.CUB(spinnerFrame.Length)));
currentFrame = (currentFrame + 1) % spinner.Frames.Count;
await Task.Delay(spinner.Interval, cancellationTokenSource.Token);
}
}, cancellationTokenSource.Token);
try
{
// Wait for the actual task to complete
if (task is Task<T> taskWithResult)
{
var result = await taskWithResult;
await cancellationTokenSource.CancelAsync();
await spinnerTask.ContinueWith(_ => { }, TaskContinuationOptions.OnlyOnCanceled);
return result;
}
else
{
await task;
await cancellationTokenSource.CancelAsync();
await spinnerTask.ContinueWith(_ => { }, TaskContinuationOptions.OnlyOnCanceled);
return default;
}
}
finally
{
var spinnerFrame = spinner.Frames[currentFrame];
ansiConsole.Write(new string(' ', spinnerFrame.Length));
ansiConsole.Write(new ControlCode(AnsiSequences.CUB(spinnerFrame.Length)));
ansiConsole.Cursor.Show();
await cancellationTokenSource.CancelAsync();
}
}
}

View File

@@ -1,55 +1,31 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="IAnsiConsole"/>.
/// </summary>
public static partial class AnsiConsoleExtensions
{
extension(AnsiConsole)
/// <summary>
/// Writes an exception to the console.
/// </summary>
/// <param name="console">The console.</param>
/// <param name="exception">The exception to write to the console.</param>
/// <param name="format">The exception format options.</param>
[RequiresDynamicCode(ExceptionFormatter.AotWarning)]
public static void WriteException(this IAnsiConsole console, Exception exception, ExceptionFormats format = ExceptionFormats.Default)
{
/// <summary>
/// Writes an exception to the console.
/// </summary>
/// <param name="exception">The exception to write to the console.</param>
/// <param name="format">The exception format options.</param>
[RequiresDynamicCode(ExceptionFormatter.AotWarning)]
public static void WriteException(Exception exception, ExceptionFormats format = ExceptionFormats.Default)
{
AnsiConsole.Console.WriteException(exception, format);
}
/// <summary>
/// Writes an exception to the console.
/// </summary>
/// <param name="exception">The exception to write to the console.</param>
/// <param name="settings">The exception settings.</param>
[RequiresDynamicCode(ExceptionFormatter.AotWarning)]
public static void WriteException(Exception exception, ExceptionSettings settings)
{
AnsiConsole.Console.WriteException(exception, settings);
}
console.Write(exception.GetRenderable(format));
}
/// <summary>
/// Writes an exception to the console.
/// </summary>
/// <param name="console">The console.</param>
extension(IAnsiConsole console)
/// <param name="exception">The exception to write to the console.</param>
/// <param name="settings">The exception settings.</param>
[RequiresDynamicCode(ExceptionFormatter.AotWarning)]
public static void WriteException(this IAnsiConsole console, Exception exception, ExceptionSettings settings)
{
/// <summary>
/// Writes an exception to the console.
/// </summary>
/// <param name="exception">The exception to write to the console.</param>
/// <param name="format">The exception format options.</param>
[RequiresDynamicCode(ExceptionFormatter.AotWarning)]
public void WriteException(Exception exception, ExceptionFormats format = ExceptionFormats.Default)
{
console.Write(exception.GetRenderable(format));
}
/// <summary>
/// Writes an exception to the console.
/// </summary>
/// <param name="exception">The exception to write to the console.</param>
/// <param name="settings">The exception settings.</param>
[RequiresDynamicCode(ExceptionFormatter.AotWarning)]
public void WriteException(Exception exception, ExceptionSettings settings)
{
console.Write(exception.GetRenderable(settings));
}
console.Write(exception.GetRenderable(settings));
}
}

View File

@@ -1,30 +1,31 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="IAnsiConsole"/>.
/// </summary>
public static partial class AnsiConsoleExtensions
{
/// <summary>
/// Runs the specified function in exclusive mode.
/// </summary>
/// <typeparam name="T">The result type.</typeparam>
/// <param name="console">The console.</param>
extension(IAnsiConsole console)
/// <param name="func">The func to run in exclusive mode.</param>
/// <returns>The result of the function.</returns>
public static T RunExclusive<T>(this IAnsiConsole console, Func<T> func)
{
/// <summary>
/// Runs the specified function in exclusive mode.
/// </summary>
/// <typeparam name="T">The result type.</typeparam>
/// <param name="func">The func to run in exclusive mode.</param>
/// <returns>The result of the function.</returns>
public T RunExclusive<T>(Func<T> func)
{
return console.ExclusivityMode.Run(func);
}
return console.ExclusivityMode.Run(func);
}
/// <summary>
/// Runs the specified function in exclusive mode asynchronously.
/// </summary>
/// <typeparam name="T">The result type.</typeparam>
/// <param name="func">The func to run in exclusive mode.</param>
/// <returns>The result of the function.</returns>
public Task<T> RunExclusive<T>(Func<Task<T>> func)
{
return console.ExclusivityMode.RunAsync(func);
}
/// <summary>
/// Runs the specified function in exclusive mode asynchronously.
/// </summary>
/// <typeparam name="T">The result type.</typeparam>
/// <param name="console">The console.</param>
/// <param name="func">The func to run in exclusive mode.</param>
/// <returns>The result of the function.</returns>
public static Task<T> RunExclusive<T>(this IAnsiConsole console, Func<Task<T>> func)
{
return console.ExclusivityMode.RunAsync(func);
}
}

View File

@@ -1,81 +1,81 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="IAnsiConsole"/>.
/// </summary>
public static partial class AnsiConsoleExtensions
{
extension(IAnsiConsole console)
internal static async Task<string> ReadLine(this IAnsiConsole console, Style? style, bool secret, char? mask, IEnumerable<string>? items = null, CancellationToken cancellationToken = default)
{
internal async Task<string> ReadLine(
Style style, bool secret, char? mask,
IEnumerable<string>? items = null,
CancellationToken cancellationToken = default)
if (console is null)
{
ArgumentNullException.ThrowIfNull(console);
throw new ArgumentNullException(nameof(console));
}
style ??= Style.Plain;
var text = string.Empty;
style ??= Style.Plain;
var text = string.Empty;
var autocomplete = new List<string>(items ?? Enumerable.Empty<string>());
var autocomplete = new List<string>(items ?? Enumerable.Empty<string>());
while (true)
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
var rawKey = await console.Input.ReadKeyAsync(true, cancellationToken).ConfigureAwait(false);
if (rawKey == null)
{
cancellationToken.ThrowIfCancellationRequested();
var rawKey = await console.Input.ReadKeyAsync(true, cancellationToken).ConfigureAwait(false);
if (rawKey == null)
continue;
}
var key = rawKey.Value;
if (key.Key == ConsoleKey.Enter)
{
return text;
}
if (key.Key == ConsoleKey.Tab && autocomplete.Count > 0)
{
var autoCompleteDirection = key.Modifiers.HasFlag(ConsoleModifiers.Shift)
? AutoCompleteDirection.Backward
: AutoCompleteDirection.Forward;
var replace = AutoComplete(autocomplete, text, autoCompleteDirection);
if (!string.IsNullOrEmpty(replace))
{
// Render the suggestion
console.Write("\b \b".Repeat(text.Length), style);
console.Write(replace);
text = replace;
continue;
}
}
var key = rawKey.Value;
if (key.Key == ConsoleKey.Enter)
if (key.Key == ConsoleKey.Backspace)
{
if (text.Length > 0)
{
return text;
}
var lastChar = text.Last();
text = text.Substring(0, text.Length - 1);
if (key.Key == ConsoleKey.Tab && autocomplete.Count > 0)
{
var autoCompleteDirection = key.Modifiers.HasFlag(ConsoleModifiers.Shift)
? AutoCompleteDirection.Backward
: AutoCompleteDirection.Forward;
var replace = AutoComplete(autocomplete, text, autoCompleteDirection);
if (!string.IsNullOrEmpty(replace))
if (mask != null)
{
// Render the suggestion
console.Write("\b \b".Repeat(text.Length), style);
console.Write(replace);
text = replace;
continue;
}
}
if (key.Key == ConsoleKey.Backspace)
{
if (text.Length > 0)
{
var lastChar = text.Last();
text = text.Substring(0, text.Length - 1);
if (mask != null)
if (UnicodeCalculator.GetWidth(lastChar) == 1)
{
if (UnicodeCalculator.GetWidth(lastChar) == 1)
{
console.Write("\b \b");
}
else if (UnicodeCalculator.GetWidth(lastChar) == 2)
{
console.Write("\b \b\b \b");
}
console.Write("\b \b");
}
else if (UnicodeCalculator.GetWidth(lastChar) == 2)
{
console.Write("\b \b\b \b");
}
}
continue;
}
if (!char.IsControl(key.KeyChar))
{
text += key.KeyChar.ToString();
var output = key.KeyChar.ToString();
console.Write(secret ? output.Mask(mask) : output, style);
}
continue;
}
if (!char.IsControl(key.KeyChar))
{
text += key.KeyChar.ToString();
var output = key.KeyChar.ToString();
console.Write(secret ? output.Mask(mask) : output, style);
}
}
}

View File

@@ -1,35 +1,28 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="IAnsiConsole"/>.
/// </summary>
public static partial class AnsiConsoleExtensions
{
extension(AnsiConsole)
{
/// <summary>
/// Creates a new <see cref="LiveDisplay"/> instance.
/// </summary>
/// <param name="target">The target renderable to update.</param>
/// <returns>A <see cref="LiveDisplay"/> instance.</returns>
public static LiveDisplay Live(IRenderable target)
{
return AnsiConsole.Console.Live(target);
}
}
/// <summary>
/// Creates a new <see cref="LiveDisplay"/> instance for the console.
/// </summary>
/// <param name="console">The console.</param>
extension(IAnsiConsole console)
/// <param name="target">The target renderable to update.</param>
/// <returns>A <see cref="LiveDisplay"/> instance.</returns>
public static LiveDisplay Live(this IAnsiConsole console, IRenderable target)
{
/// <summary>
/// Creates a new <see cref="LiveDisplay"/> instance for the console.
/// </summary>
/// <param name="target">The target renderable to update.</param>
/// <returns>A <see cref="LiveDisplay"/> instance.</returns>
public LiveDisplay Live(IRenderable target)
if (console is null)
{
ArgumentNullException.ThrowIfNull(console);
ArgumentNullException.ThrowIfNull(target);
return new LiveDisplay(console, target);
throw new ArgumentNullException(nameof(console));
}
if (target is null)
{
throw new ArgumentNullException(nameof(target));
}
return new LiveDisplay(console, target);
}
}

View File

@@ -1,5 +1,8 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="IAnsiConsole"/>.
/// </summary>
public static partial class AnsiConsoleExtensions
{
/// <summary>
@@ -10,12 +13,28 @@ public static partial class AnsiConsoleExtensions
/// <param name="args">An array of objects to write.</param>
public static void Markup(this IAnsiConsole console, string format, params object[] args)
{
// TODO: This is here temporary due to a bug in the .NET SDK
// See issue: https://github.com/dotnet/roslyn/issues/80024
Markup(console, CultureInfo.CurrentCulture, format, args);
}
/// <summary>
/// Writes the specified markup to the console.
/// <para/>
/// All interpolation holes which contain a string are automatically escaped so you must not call <see cref="StringExtensions.EscapeMarkup"/>.
/// </summary>
/// <example>
/// <code>
/// string input = args[0];
/// string output = Process(input);
/// console.MarkupInterpolated($"[blue]{input}[/] -> [green]{output}[/]");
/// </code>
/// </example>
/// <param name="console">The console to write to.</param>
/// <param name="value">The interpolated string value to write.</param>
public static void MarkupInterpolated(this IAnsiConsole console, FormattableString value)
{
MarkupInterpolated(console, CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the specified markup to the console.
/// </summary>
@@ -25,12 +44,39 @@ public static partial class AnsiConsoleExtensions
/// <param name="args">An array of objects to write.</param>
public static void Markup(this IAnsiConsole console, IFormatProvider provider, string format, params object[] args)
{
// TODO: This is here temporary due to a bug in the .NET SDK
// See issue: https://github.com/dotnet/roslyn/issues/80024
Markup(console, string.Format(provider, format, args));
}
/// <summary>
/// Writes the specified markup to the console.
/// <para/>
/// All interpolation holes which contain a string are automatically escaped so you must not call <see cref="StringExtensions.EscapeMarkup"/>.
/// </summary>
/// <example>
/// <code>
/// string input = args[0];
/// string output = Process(input);
/// console.MarkupInterpolated(CultureInfo.InvariantCulture, $"[blue]{input}[/] -> [green]{output}[/]");
/// </code>
/// </example>
/// <param name="console">The console to write to.</param>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The interpolated string value to write.</param>
public static void MarkupInterpolated(this IAnsiConsole console, IFormatProvider provider, FormattableString value)
{
Markup(console, Console.Markup.EscapeInterpolated(provider, value));
}
/// <summary>
/// Writes the specified markup to the console.
/// </summary>
/// <param name="console">The console to write to.</param>
/// <param name="value">The value to write.</param>
public static void Markup(this IAnsiConsole console, string value)
{
console.Write(MarkupParser.Parse(value));
}
/// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console.
/// </summary>
@@ -39,12 +85,38 @@ public static partial class AnsiConsoleExtensions
/// <param name="args">An array of objects to write.</param>
public static void MarkupLine(this IAnsiConsole console, string format, params object[] args)
{
// TODO: This is here temporary due to a bug in the .NET SDK
// See issue: https://github.com/dotnet/roslyn/issues/80024
MarkupLine(console, CultureInfo.CurrentCulture, format, args);
}
/// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console.
/// <para/>
/// All interpolation holes which contain a string are automatically escaped so you must not call <see cref="StringExtensions.EscapeMarkup"/>.
/// </summary>
/// <example>
/// <code>
/// string input = args[0];
/// string output = Process(input);
/// console.MarkupLineInterpolated($"[blue]{input}[/] -> [green]{output}[/]");
/// </code>
/// </example>
/// <param name="console">The console to write to.</param>
/// <param name="value">The interpolated string value to write.</param>
public static void MarkupLineInterpolated(this IAnsiConsole console, FormattableString value)
{
MarkupLineInterpolated(console, CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console.
/// </summary>
/// <param name="console">The console to write to.</param>
/// <param name="value">The value to write.</param>
public static void MarkupLine(this IAnsiConsole console, string value)
{
Markup(console, value + Environment.NewLine);
}
/// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console.
/// </summary>
@@ -54,200 +126,26 @@ public static partial class AnsiConsoleExtensions
/// <param name="args">An array of objects to write.</param>
public static void MarkupLine(this IAnsiConsole console, IFormatProvider provider, string format, params object[] args)
{
// TODO: This is here temporary due to a bug in the .NET SDK
// See issue: https://github.com/dotnet/roslyn/issues/80024
Markup(console, provider, format + Environment.NewLine, args);
}
extension(AnsiConsole)
{
/// <summary>
/// Writes the specified markup to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Markup(string value)
{
AnsiConsole.Console.Markup(value);
}
/// <summary>
/// Writes the specified markup to the console.
/// <para/>
/// All interpolation holes which contain a string are automatically escaped so you must not call <see cref="StringExtensions.EscapeMarkup"/>.
/// </summary>
/// <example>
/// <code>
/// string input = args[0];
/// string output = Process(input);
/// AnsiConsole.MarkupInterpolated($"[blue]{input}[/] -> [green]{output}[/]");
/// </code>
/// </example>
/// <param name="value">The interpolated string value to write.</param>
public static void MarkupInterpolated(FormattableString value)
{
AnsiConsole.Console.MarkupInterpolated(value);
}
/// <summary>
/// Writes the specified markup to the console.
/// <para/>
/// All interpolation holes which contain a string are automatically escaped so you must not call <see cref="StringExtensions.EscapeMarkup"/>.
/// </summary>
/// <example>
/// <code>
/// string input = args[0];
/// string output = Process(input);
/// AnsiConsole.MarkupInterpolated(CultureInfo.InvariantCulture, $"[blue]{input}[/] -> [green]{output}[/]");
/// </code>
/// </example>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The interpolated string value to write.</param>
public static void MarkupInterpolated(IFormatProvider provider, FormattableString value)
{
AnsiConsole.Console.MarkupInterpolated(provider, value);
}
/// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void MarkupLine(string value)
{
AnsiConsole.Console.MarkupLine(value);
}
/// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console.
/// <para/>
/// All interpolation holes which contain a string are automatically escaped so you must not call <see cref="StringExtensions.EscapeMarkup"/>.
/// </summary>
/// <example>
/// <code>
/// string input = args[0];
/// string output = Process(input);
/// AnsiConsole.MarkupLineInterpolated($"[blue]{input}[/] -> [green]{output}[/]");
/// </code>
/// </example>
/// <param name="value">The interpolated string value to write.</param>
public static void MarkupLineInterpolated(FormattableString value)
{
AnsiConsole.Console.MarkupLineInterpolated(value);
}
/// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console.
/// <para/>
/// All interpolation holes which contain a string are automatically escaped so you must not call <see cref="StringExtensions.EscapeMarkup"/>.
/// </summary>
/// <example>
/// <code>
/// string input = args[0];
/// string output = Process(input);
/// AnsiConsole.MarkupLineInterpolated(CultureInfo.InvariantCulture, $"[blue]{input}[/] -> [green]{output}[/]");
/// </code>
/// </example>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The interpolated string value to write.</param>
public static void MarkupLineInterpolated(IFormatProvider provider, FormattableString value)
{
AnsiConsole.Console.MarkupLineInterpolated(provider, value);
}
}
/// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console.
/// <para/>
/// All interpolation holes which contain a string are automatically escaped so you must not call <see cref="StringExtensions.EscapeMarkup"/>.
/// </summary>
/// <example>
/// <code>
/// string input = args[0];
/// string output = Process(input);
/// console.MarkupLineInterpolated(CultureInfo.InvariantCulture, $"[blue]{input}[/] -> [green]{output}[/]");
/// </code>
/// </example>
/// <param name="console">The console to write to.</param>
extension(IAnsiConsole console)
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The interpolated string value to write.</param>
public static void MarkupLineInterpolated(this IAnsiConsole console, IFormatProvider provider, FormattableString value)
{
/// <summary>
/// Writes the specified markup to the console.
/// <para/>
/// All interpolation holes which contain a string are automatically escaped so you must not call <see cref="StringExtensions.EscapeMarkup"/>.
/// </summary>
/// <example>
/// <code>
/// string input = args[0];
/// string output = Process(input);
/// console.MarkupInterpolated($"[blue]{input}[/] -> [green]{output}[/]");
/// </code>
/// </example>
/// <param name="value">The interpolated string value to write.</param>
public void MarkupInterpolated(FormattableString value)
{
MarkupInterpolated(console, CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the specified markup to the console.
/// <para/>
/// All interpolation holes which contain a string are automatically escaped so you must not call <see cref="StringExtensions.EscapeMarkup"/>.
/// </summary>
/// <example>
/// <code>
/// string input = args[0];
/// string output = Process(input);
/// console.MarkupInterpolated(CultureInfo.InvariantCulture, $"[blue]{input}[/] -> [green]{output}[/]");
/// </code>
/// </example>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The interpolated string value to write.</param>
public void MarkupInterpolated(IFormatProvider provider, FormattableString value)
{
Markup(console, Console.Markup.EscapeInterpolated(provider, value));
}
/// <summary>
/// Writes the specified markup to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public void Markup(string value)
{
console.Write(MarkupParser.Parse(value));
}
/// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console.
/// <para/>
/// All interpolation holes which contain a string are automatically escaped so you must not call <see cref="StringExtensions.EscapeMarkup"/>.
/// </summary>
/// <example>
/// <code>
/// string input = args[0];
/// string output = Process(input);
/// console.MarkupLineInterpolated($"[blue]{input}[/] -> [green]{output}[/]");
/// </code>
/// </example>
/// <param name="value">The interpolated string value to write.</param>
public void MarkupLineInterpolated(FormattableString value)
{
MarkupLineInterpolated(console, CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public void MarkupLine(string value)
{
Markup(console, value + Environment.NewLine);
}
/// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console.
/// <para/>
/// All interpolation holes which contain a string are automatically escaped so you must not call <see cref="StringExtensions.EscapeMarkup"/>.
/// </summary>
/// <example>
/// <code>
/// string input = args[0];
/// string output = Process(input);
/// console.MarkupLineInterpolated(CultureInfo.InvariantCulture, $"[blue]{input}[/] -> [green]{output}[/]");
/// </code>
/// </example>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The interpolated string value to write.</param>
public void MarkupLineInterpolated(IFormatProvider provider, FormattableString value)
{
MarkupLine(console, Console.Markup.EscapeInterpolated(provider, value));
}
MarkupLine(console, Console.Markup.EscapeInterpolated(provider, value));
}
}

View File

@@ -1,51 +1,37 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="IAnsiConsole"/>.
/// </summary>
public static partial class AnsiConsoleExtensions
{
extension(AnsiConsole)
/// <summary>
/// Creates a new <see cref="Progress"/> instance for the console.
/// </summary>
/// <param name="console">The console.</param>
/// <returns>A <see cref="Progress"/> instance.</returns>
public static Progress Progress(this IAnsiConsole console)
{
/// <summary>
/// Creates a new <see cref="Spectre.Console.Progress"/> instance.
/// </summary>
/// <returns>A <see cref="Spectre.Console.Progress"/> instance.</returns>
public static Progress Progress()
if (console is null)
{
return AnsiConsole.Console.Progress();
throw new ArgumentNullException(nameof(console));
}
/// <summary>
/// Creates a new <see cref="Spectre.Console.Status"/> instance.
/// </summary>
/// <returns>A <see cref="Spectre.Console.Status"/> instance.</returns>
public static Status Status()
{
return AnsiConsole.Console.Status();
}
return new Progress(console);
}
/// <summary>
/// Creates a new <see cref="Status"/> instance for the console.
/// </summary>
/// <param name="console">The console.</param>
extension(IAnsiConsole console)
/// <returns>A <see cref="Status"/> instance.</returns>
public static Status Status(this IAnsiConsole console)
{
/// <summary>
/// Creates a new <see cref="Spectre.Console.Progress"/> instance for the console.
/// </summary>
/// <returns>A <see cref="Spectre.Console.Progress"/> instance.</returns>
public Progress Progress()
if (console is null)
{
ArgumentNullException.ThrowIfNull(console);
return new Progress(console);
throw new ArgumentNullException(nameof(console));
}
/// <summary>
/// Creates a new <see cref="Spectre.Console.Status"/> instance for the console.
/// </summary>
/// <returns>A <see cref="Spectre.Console.Status"/> instance.</returns>
public Status Status()
{
ArgumentNullException.ThrowIfNull(console);
return new Status(console);
}
return new Status(console);
}
}

View File

@@ -1,233 +1,131 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="IAnsiConsole"/>.
/// </summary>
public static partial class AnsiConsoleExtensions
{
extension(AnsiConsole)
/// <summary>
/// Displays a prompt to the user.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="console">The console.</param>
/// <param name="prompt">The prompt to display.</param>
/// <returns>The prompt input result.</returns>
public static T Prompt<T>(this IAnsiConsole console, IPrompt<T> prompt)
{
/// <summary>
/// Displays a prompt to the user.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="prompt">The prompt to display.</param>
/// <returns>The prompt input result.</returns>
public static T Prompt<T>(IPrompt<T> prompt)
if (prompt is null)
{
ArgumentNullException.ThrowIfNull(prompt);
return prompt.Show(AnsiConsole.Console);
throw new ArgumentNullException(nameof(prompt));
}
/// <summary>
/// Displays a prompt to the user.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="prompt">The prompt to display.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>The prompt input result.</returns>
public static Task<T> PromptAsync<T>(IPrompt<T> prompt, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(prompt);
return prompt.ShowAsync(AnsiConsole.Console, cancellationToken);
}
/// <summary>
/// Displays a prompt to the user.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="prompt">The prompt markup text.</param>
/// <returns>The prompt input result.</returns>
public static T Ask<T>(string prompt)
{
return new TextPrompt<T>(prompt).Show(AnsiConsole.Console);
}
/// <summary>
/// Displays a prompt to the user.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="prompt">The prompt markup text.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>The prompt input result.</returns>
public static Task<T> AskAsync<T>(string prompt, CancellationToken cancellationToken = default)
{
return new TextPrompt<T>(prompt).ShowAsync(AnsiConsole.Console, cancellationToken);
}
/// <summary>
/// Displays a prompt to the user with a given default.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="prompt">The prompt markup text.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The prompt input result.</returns>
public static T Ask<T>(string prompt, T defaultValue)
{
return new TextPrompt<T>(prompt)
.DefaultValue(defaultValue)
.Show(AnsiConsole.Console);
}
/// <summary>
/// Displays a prompt to the user with a given default.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="prompt">The prompt markup text.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>The prompt input result.</returns>
public static Task<T> AskAsync<T>(string prompt, T defaultValue, CancellationToken cancellationToken = default)
{
return new TextPrompt<T>(prompt)
.DefaultValue(defaultValue)
.ShowAsync(AnsiConsole.Console, cancellationToken);
}
/// <summary>
/// Displays a prompt with two choices, yes or no.
/// </summary>
/// <param name="prompt">The prompt markup text.</param>
/// <param name="defaultValue">Specifies the default answer.</param>
/// <returns><c>true</c> if the user selected "yes", otherwise <c>false</c>.</returns>
public static bool Confirm(string prompt, bool defaultValue = true)
{
return new ConfirmationPrompt(prompt)
{
DefaultValue = defaultValue,
}
.Show(AnsiConsole.Console);
}
/// <summary>
/// Displays a prompt with two choices, yes or no.
/// </summary>
/// <param name="prompt">The prompt markup text.</param>
/// <param name="defaultValue">Specifies the default answer.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns><c>true</c> if the user selected "yes", otherwise <c>false</c>.</returns>
public static Task<bool> ConfirmAsync(string prompt, bool defaultValue = true,
CancellationToken cancellationToken = default)
{
return new ConfirmationPrompt(prompt)
{
DefaultValue = defaultValue,
}
.ShowAsync(AnsiConsole.Console, cancellationToken);
}
return prompt.Show(console);
}
/// <summary>
/// Displays a prompt to the user.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="console">The console.</param>
extension(IAnsiConsole console)
/// <param name="prompt">The prompt markup text.</param>
/// <returns>The prompt input result.</returns>
public static T Ask<T>(this IAnsiConsole console, string prompt)
{
/// <summary>
/// Displays a prompt to the user.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="prompt">The prompt to display.</param>
/// <returns>The prompt input result.</returns>
public T Prompt<T>(IPrompt<T> prompt)
{
ArgumentNullException.ThrowIfNull(prompt);
return new TextPrompt<T>(prompt).Show(console);
}
return prompt.Show(console);
/// <summary>
/// Displays a prompt to the user.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="console">The console.</param>
/// <param name="prompt">The prompt markup text.</param>
/// <param name="culture">Specific CultureInfo to use when converting input.</param>
/// <returns>The prompt input result.</returns>
public static T Ask<T>(this IAnsiConsole console, string prompt, CultureInfo? culture)
{
var textPrompt = new TextPrompt<T>(prompt);
textPrompt.Culture = culture;
return textPrompt.Show(console);
}
/// <summary>
/// Displays a prompt with two choices, yes or no.
/// </summary>
/// <param name="console">The console.</param>
/// <param name="prompt">The prompt markup text.</param>
/// <param name="defaultValue">Specifies the default answer.</param>
/// <returns><c>true</c> if the user selected "yes", otherwise <c>false</c>.</returns>
public static bool Confirm(this IAnsiConsole console, string prompt, bool defaultValue = true)
{
return new ConfirmationPrompt(prompt)
{
DefaultValue = defaultValue,
}
.Show(console);
}
/// <summary>
/// Displays a prompt to the user.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="console">The console.</param>
/// <param name="prompt">The prompt to display.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>The prompt input result.</returns>
public static Task<T> PromptAsync<T>(this IAnsiConsole console, IPrompt<T> prompt, CancellationToken cancellationToken = default)
{
if (prompt is null)
{
throw new ArgumentNullException(nameof(prompt));
}
/// <summary>
/// Displays a prompt to the user.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="prompt">The prompt markup text.</param>
/// <returns>The prompt input result.</returns>
public T Ask<T>(string prompt)
{
return new TextPrompt<T>(prompt).Show(console);
}
return prompt.ShowAsync(console, cancellationToken);
}
/// <summary>
/// Displays a prompt to the user.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="prompt">The prompt markup text.</param>
/// <param name="culture">Specific CultureInfo to use when converting input.</param>
/// <returns>The prompt input result.</returns>
public T Ask<T>(string prompt, CultureInfo? culture)
{
var textPrompt = new TextPrompt<T>(prompt);
textPrompt.Culture = culture;
return textPrompt.Show(console);
}
/// <summary>
/// Displays a prompt to the user.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="console">The console.</param>
/// <param name="prompt">The prompt markup text.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>The prompt input result.</returns>
public static Task<T> AskAsync<T>(this IAnsiConsole console, string prompt, CancellationToken cancellationToken = default)
{
return new TextPrompt<T>(prompt).ShowAsync(console, cancellationToken);
}
/// <summary>
/// Displays a prompt with two choices, yes or no.
/// </summary>
/// <param name="prompt">The prompt markup text.</param>
/// <param name="defaultValue">Specifies the default answer.</param>
/// <returns><c>true</c> if the user selected "yes", otherwise <c>false</c>.</returns>
public bool Confirm(string prompt, bool defaultValue = true)
{
return new ConfirmationPrompt(prompt)
{
DefaultValue = defaultValue,
}
.Show(console);
}
/// <summary>
/// Displays a prompt to the user.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="console">The console.</param>
/// <param name="prompt">The prompt markup text.</param>
/// <param name="culture">Specific CultureInfo to use when converting input.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>The prompt input result.</returns>
public static Task<T> AskAsync<T>(this IAnsiConsole console, string prompt, CultureInfo? culture, CancellationToken cancellationToken = default)
{
var textPrompt = new TextPrompt<T>(prompt);
textPrompt.Culture = culture;
return textPrompt.ShowAsync(console, cancellationToken);
}
/// <summary>
/// Displays a prompt to the user.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="prompt">The prompt to display.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>The prompt input result.</returns>
public Task<T> PromptAsync<T>(IPrompt<T> prompt, CancellationToken cancellationToken = default)
/// <summary>
/// Displays a prompt with two choices, yes or no.
/// </summary>
/// <param name="console">The console.</param>
/// <param name="prompt">The prompt markup text.</param>
/// <param name="defaultValue">Specifies the default answer.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns><c>true</c> if the user selected "yes", otherwise <c>false</c>.</returns>
public static Task<bool> ConfirmAsync(this IAnsiConsole console, string prompt, bool defaultValue = true, CancellationToken cancellationToken = default)
{
return new ConfirmationPrompt(prompt)
{
ArgumentNullException.ThrowIfNull(prompt);
return prompt.ShowAsync(console, cancellationToken);
}
/// <summary>
/// Displays a prompt to the user.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="prompt">The prompt markup text.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>The prompt input result.</returns>
public Task<T> AskAsync<T>(string prompt, CancellationToken cancellationToken = default)
{
return new TextPrompt<T>(prompt).ShowAsync(console, cancellationToken);
}
/// <summary>
/// Displays a prompt to the user.
/// </summary>
/// <typeparam name="T">The prompt result type.</typeparam>
/// <param name="prompt">The prompt markup text.</param>
/// <param name="culture">Specific CultureInfo to use when converting input.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>The prompt input result.</returns>
public Task<T> AskAsync<T>(string prompt, CultureInfo? culture, CancellationToken cancellationToken = default)
{
var textPrompt = new TextPrompt<T>(prompt);
textPrompt.Culture = culture;
return textPrompt.ShowAsync(console, cancellationToken);
}
/// <summary>
/// Displays a prompt with two choices, yes or no.
/// </summary>
/// <param name="prompt">The prompt markup text.</param>
/// <param name="defaultValue">Specifies the default answer.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns><c>true</c> if the user selected "yes", otherwise <c>false</c>.</returns>
public Task<bool> ConfirmAsync(string prompt, bool defaultValue = true,
CancellationToken cancellationToken = default)
{
return new ConfirmationPrompt(prompt)
{
DefaultValue = defaultValue,
}
.ShowAsync(console, cancellationToken);
DefaultValue = defaultValue,
}
.ShowAsync(console, cancellationToken);
}
}

View File

@@ -1,76 +0,0 @@
namespace Spectre.Console;
public static partial class AnsiConsoleExtensions
{
extension(AnsiConsole)
{
/// <summary>
/// Creates a recorder for the specified console.
/// </summary>
/// <returns>A recorder for the specified console.</returns>
public static Recorder CreateRecorder()
{
return new Recorder(AnsiConsole.Console);
}
/// <summary>
/// Starts recording the console output.
/// </summary>
[Obsolete("Use AnsiConsole.CreateRecorder instead")]
public static void Record()
{
if (AnsiConsole.Recorder == null)
{
AnsiConsole.Recorder = new Recorder(AnsiConsole.Console);
}
}
/// <summary>
/// Exports all recorded console output as text.
/// </summary>
/// <returns>The recorded output as text.</returns>
[Obsolete("Use recorder from AnsiConsole.CreateRecorder instead")]
public static string ExportText()
{
if (AnsiConsole.Recorder == null)
{
throw new InvalidOperationException("Cannot export text since a recording hasn't been started.");
}
return AnsiConsole.Recorder.ExportText();
}
/// <summary>
/// Exports all recorded console output as HTML text.
/// </summary>
/// <returns>The recorded output as HTML text.</returns>
[Obsolete("Use recorder from AnsiConsole.CreateRecorder instead")]
public static string ExportHtml()
{
if (AnsiConsole.Recorder == null)
{
throw new InvalidOperationException("Cannot export HTML since a recording hasn't been started.");
}
return AnsiConsole.Recorder.ExportHtml();
}
/// <summary>
/// Exports all recorded console output using a custom encoder.
/// </summary>
/// <param name="encoder">The encoder to use.</param>
/// <returns>The recorded output.</returns>
[Obsolete("Use recorder from AnsiConsole.CreateRecorder instead")]
public static string ExportCustom(IAnsiConsoleEncoder encoder)
{
if (AnsiConsole.Recorder == null)
{
throw new InvalidOperationException("Cannot export HTML since a recording hasn't been started.");
}
ArgumentNullException.ThrowIfNull(encoder);
return AnsiConsole.Recorder.Export(encoder);
}
}
}

View File

@@ -1,46 +1,28 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="IAnsiConsole"/>.
/// </summary>
public static partial class AnsiConsoleExtensions
{
extension(AnsiConsole)
{
/// <summary>
/// Renders the specified object to the console.
/// </summary>
/// <param name="renderable">The object to render.</param>
[Obsolete("Consider using AnsiConsole.Write instead.")]
public static void Render(IRenderable renderable)
{
Write(renderable);
}
/// <summary>
/// Renders the specified <see cref="IRenderable"/> to the console.
/// </summary>
/// <param name="renderable">The object to render.</param>
public static void Write(IRenderable renderable)
{
ArgumentNullException.ThrowIfNull(renderable);
AnsiConsole.Console.Write(renderable);
}
}
/// <summary>
/// Renders the specified object to the console.
/// </summary>
/// <param name="console">The console to render to.</param>
extension(IAnsiConsole console)
/// <param name="renderable">The object to render.</param>
[Obsolete("Consider using IAnsiConsole.Write instead.")]
public static void Render(this IAnsiConsole console, IRenderable renderable)
{
/// <summary>
/// Renders the specified object to the console.
/// </summary>
/// <param name="renderable">The object to render.</param>
[Obsolete("Consider using IAnsiConsole.Write instead.")]
public void Render(IRenderable renderable)
if (console is null)
{
ArgumentNullException.ThrowIfNull(console);
ArgumentNullException.ThrowIfNull(renderable);
console.Write(renderable);
throw new ArgumentNullException(nameof(console));
}
if (renderable is null)
{
throw new ArgumentNullException(nameof(renderable));
}
console.Write(renderable);
}
}

View File

@@ -1,54 +1,44 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="IAnsiConsole"/>.
/// </summary>
public static partial class AnsiConsoleExtensions
{
extension(AnsiConsole)
{
/// <summary>
/// Switches to an alternate screen buffer if the terminal supports it.
/// </summary>
/// <param name="action">The action to execute within the alternate screen buffer.</param>
public static void AlternateScreen(Action action)
{
AnsiConsole.Console.AlternateScreen(action);
}
}
/// <summary>
/// Switches to an alternate screen buffer if the terminal supports it.
/// </summary>
/// <param name="console">The console.</param>
extension(IAnsiConsole console)
/// <param name="action">The action to execute within the alternate screen buffer.</param>
public static void AlternateScreen(this IAnsiConsole console, Action action)
{
/// <summary>
/// Switches to an alternate screen buffer if the terminal supports it.
/// </summary>
/// <param name="action">The action to execute within the alternate screen buffer.</param>
public void AlternateScreen(Action action)
if (console is null)
{
ArgumentNullException.ThrowIfNull(console);
throw new ArgumentNullException(nameof(console));
}
if (!console.Profile.Capabilities.Ansi)
{
throw new NotSupportedException(
"Alternate buffers are not supported since your terminal does not support ANSI.");
}
if (!console.Profile.Capabilities.Ansi)
{
throw new NotSupportedException("Alternate buffers are not supported since your terminal does not support ANSI.");
}
if (!console.Profile.Capabilities.AlternateBuffer)
{
throw new NotSupportedException("Alternate buffers are not supported by your terminal.");
}
if (!console.Profile.Capabilities.AlternateBuffer)
{
throw new NotSupportedException("Alternate buffers are not supported by your terminal.");
}
// Switch to alternate screen
console.Write(new ControlCode("\u001b[?1049h\u001b[H"));
// Switch to alternate screen
console.Write(new ControlCode("\u001b[?1049h\u001b[H"));
try
{
// Execute custom action
action();
}
finally
{
// Switch back to primary screen
console.Write(new ControlCode("\u001b[?1049l"));
}
try
{
// Execute custom action
action();
}
finally
{
// Switch back to primary screen
console.Write(new ControlCode("\u001b[?1049l"));
}
}
}

View File

@@ -1,65 +0,0 @@
namespace Spectre.Console;
public static partial class AnsiConsoleExtensions
{
extension(AnsiConsole)
{
/// <summary>
/// Gets or sets the foreground color.
/// </summary>
[Obsolete("Static global state has been obsolete and will be removed in a future version")]
public static Color Foreground
{
get => AnsiConsole.CurrentStyle.Foreground;
set => AnsiConsole.CurrentStyle = AnsiConsole.CurrentStyle.Foreground(value);
}
/// <summary>
/// Gets or sets the background color.
/// </summary>
[Obsolete("Static global state has been obsolete and will be removed in a future version")]
public static Color Background
{
get => AnsiConsole.CurrentStyle.Background;
set => AnsiConsole.CurrentStyle = AnsiConsole.CurrentStyle.Background(value);
}
/// <summary>
/// Gets or sets the text decoration.
/// </summary>
[Obsolete("Static global state has been obsolete and will be removed in a future version")]
public static Decoration Decoration
{
get => AnsiConsole.CurrentStyle.Decoration;
set => AnsiConsole.CurrentStyle = AnsiConsole.CurrentStyle.Decoration(value);
}
/// <summary>
/// Resets colors and text decorations.
/// </summary>
[Obsolete("Static global state has been obsolete and will be removed in a future version")]
public static void Reset()
{
ResetColors();
ResetDecoration();
}
/// <summary>
/// Resets the current applied text decorations.
/// </summary>
[Obsolete("Static global state has been obsolete and will be removed in a future version")]
public static void ResetDecoration()
{
AnsiConsole.Decoration = Decoration.None;
}
/// <summary>
/// Resets the current applied foreground and background colors.
/// </summary>
[Obsolete("Static global state has been obsolete and will be removed in a future version")]
public static void ResetColors()
{
AnsiConsole.CurrentStyle = Style.Plain;
}
}
}

View File

@@ -1,249 +0,0 @@
namespace Spectre.Console;
public static partial class AnsiConsoleExtensions
{
extension(AnsiConsole)
{
/// <summary>
/// Writes the specified string value to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Write(string value)
{
AnsiConsole.Write(value, AnsiConsole.CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified 32-bit
/// signed integer value to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Write(int value)
{
Write(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified 32-bit
/// signed integer value to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void Write(IFormatProvider provider, int value)
{
AnsiConsole.Console.Write(value.ToString(provider), AnsiConsole.CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified 32-bit
/// unsigned integer value to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Write(uint value)
{
Write(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified 32-bit
/// unsigned integer value to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void Write(IFormatProvider provider, uint value)
{
AnsiConsole.Console.Write(value.ToString(provider), AnsiConsole.CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified 64-bit
/// signed integer value to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Write(long value)
{
Write(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified 64-bit
/// signed integer value to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void Write(IFormatProvider provider, long value)
{
AnsiConsole.Console.Write(value.ToString(provider), AnsiConsole.CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified 64-bit
/// unsigned integer value to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Write(ulong value)
{
Write(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified 64-bit
/// unsigned integer value to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void Write(IFormatProvider provider, ulong value)
{
AnsiConsole.Console.Write(value.ToString(provider), AnsiConsole.CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified single-precision
/// floating-point value to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Write(float value)
{
Write(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified single-precision
/// floating-point value to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void Write(IFormatProvider provider, float value)
{
AnsiConsole.Console.Write(value.ToString(provider), AnsiConsole.CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified double-precision
/// floating-point value to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Write(double value)
{
Write(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified double-precision
/// floating-point value to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void Write(IFormatProvider provider, double value)
{
AnsiConsole.Console.Write(value.ToString(provider), AnsiConsole.CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified decimal value, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Write(decimal value)
{
Write(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified decimal value, to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void Write(IFormatProvider provider, decimal value)
{
AnsiConsole.Console.Write(value.ToString(provider), AnsiConsole.CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified boolean value to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Write(bool value)
{
Write(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified boolean value to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void Write(IFormatProvider provider, bool value)
{
AnsiConsole.Console.Write(value.ToString(provider), AnsiConsole.CurrentStyle);
}
/// <summary>
/// Writes the specified Unicode character to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Write(char value)
{
Write(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the specified Unicode character to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void Write(IFormatProvider provider, char value)
{
AnsiConsole.Console.Write(value.ToString(provider), AnsiConsole.CurrentStyle);
}
/// <summary>
/// Writes the specified array of Unicode characters to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void Write(char[] value)
{
Write(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the specified array of Unicode characters to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void Write(IFormatProvider provider, char[] value)
{
ArgumentNullException.ThrowIfNull(value);
for (var index = 0; index < value.Length; index++)
{
AnsiConsole.Console.Write(value[index].ToString(provider), AnsiConsole.CurrentStyle);
}
}
}
extension(IAnsiConsole console)
{
/// <summary>
/// Writes the specified string value to the console.
/// </summary>
/// <param name="text">The text to write.</param>
public void Write(string text)
{
ArgumentNullException.ThrowIfNull(console);
console.Write(new Text(text, Style.Plain));
}
/// <summary>
/// Writes the specified string value to the console.
/// </summary>
/// <param name="text">The text to write.</param>
/// <param name="style">The text style or <see cref="Style.Plain"/> if <see langword="null"/>.</param>
public void Write(string text, Style? style)
{
ArgumentNullException.ThrowIfNull(console);
console.Write(new Text(text, style));
}
}
}

View File

@@ -1,277 +0,0 @@
namespace Spectre.Console;
public static partial class AnsiConsoleExtensions
{
extension(AnsiConsole)
{
/// <summary>
/// Writes an empty line to the console.
/// </summary>
public static void WriteLine()
{
AnsiConsole.Console.WriteLine();
}
/// <summary>
/// Writes the specified string value, followed by the current line terminator, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void WriteLine(string value)
{
AnsiConsole.Console.WriteLine(value, AnsiConsole.CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified 32-bit signed integer value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void WriteLine(int value)
{
WriteLine(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified 32-bit signed integer value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void WriteLine(IFormatProvider provider, int value)
{
AnsiConsole.Console.WriteLine(value.ToString(provider), AnsiConsole.CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified 32-bit unsigned integer value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void WriteLine(uint value)
{
WriteLine(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified 32-bit unsigned integer value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void WriteLine(IFormatProvider provider, uint value)
{
AnsiConsole.Console.WriteLine(value.ToString(provider), AnsiConsole.CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified 64-bit signed integer value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void WriteLine(long value)
{
WriteLine(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified 64-bit signed integer value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void WriteLine(IFormatProvider provider, long value)
{
AnsiConsole.Console.WriteLine(value.ToString(provider), AnsiConsole.CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified 64-bit unsigned integer value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void WriteLine(ulong value)
{
WriteLine(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified 64-bit unsigned integer value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void WriteLine(IFormatProvider provider, ulong value)
{
AnsiConsole.Console.WriteLine(value.ToString(provider), AnsiConsole.CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified single-precision floating-point
/// value, followed by the current line terminator, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void WriteLine(float value)
{
WriteLine(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified single-precision floating-point
/// value, followed by the current line terminator, to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void WriteLine(IFormatProvider provider, float value)
{
AnsiConsole.Console.WriteLine(value.ToString(provider), AnsiConsole.CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified double-precision floating-point
/// value, followed by the current line terminator, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void WriteLine(double value)
{
WriteLine(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified double-precision floating-point
/// value, followed by the current line terminator, to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void WriteLine(IFormatProvider provider, double value)
{
AnsiConsole.Console.WriteLine(value.ToString(provider), AnsiConsole.CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified decimal value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void WriteLine(decimal value)
{
WriteLine(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified decimal value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void WriteLine(IFormatProvider provider, decimal value)
{
AnsiConsole.Console.WriteLine(value.ToString(provider), AnsiConsole.CurrentStyle);
}
/// <summary>
/// Writes the text representation of the specified boolean value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void WriteLine(bool value)
{
WriteLine(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the text representation of the specified boolean value,
/// followed by the current line terminator, to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void WriteLine(IFormatProvider provider, bool value)
{
AnsiConsole.Console.WriteLine(value.ToString(provider), AnsiConsole.CurrentStyle);
}
/// <summary>
/// Writes the specified Unicode character, followed by the current
/// line terminator, value to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void WriteLine(char value)
{
WriteLine(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the specified Unicode character, followed by the current
/// line terminator, value to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void WriteLine(IFormatProvider provider, char value)
{
AnsiConsole.Console.WriteLine(value.ToString(provider), AnsiConsole.CurrentStyle);
}
/// <summary>
/// Writes the specified array of Unicode characters, followed by the current
/// line terminator, value to the console.
/// </summary>
/// <param name="value">The value to write.</param>
public static void WriteLine(char[] value)
{
WriteLine(CultureInfo.CurrentCulture, value);
}
/// <summary>
/// Writes the specified array of Unicode characters, followed by the current
/// line terminator, value to the console.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="value">The value to write.</param>
public static void WriteLine(IFormatProvider provider, char[] value)
{
ArgumentNullException.ThrowIfNull(value);
for (var index = 0; index < value.Length; index++)
{
AnsiConsole.Console.Write(value[index].ToString(provider), AnsiConsole.CurrentStyle);
}
AnsiConsole.Console.WriteLine();
}
}
extension(IAnsiConsole console)
{
/// <summary>
/// Writes an empty line to the console.
/// </summary>
public void WriteLine()
{
ArgumentNullException.ThrowIfNull(console);
console.Write(Text.NewLine);
}
/// <summary>
/// Writes the specified string value, followed by the current line terminator, to the console.
/// </summary>
/// <param name="text">The text to write.</param>
public void WriteLine(string text)
{
WriteLine(console, text, Style.Plain);
}
/// <summary>
/// Writes the specified string value, followed by the current line terminator, to the console.
/// </summary>
/// <param name="text">The text to write.</param>
/// <param name="style">The text style or <see cref="Style.Plain"/> if <see langword="null"/>.</param>
public void WriteLine(string text, Style? style)
{
ArgumentNullException.ThrowIfNull(console);
ArgumentNullException.ThrowIfNull(text);
console.Write(text + Environment.NewLine, style);
}
}
}

View File

@@ -5,28 +5,103 @@ namespace Spectre.Console;
/// </summary>
public static partial class AnsiConsoleExtensions
{
extension(AnsiConsole)
/// <summary>
/// Creates a recorder for the specified console.
/// </summary>
/// <param name="console">The console to record.</param>
/// <returns>A recorder for the specified console.</returns>
public static Recorder CreateRecorder(this IAnsiConsole console)
{
/// <summary>
/// Clears the console.
/// </summary>
public static void Clear()
{
AnsiConsole.Console.Clear();
}
return new Recorder(console);
}
/// <param name="console">The console to record.</param>
extension(IAnsiConsole console)
/// <summary>
/// Clears the console.
/// </summary>
/// <param name="console">The console to clear.</param>
public static void Clear(this IAnsiConsole console)
{
/// <summary>
/// Clears the console.
/// </summary>
public void Clear()
if (console is null)
{
ArgumentNullException.ThrowIfNull(console);
console.Clear(true);
throw new ArgumentNullException(nameof(console));
}
console.Clear(true);
}
/// <summary>
/// Writes the specified string value to the console.
/// </summary>
/// <param name="console">The console to write to.</param>
/// <param name="text">The text to write.</param>
public static void Write(this IAnsiConsole console, string text)
{
if (console is null)
{
throw new ArgumentNullException(nameof(console));
}
console.Write(new Text(text, Style.Plain));
}
/// <summary>
/// Writes the specified string value to the console.
/// </summary>
/// <param name="console">The console to write to.</param>
/// <param name="text">The text to write.</param>
/// <param name="style">The text style or <see cref="Style.Plain"/> if <see langword="null"/>.</param>
public static void Write(this IAnsiConsole console, string text, Style? style)
{
if (console is null)
{
throw new ArgumentNullException(nameof(console));
}
console.Write(new Text(text, style));
}
/// <summary>
/// Writes an empty line to the console.
/// </summary>
/// <param name="console">The console to write to.</param>
public static void WriteLine(this IAnsiConsole console)
{
if (console is null)
{
throw new ArgumentNullException(nameof(console));
}
console.Write(Text.NewLine);
}
/// <summary>
/// Writes the specified string value, followed by the current line terminator, to the console.
/// </summary>
/// <param name="console">The console to write to.</param>
/// <param name="text">The text to write.</param>
public static void WriteLine(this IAnsiConsole console, string text)
{
WriteLine(console, text, Style.Plain);
}
/// <summary>
/// Writes the specified string value, followed by the current line terminator, to the console.
/// </summary>
/// <param name="console">The console to write to.</param>
/// <param name="text">The text to write.</param>
/// <param name="style">The text style or <see cref="Style.Plain"/> if <see langword="null"/>.</param>
public static void WriteLine(this IAnsiConsole console, string text, Style? style)
{
if (console is null)
{
throw new ArgumentNullException(nameof(console));
}
if (text is null)
{
throw new ArgumentNullException(nameof(text));
}
console.Write(text + Environment.NewLine, style);
}
}

View File

@@ -0,0 +1,292 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="BarChart"/>.
/// </summary>
public static class BarChartExtensions
{
/// <summary>
/// Adds an item to the bar chart.
/// </summary>
/// <param name="chart">The bar chart.</param>
/// <param name="label">The item label.</param>
/// <param name="value">The item value.</param>
/// <param name="color">The item color.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BarChart AddItem(this BarChart chart, string label, double value, Color? color = null)
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
chart.Data.Add(new BarChartItem(label, value, color));
return chart;
}
/// <summary>
/// Adds an item to the bar chart.
/// </summary>
/// <typeparam name="T">A type that implements <see cref="IBarChartItem"/>.</typeparam>
/// <param name="chart">The bar chart.</param>
/// <param name="item">The item.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BarChart AddItem<T>(this BarChart chart, T item)
where T : IBarChartItem
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
if (item is BarChartItem barChartItem)
{
chart.Data.Add(barChartItem);
}
else
{
chart.Data.Add(
new BarChartItem(
item.Label,
item.Value,
item.Color));
}
return chart;
}
/// <summary>
/// Adds multiple items to the bar chart.
/// </summary>
/// <typeparam name="T">A type that implements <see cref="IBarChartItem"/>.</typeparam>
/// <param name="chart">The bar chart.</param>
/// <param name="items">The items.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BarChart AddItems<T>(this BarChart chart, IEnumerable<T> items)
where T : IBarChartItem
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
if (items is null)
{
throw new ArgumentNullException(nameof(items));
}
foreach (var item in items)
{
AddItem(chart, item);
}
return chart;
}
/// <summary>
/// Adds multiple items to the bar chart.
/// </summary>
/// <typeparam name="T">A type that implements <see cref="IBarChartItem"/>.</typeparam>
/// <param name="chart">The bar chart.</param>
/// <param name="items">The items.</param>
/// <param name="converter">The converter that converts instances of <c>T</c> to <see cref="BarChartItem"/>.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BarChart AddItems<T>(this BarChart chart, IEnumerable<T> items, Func<T, BarChartItem> converter)
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
if (items is null)
{
throw new ArgumentNullException(nameof(items));
}
if (converter is null)
{
throw new ArgumentNullException(nameof(converter));
}
foreach (var item in items)
{
chart.Data.Add(converter(item));
}
return chart;
}
/// <summary>
/// Sets the value formatter for the bar chart using culture info.
/// </summary>
/// <param name="chart">The bar chart.</param>
/// <param name="func">The value formatter function with culture info.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BarChart UseValueFormatter(this BarChart chart, Func<double, CultureInfo, string>? func)
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
chart.ValueFormatter = func;
return chart;
}
/// <summary>
/// Sets the value formatter for the bar chart.
/// </summary>
/// <param name="chart">The bar chart.</param>
/// <param name="func">The value formatter to use.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BarChart UseValueFormatter(this BarChart chart, Func<double, string>? func)
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
chart.ValueFormatter = func != null
? (value, _) => func(value)
: null;
return chart;
}
/// <summary>
/// Sets the width of the bar chart.
/// </summary>
/// <param name="chart">The bar chart.</param>
/// <param name="width">The bar chart width.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BarChart Width(this BarChart chart, int? width)
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
chart.Width = width;
return chart;
}
/// <summary>
/// Sets the label of the bar chart.
/// </summary>
/// <param name="chart">The bar chart.</param>
/// <param name="label">The bar chart label.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BarChart Label(this BarChart chart, string? label)
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
chart.Label = label;
return chart;
}
/// <summary>
/// Shows values next to each bar in the bar chart.
/// </summary>
/// <param name="chart">The bar chart.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BarChart ShowValues(this BarChart chart)
{
return ShowValues(chart, true);
}
/// <summary>
/// Hides values next to each bar in the bar chart.
/// </summary>
/// <param name="chart">The bar chart.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BarChart HideValues(this BarChart chart)
{
return ShowValues(chart, false);
}
/// <summary>
/// Sets whether or not values should be shown
/// next to each bar.
/// </summary>
/// <param name="chart">The bar chart.</param>
/// <param name="show">Whether or not values should be shown next to each bar.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BarChart ShowValues(this BarChart chart, bool show)
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
chart.ShowValues = show;
return chart;
}
/// <summary>
/// Aligns the label to the left.
/// </summary>
/// <param name="chart">The bar chart.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BarChart LeftAlignLabel(this BarChart chart)
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
chart.LabelAlignment = Justify.Left;
return chart;
}
/// <summary>
/// Centers the label.
/// </summary>
/// <param name="chart">The bar chart.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BarChart CenterLabel(this BarChart chart)
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
chart.LabelAlignment = Justify.Center;
return chart;
}
/// <summary>
/// Aligns the label to the right.
/// </summary>
/// <param name="chart">The bar chart.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BarChart RightAlignLabel(this BarChart chart)
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
chart.LabelAlignment = Justify.Right;
return chart;
}
/// <summary>
/// Sets the max fixed value for the chart.
/// </summary>
/// <param name="chart">The bar chart.</param>
/// <param name="maxValue">Max value for the chart.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BarChart WithMaxValue(this BarChart chart, double maxValue)
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
chart.MaxValue = maxValue;
return chart;
}
}

View File

@@ -1,27 +0,0 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="char"/>.
/// </summary>
public static partial class CharExtensions
{
/// <param name="character">The character to get the cell width of.</param>
extension(char character)
{
#if WCWIDTH
/// <summary>
/// Gets the cell width of a character.
/// </summary>
/// <returns>The cell width of the character.</returns>
public int GetCellWidth()
{
return Cell.GetCellLength(character);
}
#endif
internal bool IsDigit(int min = 0)
{
return char.IsDigit(character) && character >= (char)min;
}
}
}

View File

@@ -1,26 +0,0 @@
namespace Spectre.Console;
internal static class DayOfWeekExtensions
{
extension(DayOfWeek day)
{
public string GetAbbreviatedDayName(CultureInfo culture)
{
culture ??= CultureInfo.InvariantCulture;
return culture.DateTimeFormat
.GetAbbreviatedDayName(day)
.CapitalizeFirstLetter(culture);
}
public DayOfWeek GetNextWeekDay()
{
var next = (int)day + 1;
if (next > (int)DayOfWeek.Saturday)
{
return DayOfWeek.Sunday;
}
return (DayOfWeek)next;
}
}
}

View File

@@ -1,13 +0,0 @@
namespace Spectre.Console;
internal static class DictionaryExtensions
{
extension<T1, T2>(KeyValuePair<T1, T2> tuple)
{
public void Deconstruct(out T1 key, out T2 value)
{
key = tuple.Key;
value = tuple.Value;
}
}
}

View File

@@ -1,42 +0,0 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="Exception"/>.
/// </summary>
public static class ExceptionExtensions
{
/// <param name="exception">The exception to format.</param>
extension(Exception exception)
{
/// <summary>
/// Gets a <see cref="IRenderable"/> representation of the exception.
/// </summary>
/// <param name="format">The exception format options.</param>
/// <returns>A <see cref="IRenderable"/> representing the exception.</returns>
[RequiresDynamicCode(ExceptionFormatter.AotWarning)]
public IRenderable GetRenderable(ExceptionFormats format = ExceptionFormats.Default)
{
ArgumentNullException.ThrowIfNull(exception);
return GetRenderable(exception, new ExceptionSettings
{
Format = format,
});
}
/// <summary>
/// Gets a <see cref="IRenderable"/> representation of the exception.
/// </summary>
/// <param name="settings">The exception settings.</param>
/// <returns>A <see cref="IRenderable"/> representing the exception.</returns>
[RequiresDynamicCode(ExceptionFormatter.AotWarning)]
public IRenderable GetRenderable(ExceptionSettings settings)
{
ArgumentNullException.ThrowIfNull(exception);
ArgumentNullException.ThrowIfNull(settings);
return ExceptionFormatter.Format(exception, settings);
}
}
}

View File

@@ -1,22 +0,0 @@
namespace Spectre.Console;
internal static class Int32Extensions
{
extension(int value)
{
public int Clamp(int min, int max)
{
if (value <= min)
{
return min;
}
if (value >= max)
{
return max;
}
return value;
}
}
}

View File

@@ -1,31 +0,0 @@
namespace Spectre.Console;
internal static class ListExtensions
{
extension<T>(List<T> list)
{
public void RemoveLast()
{
ArgumentNullException.ThrowIfNull(list);
if (list.Count > 0)
{
list.RemoveAt(list.Count - 1);
}
}
public void AddOrReplaceLast(T item)
{
ArgumentNullException.ThrowIfNull(list);
if (list.Count == 0)
{
list.Add(item);
}
else
{
list[list.Count - 1] = item;
}
}
}
}

View File

@@ -1,19 +0,0 @@
namespace Spectre.Console;
internal static class ReadOnlySpanExtensions
{
extension<T>(ReadOnlySpan<T> span)
where T : IEquatable<T>
{
public int IndexOf(T value, int startIndex)
{
var indexInSlice = span[startIndex..].IndexOf(value);
if (indexInSlice == -1)
{
return -1;
}
return startIndex + indexInSlice;
}
}
}

View File

@@ -1,20 +0,0 @@
namespace Spectre.Console;
internal static class StackExtensions
{
extension<T>(Stack<T> stack)
{
public void PushRange(IEnumerable<T> source)
{
ArgumentNullException.ThrowIfNull(stack);
if (source != null)
{
foreach (var item in source)
{
stack.Push(item);
}
}
}
}
}

View File

@@ -1,42 +0,0 @@
namespace Spectre.Console;
internal static class StringBuilderExtensions
{
extension(StringBuilder builder)
{
public StringBuilder AppendWithStyle(Style? style, int? value)
{
return AppendWithStyle(builder, style, value?.ToString(CultureInfo.InvariantCulture));
}
}
extension(StringBuilder builder)
{
public StringBuilder AppendWithStyle(Style? style, string? value)
{
value ??= string.Empty;
if (style != null)
{
return builder.Append('[')
.Append(style.ToMarkup())
.Append(']')
.Append(value.EscapeMarkup())
.Append("[/]");
}
return builder.Append(value);
}
public void AppendSpan(ReadOnlySpan<char> span)
{
// NetStandard 2 lacks the override for StringBuilder to add the span. We'll need to convert the span
// to a string for it, but for .NET 6.0 or newer we'll use the override.
#if NETSTANDARD2_0
builder.Append(span.ToString());
#else
builder.Append(span);
#endif
}
}
}

View File

@@ -1,332 +0,0 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="string"/>.
/// </summary>
public static class StringExtensions
{
// Cache whether or not internally normalized line endings
// already are normalized. No reason to do yet another replace if it is.
private static readonly bool _alreadyNormalized
= Environment.NewLine.Equals("\n", StringComparison.OrdinalIgnoreCase);
/// <param name="text">The text to escape.</param>
extension(string? text)
{
/// <summary>
/// Escapes text so that it wont be interpreted as markup.
/// </summary>
/// <returns>A string that is safe to use in markup.</returns>
public string EscapeMarkup()
{
if (text == null)
{
return string.Empty;
}
return text
.ReplaceExact("[", "[[")
.ReplaceExact("]", "]]");
}
/// <summary>
/// Removes markup from the specified string.
/// </summary>
/// <returns>A string that does not have any markup.</returns>
public string RemoveMarkup()
{
if (string.IsNullOrWhiteSpace(text))
{
return string.Empty;
}
var result = new StringBuilder();
var tokenizer = new MarkupTokenizer(text);
while (tokenizer.MoveNext() && tokenizer.Current != null)
{
if (tokenizer.Current.Kind == MarkupTokenKind.Text)
{
result.Append(tokenizer.Current.Value);
}
}
return result.ToString();
}
internal bool TryGetUri([NotNullWhen(true)] out Uri? result)
{
try
{
if (!Uri.TryCreate(text, UriKind.Absolute, out var uri))
{
result = null;
return false;
}
if (uri.Scheme == "file")
{
// For local files, we need to append
// the host name. Otherwise the terminal
// will most probably not allow it.
var builder = new UriBuilder(uri)
{
Host = Dns.GetHostName(),
};
uri = builder.Uri;
}
result = uri;
return true;
}
catch
{
result = null;
return false;
}
}
internal string CapitalizeFirstLetter(CultureInfo? culture = null)
{
if (text == null)
{
return string.Empty;
}
culture ??= CultureInfo.InvariantCulture;
if (text.Length > 0 && char.IsLower(text[0]))
{
text = string.Format(culture, "{0}{1}", char.ToUpper(text[0], culture), text.Substring(1));
}
return text;
}
internal string? RemoveNewLines()
{
return text?.ReplaceExact("\r\n", string.Empty)
?.ReplaceExact("\n", string.Empty);
}
internal string NormalizeNewLines(bool native = false)
{
text = text?.ReplaceExact("\r\n", "\n");
text ??= string.Empty;
if (native && !_alreadyNormalized)
{
text = text.ReplaceExact("\n", Environment.NewLine);
}
return text;
}
}
extension(string text)
{
/// <summary>
/// Gets the cell width of the specified text.
/// </summary>
/// <param name="text">The text to get the cell width of.</param>
/// <returns>The cell width of the text.</returns>
public int GetCellWidth()
{
return Cell.GetCellLength(text);
}
internal string[] SplitLines()
{
var result = text?.NormalizeNewLines()?.Split(new[] { '\n' }, StringSplitOptions.None);
return result ?? Array.Empty<string>();
}
internal string[] SplitWords(StringSplitOptions options = StringSplitOptions.None)
{
var result = new List<string>();
static string Read(StringBuffer reader, Func<char, bool> criteria)
{
var buffer = new StringBuilder();
while (!reader.Eof)
{
var current = reader.Peek();
if (!criteria(current))
{
break;
}
buffer.Append(reader.Read());
}
return buffer.ToString();
}
using (var reader = new StringBuffer(text))
{
while (!reader.Eof)
{
var current = reader.Peek();
if (char.IsWhiteSpace(current))
{
var x = Read(reader, c => char.IsWhiteSpace(c));
if (options != StringSplitOptions.RemoveEmptyEntries)
{
result.Add(x);
}
}
else
{
result.Add(Read(reader, c => !char.IsWhiteSpace(c)));
}
}
}
return result.ToArray();
}
internal string Repeat(int count)
{
ArgumentNullException.ThrowIfNull(text);
if (count <= 0)
{
return string.Empty;
}
if (count == 1)
{
return text;
}
return string.Concat(Enumerable.Repeat(text, count));
}
/// <summary>
/// "Masks" every character in a string.
/// </summary>
/// <param name="value">String value to mask.</param>
/// <param name="mask">Character to use for masking.</param>
/// <returns>Masked string.</returns>
public string Mask(char? mask)
{
if (mask is null)
{
return string.Empty;
}
return new string(mask.Value, text.Length);
}
/// <summary>
/// Highlights the first text match in provided value.
/// </summary>
/// <param name="value">Input value.</param>
/// <param name="searchText">Text to search for.</param>
/// <param name="highlightStyle">The style to apply to the matched text.</param>
/// <returns>Markup of input with the first matched text highlighted.</returns>
internal string Highlight(string searchText, Style? highlightStyle)
{
ArgumentNullException.ThrowIfNull(text);
ArgumentNullException.ThrowIfNull(searchText);
ArgumentNullException.ThrowIfNull(highlightStyle);
if (searchText.Length == 0)
{
return text;
}
var foundSearchPattern = false;
var builder = new StringBuilder();
using var tokenizer = new MarkupTokenizer(text);
while (tokenizer.MoveNext())
{
var token = tokenizer.Current!;
switch (token.Kind)
{
case MarkupTokenKind.Text:
{
var tokenValue = token.Value;
if (tokenValue.Length == 0)
{
break;
}
if (foundSearchPattern)
{
builder.Append(tokenValue);
break;
}
var index = tokenValue.IndexOf(searchText, StringComparison.OrdinalIgnoreCase);
if (index == -1)
{
builder.Append(tokenValue);
break;
}
foundSearchPattern = true;
var before = tokenValue.Substring(0, index);
var match = tokenValue.Substring(index, searchText.Length);
var after = tokenValue.Substring(index + searchText.Length);
builder
.Append(before)
.AppendWithStyle(highlightStyle, match)
.Append(after);
break;
}
case MarkupTokenKind.Open:
{
builder.Append("[" + token.Value + "]");
break;
}
case MarkupTokenKind.Close:
{
builder.Append("[/]");
break;
}
default:
{
throw new InvalidOperationException("Unknown markup token kind.");
}
}
}
return builder.ToString();
}
internal string ReplaceExact(string oldValue, string? newValue)
{
#if NETSTANDARD2_0
return text.Replace(oldValue, newValue);
#else
return text.Replace(oldValue, newValue, StringComparison.Ordinal);
#endif
}
internal bool ContainsExact(string value)
{
#if NETSTANDARD2_0
return text.Contains(value);
#else
return text.Contains(value, StringComparison.Ordinal);
#endif
}
#if NETSTANDARD2_0
internal bool Contains(string value, System.StringComparison comparisonType)
{
return text.IndexOf(value, comparisonType) != -1;
}
#endif
}
}

View File

@@ -1,31 +0,0 @@
namespace Spectre.Console;
internal static class TextWriterExtensions
{
extension(TextWriter writer)
{
public bool IsStandardOut()
{
try
{
return writer == System.Console.Out;
}
catch
{
return false;
}
}
public bool IsStandardError()
{
try
{
return writer == System.Console.Error;
}
catch
{
return false;
}
}
}
}

View File

@@ -0,0 +1,28 @@
namespace Spectre.Console.Rendering;
/// <summary>
/// Contains extension methods for <see cref="BoxBorder"/>.
/// </summary>
public static class BoxExtensions
{
/// <summary>
/// Gets the safe border for a border.
/// </summary>
/// <param name="border">The border to get the safe border for.</param>
/// <param name="safe">Whether or not to return the safe border.</param>
/// <returns>The safe border if one exist, otherwise the original border.</returns>
public static BoxBorder GetSafeBorder(this BoxBorder border, bool safe)
{
if (border is null)
{
throw new ArgumentNullException(nameof(border));
}
if (safe && border.SafeBorder != null)
{
border = border.SafeBorder;
}
return border;
}
}

View File

@@ -0,0 +1,317 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="BreakdownChart"/>.
/// </summary>
public static class BreakdownChartExtensions
{
/// <summary>
/// Adds an item to the breakdown chart.
/// </summary>
/// <param name="chart">The breakdown chart.</param>
/// <param name="label">The item label.</param>
/// <param name="value">The item value.</param>
/// <param name="color">The item color.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BreakdownChart AddItem(this BreakdownChart chart, string label, double value, Color color)
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
chart.Data.Add(new BreakdownChartItem(label, value, color));
return chart;
}
/// <summary>
/// Adds an item to the breakdown chart.
/// </summary>
/// <typeparam name="T">A type that implements <see cref="IBreakdownChartItem"/>.</typeparam>
/// <param name="chart">The breakdown chart.</param>
/// <param name="item">The item.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BreakdownChart AddItem<T>(this BreakdownChart chart, T item)
where T : IBreakdownChartItem
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
if (item is BreakdownChartItem chartItem)
{
chart.Data.Add(chartItem);
}
else
{
chart.Data.Add(
new BreakdownChartItem(
item.Label,
item.Value,
item.Color));
}
return chart;
}
/// <summary>
/// Adds multiple items to the breakdown chart.
/// </summary>
/// <typeparam name="T">A type that implements <see cref="IBreakdownChartItem"/>.</typeparam>
/// <param name="chart">The breakdown chart.</param>
/// <param name="items">The items.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BreakdownChart AddItems<T>(this BreakdownChart chart, IEnumerable<T> items)
where T : IBreakdownChartItem
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
if (items is null)
{
throw new ArgumentNullException(nameof(items));
}
foreach (var item in items)
{
AddItem(chart, item);
}
return chart;
}
/// <summary>
/// Adds multiple items to the breakdown chart.
/// </summary>
/// <typeparam name="T">A type that implements <see cref="IBarChartItem"/>.</typeparam>
/// <param name="chart">The breakdown chart.</param>
/// <param name="items">The items.</param>
/// <param name="converter">The converter that converts instances of <c>T</c> to <see cref="IBreakdownChartItem"/>.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BreakdownChart AddItems<T>(this BreakdownChart chart, IEnumerable<T> items, Func<T, IBreakdownChartItem> converter)
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
if (items is null)
{
throw new ArgumentNullException(nameof(items));
}
if (converter is null)
{
throw new ArgumentNullException(nameof(converter));
}
foreach (var item in items)
{
chart.Data.Add(converter(item));
}
return chart;
}
/// <summary>
/// Sets the width of the breakdown chart.
/// </summary>
/// <param name="chart">The breakdown chart.</param>
/// <param name="width">The breakdown chart width.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BreakdownChart Width(this BreakdownChart chart, int? width)
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
chart.Width = width;
return chart;
}
/// <summary>
/// Tags will be shown.
/// </summary>
/// <param name="chart">The breakdown chart.</param>
/// <param name="func">The value formatter to use.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BreakdownChart UseValueFormatter(this BreakdownChart chart, Func<double, CultureInfo, string>? func)
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
chart.ValueFormatter = func;
return chart;
}
/// <summary>
/// Tags will be shown.
/// </summary>
/// <param name="chart">The breakdown chart.</param>
/// <param name="func">The value formatter to use.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BreakdownChart UseValueFormatter(this BreakdownChart chart, Func<double, string>? func)
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
chart.ValueFormatter = func != null
? (value, _) => func(value)
: null;
return chart;
}
/// <summary>
/// Tags will be shown.
/// </summary>
/// <param name="chart">The breakdown chart.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BreakdownChart ShowPercentage(this BreakdownChart chart)
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
chart.ValueFormatter = (value, culture) => string.Format(culture, "{0}%", value);
return chart;
}
/// <summary>
/// Tags will be shown.
/// </summary>
/// <param name="chart">The breakdown chart.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BreakdownChart ShowTags(this BreakdownChart chart)
{
return ShowTags(chart, true);
}
/// <summary>
/// Tags will be not be shown.
/// </summary>
/// <param name="chart">The breakdown chart.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BreakdownChart HideTags(this BreakdownChart chart)
{
return ShowTags(chart, false);
}
/// <summary>
/// Sets whether or not tags will be shown.
/// </summary>
/// <param name="chart">The breakdown chart.</param>
/// <param name="show">Whether or not tags will be shown.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BreakdownChart ShowTags(this BreakdownChart chart, bool show)
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
chart.ShowTags = show;
return chart;
}
/// <summary>
/// Tag values will be shown.
/// </summary>
/// <param name="chart">The breakdown chart.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BreakdownChart ShowTagValues(this BreakdownChart chart)
{
return ShowTagValues(chart, true);
}
/// <summary>
/// Tag values will be not be shown.
/// </summary>
/// <param name="chart">The breakdown chart.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BreakdownChart HideTagValues(this BreakdownChart chart)
{
return ShowTagValues(chart, false);
}
/// <summary>
/// Sets whether or not tag values will be shown.
/// </summary>
/// <param name="chart">The breakdown chart.</param>
/// <param name="show">Whether or not tag values will be shown.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BreakdownChart ShowTagValues(this BreakdownChart chart, bool show)
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
chart.ShowTagValues = show;
return chart;
}
/// <summary>
/// Chart and tags is rendered in compact mode.
/// </summary>
/// <param name="chart">The breakdown chart.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BreakdownChart Compact(this BreakdownChart chart)
{
return Compact(chart, true);
}
/// <summary>
/// Chart and tags is rendered in full size mode.
/// </summary>
/// <param name="chart">The breakdown chart.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BreakdownChart FullSize(this BreakdownChart chart)
{
return Compact(chart, false);
}
/// <summary>
/// Sets whether or not the chart and tags should be rendered in compact mode.
/// </summary>
/// <param name="chart">The breakdown chart.</param>
/// <param name="compact">Whether or not the chart and tags should be rendered in compact mode.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BreakdownChart Compact(this BreakdownChart chart, bool compact)
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
chart.Compact = compact;
return chart;
}
/// <summary>
/// Sets the <see cref="BreakdownChart.ValueColor"/>.
/// </summary>
/// <param name="chart">The breakdown chart.</param>
/// <param name="color">The <see cref="Color"/> to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static BreakdownChart WithValueColor(this BreakdownChart chart, Color color)
{
if (chart is null)
{
throw new ArgumentNullException(nameof(chart));
}
chart.ValueColor = color;
return chart;
}
}

View File

@@ -0,0 +1,133 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="Calendar"/>.
/// </summary>
public static class CalendarExtensions
{
/// <summary>
/// Adds a calendar event.
/// </summary>
/// <param name="calendar">The calendar to add the calendar event to.</param>
/// <param name="date">The calendar event date.</param>
/// <param name="customEventHighlightStyle">The calendar event custom highlight style.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Calendar AddCalendarEvent(this Calendar calendar, DateTime date, Style? customEventHighlightStyle = null)
{
return AddCalendarEvent(calendar, string.Empty, date.Year, date.Month, date.Day, customEventHighlightStyle);
}
/// <summary>
/// Adds a calendar event.
/// </summary>
/// <param name="calendar">The calendar to add the calendar event to.</param>
/// <param name="description">The calendar event description.</param>
/// <param name="date">The calendar event date.</param>
/// <param name="customEventHighlightStyle">The calendar event custom highlight style.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Calendar AddCalendarEvent(this Calendar calendar, string description, DateTime date, Style? customEventHighlightStyle = null)
{
return AddCalendarEvent(calendar, description, date.Year, date.Month, date.Day, customEventHighlightStyle);
}
/// <summary>
/// Adds a calendar event.
/// </summary>
/// <param name="calendar">The calendar to add the calendar event to.</param>
/// <param name="year">The year of the calendar event.</param>
/// <param name="month">The month of the calendar event.</param>
/// <param name="day">The day of the calendar event.</param>
/// <param name="customEventHighlightStyle">The calendar event custom highlight style.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Calendar AddCalendarEvent(this Calendar calendar, int year, int month, int day, Style? customEventHighlightStyle = null)
{
return AddCalendarEvent(calendar, string.Empty, year, month, day, customEventHighlightStyle);
}
/// <summary>
/// Adds a calendar event.
/// </summary>
/// <param name="calendar">The calendar.</param>
/// <param name="description">The calendar event description.</param>
/// <param name="year">The year of the calendar event.</param>
/// <param name="month">The month of the calendar event.</param>
/// <param name="day">The day of the calendar event.</param>
/// <param name="customEventHighlightStyle">The calendar event custom highlight style.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Calendar AddCalendarEvent(this Calendar calendar, string description, int year, int month, int day, Style? customEventHighlightStyle = null)
{
if (calendar is null)
{
throw new ArgumentNullException(nameof(calendar));
}
calendar.CalendarEvents.Add(new CalendarEvent(description, year, month, day, customEventHighlightStyle));
return calendar;
}
/// <summary>
/// Sets the calendar's highlight <see cref="Style"/>.
/// </summary>
/// <param name="calendar">The calendar.</param>
/// <param name="style">The default highlight style.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Calendar HighlightStyle(this Calendar calendar, Style? style)
{
if (calendar is null)
{
throw new ArgumentNullException(nameof(calendar));
}
calendar.HighlightStyle = style ?? Style.Plain;
return calendar;
}
/// <summary>
/// Sets the calendar's header <see cref="Style"/>.
/// </summary>
/// <param name="calendar">The calendar.</param>
/// <param name="style">The header style.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Calendar HeaderStyle(this Calendar calendar, Style? style)
{
if (calendar is null)
{
throw new ArgumentNullException(nameof(calendar));
}
calendar.HeaderStyle = style ?? Style.Plain;
return calendar;
}
/// <summary>
/// Shows the calendar header.
/// </summary>
/// <param name="calendar">The calendar.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Calendar ShowHeader(this Calendar calendar)
{
if (calendar is null)
{
throw new ArgumentNullException(nameof(calendar));
}
calendar.ShowHeader = true;
return calendar;
}
/// <summary>
/// Hides the calendar header.
/// </summary>
/// <param name="calendar">The calendar.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Calendar HideHeader(this Calendar calendar)
{
if (calendar is null)
{
throw new ArgumentNullException(nameof(calendar));
}
calendar.ShowHeader = false;
return calendar;
}
}

View File

@@ -0,0 +1,17 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="char"/>.
/// </summary>
public static partial class CharExtensions
{
/// <summary>
/// Gets the cell width of a character.
/// </summary>
/// <param name="character">The character to get the cell width of.</param>
/// <returns>The cell width of the character.</returns>
public static int GetCellWidth(this char character)
{
return Cell.GetCellLength(character);
}
}

View File

@@ -0,0 +1,44 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="IColumn"/>.
/// </summary>
public static class ColumnExtensions
{
/// <summary>
/// Prevents a column from wrapping.
/// </summary>
/// <typeparam name="T">An object implementing <see cref="IColumn"/>.</typeparam>
/// <param name="obj">The column.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T NoWrap<T>(this T obj)
where T : class, IColumn
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
obj.NoWrap = true;
return obj;
}
/// <summary>
/// Sets the width of the column.
/// </summary>
/// <typeparam name="T">An object implementing <see cref="IColumn"/>.</typeparam>
/// <param name="obj">The column.</param>
/// <param name="width">The column width.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T Width<T>(this T obj, int? width)
where T : class, IColumn
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
obj.Width = width;
return obj;
}
}

View File

@@ -0,0 +1,166 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="ConfirmationPrompt"/>.
/// </summary>
public static class ConfirmationPromptExtensions
{
/// <summary>
/// Show or hide choices.
/// </summary>
/// <param name="obj">The prompt.</param>
/// <param name="show">Whether or not the choices should be visible.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static ConfirmationPrompt ShowChoices(this ConfirmationPrompt obj, bool show)
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
obj.ShowChoices = show;
return obj;
}
/// <summary>
/// Shows choices.
/// </summary>
/// <param name="obj">The prompt.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static ConfirmationPrompt ShowChoices(this ConfirmationPrompt obj)
{
return ShowChoices(obj, true);
}
/// <summary>
/// Hides choices.
/// </summary>
/// <param name="obj">The prompt.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static ConfirmationPrompt HideChoices(this ConfirmationPrompt obj)
{
return ShowChoices(obj, false);
}
/// <summary>
/// Sets the style in which the list of choices is displayed.
/// </summary>
/// <param name="obj">The confirmation prompt.</param>
/// <param name="style">The style to use for displaying the choices or <see langword="null"/> to use the default style (blue).</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static ConfirmationPrompt ChoicesStyle(this ConfirmationPrompt obj, Style? style)
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
obj.ChoicesStyle = style;
return obj;
}
/// <summary>
/// Show or hide the default value.
/// </summary>
/// <param name="obj">The prompt.</param>
/// <param name="show">Whether or not the default value should be visible.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static ConfirmationPrompt ShowDefaultValue(this ConfirmationPrompt obj, bool show)
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
obj.ShowDefaultValue = show;
return obj;
}
/// <summary>
/// Shows the default value.
/// </summary>
/// <param name="obj">The prompt.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static ConfirmationPrompt ShowDefaultValue(this ConfirmationPrompt obj)
{
return ShowDefaultValue(obj, true);
}
/// <summary>
/// Hides the default value.
/// </summary>
/// <param name="obj">The prompt.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static ConfirmationPrompt HideDefaultValue(this ConfirmationPrompt obj)
{
return ShowDefaultValue(obj, false);
}
/// <summary>
/// Sets the style in which the default value is displayed.
/// </summary>
/// <param name="obj">The confirmation prompt.</param>
/// <param name="style">The default value style or <see langword="null"/> to use the default style (green).</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static ConfirmationPrompt DefaultValueStyle(this ConfirmationPrompt obj, Style? style)
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
obj.DefaultValueStyle = style;
return obj;
}
/// <summary>
/// Sets the "invalid choice" message for the prompt.
/// </summary>
/// <param name="obj">The prompt.</param>
/// <param name="message">The "invalid choice" message.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static ConfirmationPrompt InvalidChoiceMessage(this ConfirmationPrompt obj, string message)
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
obj.InvalidChoiceMessage = message;
return obj;
}
/// <summary>
/// Sets the character to interpret as "yes".
/// </summary>
/// <param name="obj">The confirmation prompt.</param>
/// <param name="character">The character to interpret as "yes".</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static ConfirmationPrompt Yes(this ConfirmationPrompt obj, char character)
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
obj.Yes = character;
return obj;
}
/// <summary>
/// Sets the character to interpret as "no".
/// </summary>
/// <param name="obj">The confirmation prompt.</param>
/// <param name="character">The character to interpret as "no".</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static ConfirmationPrompt No(this ConfirmationPrompt obj, char character)
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
obj.No = character;
return obj;
}
}

View File

@@ -0,0 +1,151 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="IAnsiConsoleCursor"/>.
/// </summary>
public static class CursorExtensions
{
/// <summary>
/// Shows the cursor.
/// </summary>
/// <param name="cursor">The cursor.</param>
public static void Show(this IAnsiConsoleCursor cursor)
{
if (cursor is null)
{
throw new System.ArgumentNullException(nameof(cursor));
}
cursor.Show(true);
}
/// <summary>
/// Hides the cursor.
/// </summary>
/// <param name="cursor">The cursor.</param>
public static void Hide(this IAnsiConsoleCursor cursor)
{
if (cursor is null)
{
throw new System.ArgumentNullException(nameof(cursor));
}
cursor.Show(false);
}
/// <summary>
/// Moves the cursor up.
/// </summary>
/// <param name="cursor">The cursor.</param>
public static void MoveUp(this IAnsiConsoleCursor cursor)
{
if (cursor is null)
{
throw new System.ArgumentNullException(nameof(cursor));
}
cursor.Move(CursorDirection.Up, 1);
}
/// <summary>
/// Moves the cursor up.
/// </summary>
/// <param name="cursor">The cursor.</param>
/// <param name="steps">The number of steps to move the cursor.</param>
public static void MoveUp(this IAnsiConsoleCursor cursor, int steps)
{
if (cursor is null)
{
throw new System.ArgumentNullException(nameof(cursor));
}
cursor.Move(CursorDirection.Up, steps);
}
/// <summary>
/// Moves the cursor down.
/// </summary>
/// <param name="cursor">The cursor.</param>
public static void MoveDown(this IAnsiConsoleCursor cursor)
{
if (cursor is null)
{
throw new System.ArgumentNullException(nameof(cursor));
}
cursor.Move(CursorDirection.Down, 1);
}
/// <summary>
/// Moves the cursor down.
/// </summary>
/// <param name="cursor">The cursor.</param>
/// <param name="steps">The number of steps to move the cursor.</param>
public static void MoveDown(this IAnsiConsoleCursor cursor, int steps)
{
if (cursor is null)
{
throw new System.ArgumentNullException(nameof(cursor));
}
cursor.Move(CursorDirection.Down, steps);
}
/// <summary>
/// Moves the cursor to the left.
/// </summary>
/// <param name="cursor">The cursor.</param>
public static void MoveLeft(this IAnsiConsoleCursor cursor)
{
if (cursor is null)
{
throw new System.ArgumentNullException(nameof(cursor));
}
cursor.Move(CursorDirection.Left, 1);
}
/// <summary>
/// Moves the cursor to the left.
/// </summary>
/// <param name="cursor">The cursor.</param>
/// <param name="steps">The number of steps to move the cursor.</param>
public static void MoveLeft(this IAnsiConsoleCursor cursor, int steps)
{
if (cursor is null)
{
throw new System.ArgumentNullException(nameof(cursor));
}
cursor.Move(CursorDirection.Left, steps);
}
/// <summary>
/// Moves the cursor to the right.
/// </summary>
/// <param name="cursor">The cursor.</param>
public static void MoveRight(this IAnsiConsoleCursor cursor)
{
if (cursor is null)
{
throw new System.ArgumentNullException(nameof(cursor));
}
cursor.Move(CursorDirection.Right, 1);
}
/// <summary>
/// Moves the cursor to the right.
/// </summary>
/// <param name="cursor">The cursor.</param>
/// <param name="steps">The number of steps to move the cursor.</param>
public static void MoveRight(this IAnsiConsoleCursor cursor, int steps)
{
if (cursor is null)
{
throw new System.ArgumentNullException(nameof(cursor));
}
cursor.Move(CursorDirection.Right, steps);
}
}

View File

@@ -0,0 +1,23 @@
namespace Spectre.Console;
internal static class DayOfWeekExtensions
{
public static string GetAbbreviatedDayName(this DayOfWeek day, CultureInfo culture)
{
culture ??= CultureInfo.InvariantCulture;
return culture.DateTimeFormat
.GetAbbreviatedDayName(day)
.CapitalizeFirstLetter(culture);
}
public static DayOfWeek GetNextWeekDay(this DayOfWeek day)
{
var next = (int)day + 1;
if (next > (int)DayOfWeek.Saturday)
{
return DayOfWeek.Sunday;
}
return (DayOfWeek)next;
}
}

View File

@@ -0,0 +1,10 @@
namespace Spectre.Console;
internal static class DictionaryExtensions
{
public static void Deconstruct<T1, T2>(this KeyValuePair<T1, T2> tuple, out T1 key, out T2 value)
{
key = tuple.Key;
value = tuple.Value;
}
}

View File

@@ -0,0 +1,49 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="Exception"/>.
/// </summary>
public static class ExceptionExtensions
{
/// <summary>
/// Gets a <see cref="IRenderable"/> representation of the exception.
/// </summary>
/// <param name="exception">The exception to format.</param>
/// <param name="format">The exception format options.</param>
/// <returns>A <see cref="IRenderable"/> representing the exception.</returns>
[RequiresDynamicCode(ExceptionFormatter.AotWarning)]
public static IRenderable GetRenderable(this Exception exception, ExceptionFormats format = ExceptionFormats.Default)
{
if (exception is null)
{
throw new ArgumentNullException(nameof(exception));
}
return GetRenderable(exception, new ExceptionSettings
{
Format = format,
});
}
/// <summary>
/// Gets a <see cref="IRenderable"/> representation of the exception.
/// </summary>
/// <param name="exception">The exception to format.</param>
/// <param name="settings">The exception settings.</param>
/// <returns>A <see cref="IRenderable"/> representing the exception.</returns>
[RequiresDynamicCode(ExceptionFormatter.AotWarning)]
public static IRenderable GetRenderable(this Exception exception, ExceptionSettings settings)
{
if (exception is null)
{
throw new ArgumentNullException(nameof(exception));
}
if (settings is null)
{
throw new ArgumentNullException(nameof(settings));
}
return ExceptionFormatter.Format(exception, settings);
}
}

View File

@@ -0,0 +1,44 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="IExpandable"/>.
/// </summary>
public static class ExpandableExtensions
{
/// <summary>
/// Tells the specified object to not expand to the available area
/// but take as little space as possible.
/// </summary>
/// <typeparam name="T">The expandable object.</typeparam>
/// <param name="obj">The object to collapse.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T Collapse<T>(this T obj)
where T : class, IExpandable
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
obj.Expand = false;
return obj;
}
/// <summary>
/// Tells the specified object to expand to the available area.
/// </summary>
/// <typeparam name="T">The expandable object.</typeparam>
/// <param name="obj">The object to expand.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T Expand<T>(this T obj)
where T : class, IExpandable
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
obj.Expand = true;
return obj;
}
}

View File

@@ -0,0 +1,24 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="FigletText"/>.
/// </summary>
public static class FigletTextExtensions
{
/// <summary>
/// Sets the color of the FIGlet text.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="color">The color.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static FigletText Color(this FigletText text, Color? color)
{
if (text is null)
{
throw new ArgumentNullException(nameof(text));
}
text.Color = color ?? Console.Color.Default;
return text;
}
}

View File

@@ -0,0 +1,112 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="Grid"/>.
/// </summary>
public static class GridExtensions
{
/// <summary>
/// Adds a column to the grid.
/// </summary>
/// <param name="grid">The grid to add the column to.</param>
/// <param name="count">The number of columns to add.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Grid AddColumns(this Grid grid, int count)
{
if (grid is null)
{
throw new ArgumentNullException(nameof(grid));
}
for (var index = 0; index < count; index++)
{
grid.AddColumn(new GridColumn());
}
return grid;
}
/// <summary>
/// Adds a column to the grid.
/// </summary>
/// <param name="grid">The grid to add the column to.</param>
/// <param name="columns">The columns to add.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Grid AddColumns(this Grid grid, params GridColumn[] columns)
{
if (grid is null)
{
throw new ArgumentNullException(nameof(grid));
}
if (columns is null)
{
throw new ArgumentNullException(nameof(columns));
}
foreach (var column in columns)
{
grid.AddColumn(column);
}
return grid;
}
/// <summary>
/// Adds an empty row to the grid.
/// </summary>
/// <param name="grid">The grid to add the row to.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Grid AddEmptyRow(this Grid grid)
{
if (grid is null)
{
throw new ArgumentNullException(nameof(grid));
}
var columns = new IRenderable[grid.Columns.Count];
Enumerable.Range(0, grid.Columns.Count).ForEach(index => columns[index] = Text.Empty);
grid.AddRow(columns);
return grid;
}
/// <summary>
/// Adds a new row to the grid.
/// </summary>
/// <param name="grid">The grid to add the row to.</param>
/// <param name="columns">The columns to add.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Grid AddRow(this Grid grid, params string[] columns)
{
if (grid is null)
{
throw new ArgumentNullException(nameof(grid));
}
if (columns is null)
{
throw new ArgumentNullException(nameof(columns));
}
grid.AddRow(columns.Select(column => new Markup(column)).ToArray());
return grid;
}
/// <summary>
/// Sets the grid width.
/// </summary>
/// <param name="grid">The grid.</param>
/// <param name="width">The width.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Grid Width(this Grid grid, int? width)
{
if (grid is null)
{
throw new ArgumentNullException(nameof(grid));
}
grid.Width = width;
return grid;
}
}

View File

@@ -0,0 +1,81 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="IHasBorder"/>.
/// </summary>
public static class HasBorderExtensions
{
/// <summary>
/// Enables the safe border.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to enable the safe border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T SafeBorder<T>(this T obj)
where T : class, IHasBorder
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
obj.UseSafeBorder = true;
return obj;
}
/// <summary>
/// Disables the safe border.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to disable the safe border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T NoSafeBorder<T>(this T obj)
where T : class, IHasBorder
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
obj.UseSafeBorder = false;
return obj;
}
/// <summary>
/// Sets the border style.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border style for.</param>
/// <param name="style">The border style to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T BorderStyle<T>(this T obj, Style style)
where T : class, IHasBorder
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
obj.BorderStyle = style;
return obj;
}
/// <summary>
/// Sets the border color.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border color for.</param>
/// <param name="color">The border color to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T BorderColor<T>(this T obj, Color color)
where T : class, IHasBorder
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
obj.BorderStyle = (obj.BorderStyle ?? Style.Plain).Foreground(color);
return obj;
}
}

View File

@@ -0,0 +1,98 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="IHasBoxBorder"/>.
/// </summary>
public static class HasBoxBorderExtensions
{
/// <summary>
/// Sets the border.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <param name="border">The border to use.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T Border<T>(this T obj, BoxBorder border)
where T : class, IHasBoxBorder
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
obj.Border = border;
return obj;
}
/// <summary>
/// Do not display a border.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T NoBorder<T>(this T obj)
where T : class, IHasBoxBorder
{
return Border(obj, BoxBorder.None);
}
/// <summary>
/// Display a square border.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T SquareBorder<T>(this T obj)
where T : class, IHasBoxBorder
{
return Border(obj, BoxBorder.Square);
}
/// <summary>
/// Display an ASCII border.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T AsciiBorder<T>(this T obj)
where T : class, IHasBoxBorder
{
return Border(obj, BoxBorder.Ascii);
}
/// <summary>
/// Display a rounded border.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T RoundedBorder<T>(this T obj)
where T : class, IHasBoxBorder
{
return Border(obj, BoxBorder.Rounded);
}
/// <summary>
/// Display a heavy border.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T HeavyBorder<T>(this T obj)
where T : class, IHasBoxBorder
{
return Border(obj, BoxBorder.Heavy);
}
/// <summary>
/// Display a double border.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T DoubleBorder<T>(this T obj)
where T : class, IHasBoxBorder
{
return Border(obj, BoxBorder.Double);
}
}

View File

@@ -0,0 +1,62 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="IHasCulture"/>.
/// </summary>
public static class HasCultureExtensions
{
/// <summary>
/// Sets the culture.
/// </summary>
/// <typeparam name="T">An object type with a culture.</typeparam>
/// <param name="obj">The object to set the culture for.</param>
/// <param name="culture">The culture to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T Culture<T>(this T obj, CultureInfo culture)
where T : class, IHasCulture
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
if (culture is null)
{
throw new ArgumentNullException(nameof(culture));
}
obj.Culture = culture;
return obj;
}
/// <summary>
/// Sets the culture.
/// </summary>
/// <typeparam name="T">An object type with a culture.</typeparam>
/// <param name="obj">The object to set the culture for.</param>
/// <param name="name">The culture to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T Culture<T>(this T obj, string name)
where T : class, IHasCulture
{
if (name is null)
{
throw new ArgumentNullException(nameof(name));
}
return Culture(obj, CultureInfo.GetCultureInfo(name));
}
/// <summary>
/// Sets the culture.
/// </summary>
/// <typeparam name="T">An object type with a culture.</typeparam>
/// <param name="obj">The object to set the culture for.</param>
/// <param name="culture">The culture to set.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T Culture<T>(this T obj, int culture)
where T : class, IHasCulture
{
return Culture(obj, CultureInfo.GetCultureInfo(culture));
}
}

View File

@@ -0,0 +1,80 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="IHasJustification"/>.
/// </summary>
public static class HasJustificationExtensions
{
/// <summary>
/// Sets the justification for an <see cref="IHasJustification"/> object.
/// </summary>
/// <typeparam name="T">The type that can be justified.</typeparam>
/// <param name="obj">The alignable object.</param>
/// <param name="alignment">The alignment.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T Justify<T>(this T obj, Justify? alignment)
where T : class, IHasJustification
{
if (obj is null)
{
throw new System.ArgumentNullException(nameof(obj));
}
obj.Justification = alignment;
return obj;
}
/// <summary>
/// Sets the <see cref="IHasJustification"/> object to be left justified.
/// </summary>
/// <typeparam name="T">The type that can be justified.</typeparam>
/// <param name="obj">The alignable object.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T LeftJustified<T>(this T obj)
where T : class, IHasJustification
{
if (obj is null)
{
throw new System.ArgumentNullException(nameof(obj));
}
obj.Justification = Console.Justify.Left;
return obj;
}
/// <summary>
/// Sets the <see cref="IHasJustification"/> object to be centered.
/// </summary>
/// <typeparam name="T">The type that can be justified.</typeparam>
/// <param name="obj">The alignable object.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T Centered<T>(this T obj)
where T : class, IHasJustification
{
if (obj is null)
{
throw new System.ArgumentNullException(nameof(obj));
}
obj.Justification = Console.Justify.Center;
return obj;
}
/// <summary>
/// Sets the <see cref="IHasJustification"/> object to be right justified.
/// </summary>
/// <typeparam name="T">The type that can be justified.</typeparam>
/// <param name="obj">The alignable object.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T RightJustified<T>(this T obj)
where T : class, IHasJustification
{
if (obj is null)
{
throw new System.ArgumentNullException(nameof(obj));
}
obj.Justification = Console.Justify.Right;
return obj;
}
}

View File

@@ -0,0 +1,242 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="IHasTableBorder"/>.
/// </summary>
public static class HasTableBorderExtensions
{
/// <summary>
/// Do not display a border.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T NoBorder<T>(this T obj)
where T : class, IHasTableBorder
{
return Border(obj, TableBorder.None);
}
/// <summary>
/// Display a square border.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T SquareBorder<T>(this T obj)
where T : class, IHasTableBorder
{
return Border(obj, TableBorder.Square);
}
/// <summary>
/// Display an ASCII border.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T AsciiBorder<T>(this T obj)
where T : class, IHasTableBorder
{
return Border(obj, TableBorder.Ascii);
}
/// <summary>
/// Display another ASCII border.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T Ascii2Border<T>(this T obj)
where T : class, IHasTableBorder
{
return Border(obj, TableBorder.Ascii2);
}
/// <summary>
/// Display an ASCII border with a double header border.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T AsciiDoubleHeadBorder<T>(this T obj)
where T : class, IHasTableBorder
{
return Border(obj, TableBorder.AsciiDoubleHead);
}
/// <summary>
/// Display a rounded border.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T RoundedBorder<T>(this T obj)
where T : class, IHasTableBorder
{
return Border(obj, TableBorder.Rounded);
}
/// <summary>
/// Display a minimal border.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T MinimalBorder<T>(this T obj)
where T : class, IHasTableBorder
{
return Border(obj, TableBorder.Minimal);
}
/// <summary>
/// Display a minimal border with a heavy head.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T MinimalHeavyHeadBorder<T>(this T obj)
where T : class, IHasTableBorder
{
return Border(obj, TableBorder.MinimalHeavyHead);
}
/// <summary>
/// Display a minimal border with a double header border.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T MinimalDoubleHeadBorder<T>(this T obj)
where T : class, IHasTableBorder
{
return Border(obj, TableBorder.MinimalDoubleHead);
}
/// <summary>
/// Display a simple border.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T SimpleBorder<T>(this T obj)
where T : class, IHasTableBorder
{
return Border(obj, TableBorder.Simple);
}
/// <summary>
/// Display a simple border with heavy lines.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T SimpleHeavyBorder<T>(this T obj)
where T : class, IHasTableBorder
{
return Border(obj, TableBorder.SimpleHeavy);
}
/// <summary>
/// Display a simple border.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T HorizontalBorder<T>(this T obj)
where T : class, IHasTableBorder
{
return Border(obj, TableBorder.Horizontal);
}
/// <summary>
/// Display a heavy border.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T HeavyBorder<T>(this T obj)
where T : class, IHasTableBorder
{
return Border(obj, TableBorder.Heavy);
}
/// <summary>
/// Display a border with a heavy edge.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T HeavyEdgeBorder<T>(this T obj)
where T : class, IHasTableBorder
{
return Border(obj, TableBorder.HeavyEdge);
}
/// <summary>
/// Display a border with a heavy header.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T HeavyHeadBorder<T>(this T obj)
where T : class, IHasTableBorder
{
return Border(obj, TableBorder.HeavyHead);
}
/// <summary>
/// Display a double border.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T DoubleBorder<T>(this T obj)
where T : class, IHasTableBorder
{
return Border(obj, TableBorder.Double);
}
/// <summary>
/// Display a border with a double edge.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T DoubleEdgeBorder<T>(this T obj)
where T : class, IHasTableBorder
{
return Border(obj, TableBorder.DoubleEdge);
}
/// <summary>
/// Display a markdown border.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T MarkdownBorder<T>(this T obj)
where T : class, IHasTableBorder
{
return Border(obj, TableBorder.Markdown);
}
/// <summary>
/// Sets the border.
/// </summary>
/// <typeparam name="T">An object type with a border.</typeparam>
/// <param name="obj">The object to set the border for.</param>
/// <param name="border">The border to use.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T Border<T>(this T obj, TableBorder border)
where T : class, IHasTableBorder
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
obj.Border = border;
return obj;
}
}

View File

@@ -0,0 +1,211 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="IHasTreeNodes"/>.
/// </summary>
public static class HasTreeNodeExtensions
{
/// <summary>
/// Adds a tree node.
/// </summary>
/// <typeparam name="T">An object with tree nodes.</typeparam>
/// <param name="obj">The object to add the tree node to.</param>
/// <param name="markup">The node's markup text.</param>
/// <returns>The added tree node.</returns>
public static TreeNode AddNode<T>(this T obj, string markup)
where T : IHasTreeNodes
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
if (markup is null)
{
throw new ArgumentNullException(nameof(markup));
}
return AddNode(obj, new Markup(markup));
}
/// <summary>
/// Adds a tree node.
/// </summary>
/// <typeparam name="T">An object with tree nodes.</typeparam>
/// <param name="obj">The object to add the tree node to.</param>
/// <param name="renderable">The renderable to add.</param>
/// <returns>The added tree node.</returns>
public static TreeNode AddNode<T>(this T obj, IRenderable renderable)
where T : IHasTreeNodes
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
if (renderable is null)
{
throw new ArgumentNullException(nameof(renderable));
}
var node = new TreeNode(renderable);
obj.Nodes.Add(node);
return node;
}
/// <summary>
/// Adds a tree node.
/// </summary>
/// <typeparam name="T">An object with tree nodes.</typeparam>
/// <param name="obj">The object to add the tree node to.</param>
/// <param name="node">The tree node to add.</param>
/// <returns>The added tree node.</returns>
public static TreeNode AddNode<T>(this T obj, TreeNode node)
where T : IHasTreeNodes
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
if (node is null)
{
throw new ArgumentNullException(nameof(node));
}
obj.Nodes.Add(node);
return node;
}
/// <summary>
/// Add multiple tree nodes.
/// </summary>
/// <typeparam name="T">An object with tree nodes.</typeparam>
/// <param name="obj">The object to add the tree nodes to.</param>
/// <param name="nodes">The tree nodes to add.</param>
public static void AddNodes<T>(this T obj, params string[] nodes)
where T : IHasTreeNodes
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
if (nodes is null)
{
throw new ArgumentNullException(nameof(nodes));
}
obj.Nodes.AddRange(nodes.Select(node => new TreeNode(new Markup(node))));
}
/// <summary>
/// Add multiple tree nodes.
/// </summary>
/// <typeparam name="T">An object with tree nodes.</typeparam>
/// <param name="obj">The object to add the tree nodes to.</param>
/// <param name="nodes">The tree nodes to add.</param>
public static void AddNodes<T>(this T obj, IEnumerable<string> nodes)
where T : IHasTreeNodes
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
if (nodes is null)
{
throw new ArgumentNullException(nameof(nodes));
}
obj.Nodes.AddRange(nodes.Select(node => new TreeNode(new Markup(node))));
}
/// <summary>
/// Add multiple tree nodes.
/// </summary>
/// <typeparam name="T">An object with tree nodes.</typeparam>
/// <param name="obj">The object to add the tree nodes to.</param>
/// <param name="nodes">The tree nodes to add.</param>
public static void AddNodes<T>(this T obj, params IRenderable[] nodes)
where T : IHasTreeNodes
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
if (nodes is null)
{
throw new ArgumentNullException(nameof(nodes));
}
obj.Nodes.AddRange(nodes.Select(node => new TreeNode(node)));
}
/// <summary>
/// Add multiple tree nodes.
/// </summary>
/// <typeparam name="T">An object with tree nodes.</typeparam>
/// <param name="obj">The object to add the tree nodes to.</param>
/// <param name="nodes">The tree nodes to add.</param>
public static void AddNodes<T>(this T obj, IEnumerable<IRenderable> nodes)
where T : IHasTreeNodes
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
if (nodes is null)
{
throw new ArgumentNullException(nameof(nodes));
}
obj.Nodes.AddRange(nodes.Select(node => new TreeNode(node)));
}
/// <summary>
/// Add multiple tree nodes.
/// </summary>
/// <typeparam name="T">An object with tree nodes.</typeparam>
/// <param name="obj">The object to add the tree nodes to.</param>
/// <param name="nodes">The tree nodes to add.</param>
public static void AddNodes<T>(this T obj, params TreeNode[] nodes)
where T : IHasTreeNodes
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
if (nodes is null)
{
throw new ArgumentNullException(nameof(nodes));
}
obj.Nodes.AddRange(nodes);
}
/// <summary>
/// Add multiple tree nodes.
/// </summary>
/// <typeparam name="T">An object with tree nodes.</typeparam>
/// <param name="obj">The object to add the tree nodes to.</param>
/// <param name="nodes">The tree nodes to add.</param>
public static void AddNodes<T>(this T obj, IEnumerable<TreeNode> nodes)
where T : IHasTreeNodes
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
if (nodes is null)
{
throw new ArgumentNullException(nameof(nodes));
}
obj.Nodes.AddRange(nodes);
}
}

View File

@@ -0,0 +1,19 @@
namespace Spectre.Console;
internal static class Int32Extensions
{
public static int Clamp(this int value, int min, int max)
{
if (value <= min)
{
return min;
}
if (value >= max)
{
return max;
}
return value;
}
}

View File

@@ -0,0 +1,58 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="Layout"/>.
/// </summary>
public static class LayoutExtensions
{
/// <summary>
/// Sets the ratio of the layout.
/// </summary>
/// <param name="layout">The layout.</param>
/// <param name="ratio">The ratio.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Layout Ratio(this Layout layout, int ratio)
{
if (layout is null)
{
throw new ArgumentNullException(nameof(layout));
}
layout.Ratio = ratio;
return layout;
}
/// <summary>
/// Sets the size of the layout.
/// </summary>
/// <param name="layout">The layout.</param>
/// <param name="size">The size.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Layout Size(this Layout layout, int size)
{
if (layout is null)
{
throw new ArgumentNullException(nameof(layout));
}
layout.Size = size;
return layout;
}
/// <summary>
/// Sets the minimum width of the layout.
/// </summary>
/// <param name="layout">The layout.</param>
/// <param name="size">The size.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Layout MinimumSize(this Layout layout, int size)
{
if (layout is null)
{
throw new ArgumentNullException(nameof(layout));
}
layout.MinimumSize = size;
return layout;
}
}

View File

@@ -0,0 +1,34 @@
namespace Spectre.Console;
internal static class ListExtensions
{
public static void RemoveLast<T>(this List<T> list)
{
if (list is null)
{
throw new ArgumentNullException(nameof(list));
}
if (list.Count > 0)
{
list.RemoveAt(list.Count - 1);
}
}
public static void AddOrReplaceLast<T>(this List<T> list, T item)
{
if (list is null)
{
throw new ArgumentNullException(nameof(list));
}
if (list.Count == 0)
{
list.Add(item);
}
else
{
list[list.Count - 1] = item;
}
}
}

View File

@@ -0,0 +1,62 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="LiveDisplay"/>.
/// </summary>
public static class LiveDisplayExtensions
{
/// <summary>
/// Sets whether or not auto clear is enabled.
/// If enabled, the live display will be cleared when done.
/// </summary>
/// <param name="live">The <see cref="LiveDisplay"/> instance.</param>
/// <param name="enabled">Whether or not auto clear is enabled.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static LiveDisplay AutoClear(this LiveDisplay live, bool enabled)
{
if (live is null)
{
throw new ArgumentNullException(nameof(live));
}
live.AutoClear = enabled;
return live;
}
/// <summary>
/// Sets the vertical overflow strategy.
/// </summary>
/// <param name="live">The <see cref="LiveDisplay"/> instance.</param>
/// <param name="overflow">The overflow strategy to use.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static LiveDisplay Overflow(this LiveDisplay live, VerticalOverflow overflow)
{
if (live is null)
{
throw new ArgumentNullException(nameof(live));
}
live.Overflow = overflow;
return live;
}
/// <summary>
/// Sets the vertical overflow cropping strategy.
/// </summary>
/// <param name="live">The <see cref="LiveDisplay"/> instance.</param>
/// <param name="cropping">The overflow cropping strategy to use.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static LiveDisplay Cropping(this LiveDisplay live, VerticalOverflowCropping cropping)
{
if (live is null)
{
throw new ArgumentNullException(nameof(live));
}
live.Cropping = cropping;
return live;
}
}

View File

@@ -0,0 +1,77 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="IOverflowable"/>.
/// </summary>
public static class OverflowableExtensions
{
/// <summary>
/// Folds any overflowing text.
/// </summary>
/// <typeparam name="T">An object implementing <see cref="IOverflowable"/>.</typeparam>
/// <param name="obj">The overflowable object instance.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T Fold<T>(this T obj)
where T : class, IOverflowable
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
return Overflow(obj, Console.Overflow.Fold);
}
/// <summary>
/// Crops any overflowing text.
/// </summary>
/// <typeparam name="T">An object implementing <see cref="IOverflowable"/>.</typeparam>
/// <param name="obj">The overflowable object instance.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T Crop<T>(this T obj)
where T : class, IOverflowable
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
return Overflow(obj, Console.Overflow.Crop);
}
/// <summary>
/// Crops any overflowing text and adds an ellipsis to the end.
/// </summary>
/// <typeparam name="T">An object implementing <see cref="IOverflowable"/>.</typeparam>
/// <param name="obj">The overflowable object instance.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T Ellipsis<T>(this T obj)
where T : class, IOverflowable
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
return Overflow(obj, Console.Overflow.Ellipsis);
}
/// <summary>
/// Sets the overflow strategy.
/// </summary>
/// <typeparam name="T">An object implementing <see cref="IOverflowable"/>.</typeparam>
/// <param name="obj">The overflowable object instance.</param>
/// <param name="overflow">The overflow strategy to use.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T Overflow<T>(this T obj, Overflow overflow)
where T : class, IOverflowable
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
obj.Overflow = overflow;
return obj;
}
}

View File

@@ -0,0 +1,128 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="IPaddable"/>.
/// </summary>
public static class PaddableExtensions
{
/// <summary>
/// Sets the left padding.
/// </summary>
/// <typeparam name="T">An object implementing <see cref="IPaddable"/>.</typeparam>
/// <param name="obj">The paddable object instance.</param>
/// <param name="left">The left padding.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T PadLeft<T>(this T obj, int left)
where T : class, IPaddable
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
return Padding(obj, new Padding(left, obj.Padding.GetTopSafe(), obj.Padding.GetRightSafe(), obj.Padding.GetBottomSafe()));
}
/// <summary>
/// Sets the top padding.
/// </summary>
/// <typeparam name="T">An object implementing <see cref="IPaddable"/>.</typeparam>
/// <param name="obj">The paddable object instance.</param>
/// <param name="top">The top padding.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T PadTop<T>(this T obj, int top)
where T : class, IPaddable
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
return Padding(obj, new Padding(obj.Padding.GetLeftSafe(), top, obj.Padding.GetRightSafe(), obj.Padding.GetBottomSafe()));
}
/// <summary>
/// Sets the right padding.
/// </summary>
/// <typeparam name="T">An object implementing <see cref="IPaddable"/>.</typeparam>
/// <param name="obj">The paddable object instance.</param>
/// <param name="right">The right padding.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T PadRight<T>(this T obj, int right)
where T : class, IPaddable
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
return Padding(obj, new Padding(obj.Padding.GetLeftSafe(), obj.Padding.GetTopSafe(), right, obj.Padding.GetBottomSafe()));
}
/// <summary>
/// Sets the bottom padding.
/// </summary>
/// <typeparam name="T">An object implementing <see cref="IPaddable"/>.</typeparam>
/// <param name="obj">The paddable object instance.</param>
/// <param name="bottom">The bottom padding.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T PadBottom<T>(this T obj, int bottom)
where T : class, IPaddable
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
return Padding(obj, new Padding(obj.Padding.GetLeftSafe(), obj.Padding.GetTopSafe(), obj.Padding.GetRightSafe(), bottom));
}
/// <summary>
/// Sets the left, top, right and bottom padding.
/// </summary>
/// <typeparam name="T">An object implementing <see cref="IPaddable"/>.</typeparam>
/// <param name="obj">The paddable object instance.</param>
/// <param name="left">The left padding to apply.</param>
/// <param name="top">The top padding to apply.</param>
/// <param name="right">The right padding to apply.</param>
/// <param name="bottom">The bottom padding to apply.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T Padding<T>(this T obj, int left, int top, int right, int bottom)
where T : class, IPaddable
{
return Padding(obj, new Padding(left, top, right, bottom));
}
/// <summary>
/// Sets the horizontal and vertical padding.
/// </summary>
/// <typeparam name="T">An object implementing <see cref="IPaddable"/>.</typeparam>
/// <param name="obj">The paddable object instance.</param>
/// <param name="horizontal">The left and right padding.</param>
/// <param name="vertical">The top and bottom padding.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T Padding<T>(this T obj, int horizontal, int vertical)
where T : class, IPaddable
{
return Padding(obj, new Padding(horizontal, vertical));
}
/// <summary>
/// Sets the padding.
/// </summary>
/// <typeparam name="T">An object implementing <see cref="IPaddable"/>.</typeparam>
/// <param name="obj">The paddable object instance.</param>
/// <param name="padding">The padding to apply.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static T Padding<T>(this T obj, Padding padding)
where T : class, IPaddable
{
if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}
obj.Padding = padding;
return obj;
}
}

View File

@@ -0,0 +1,47 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="Padding"/>.
/// </summary>
public static class PaddingExtensions
{
/// <summary>
/// Gets the left padding.
/// </summary>
/// <param name="padding">The padding.</param>
/// <returns>The left padding or zero if <c>padding</c> is null.</returns>
public static int GetLeftSafe(this Padding? padding)
{
return padding?.Left ?? 0;
}
/// <summary>
/// Gets the right padding.
/// </summary>
/// <param name="padding">The padding.</param>
/// <returns>The right padding or zero if <c>padding</c> is null.</returns>
public static int GetRightSafe(this Padding? padding)
{
return padding?.Right ?? 0;
}
/// <summary>
/// Gets the top padding.
/// </summary>
/// <param name="padding">The padding.</param>
/// <returns>The top padding or zero if <c>padding</c> is null.</returns>
public static int GetTopSafe(this Padding? padding)
{
return padding?.Top ?? 0;
}
/// <summary>
/// Gets the bottom padding.
/// </summary>
/// <param name="padding">The padding.</param>
/// <returns>The bottom padding or zero if <c>padding</c> is null.</returns>
public static int GetBottomSafe(this Padding? padding)
{
return padding?.Bottom ?? 0;
}
}

View File

@@ -0,0 +1,74 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="Panel"/>.
/// </summary>
public static class PanelExtensions
{
/// <summary>
/// Sets the panel header.
/// </summary>
/// <param name="panel">The panel.</param>
/// <param name="text">The header text.</param>
/// <param name="alignment">The header alignment.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Panel Header(this Panel panel, string text, Justify? alignment = null)
{
if (panel is null)
{
throw new ArgumentNullException(nameof(panel));
}
if (text is null)
{
throw new ArgumentNullException(nameof(text));
}
alignment ??= panel.Header?.Justification;
return Header(panel, new PanelHeader(text, alignment));
}
/// <summary>
/// Sets the panel header alignment.
/// </summary>
/// <param name="panel">The panel.</param>
/// <param name="alignment">The header alignment.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Panel HeaderAlignment(this Panel panel, Justify alignment)
{
if (panel is null)
{
throw new ArgumentNullException(nameof(panel));
}
if (panel.Header != null)
{
// Update existing style
panel.Header.Justification = alignment;
}
else
{
// Create header
Header(panel, string.Empty, alignment);
}
return panel;
}
/// <summary>
/// Sets the panel header.
/// </summary>
/// <param name="panel">The panel.</param>
/// <param name="header">The header to use.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static Panel Header(this Panel panel, PanelHeader header)
{
if (panel is null)
{
throw new ArgumentNullException(nameof(panel));
}
panel.Header = header;
return panel;
}
}

View File

@@ -0,0 +1,51 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="PercentageColumn"/>.
/// </summary>
public static class PercentageColumnExtensions
{
/// <summary>
/// Sets the style for a non-complete task.
/// </summary>
/// <param name="column">The column.</param>
/// <param name="style">The style.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static PercentageColumn Style(this PercentageColumn column, Style style)
{
if (column is null)
{
throw new ArgumentNullException(nameof(column));
}
if (style is null)
{
throw new ArgumentNullException(nameof(style));
}
column.Style = style;
return column;
}
/// <summary>
/// Sets the style for a completed task.
/// </summary>
/// <param name="column">The column.</param>
/// <param name="style">The style.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static PercentageColumn CompletedStyle(this PercentageColumn column, Style style)
{
if (column is null)
{
throw new ArgumentNullException(nameof(column));
}
if (style is null)
{
throw new ArgumentNullException(nameof(style));
}
column.CompletedStyle = style;
return column;
}
}

View File

@@ -0,0 +1,73 @@
namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="ProgressBarColumn"/>.
/// </summary>
public static class ProgressBarColumnExtensions
{
/// <summary>
/// Sets the style of completed portions of the progress bar.
/// </summary>
/// <param name="column">The column.</param>
/// <param name="style">The style.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static ProgressBarColumn CompletedStyle(this ProgressBarColumn column, Style style)
{
if (column is null)
{
throw new ArgumentNullException(nameof(column));
}
if (style is null)
{
throw new ArgumentNullException(nameof(style));
}
column.CompletedStyle = style;
return column;
}
/// <summary>
/// Sets the style of a finished progress bar.
/// </summary>
/// <param name="column">The column.</param>
/// <param name="style">The style.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static ProgressBarColumn FinishedStyle(this ProgressBarColumn column, Style style)
{
if (column is null)
{
throw new ArgumentNullException(nameof(column));
}
if (style is null)
{
throw new ArgumentNullException(nameof(style));
}
column.FinishedStyle = style;
return column;
}
/// <summary>
/// Sets the style of remaining portions of the progress bar.
/// </summary>
/// <param name="column">The column.</param>
/// <param name="style">The style.</param>
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static ProgressBarColumn RemainingStyle(this ProgressBarColumn column, Style style)
{
if (column is null)
{
throw new ArgumentNullException(nameof(column));
}
if (style is null)
{
throw new ArgumentNullException(nameof(style));
}
column.RemainingStyle = style;
return column;
}
}

Some files were not shown because too many files have changed in this diff Show More