Modernization of the code base (#1993)

* Update packages
* Convert extension methods to extension blocks
* Move extension methods closer to what they are extending
* Use ArgumentNullException.ThrowIfNull
* Move WriteAnsi and ToAnsi methods to Spectre.Console namespace
* Make shared global state obsolete
* Make AnsiConsole.Clear an extension method
* Linting should not fail build
This commit is contained in:
Patrik Svensson
2026-01-05 00:32:54 +01:00
committed by GitHub
parent 129fd710c1
commit 3f57df5af6
204 changed files with 7111 additions and 8515 deletions

View File

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

View File

@@ -1,6 +1,12 @@
root = false
[*.cs] [*.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
# Prefer file scoped namespace declarations # Prefer file scoped namespace declarations
csharp_style_namespace_declarations = file_scoped:warning csharp_style_namespace_declarations = file_scoped:warning

View File

@@ -1,4 +1,4 @@
<Project> <Project>
<PropertyGroup Label="Settings"> <PropertyGroup Label="Settings">
<Deterministic>true</Deterministic> <Deterministic>true</Deterministic>
<LangVersion>14</LangVersion> <LangVersion>14</LangVersion>
@@ -14,6 +14,18 @@
<SignAssembly>true</SignAssembly> <SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>$(MSBuildThisFileDirectory)\..\resources\spectre.snk</AssemblyOriginatorKeyFile> <AssemblyOriginatorKeyFile>$(MSBuildThisFileDirectory)\..\resources\spectre.snk</AssemblyOriginatorKeyFile>
<PublicKey>00240000048000009400000006020000002400005253413100040000010001006146d3789d31477cf4a3b508dcf772ff9ccad8613f6bd6b17b9c4a960a7a7b551ecd22e4f4119ced70ee8bbdf3ca0a117c99fd6248c16255ea9033110c2233d42e74e81bf4f3f7eb09bfe8b53ad399d957514f427171a86f5fe9fe0014be121d571c80c4a0cfc3531bdbf5a2900d936d93f2c94171b9134f7644a1ac3612a0d0</PublicKey> <PublicKey>00240000048000009400000006020000002400005253413100040000010001006146d3789d31477cf4a3b508dcf772ff9ccad8613f6bd6b17b9c4a960a7a7b551ecd22e4f4119ced70ee8bbdf3ca0a117c99fd6248c16255ea9033110c2233d42e74e81bf4f3f7eb09bfe8b53ad399d957514f427171a86f5fe9fe0014be121d571c80c4a0cfc3531bdbf5a2900d936d93f2c94171b9134f7644a1ac3612a0d0</PublicKey>
<PolyArgumentExceptions>true</PolyArgumentExceptions>
</PropertyGroup>
<!-- Due to a bug in the .NET SDK (10.0.101), a false positive CS8620 warning is emitted -->
<!-- when "params" are used together with extension blocks -->
<PropertyGroup>
<NoWarn>$(NoWarn);CS8620</NoWarn>
</PropertyGroup>
<!-- Earlier (<10.0.100) SDK throws on extension blocks -->
<PropertyGroup Condition="'$(TargetFramework)' != 'net10.0'">
<NoWarn>$(NoWarn);AD0001</NoWarn>
</PropertyGroup> </PropertyGroup>
<!-- Disable nullability for netstandard2.0 since polyfills are not --> <!-- Disable nullability for netstandard2.0 since polyfills are not -->

View File

@@ -4,23 +4,23 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageVersion Include="AngleSharp" Version="1.4.0" /> <PackageVersion Include="AngleSharp" Version="1.4.0" />
<PackageVersion Include="Humanizer.Core" Version="2.14.1" /> <PackageVersion Include="Humanizer.Core" Version="3.0.1" />
<PackageVersion Include="IsExternalInit" Version="1.0.3" /> <PackageVersion Include="IsExternalInit" Version="1.0.3" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.0.1" /> <PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.0.1" />
<PackageVersion Include="Microsoft.SourceLink.GitHub" PrivateAssets="All" Version="8.0.0" /> <PackageVersion Include="Microsoft.SourceLink.GitHub" PrivateAssets="All" Version="8.0.0" />
<PackageVersion Include="MinVer" PrivateAssets="All" Version="6.0.0" /> <PackageVersion Include="MinVer" PrivateAssets="All" Version="6.1.0" />
<PackageVersion Include="Newtonsoft.Json" Version="13.0.4" /> <PackageVersion Include="Newtonsoft.Json" Version="13.0.4" />
<PackageVersion Include="Polyfill" Version="9.0.3" /> <PackageVersion Include="Polyfill" Version="9.6.0" />
<PackageVersion Include="Roslynator.Analyzers" PrivateAssets="All" Version="4.14.1" /> <PackageVersion Include="Roslynator.Analyzers" PrivateAssets="All" Version="4.15.0" />
<PackageVersion Include="Scriban" Version="6.5.0" /> <PackageVersion Include="Scriban" Version="6.5.2" />
<PackageVersion Include="Shouldly" Version="4.3.0" /> <PackageVersion Include="Shouldly" Version="4.3.0" />
<PackageVersion Include="SixLabors.ImageSharp" Version="3.1.12" /> <PackageVersion Include="SixLabors.ImageSharp" Version="3.1.12" />
<PackageVersion Include="Spectre.Console.Cli" Version="0.53.0" /> <PackageVersion Include="Spectre.Console.Cli" Version="0.53.1" />
<PackageVersion Include="Spectre.IO" Version="0.21.0" /> <PackageVersion Include="Spectre.IO" Version="0.21.0" />
<PackageVersion Include="Spectre.Verify.Extensions" Version="28.16.0" /> <PackageVersion Include="Spectre.Verify.Extensions" Version="28.16.0" />
<PackageVersion Include="System.Memory" Version="4.6.3" /> <PackageVersion Include="System.Memory" Version="4.6.3" />
<PackageVersion Include="TunnelVisionLabs.ReferenceAssemblyAnnotator" Version="1.0.0-alpha.160" /> <PackageVersion Include="TunnelVisionLabs.ReferenceAssemblyAnnotator" Version="1.0.0-alpha.160" />
<PackageVersion Include="Verify.Xunit" Version="31.7.1" /> <PackageVersion Include="Verify.Xunit" Version="31.9.3" />
<PackageVersion Include="Wcwidth.Sources" Version="4.0.1" /> <PackageVersion Include="Wcwidth.Sources" Version="4.0.1" />
<PackageVersion Include="xunit" Version="2.9.3" /> <PackageVersion Include="xunit" Version="2.9.3" />
<PackageVersion Include="xunit.runner.visualstudio" Version="3.1.5"> <PackageVersion Include="xunit.runner.visualstudio" Version="3.1.5">

View File

@@ -8,127 +8,100 @@ namespace Spectre.Console;
/// </summary> /// </summary>
public static class CanvasImageExtensions public static class CanvasImageExtensions
{ {
/// <summary>
/// Sets the maximum width of the rendered image.
/// </summary>
/// <param name="image">The canvas image.</param> /// <param name="image">The canvas image.</param>
/// <param name="maxWidth">The maximum width.</param> extension(CanvasImage image)
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static CanvasImage MaxWidth(this CanvasImage image, int? maxWidth)
{ {
if (image is null) /// <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)
{ {
throw new ArgumentNullException(nameof(image)); ArgumentNullException.ThrowIfNull(image);
image.MaxWidth = maxWidth;
return image;
} }
image.MaxWidth = maxWidth; /// <summary>
return image; /// Disables the maximum width of the rendered image.
} /// </summary>
/// <returns>The same instance so that multiple calls can be chained.</returns>
/// <summary> public CanvasImage NoMaxWidth()
/// 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)); ArgumentNullException.ThrowIfNull(image);
image.MaxWidth = null;
return image;
} }
image.MaxWidth = null; /// <summary>
return image; /// Sets the pixel width.
} /// </summary>
/// <param name="width">The pixel width.</param>
/// <summary> /// <returns>The same instance so that multiple calls can be chained.</returns>
/// Sets the pixel width. public CanvasImage PixelWidth(int 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)); ArgumentNullException.ThrowIfNull(image);
image.PixelWidth = width;
return image;
} }
image.PixelWidth = width; /// <summary>
return image; /// Mutates the underlying image.
} /// </summary>
/// <param name="action">The action that mutates the underlying image.</param>
/// <summary> /// <returns>The same instance so that multiple calls can be chained.</returns>
/// Mutates the underlying image. public CanvasImage Mutate(Action<IImageProcessingContext> action)
/// </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)
{ {
throw new ArgumentNullException(nameof(image)); ArgumentNullException.ThrowIfNull(image);
ArgumentNullException.ThrowIfNull(action);
image.Image.Mutate(action);
return image;
} }
if (action is null) /// <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()
{ {
throw new ArgumentNullException(nameof(action)); ArgumentNullException.ThrowIfNull(image);
image.Resampler = KnownResamplers.Bicubic;
return image;
} }
image.Image.Mutate(action); /// <summary>
return image; /// 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> /// </summary>
/// Uses a bicubic sampler that implements the bicubic kernel algorithm W(x). /// <returns>The same instance so that multiple calls can be chained.</returns>
/// </summary> public CanvasImage BilinearResampler()
/// <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)); ArgumentNullException.ThrowIfNull(image);
image.Resampler = KnownResamplers.Triangle;
return image;
} }
image.Resampler = KnownResamplers.Bicubic; /// <summary>
return image; /// 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> /// </summary>
/// Uses a bilinear sampler. This interpolation algorithm /// <returns>The same instance so that multiple calls can be chained.</returns>
/// can be used where perfect image transformation with pixel matching is impossible, public CanvasImage NearestNeighborResampler()
/// 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)); ArgumentNullException.ThrowIfNull(image);
image.Resampler = KnownResamplers.NearestNeighbor;
return 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,309 +5,241 @@ namespace Spectre.Console.Json;
/// </summary> /// </summary>
public static class JsonTextExtensions public static class JsonTextExtensions
{ {
/// <summary>
/// Sets the style used for braces.
/// </summary>
/// <param name="text">The JSON text instance.</param> /// <param name="text">The JSON text instance.</param>
/// <param name="style">The style to set.</param> extension(JsonText text)
/// <returns>The same instance so that multiple calls can be chained.</returns>
public static JsonText BracesStyle(this JsonText text, Style? style)
{ {
if (text == null) /// <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)
{ {
throw new ArgumentNullException(nameof(text)); ArgumentNullException.ThrowIfNull(text);
text.BracesStyle = style;
return text;
} }
text.BracesStyle = style; /// <summary>
return text; /// Sets the style used for brackets.
} /// </summary>
/// <param name="style">The style to set.</param>
/// <summary> /// <returns>The same instance so that multiple calls can be chained.</returns>
/// Sets the style used for brackets. public JsonText BracketStyle(Style? style)
/// </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)); ArgumentNullException.ThrowIfNull(text);
text.BracketsStyle = style;
return text;
} }
text.BracketsStyle = style; /// <summary>
return text; /// Sets the style used for member names.
} /// </summary>
/// <param name="style">The style to set.</param>
/// <summary> /// <returns>The same instance so that multiple calls can be chained.</returns>
/// Sets the style used for member names. public JsonText MemberStyle(Style? style)
/// </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)); ArgumentNullException.ThrowIfNull(text);
text.MemberStyle = style;
return text;
} }
text.MemberStyle = style; /// <summary>
return text; /// Sets the style used for colons.
} /// </summary>
/// <param name="style">The style to set.</param>
/// <summary> /// <returns>The same instance so that multiple calls can be chained.</returns>
/// Sets the style used for colons. public JsonText ColonStyle(Style? style)
/// </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)); ArgumentNullException.ThrowIfNull(text);
text.ColonStyle = style;
return text;
} }
text.ColonStyle = style; /// <summary>
return text; /// Sets the style used for commas.
} /// </summary>
/// <param name="style">The style to set.</param>
/// <summary> /// <returns>The same instance so that multiple calls can be chained.</returns>
/// Sets the style used for commas. public JsonText CommaStyle(Style? style)
/// </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)); ArgumentNullException.ThrowIfNull(text);
text.CommaStyle = style;
return text;
} }
text.CommaStyle = style; /// <summary>
return text; /// Sets the style used for string literals.
} /// </summary>
/// <param name="style">The style to set.</param>
/// <summary> /// <returns>The same instance so that multiple calls can be chained.</returns>
/// Sets the style used for string literals. public JsonText StringStyle(Style? style)
/// </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)); ArgumentNullException.ThrowIfNull(text);
text.StringStyle = style;
return text;
} }
text.StringStyle = style; /// <summary>
return text; /// Sets the style used for number literals.
} /// </summary>
/// <param name="style">The style to set.</param>
/// <summary> /// <returns>The same instance so that multiple calls can be chained.</returns>
/// Sets the style used for number literals. public JsonText NumberStyle(Style? style)
/// </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)); ArgumentNullException.ThrowIfNull(text);
text.NumberStyle = style;
return text;
} }
text.NumberStyle = style; /// <summary>
return text; /// Sets the style used for boolean literals.
} /// </summary>
/// <param name="style">The style to set.</param>
/// <summary> /// <returns>The same instance so that multiple calls can be chained.</returns>
/// Sets the style used for boolean literals. public JsonText BooleanStyle(Style? style)
/// </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)); ArgumentNullException.ThrowIfNull(text);
text.BooleanStyle = style;
return text;
} }
text.BooleanStyle = style; /// <summary>
return text; /// Sets the style used for <c>null</c> literals.
} /// </summary>
/// <param name="style">The style to set.</param>
/// <summary> /// <returns>The same instance so that multiple calls can be chained.</returns>
/// Sets the style used for <c>null</c> literals. public JsonText NullStyle(Style? style)
/// </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)); ArgumentNullException.ThrowIfNull(text);
text.NullStyle = style;
return text;
} }
text.NullStyle = style; /// <summary>
return text; /// Sets the color used for braces.
} /// </summary>
/// <param name="color">The color to set.</param>
/// <summary> /// <returns>The same instance so that multiple calls can be chained.</returns>
/// Sets the color used for braces. public JsonText BracesColor(Color color)
/// </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)); ArgumentNullException.ThrowIfNull(text);
text.BracesStyle = new Style(color);
return text;
} }
text.BracesStyle = new Style(color); /// <summary>
return text; /// Sets the color used for brackets.
} /// </summary>
/// <param name="color">The color to set.</param>
/// <summary> /// <returns>The same instance so that multiple calls can be chained.</returns>
/// Sets the color used for brackets. public JsonText BracketColor(Color color)
/// </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)); ArgumentNullException.ThrowIfNull(text);
text.BracketsStyle = new Style(color);
return text;
} }
text.BracketsStyle = new Style(color); /// <summary>
return text; /// Sets the color used for member names.
} /// </summary>
/// <param name="color">The color to set.</param>
/// <summary> /// <returns>The same instance so that multiple calls can be chained.</returns>
/// Sets the color used for member names. public JsonText MemberColor(Color color)
/// </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)); ArgumentNullException.ThrowIfNull(text);
text.MemberStyle = new Style(color);
return text;
} }
text.MemberStyle = new Style(color); /// <summary>
return text; /// Sets the color used for colons.
} /// </summary>
/// <param name="color">The color to set.</param>
/// <summary> /// <returns>The same instance so that multiple calls can be chained.</returns>
/// Sets the color used for colons. public JsonText ColonColor(Color color)
/// </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)); ArgumentNullException.ThrowIfNull(text);
text.ColonStyle = new Style(color);
return text;
} }
text.ColonStyle = new Style(color); /// <summary>
return text; /// Sets the color used for commas.
} /// </summary>
/// <param name="color">The color to set.</param>
/// <summary> /// <returns>The same instance so that multiple calls can be chained.</returns>
/// Sets the color used for commas. public JsonText CommaColor(Color color)
/// </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)); ArgumentNullException.ThrowIfNull(text);
text.CommaStyle = new Style(color);
return text;
} }
text.CommaStyle = new Style(color); /// <summary>
return text; /// Sets the color used for string literals.
} /// </summary>
/// <param name="color">The color to set.</param>
/// <summary> /// <returns>The same instance so that multiple calls can be chained.</returns>
/// Sets the color used for string literals. public JsonText StringColor(Color color)
/// </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)); ArgumentNullException.ThrowIfNull(text);
text.StringStyle = new Style(color);
return text;
} }
text.StringStyle = new Style(color); /// <summary>
return text; /// Sets the color used for number literals.
} /// </summary>
/// <param name="color">The color to set.</param>
/// <summary> /// <returns>The same instance so that multiple calls can be chained.</returns>
/// Sets the color used for number literals. public JsonText NumberColor(Color color)
/// </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)); ArgumentNullException.ThrowIfNull(text);
text.NumberStyle = new Style(color);
return text;
} }
text.NumberStyle = new Style(color); /// <summary>
return text; /// Sets the color used for boolean literals.
} /// </summary>
/// <param name="color">The color to set.</param>
/// <summary> /// <returns>The same instance so that multiple calls can be chained.</returns>
/// Sets the color used for boolean literals. public JsonText BooleanColor(Color color)
/// </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)); ArgumentNullException.ThrowIfNull(text);
text.BooleanStyle = new Style(color);
return text;
} }
text.BooleanStyle = new Style(color); /// <summary>
return text; /// Sets the color used for <c>null</c> literals.
} /// </summary>
/// <param name="color">The color to set.</param>
/// <summary> /// <returns>The same instance so that multiple calls can be chained.</returns>
/// Sets the color used for <c>null</c> literals. public JsonText NullColor(Color color)
/// </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)); ArgumentNullException.ThrowIfNull(text);
}
text.NullStyle = new Style(color); text.NullStyle = new Style(color);
return text; return text;
}
} }
} }

View File

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

View File

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

View File

@@ -7,26 +7,29 @@ namespace DocExampleGenerator;
internal static class AnsiConsoleExtensions internal static class AnsiConsoleExtensions
{ {
/// <summary>
/// Displays something via AnsiConsole, waits a bit and then simulates typing based on the input. If the console
/// doesn't have the focus this will just type into whatever window does so watch the alt-tab.
/// </summary>
/// <param name="console"></param> /// <param name="console"></param>
/// <param name="action">The display action.</param> extension(IAnsiConsole console)
/// <param name="input">The characters to type. ↑ for an up arrow, ↓ for down arrow, ↲ for a return and ¦ for a pause.</param>
/// <param name="initialDelayMs">How long to delay before typing. This should be at least 100ms because we won't check if the prompt has displayed before simulating typing.</param>
/// <param name="keypressDelayMs">Delay between keypresses. There will be a bit of randomness between each keypress +/- 20% of this value.</param>
public static void DisplayThenType(this IAnsiConsole console, Action<IAnsiConsole> action, string input, int initialDelayMs = 500, int keypressDelayMs = 200)
{ {
if (console is not AsciiCastConsole asciiConsole) /// <summary>
/// Displays something via AnsiConsole, waits a bit and then simulates typing based on the input. If the console
/// doesn't have the focus this will just type into whatever window does so watch the alt-tab.
/// </summary>
/// <param name="action">The display action.</param>
/// <param name="input">The characters to type. ↑ for an up arrow, ↓ for down arrow, ↲ for a return and ¦ for a pause.</param>
/// <param name="initialDelayMs">How long to delay before typing. This should be at least 100ms because we won't check if the prompt has displayed before simulating typing.</param>
/// <param name="keypressDelayMs">Delay between keypresses. There will be a bit of randomness between each keypress +/- 20% of this value.</param>
public void DisplayThenType(Action<IAnsiConsole> action, string input, int initialDelayMs = 500, int keypressDelayMs = 200)
{ {
throw new InvalidOperationException("Not an ASCII cast console"); if (console is not AsciiCastConsole asciiConsole)
{
throw new InvalidOperationException("Not an ASCII cast console");
}
asciiConsole.Input.PushText(input, keypressDelayMs);
Thread.Sleep(initialDelayMs);
action(console);
} }
asciiConsole.Input.PushText(input, keypressDelayMs);
Thread.Sleep(initialDelayMs);
action(console);
} }
} }

View File

@@ -4,11 +4,14 @@ namespace Generator.Commands;
public static class AsciiCastExtensions public static class AsciiCastExtensions
{ {
public static AsciiCastOut WrapWithAsciiCastRecorder(this IAnsiConsole ansiConsole) extension(IAnsiConsole ansiConsole)
{ {
AsciiCastOut castRecorder = new(ansiConsole.Profile.Out); public AsciiCastOut WrapWithAsciiCastRecorder()
ansiConsole.Profile.Out = castRecorder; {
AsciiCastOut castRecorder = new(ansiConsole.Profile.Out);
ansiConsole.Profile.Out = castRecorder;
return castRecorder; return castRecorder;
}
} }
} }

View File

@@ -18,10 +18,7 @@ public sealed class AsciiCastInput : IAnsiConsoleInput
public void PushText(string input, int keypressDelayMs) public void PushText(string input, int keypressDelayMs)
{ {
if (input is null) ArgumentNullException.ThrowIfNull(input);
{
throw new ArgumentNullException(nameof(input));
}
foreach (var character in input) foreach (var character in input)
{ {

View File

@@ -1,7 +1,6 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using Generator.Commands.Samples; using Generator.Commands.Samples;
using Spectre.Console; using Spectre.Console;
using Spectre.Console.Extensions;
namespace Generator.Commands.AsciiCast.Samples; namespace Generator.Commands.AsciiCast.Samples;

15
src/Polyfills.cs Normal file
View File

@@ -0,0 +1,15 @@
#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> /// </summary>
public static class ShouldlyExtensions public static class ShouldlyExtensions
{ {
/// <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>
/// <param name="item">The object to operate on.</param> /// <param name="item">The object to operate on.</param>
/// <param name="action">An action to perform on the object.</param> /// <typeparam name="T">The type of the object.</typeparam>
/// <returns>The original object, to allow further chaining.</returns> extension<T>(T item)
/// <exception cref="ArgumentNullException">Thrown if <paramref name="action"/> is null.</exception>
[DebuggerStepThrough]
public static T And<T>(this T item, Action<T> action)
{ {
if (action == null) /// <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)
{ {
throw new ArgumentNullException(nameof(action)); ArgumentNullException.ThrowIfNull(action);
}
action(item); action(item);
return item; return item;
}
} }
} }

View File

@@ -5,40 +5,42 @@ namespace Spectre.Console.Testing;
/// </summary> /// </summary>
public static class StringExtensions 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> /// <param name="value">The string to trim.</param>
/// <returns>A new string with all lines trimmed of trailing whitespace.</returns> extension(string value)
public static string TrimLines(this string value)
{ {
if (value is null) /// <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)
{
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; 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,20 +5,23 @@ namespace Spectre.Console.Testing;
/// </summary> /// </summary>
public static class StyleExtensions public static class StyleExtensions
{ {
/// <summary>
/// Sets the foreground or background color of the specified style.
/// </summary>
/// <param name="style">The style.</param> /// <param name="style">The style.</param>
/// <param name="color">The color.</param> extension(Style style)
/// <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)
{ {
if (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)
{ {
return style.Foreground(color); if (foreground)
} {
return style.Foreground(color);
}
return style.Background(color); return style.Background(color);
}
} }
} }

View File

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

View File

@@ -10,5 +10,15 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Spectre.Console\Spectre.Console.csproj" /> <ProjectReference Include="..\Spectre.Console\Spectre.Console.csproj" />
</ItemGroup> </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> </Project>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -12,7 +12,7 @@
<File Path="Directory.Packages.props" /> <File Path="Directory.Packages.props" />
</Folder> </Folder>
<Folder Name="/Build/Generator/"> <Folder Name="/Build/Generator/">
<Project Path="Generator\Generator.csproj" Type="Classic C#"> <Project Path="Generator\Generator.csproj" Type="C#">
<Configuration Solution="Debug|x64" Project="Debug|Any CPU" /> <Configuration Solution="Debug|x64" Project="Debug|Any CPU" />
<Configuration Solution="Debug|x86" Project="Debug|Any CPU" /> <Configuration Solution="Debug|x86" Project="Debug|Any CPU" />
<Configuration Solution="Release|x64" Project="Release|Any CPU" /> <Configuration Solution="Release|x64" Project="Release|Any CPU" />

View File

@@ -1,29 +0,0 @@
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

@@ -1,17 +0,0 @@
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

@@ -1,141 +0,0 @@
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

@@ -1,25 +0,0 @@
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

@@ -1,123 +0,0 @@
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

@@ -1,66 +0,0 @@
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

@@ -1,31 +0,0 @@
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

@@ -1,16 +0,0 @@
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

@@ -1,62 +0,0 @@
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

@@ -1,249 +0,0 @@
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

@@ -1,269 +0,0 @@
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,7 +9,11 @@ public static partial class AnsiConsole
private static readonly AnsiConsoleFactory _factory = new AnsiConsoleFactory(); private static readonly AnsiConsoleFactory _factory = new AnsiConsoleFactory();
#pragma warning restore CS0618 #pragma warning restore CS0618
private static Recorder? _recorder; internal static Style CurrentStyle { get; set; } = Style.Plain;
internal static Recorder? Recorder { get; set; }
internal static bool Created { get; private set; }
private static Lazy<IAnsiConsole> _console = new Lazy<IAnsiConsole>( private static Lazy<IAnsiConsole> _console = new Lazy<IAnsiConsole>(
() => () =>
{ {
@@ -31,18 +35,12 @@ public static partial class AnsiConsole
{ {
get get
{ {
return _recorder ?? _console.Value; return Recorder ?? _console.Value;
} }
set set
{ {
_console = new Lazy<IAnsiConsole>(() => value); _console = new Lazy<IAnsiConsole>(() => value);
Recorder = Recorder?.Clone(value); // Recreate the recorder
if (_recorder != null)
{
// Recreate the recorder
_recorder = _recorder.Clone(value);
}
Created = true; Created = true;
} }
} }
@@ -50,7 +48,7 @@ public static partial class AnsiConsole
/// <summary> /// <summary>
/// Gets the <see cref="IAnsiConsoleCursor"/>. /// Gets the <see cref="IAnsiConsoleCursor"/>.
/// </summary> /// </summary>
public static IAnsiConsoleCursor Cursor => _recorder?.Cursor ?? _console.Value.Cursor; public static IAnsiConsoleCursor Cursor => Recorder?.Cursor ?? _console.Value.Cursor;
/// <summary> /// <summary>
/// Gets the console profile. /// Gets the console profile.
@@ -67,12 +65,4 @@ public static partial class AnsiConsole
{ {
return _factory.Create(settings); return _factory.Create(settings);
} }
/// <summary>
/// Clears the console.
/// </summary>
public static void Clear()
{
Console.Clear();
}
} }

View File

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

View File

@@ -16,4 +16,31 @@ public abstract partial class BoxBorder
/// <param name="part">The part to get the character representation for.</param> /// <param name="part">The part to get the character representation for.</param>
/// <returns>A character representation of the specified border part.</returns> /// <returns>A character representation of the specified border part.</returns>
public abstract string GetPart(BoxBorderPart part); 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,10 +220,7 @@ public partial struct Color : IEquatable<Color>
/// <returns>The color created from the hexadecimal string.</returns> /// <returns>The color created from the hexadecimal string.</returns>
public static Color FromHex(string hex) public static Color FromHex(string hex)
{ {
if (hex is null) ArgumentNullException.ThrowIfNull(hex);
{
throw new ArgumentNullException(nameof(hex));
}
if (hex.StartsWith("#")) if (hex.StartsWith("#"))
{ {

View File

@@ -19,15 +19,9 @@ public static partial class Emoji
/// <param name="emoji">The emoji.</param> /// <param name="emoji">The emoji.</param>
public static void Remap(string tag, string emoji) public static void Remap(string tag, string emoji)
{ {
if (tag is null) ArgumentNullException.ThrowIfNull(tag);
{
throw new ArgumentNullException(nameof(tag));
}
if (emoji is null) ArgumentNullException.ThrowIfNull(emoji);
{
throw new ArgumentNullException(nameof(emoji));
}
tag = tag.TrimStart(':').TrimEnd(':'); tag = tag.TrimStart(':').TrimEnd(':');
emoji = emoji.TrimStart(':').TrimEnd(':'); emoji = emoji.TrimStart(':').TrimEnd(':');
@@ -112,16 +106,4 @@ public static partial class Emoji
value = string.Empty; value = string.Empty;
return false; 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,10 +25,7 @@ internal static class ProfileEnricher
ProfileEnrichment settings, ProfileEnrichment settings,
IDictionary<string, string>? environmentVariables) IDictionary<string, string>? environmentVariables)
{ {
if (profile is null) ArgumentNullException.ThrowIfNull(profile);
{
throw new ArgumentNullException(nameof(profile));
}
settings ??= new ProfileEnrichment(); settings ??= new ProfileEnrichment();

View File

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

@@ -1,106 +0,0 @@
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

@@ -1,80 +0,0 @@
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

@@ -0,0 +1,53 @@
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

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

View File

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

View File

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

View File

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

View File

@@ -1,151 +1,279 @@
namespace Spectre.Console; namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="IAnsiConsole"/>.
/// </summary>
public static partial class AnsiConsoleExtensions public static partial class AnsiConsoleExtensions
{ {
/// <summary> extension(AnsiConsole)
/// Writes the specified markup to the console.
/// </summary>
/// <param name="console">The console to write to.</param>
/// <param name="format">A composite format string.</param>
/// <param name="args">An array of objects to write.</param>
public static void Markup(this IAnsiConsole console, string format, params object[] args)
{ {
Markup(console, CultureInfo.CurrentCulture, format, args); /// <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.
/// </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)
{
AnsiConsole.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)
{
AnsiConsole.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)
{
AnsiConsole.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)
{
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.
/// </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)
{
AnsiConsole.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)
{
AnsiConsole.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)
{
AnsiConsole.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)
{
AnsiConsole.Console.MarkupLineInterpolated(provider, 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="console">The console to write to.</param> /// <param name="console">The console to write to.</param>
/// <param name="value">The interpolated string value to write.</param> extension(IAnsiConsole console)
public static void MarkupInterpolated(this IAnsiConsole console, FormattableString value)
{ {
MarkupInterpolated(console, CultureInfo.CurrentCulture, 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 void Markup(string format, params object[] args)
{
Markup(console, CultureInfo.CurrentCulture, format, args);
}
/// <summary> /// <summary>
/// Writes the specified markup to the console. /// Writes the specified markup to the console.
/// </summary> /// <para/>
/// <param name="console">The console to write to.</param> /// All interpolation holes which contain a string are automatically escaped so you must not call <see cref="StringExtensions.EscapeMarkup"/>.
/// <param name="provider">An object that supplies culture-specific formatting information.</param> /// </summary>
/// <param name="format">A composite format string.</param> /// <example>
/// <param name="args">An array of objects to write.</param> /// <code>
public static void Markup(this IAnsiConsole console, IFormatProvider provider, string format, params object[] args) /// string input = args[0];
{ /// string output = Process(input);
Markup(console, string.Format(provider, format, args)); /// 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> /// <summary>
/// Writes the specified markup to the console. /// Writes the specified markup to the console.
/// <para/> /// </summary>
/// All interpolation holes which contain a string are automatically escaped so you must not call <see cref="StringExtensions.EscapeMarkup"/>. /// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// </summary> /// <param name="format">A composite format string.</param>
/// <example> /// <param name="args">An array of objects to write.</param>
/// <code> public void Markup(IFormatProvider provider, string format, params object[] args)
/// string input = args[0]; {
/// string output = Process(input); Markup(console, string.Format(provider, format, args));
/// 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> /// <summary>
/// Writes the specified markup to the console. /// Writes the specified markup to the console.
/// </summary> /// <para/>
/// <param name="console">The console to write to.</param> /// All interpolation holes which contain a string are automatically escaped so you must not call <see cref="StringExtensions.EscapeMarkup"/>.
/// <param name="value">The value to write.</param> /// </summary>
public static void Markup(this IAnsiConsole console, string value) /// <example>
{ /// <code>
console.Write(MarkupParser.Parse(value)); /// 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> /// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console. /// Writes the specified markup to the console.
/// </summary> /// </summary>
/// <param name="console">The console to write to.</param> /// <param name="value">The value to write.</param>
/// <param name="format">A composite format string.</param> public void Markup(string value)
/// <param name="args">An array of objects to write.</param> {
public static void MarkupLine(this IAnsiConsole console, string format, params object[] args) console.Write(MarkupParser.Parse(value));
{ }
MarkupLine(console, CultureInfo.CurrentCulture, format, args);
}
/// <summary> /// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console. /// Writes the specified markup, followed by the current line terminator, to the console.
/// <para/> /// </summary>
/// All interpolation holes which contain a string are automatically escaped so you must not call <see cref="StringExtensions.EscapeMarkup"/>. /// <param name="format">A composite format string.</param>
/// </summary> /// <param name="args">An array of objects to write.</param>
/// <example> public void MarkupLine(string format, params object[] args)
/// <code> {
/// string input = args[0]; MarkupLine(console, CultureInfo.CurrentCulture, format, args);
/// 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> /// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console. /// Writes the specified markup, followed by the current line terminator, to the console.
/// </summary> /// <para/>
/// <param name="console">The console to write to.</param> /// All interpolation holes which contain a string are automatically escaped so you must not call <see cref="StringExtensions.EscapeMarkup"/>.
/// <param name="value">The value to write.</param> /// </summary>
public static void MarkupLine(this IAnsiConsole console, string value) /// <example>
{ /// <code>
Markup(console, value + Environment.NewLine); /// 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> /// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console. /// Writes the specified markup, followed by the current line terminator, to the console.
/// </summary> /// </summary>
/// <param name="console">The console to write to.</param> /// <param name="value">The value to write.</param>
/// <param name="provider">An object that supplies culture-specific formatting information.</param> public void MarkupLine(string value)
/// <param name="format">A composite format string.</param> {
/// <param name="args">An array of objects to write.</param> Markup(console, value + Environment.NewLine);
public static void MarkupLine(this IAnsiConsole console, IFormatProvider provider, string format, params object[] args) }
{
Markup(console, provider, format + Environment.NewLine, args);
}
/// <summary> /// <summary>
/// Writes the specified markup, followed by the current line terminator, to the console. /// Writes the specified markup, followed by the current line terminator, to the console.
/// <para/> /// </summary>
/// All interpolation holes which contain a string are automatically escaped so you must not call <see cref="StringExtensions.EscapeMarkup"/>. /// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// </summary> /// <param name="format">A composite format string.</param>
/// <example> /// <param name="args">An array of objects to write.</param>
/// <code> public void MarkupLine(IFormatProvider provider, string format, params object[] args)
/// string input = args[0]; {
/// string output = Process(input); Markup(console, provider, format + Environment.NewLine, args);
/// console.MarkupLineInterpolated(CultureInfo.InvariantCulture, $"[blue]{input}[/] -> [green]{output}[/]"); }
/// </code>
/// </example> /// <summary>
/// <param name="console">The console to write to.</param> /// Writes the specified markup, followed by the current line terminator, to the console.
/// <param name="provider">An object that supplies culture-specific formatting information.</param> /// <para/>
/// <param name="value">The interpolated string value to write.</param> /// All interpolation holes which contain a string are automatically escaped so you must not call <see cref="StringExtensions.EscapeMarkup"/>.
public static void MarkupLineInterpolated(this IAnsiConsole console, IFormatProvider provider, FormattableString value) /// </summary>
{ /// <example>
MarkupLine(console, Console.Markup.EscapeInterpolated(provider, value)); /// <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));
}
} }
} }

View File

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

View File

@@ -1,131 +1,233 @@
namespace Spectre.Console; namespace Spectre.Console;
/// <summary>
/// Contains extension methods for <see cref="IAnsiConsole"/>.
/// </summary>
public static partial class AnsiConsoleExtensions public static partial class AnsiConsoleExtensions
{ {
/// <summary> extension(AnsiConsole)
/// 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)
{ {
if (prompt is null) /// <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)
{ {
throw new ArgumentNullException(nameof(prompt)); ArgumentNullException.ThrowIfNull(prompt);
return prompt.Show(AnsiConsole.Console);
} }
return prompt.Show(console); /// <summary>
} /// Displays a prompt to the user.
/// </summary>
/// <summary> /// <typeparam name="T">The prompt result type.</typeparam>
/// Displays a prompt to the user. /// <param name="prompt">The prompt to display.</param>
/// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <typeparam name="T">The prompt result type.</typeparam> /// <returns>The prompt input result.</returns>
/// <param name="console">The console.</param> public static Task<T> PromptAsync<T>(IPrompt<T> prompt, CancellationToken cancellationToken = default)
/// <param name="prompt">The prompt markup text.</param>
/// <returns>The prompt input result.</returns>
public static T Ask<T>(this IAnsiConsole console, 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="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, ArgumentNullException.ThrowIfNull(prompt);
}
.Show(console);
}
/// <summary> return prompt.ShowAsync(AnsiConsole.Console, cancellationToken);
/// 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));
} }
return prompt.ShowAsync(console, cancellationToken); /// <summary>
} /// Displays a prompt to the user.
/// </summary>
/// <summary> /// <typeparam name="T">The prompt result type.</typeparam>
/// Displays a prompt to the user. /// <param name="prompt">The prompt markup text.</param>
/// </summary> /// <returns>The prompt input result.</returns>
/// <typeparam name="T">The prompt result type.</typeparam> public static T Ask<T>(string prompt)
/// <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 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 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)
{ {
DefaultValue = defaultValue, 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);
}
}
/// <param name="console">The console.</param>
extension(IAnsiConsole 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>
/// <returns>The prompt input result.</returns>
public T Prompt<T>(IPrompt<T> prompt)
{
ArgumentNullException.ThrowIfNull(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 markup text.</param>
/// <returns>The prompt input result.</returns>
public 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="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 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="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)
{
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);
} }
.ShowAsync(console, cancellationToken);
} }
} }

View File

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

View File

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

View File

@@ -0,0 +1,65 @@
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

@@ -0,0 +1,272 @@
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)
{
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);
}
}
/// <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)
{
AnsiConsole.Console.Write(string.Format(provider, format, args), 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

@@ -0,0 +1,302 @@
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();
}
/// <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)
{
AnsiConsole.Console.WriteLine(string.Format(provider, format, args), AnsiConsole.CurrentStyle);
}
}
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,103 +5,28 @@ namespace Spectre.Console;
/// </summary> /// </summary>
public static partial class AnsiConsoleExtensions public static partial class AnsiConsoleExtensions
{ {
/// <summary> extension(AnsiConsole)
/// Creates a recorder for the specified console. {
/// </summary> /// <summary>
/// Clears the console.
/// </summary>
public static void Clear()
{
AnsiConsole.Console.Clear();
}
}
/// <param name="console">The console to record.</param> /// <param name="console">The console to record.</param>
/// <returns>A recorder for the specified console.</returns> extension(IAnsiConsole console)
public static Recorder CreateRecorder(this IAnsiConsole console)
{ {
return new Recorder(console); /// <summary>
} /// Clears the console.
/// </summary>
/// <summary> public void Clear()
/// Clears the console.
/// </summary>
/// <param name="console">The console to clear.</param>
public static void Clear(this IAnsiConsole console)
{
if (console is null)
{ {
throw new ArgumentNullException(nameof(console)); ArgumentNullException.ThrowIfNull(console);
console.Clear(true);
} }
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

@@ -1,292 +0,0 @@
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

@@ -0,0 +1,27 @@
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

@@ -0,0 +1,26 @@
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

@@ -0,0 +1,13 @@
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

@@ -6,10 +6,7 @@ internal static class EnumerableExtensions
// so we won't have to cast List<T> to IEnumerable<T>. // so we won't have to cast List<T> to IEnumerable<T>.
public static IEnumerable<T> ReverseEnumerable<T>(this IEnumerable<T> source) public static IEnumerable<T> ReverseEnumerable<T>(this IEnumerable<T> source)
{ {
if (source is null) ArgumentNullException.ThrowIfNull(source);
{
throw new ArgumentNullException(nameof(source));
}
return source.Reverse(); return source.Reverse();
} }
@@ -76,20 +73,14 @@ internal static class EnumerableExtensions
public static IEnumerable<(int Index, bool First, bool Last, T Item)> Enumerate<T>(this IEnumerable<T> source) public static IEnumerable<(int Index, bool First, bool Last, T Item)> Enumerate<T>(this IEnumerable<T> source)
{ {
if (source is null) ArgumentNullException.ThrowIfNull(source);
{
throw new ArgumentNullException(nameof(source));
}
return Enumerate(source.GetEnumerator()); return Enumerate(source.GetEnumerator());
} }
public static IEnumerable<(int Index, bool First, bool Last, T Item)> Enumerate<T>(this IEnumerator<T> source) public static IEnumerable<(int Index, bool First, bool Last, T Item)> Enumerate<T>(this IEnumerator<T> source)
{ {
if (source is null) ArgumentNullException.ThrowIfNull(source);
{
throw new ArgumentNullException(nameof(source));
}
var first = true; var first = true;
var last = !source.MoveNext(); var last = !source.MoveNext();

View File

@@ -0,0 +1,42 @@
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

@@ -0,0 +1,22 @@
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

@@ -0,0 +1,31 @@
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

@@ -0,0 +1,19 @@
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

@@ -0,0 +1,20 @@
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

@@ -0,0 +1,42 @@
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

@@ -0,0 +1,332 @@
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

@@ -0,0 +1,31 @@
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

@@ -1,28 +0,0 @@
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

@@ -1,317 +0,0 @@
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

@@ -1,133 +0,0 @@
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

@@ -1,17 +0,0 @@
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

@@ -1,44 +0,0 @@
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

@@ -1,166 +0,0 @@
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

@@ -1,151 +0,0 @@
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

@@ -1,23 +0,0 @@
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

@@ -1,10 +0,0 @@
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

@@ -1,49 +0,0 @@
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

@@ -1,44 +0,0 @@
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

@@ -1,24 +0,0 @@
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

@@ -1,112 +0,0 @@
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

@@ -1,81 +0,0 @@
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

@@ -1,98 +0,0 @@
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

@@ -1,62 +0,0 @@
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

@@ -1,80 +0,0 @@
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

@@ -1,242 +0,0 @@
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

@@ -1,211 +0,0 @@
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

@@ -1,19 +0,0 @@
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

@@ -1,58 +0,0 @@
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

@@ -1,34 +0,0 @@
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

@@ -1,62 +0,0 @@
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

@@ -1,77 +0,0 @@
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

@@ -1,128 +0,0 @@
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;
}
}

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