Skip to content

A Swiss Army knife for developers.

Ported Text Utilities tool to DevToys 2.0 + More UI fixes (#985)

Etienne BAUDOUXf6403642b436
diff --git a/src/app/dev/DevToys.Api/TextSpan.cs b/src/app/dev/DevToys.Api/TextSpan.cs
index 50340548a..e4b9e93a0 100644
--- a/src/app/dev/DevToys.Api/TextSpan.cs
+++ b/src/app/dev/DevToys.Api/TextSpan.cs
@@ -32,4 +32,17 @@ public record TextSpan
/// Gets the end position of the span.
/// </summary>
public int EndPosition => StartPosition + Length;
+
+ /// <summary>
+ /// Creates a new <see cref="TextSpan"/> from the given start and end positions.
+ /// </summary>
+ /// <param name="start">The position at which the span starts.</param>
+ /// <param name="end">The position at which the span ends.</param>
+ public static TextSpan FromBounds(int start, int end)
+ {
+ Guard.IsGreaterThanOrEqualTo(start, 0);
+ Guard.IsGreaterThanOrEqualTo(end, 0);
+ Guard.IsGreaterThanOrEqualTo(end, start);
+ return new TextSpan(start, end - start);
+ }
}
diff --git a/src/app/dev/DevToys.Blazor/Components/Layout/Container/Container.razor.cs b/src/app/dev/DevToys.Blazor/Components/Layout/Container/Container.razor.cs
index 551dd1a23..51ca23a4b 100644
--- a/src/app/dev/DevToys.Blazor/Components/Layout/Container/Container.razor.cs
+++ b/src/app/dev/DevToys.Blazor/Components/Layout/Container/Container.razor.cs
@@ -68,7 +68,7 @@ public partial class Container : StyledComponentBase
{
case UIVerticalAlignment.Stretch:
styleBuilder.AddImportantStyle("align-items", "stretch");
- styleBuilder.AddImportantStyle("height", "100%", !Height.HasValue);
+ styleBuilder.AddStyle("height", "100%", !Height.HasValue);
innerStyleBuilder.AddImportantStyle("max-height", "inherit", !Height.HasValue);
innerStyleBuilder.AddImportantStyle("height", "100%", !Height.HasValue);
innerStyleBuilder.AddImportantStyle("min-height", "min-content", !Height.HasValue);
diff --git a/src/app/dev/DevToys.Blazor/Components/Layout/Grid/GridCell.razor b/src/app/dev/DevToys.Blazor/Components/Layout/Grid/GridCell.razor
index dfa2d1409..2b66998cb 100644
--- a/src/app/dev/DevToys.Blazor/Components/Layout/Grid/GridCell.razor
+++ b/src/app/dev/DevToys.Blazor/Components/Layout/Grid/GridCell.razor
@@ -1,8 +1,9 @@
@namespace DevToys.Blazor.Components
-@inherits ComponentBase
+@inherits StyledComponentBase
<Container HorizontalAlignment="@UIHorizontalAlignment.Stretch"
VerticalAlignment="@UIVerticalAlignment.Stretch"
- Style="@GridCellStyleValue">
+ Style="@GridCellStyleValue"
+ Class="@FinalCssClasses">
@ChildContent
</Container>
\ No newline at end of file
diff --git a/src/app/dev/DevToys.Blazor/Components/Layout/Grid/GridCell.razor.cs b/src/app/dev/DevToys.Blazor/Components/Layout/Grid/GridCell.razor.cs
index 30233e7df..2eb01eeef 100644
--- a/src/app/dev/DevToys.Blazor/Components/Layout/Grid/GridCell.razor.cs
+++ b/src/app/dev/DevToys.Blazor/Components/Layout/Grid/GridCell.razor.cs
@@ -2,7 +2,7 @@
namespace DevToys.Blazor.Components;
-public partial class GridCell : ComponentBase
+public partial class GridCell : StyledComponentBase
{
protected string? GridCellStyleValue => new StyleBuilder()
.AddStyle("grid-column", $"{Column + 1}", ColumnSpan <= 1)
diff --git a/src/app/dev/DevToys.Blazor/Components/UIElements/UIDataGridPresenter.razor b/src/app/dev/DevToys.Blazor/Components/UIElements/UIDataGridPresenter.razor
index 93ac9f281..4509036d2 100644
--- a/src/app/dev/DevToys.Blazor/Components/UIElements/UIDataGridPresenter.razor
+++ b/src/app/dev/DevToys.Blazor/Components/UIElements/UIDataGridPresenter.razor
@@ -18,7 +18,7 @@
{
new UIGridLength(1, UIGridUnitType.Fraction)
})">
- <GridCell Row="0" Column="0">
+ <GridCell Row="0" Column="0" Class="ui-data-grid-presenter-title">
<TextBlock Text="@UIDataGrid.Title"
NoWrap="true"
CanTrim="true" />
diff --git a/src/app/dev/DevToys.Blazor/Components/UIElements/UIDataGridPresenter.razor.scss b/src/app/dev/DevToys.Blazor/Components/UIElements/UIDataGridPresenter.razor.scss
new file mode 100644
index 000000000..61d27573c
--- /dev/null
+++ b/src/app/dev/DevToys.Blazor/Components/UIElements/UIDataGridPresenter.razor.scss
@@ -0,0 +1,16 @@
+.ui-data-grid-presenter {
+ &-title {
+ height: 20px !important;
+ margin-top: 14px;
+ }
+}
+
+// Compact mode
+div[data-compactmode] {
+ .ui-data-grid-presenter {
+ &-title {
+ height: 20px !important;
+ margin-top: 7px;
+ }
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj b/src/app/dev/DevToys.Tools/DevToys.Tools.csproj
index 901fb94fa..c74d45a7e 100644
--- a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj
+++ b/src/app/dev/DevToys.Tools/DevToys.Tools.csproj
@@ -104,6 +104,11 @@
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
</Compile>
+ <Compile Update="Tools\Text\AnalyzerAndUtilities\AnalyzerAndUtilities.Designer.cs">
+ <DesignTime>True</DesignTime>
+ <AutoGen>True</AutoGen>
+ <DependentUpon>AnalyzerAndUtilities.resx</DependentUpon>
+ </Compile>
<Compile Update="Tools\Text\Compare\TextCompare.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
@@ -181,6 +186,10 @@
<LastGenOutput>Test.Designer.cs</LastGenOutput>
<Generator>ResXFileCodeGenerator</Generator>
</EmbeddedResource>
+ <EmbeddedResource Update="Tools\Text\AnalyzerAndUtilities\AnalyzerAndUtilities.resx">
+ <Generator>ResXFileCodeGenerator</Generator>
+ <LastGenOutput>AnalyzerAndUtilities.Designer.cs</LastGenOutput>
+ </EmbeddedResource>
<EmbeddedResource Update="Tools\Text\Compare\TextCompare.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>TextCompare.Designer.cs</LastGenOutput>
diff --git a/src/app/dev/DevToys.Tools/Helpers/Core/CustomReadOnlyMemoryOfCharComparer.cs b/src/app/dev/DevToys.Tools/Helpers/Core/CustomReadOnlyMemoryOfCharComparer.cs
new file mode 100644
index 000000000..4955b5d31
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Helpers/Core/CustomReadOnlyMemoryOfCharComparer.cs
@@ -0,0 +1,19 @@
+namespace DevToys.Tools.Helpers.Core;
+
+internal delegate int ReadOnlyMemoryOfCharComparerDelegate(ReadOnlyMemory<char> x, ReadOnlyMemory<char> y);
+
+internal sealed class CustomReadOnlyMemoryOfCharComparer : IComparer<ReadOnlyMemory<char>>
+{
+ private readonly ReadOnlyMemoryOfCharComparerDelegate _compareDelegate;
+
+ internal CustomReadOnlyMemoryOfCharComparer(ReadOnlyMemoryOfCharComparerDelegate compareDelegate)
+ {
+ Guard.IsNotNull(compareDelegate);
+ _compareDelegate = compareDelegate;
+ }
+
+ public int Compare(ReadOnlyMemory<char> x, ReadOnlyMemory<char> y)
+ {
+ return _compareDelegate(x, y);
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Helpers/MemoryExtensions.cs b/src/app/dev/DevToys.Tools/Helpers/MemoryExtensions.cs
new file mode 100644
index 000000000..c80e17589
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Helpers/MemoryExtensions.cs
@@ -0,0 +1,135 @@
+using System.Text;
+using DevToys.Tools.Models;
+
+namespace DevToys.Tools.Helpers;
+
+internal static class MemoryExtensions
+{
+ /// <summary>
+ /// Detects whether the given location in a span of characters is a line break.
+ /// </summary>
+ internal static bool IsLineBreak(this Span<char> span, int i, out EndOfLineSequence lineBreakType)
+ {
+ return ((ReadOnlySpan<char>)span).IsLineBreak(i, out lineBreakType);
+ }
+
+ /// <summary>
+ /// Detects whether the given location in a span of characters is a line break.
+ /// </summary>
+ internal static bool IsLineBreak(this ReadOnlySpan<char> span, int i, out EndOfLineSequence lineBreakType)
+ {
+ if (i < span.Length)
+ {
+ char c1 = span[i];
+ if (c1 == '\n')
+ {
+ lineBreakType = EndOfLineSequence.LineFeed;
+ return true;
+ }
+
+ if (c1 == '\r')
+ {
+ if (i < span.Length - 1 && span[i + 1] == '\n')
+ {
+ lineBreakType = EndOfLineSequence.CarriageReturnLineFeed;
+ }
+ else
+ {
+ lineBreakType = EndOfLineSequence.CarriageReturn;
+ }
+
+ return true;
+ }
+ }
+
+ lineBreakType = EndOfLineSequence.Unknown;
+ return false;
+ }
+
+ /// <summary>
+ /// Gets the last word in a span of characters. This takes into account the fact that the last word may be before a word delimiter.
+ /// For example, in the sentence "Hello world.", the last word is "world", but the last character is a dot.
+ /// </summary>
+ /// <param name="span"></param>
+ /// <returns></returns>
+ internal static ReadOnlySpan<char> GetLastWord(this ReadOnlySpan<char> span)
+ {
+ if (span.IsEmpty)
+ {
+ return span;
+ }
+
+ // Find the last word. We start reading the span from the end, and stop when we find a word delimiter such as a dot or whitespace.
+ // If the last character of the span is a word delimiter, we slice the span from the index before the last delimiter.
+ int spanEndOfLastWord = -1;
+ int spanBeginningOfLastWord = -1;
+ for (int i = span.Length - 1; i >= 0; i--)
+ {
+ if (spanEndOfLastWord == -1)
+ {
+ if (char.IsLetterOrDigit(span[i]))
+ {
+ spanEndOfLastWord = i + 1;
+ }
+ }
+ else if (!char.IsLetterOrDigit(span[i]))
+ {
+ spanBeginningOfLastWord = i + 1;
+ break;
+ }
+ else
+ {
+ spanBeginningOfLastWord = i;
+ }
+ }
+
+ if (spanBeginningOfLastWord == -1 || spanEndOfLastWord == -1)
+ {
+ spanBeginningOfLastWord = 0;
+ spanEndOfLastWord = 0;
+ }
+
+ return span.Slice(spanBeginningOfLastWord, spanEndOfLastWord - spanBeginningOfLastWord);
+ }
+
+ /// <summary>
+ /// Splits the given span of characters into lines.
+ /// </summary>
+ internal static List<ReadOnlyMemory<char>> ToLines(this ReadOnlyMemory<char> span)
+ {
+ // Split text by lines.
+ var lines = new List<ReadOnlyMemory<char>>();
+
+ SpanLineEnumerator lineEnumerator = span.Span.EnumerateLines(); // This supports every kind of line break.
+
+ while (lineEnumerator.MoveNext())
+ {
+ ReadOnlySpan<char> line = lineEnumerator.Current;
+ char[] lineBuffer = new char[line.Length];
+ line.CopyTo(lineBuffer);
+ lines.Add(lineBuffer);
+ }
+
+ return lines;
+ }
+
+ /// <summary>
+ /// Rebuilds a string from a list of lines.
+ /// </summary>
+ internal static string BuildStringFromListOfLines(this IReadOnlyList<ReadOnlyMemory<char>> lines, EndOfLineSequence endOfLineSequence)
+ {
+ var stringBuilder = new StringBuilder();
+ string endOfLineSequenceString = endOfLineSequence.ToLineBreakCharacters();
+
+ for (int i = 0; i < lines.Count; i++)
+ {
+ stringBuilder.Append(lines[i].Span);
+ if (i < lines.Count - 1)
+ {
+ stringBuilder.Append(endOfLineSequenceString);
+ }
+ }
+
+ return stringBuilder.ToString();
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Helpers/StringHelper.cs b/src/app/dev/DevToys.Tools/Helpers/StringHelper.cs
new file mode 100644
index 000000000..24ac401bc
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Helpers/StringHelper.cs
@@ -0,0 +1,714 @@
+using System.Text;
+using System.Text.RegularExpressions;
+using DevToys.Tools.Helpers.Core;
+using DevToys.Tools.Models;
+
+namespace DevToys.Tools.Helpers;
+
+internal static class StringHelper
+{
+ private static readonly Random random = new();
+
+ internal static string SortLinesAlphabetically(string text, EndOfLineSequence endOfLineSequence)
+ {
+ return SortLines(
+ text,
+ lineComparer: (ReadOnlyMemory<char> x, ReadOnlyMemory<char> y) // Order alphabetically.
+ => System.MemoryExtensions.CompareTo(x.Span, y.Span, StringComparison.CurrentCulture),
+ endOfLineSequence);
+ }
+
+ internal static string SortLinesAlphabeticallyDescending(string text, EndOfLineSequence endOfLineSequence)
+ {
+ return SortLines(
+ text,
+ lineComparer: (ReadOnlyMemory<char> x, ReadOnlyMemory<char> y) // Order reversed alphabetically.
+ => System.MemoryExtensions.CompareTo(y.Span, x.Span, StringComparison.CurrentCulture),
+ endOfLineSequence);
+ }
+
+ internal static string SortLinesByLastWord(string text, EndOfLineSequence endOfLineSequence)
+ {
+ return SortLines(
+ text,
+ lineComparer: (ReadOnlyMemory<char> x, ReadOnlyMemory<char> y) => // Order alphabetically from the end of the line.
+ {
+ ReadOnlySpan<char> span1LastWord = x.Span.GetLastWord();
+ ReadOnlySpan<char> span2LastWord = y.Span.GetLastWord();
+
+ return System.MemoryExtensions.CompareTo(span1LastWord, span2LastWord, StringComparison.CurrentCulture);
+ },
+ endOfLineSequence);
+ }
+
+ internal static string SortLinesByLastWordDescending(string text, EndOfLineSequence endOfLineSequence)
+ {
+ return SortLines(
+ text,
+ lineComparer: (ReadOnlyMemory<char> x, ReadOnlyMemory<char> y) => // Order alphabetically from the end of the line.
+ {
+ ReadOnlySpan<char> span1LastWord = x.Span.GetLastWord();
+ ReadOnlySpan<char> span2LastWord = y.Span.GetLastWord();
+
+ return System.MemoryExtensions.CompareTo(span2LastWord, span1LastWord, StringComparison.CurrentCulture);
+ },
+ endOfLineSequence);
+ }
+
+ internal static string ReverseLines(string text, EndOfLineSequence endOfLineSequence)
+ {
+ if (string.IsNullOrEmpty(text))
+ {
+ return text;
+ }
+
+ // Split text by lines.
+ List<ReadOnlyMemory<char>> lines = text.AsMemory().ToLines();
+
+ // Reverse the order of the list.
+ lines.Reverse();
+
+ // Rebuilt the text.
+ return lines.BuildStringFromListOfLines(endOfLineSequence);
+ }
+
+ internal static string ShuffleLines(string text, EndOfLineSequence endOfLineSequence)
+ {
+ return SortLines(
+ text,
+ lineComparer: (ReadOnlyMemory<char> x, ReadOnlyMemory<char> y) => // Order randomly.
+ {
+ return random.Next(-1, 1);
+ },
+ endOfLineSequence);
+ }
+
+ internal static string ConvertLineBreakToLF(string text)
+ {
+ Guard.IsNotNull(text);
+ return Regex.Replace(text, @"\r\n?|\n", "\n");
+ }
+
+ internal static string ConvertLineBreakToCRLF(string text)
+ {
+ Guard.IsNotNull(text);
+ return Regex.Replace(text, @"\r\n?|\n", "\r\n");
+ }
+
+ internal static string ConvertToSentenceCase(string text, CancellationToken cancellationToken)
+ {
+ Guard.IsNotNull(text);
+ if (text.Length == 0)
+ {
+ return text;
+ }
+
+ var sentenceCaseString = new Memory<char>(text.ToCharArray());
+ bool newSentence = true;
+ for (int i = 0; i < sentenceCaseString.Length; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ EndOfLineSequence lineBreakType = EndOfLineSequence.Unknown;
+ if (IsSentenceTerminator(sentenceCaseString.Span[i]) || sentenceCaseString.Span.IsLineBreak(i, out lineBreakType))
+ {
+ newSentence = true;
+ if (lineBreakType == EndOfLineSequence.CarriageReturnLineFeed)
+ {
+ i++;
+ }
+ continue;
+ }
+
+ if (char.IsLetterOrDigit(sentenceCaseString.Span[i]))
+ {
+ if (newSentence)
+ {
+ sentenceCaseString.Span[i] = char.ToUpperInvariant(sentenceCaseString.Span[i]);
+ newSentence = false;
+ }
+ else
+ {
+ sentenceCaseString.Span[i] = char.ToLowerInvariant(sentenceCaseString.Span[i]);
+ }
+ }
+ }
+
+ return new string(sentenceCaseString.Span);
+ }
+
+ internal static string ConvertToTitleCase(string text, CancellationToken cancellationToken)
+ {
+ Guard.IsNotNull(text);
+ if (text.Length == 0)
+ {
+ return text;
+ }
+
+ var titleCaseString = new Memory<char>(text.ToCharArray());
+
+ for (int i = 0; i < titleCaseString.Length; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ if (i == 0
+ || !char.IsLetterOrDigit(titleCaseString.Span[i - 1]))
+ {
+ titleCaseString.Span[i] = char.ToUpperInvariant(titleCaseString.Span[i]);
+ }
+ else
+ {
+ titleCaseString.Span[i] = char.ToLowerInvariant(titleCaseString.Span[i]);
+ }
+ }
+
+ return new string(titleCaseString.Span);
+ }
+
+ internal static string ConvertToCamelCase(string text, CancellationToken cancellationToken)
+ {
+ Guard.IsNotNull(text);
+ if (text.Length == 0)
+ {
+ return text;
+ }
+
+ var camelCaseStringBuilder = new StringBuilder();
+ bool nextLetterOrDigitShouldBeUppercase = false;
+
+ ReadOnlySpan<char> span = text.AsSpan();
+ for (int i = 0; i < span.Length; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ char currentChar = span[i];
+ if (char.IsLetterOrDigit(currentChar))
+ {
+ if (nextLetterOrDigitShouldBeUppercase)
+ {
+ camelCaseStringBuilder.Append(char.ToUpperInvariant(currentChar));
+ nextLetterOrDigitShouldBeUppercase = false;
+ }
+ else
+ {
+ camelCaseStringBuilder.Append(char.ToLowerInvariant(currentChar));
+ }
+ }
+ else
+ {
+ if (span.IsLineBreak(i, out EndOfLineSequence lineBreakType))
+ {
+ nextLetterOrDigitShouldBeUppercase = false;
+ camelCaseStringBuilder.Append(currentChar);
+ if (lineBreakType == EndOfLineSequence.CarriageReturnLineFeed)
+ {
+ i++;
+ currentChar = span[i];
+ camelCaseStringBuilder.Append(currentChar);
+ }
+ }
+ else
+ {
+ nextLetterOrDigitShouldBeUppercase = true;
+ }
+ }
+ }
+
+ return camelCaseStringBuilder.ToString();
+ }
+
+ internal static string ConvertToPascalCase(string text, CancellationToken cancellationToken)
+ {
+ Guard.IsNotNull(text);
+ if (text.Length == 0)
+ {
+ return text;
+ }
+
+ var pascalCaseStringBuilder = new StringBuilder();
+ bool nextLetterOrDigitShouldBeUppercase = true;
+
+ ReadOnlySpan<char> span = text.AsSpan();
+ for (int i = 0; i < span.Length; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ char currentChar = span[i];
+ if (char.IsLetterOrDigit(currentChar))
+ {
+ if (nextLetterOrDigitShouldBeUppercase)
+ {
+ pascalCaseStringBuilder.Append(char.ToUpperInvariant(currentChar));
+ nextLetterOrDigitShouldBeUppercase = false;
+ }
+ else
+ {
+ pascalCaseStringBuilder.Append(char.ToLowerInvariant(currentChar));
+ }
+ }
+ else
+ {
+ nextLetterOrDigitShouldBeUppercase = true;
+ if (span.IsLineBreak(i, out EndOfLineSequence lineBreakType))
+ {
+ pascalCaseStringBuilder.Append(currentChar);
+ if (lineBreakType == EndOfLineSequence.CarriageReturnLineFeed)
+ {
+ i++;
+ currentChar = span[i];
+ pascalCaseStringBuilder.Append(currentChar);
+ }
+ }
+ }
+ }
+
+ return pascalCaseStringBuilder.ToString();
+ }
+
+ internal static string ConvertToSnakeCase(string text, CancellationToken cancellationToken)
+ {
+ return SnakeConstantKebabCobolCaseConverter(text, '_', isUpperCase: false, cancellationToken);
+ }
+
+ internal static string ConvertToConstantCase(string text, CancellationToken cancellationToken)
+ {
+ return SnakeConstantKebabCobolCaseConverter(text, '_', isUpperCase: true, cancellationToken);
+ }
+
+ internal static string ConvertToKebabCase(string text, CancellationToken cancellationToken)
+ {
+ return SnakeConstantKebabCobolCaseConverter(text, '-', isUpperCase: false, cancellationToken);
+ }
+
+ internal static string ConvertToCobolCase(string text, CancellationToken cancellationToken)
+ {
+ return SnakeConstantKebabCobolCaseConverter(text, '-', isUpperCase: true, cancellationToken);
+ }
+
+ internal static string ConvertToTrainCase(string text, CancellationToken cancellationToken)
+ {
+ Guard.IsNotNull(text);
+ if (text.Length == 0)
+ {
+ return text;
+ }
+
+ var snakeCaseStringBuilder = new StringBuilder();
+ ReadOnlySpan<char> span = text.AsSpan();
+
+ bool nextNonLetterOrDigitShouldBeIgnored = true;
+ for (int i = 0; i < span.Length; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ char currentChar = span[i];
+ if (char.IsLetterOrDigit(currentChar))
+ {
+ if (nextNonLetterOrDigitShouldBeIgnored)
+ {
+ snakeCaseStringBuilder.Append(char.ToUpperInvariant(currentChar));
+ }
+ else
+ {
+ snakeCaseStringBuilder.Append(char.ToLowerInvariant(currentChar));
+ }
+ nextNonLetterOrDigitShouldBeIgnored = false;
+ }
+ else if (span.IsLineBreak(i, out EndOfLineSequence lineBreakType))
+ {
+ nextNonLetterOrDigitShouldBeIgnored = true;
+ snakeCaseStringBuilder.Append(currentChar);
+ if (lineBreakType == EndOfLineSequence.CarriageReturnLineFeed)
+ {
+ i++;
+ currentChar = span[i];
+ snakeCaseStringBuilder.Append(currentChar);
+ }
+ }
+ else if (!nextNonLetterOrDigitShouldBeIgnored)
+ {
+ if (i < span.Length - 1
+ && char.IsLetterOrDigit(span[i + 1]))
+ {
+ nextNonLetterOrDigitShouldBeIgnored = true;
+ snakeCaseStringBuilder.Append('-');
+ }
+ }
+ }
+
+ return snakeCaseStringBuilder.ToString();
+ }
+
+ internal static string ConvertToAlternatingCase(string text, CancellationToken cancellationToken)
+ {
+ Guard.IsNotNull(text);
+ if (text.Length == 0)
+ {
+ return text;
+ }
+
+ var alternatingCaseString = new Memory<char>(text.ToCharArray());
+
+ bool lowerCase = true;
+ for (int i = 0; i < alternatingCaseString.Length; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ if (lowerCase)
+ {
+ alternatingCaseString.Span[i] = char.ToLowerInvariant(alternatingCaseString.Span[i]);
+ }
+ else
+ {
+ alternatingCaseString.Span[i] = char.ToUpperInvariant(alternatingCaseString.Span[i]);
+ }
+
+ lowerCase = !lowerCase;
+ }
+
+ return new string(alternatingCaseString.Span);
+ }
+
+ internal static string ConvertToInverseCase(string text, CancellationToken cancellationToken)
+ {
+ Guard.IsNotNull(text);
+ if (text.Length == 0)
+ {
+ return text;
+ }
+
+ var inverseCaseString = new Memory<char>(text.ToCharArray());
+
+ bool lowerCase = false;
+ for (int i = 0; i < inverseCaseString.Length; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ if (lowerCase)
+ {
+ inverseCaseString.Span[i] = char.ToLowerInvariant(inverseCaseString.Span[i]);
+ }
+ else
+ {
+ inverseCaseString.Span[i] = char.ToUpperInvariant(inverseCaseString.Span[i]);
+ }
+
+ lowerCase = !lowerCase;
+ }
+
+ return new string(inverseCaseString.Span);
+ }
+
+ internal static EndOfLineSequence DetectLineBreakKind(string text, CancellationToken cancellationToken)
+ {
+ EndOfLineSequence overallLineBreakType = EndOfLineSequence.Unknown;
+ ReadOnlySpan<char> span = text.AsSpan();
+ for (int i = 0; i < span.Length; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ if (span.IsLineBreak(i, out EndOfLineSequence lineBreakType))
+ {
+ // Detect the overall line break type of the text we're analyzing.
+ if (overallLineBreakType == EndOfLineSequence.Unknown)
+ {
+ overallLineBreakType = lineBreakType;
+ }
+ else if (overallLineBreakType != lineBreakType)
+ {
+ overallLineBreakType = EndOfLineSequence.Mixed;
+ break;
+ }
+
+ if (lineBreakType == EndOfLineSequence.CarriageReturnLineFeed)
+ {
+ // If we found \r\n, skip the '\n' character.
+ i++;
+ continue;
+ }
+ }
+ }
+
+ return overallLineBreakType;
+ }
+
+ internal static void AnalyzeSpan(
+ string text,
+ TextSpan span,
+ CancellationToken cancellationToken,
+ out int spanLength,
+ out int spanStartPosition,
+ out int spanEndPosition,
+ out int spanLineNumber,
+ out int spanColumnNumber)
+ {
+ Guard.IsNotNull(text);
+ spanLength = span.Length;
+ spanStartPosition = span.StartPosition;
+ spanEndPosition = span.EndPosition;
+ spanLineNumber = CountLines(text, span.StartPosition);
+ int beginningOfLinePosition = text.LastIndexOf('\n', Math.Max(0, Math.Min(span.StartPosition - 1, text.Length - 1)));
+ if (beginningOfLinePosition == -1)
+ {
+ spanColumnNumber = span.StartPosition;
+ }
+ else
+ {
+ spanColumnNumber = Math.Max(span.StartPosition - beginningOfLinePosition - 1, 0);
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+ }
+
+ internal static void AnalyzeText(
+ string text,
+ CancellationToken cancellationToken,
+ out int byteCount,
+ out int characterCount,
+ out int wordCount,
+ out int sentenceCount,
+ out int paragraphCount,
+ out int lineCount,
+ out EndOfLineSequence overallLineBreakType,
+ out Dictionary<char, int> characterFrequency,
+ out Dictionary<string, int> wordFrequency)
+ {
+ Guard.IsNotNull(text);
+ byteCount = Encoding.UTF8.GetByteCount(text);
+ characterCount = text.Length;
+ wordCount = 0;
+ sentenceCount = 0;
+ lineCount = 1;
+ paragraphCount = 1;
+ overallLineBreakType = EndOfLineSequence.Unknown;
+ characterFrequency = new Dictionary<char, int>();
+ wordFrequency = new Dictionary<string, int>();
+
+ int sentenceBeginningPosition = 0;
+ int consecutiveLineBreakCount = 0;
+ bool isWordStart = true;
+ var wordBuilder = new StringBuilder();
+
+ ReadOnlySpan<char> span = text.AsSpan();
+ for (int i = 0; i < span.Length; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ char c = span[i];
+
+ // Update the character distribution
+ UpdateCharacterFrequency(characterFrequency, c);
+
+ bool isWordSeparator = IsWordSeparator(c);
+
+ // If the current character is not a word separator, append it to the word builder
+ if (!isWordSeparator)
+ {
+ wordBuilder.Append(c);
+
+ // If the current character is the start of a word, increment the word count
+ if (isWordStart)
+ {
+ wordCount++;
+ }
+ }
+ else if (wordBuilder.Length > 0)
+ {
+ // Otherwise, we reached the end of a word, let's update the word distribution
+ UpdateWordFrequency(wordFrequency, wordBuilder.ToString());
+ wordBuilder.Clear();
+ }
+
+ isWordStart = isWordSeparator;
+
+ // If we found a line break, increment the line count
+ if (span.IsLineBreak(i, out EndOfLineSequence lineBreakType))
+ {
+ lineCount++;
+ consecutiveLineBreakCount++;
+
+ // Detect the overall line break type of the text we're analyzing.
+ if (overallLineBreakType == EndOfLineSequence.Unknown)
+ {
+ overallLineBreakType = lineBreakType;
+ }
+ else if (overallLineBreakType != lineBreakType)
+ {
+ overallLineBreakType = EndOfLineSequence.Mixed;
+ }
+
+ if (lineBreakType == EndOfLineSequence.CarriageReturnLineFeed)
+ {
+ // If we found \r\n, skip the '\n' character.
+ i++;
+ continue;
+ }
+ }
+ else
+ {
+ // If there are more than one consecutive line breaks, we have a paragraph.
+ if (consecutiveLineBreakCount > 1)
+ {
+ paragraphCount++;
+ }
+
+ consecutiveLineBreakCount = 0;
+ }
+
+ // Detect sentences.
+ bool isSentenceTerminator = IsSentenceTerminator(c);
+ if (isSentenceTerminator && !IsSpanEmptyOrNotLetterAndDigit(text, TextSpan.FromBounds(sentenceBeginningPosition, i)))
+ {
+ sentenceCount++;
+ sentenceBeginningPosition = i + 1;
+ }
+ }
+
+ // Detect final sentences.
+ if (sentenceBeginningPosition < text.Length - 1
+ && !IsSpanEmptyOrNotLetterAndDigit(text, TextSpan.FromBounds(sentenceBeginningPosition, text.Length - 1)))
+ {
+ sentenceCount++;
+ }
+ }
+
+ private static void UpdateCharacterFrequency(Dictionary<char, int> characterDistribution, char c)
+ {
+ if (characterDistribution.TryGetValue(c, out int count))
+ {
+ characterDistribution[c] = ++count;
+ }
+ else
+ {
+ characterDistribution[c] = 1;
+ }
+ }
+
+ private static void UpdateWordFrequency(Dictionary<string, int> wordDistribution, string word)
+ {
+ if (wordDistribution.TryGetValue(word, out int value))
+ {
+ wordDistribution[word] = ++value;
+ }
+ else
+ {
+ wordDistribution[word] = 1;
+ }
+ }
+
+ private static bool IsWordSeparator(char c)
+ {
+ return char.IsWhiteSpace(c) || char.IsPunctuation(c);
+ }
+
+ private static bool IsSentenceTerminator(char c)
+ {
+ return c == '.' || c == '?' || c == '!';
+ }
+
+ private static bool IsSpanEmptyOrNotLetterAndDigit(string text, TextSpan span)
+ {
+ Guard.IsInRange(span.StartPosition, 0, text.Length, nameof(span));
+ Guard.IsInRange(span.EndPosition, 0, text.Length, nameof(span));
+
+ for (int i = span.StartPosition; i < span.EndPosition; i++)
+ {
+ char currentChar = text[i];
+ if (char.IsLetterOrDigit(currentChar))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private static int CountLines(string text, int length)
+ {
+ int lineCount = 1;
+
+ if (string.IsNullOrEmpty(text))
+ {
+ return lineCount;
+ }
+
+ int index = -1;
+ while (-1 != (index = text.IndexOf('\n', index + 1, length - (index + 1))))
+ {
+ lineCount++;
+ }
+
+ return lineCount;
+ }
+
+ private static string SnakeConstantKebabCobolCaseConverter(string text, char spaceReplacement, bool isUpperCase, CancellationToken cancellationToken)
+ {
+ Guard.IsNotNull(text);
+ if (text.Length == 0)
+ {
+ return text;
+ }
+
+ var snakeCaseStringBuilder = new StringBuilder();
+ ReadOnlySpan<char> span = text.AsSpan();
+
+ bool nextNonLetterOrDigitShouldBeIgnored = true;
+ for (int i = 0; i < span.Length; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ char currentChar = span[i];
+ if (char.IsLetterOrDigit(currentChar))
+ {
+ nextNonLetterOrDigitShouldBeIgnored = false;
+ if (isUpperCase)
+ {
+ snakeCaseStringBuilder.Append(char.ToUpperInvariant(currentChar));
+ }
+ else
+ {
+ snakeCaseStringBuilder.Append(char.ToLowerInvariant(currentChar));
+ }
+ }
+ else if (span.IsLineBreak(i, out EndOfLineSequence lineBreakType))
+ {
+ nextNonLetterOrDigitShouldBeIgnored = true;
+ snakeCaseStringBuilder.Append(currentChar);
+ if (lineBreakType == EndOfLineSequence.CarriageReturnLineFeed)
+ {
+ i++;
+ currentChar = span[i];
+ snakeCaseStringBuilder.Append(currentChar);
+ }
+ }
+ else if (!nextNonLetterOrDigitShouldBeIgnored)
+ {
+ if (i < span.Length - 1
+ && char.IsLetterOrDigit(span[i + 1]))
+ {
+ nextNonLetterOrDigitShouldBeIgnored = true;
+ snakeCaseStringBuilder.Append(spaceReplacement);
+ }
+ }
+ }
+
+ return snakeCaseStringBuilder.ToString();
+ }
+
+ private static string SortLines(string text, ReadOnlyMemoryOfCharComparerDelegate lineComparer, EndOfLineSequence endOfLineSequence = EndOfLineSequence.Unknown)
+ {
+ if (string.IsNullOrEmpty(text))
+ {
+ return string.Empty;
+ }
+
+ // Split text by lines.
+ List<ReadOnlyMemory<char>> lines = text.AsMemory().ToLines();
+
+ // Order lines.
+ lines.Sort(new CustomReadOnlyMemoryOfCharComparer(lineComparer));
+
+ // Rebuilt the text.
+ return lines.BuildStringFromListOfLines(endOfLineSequence);
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Models/EndOfLineSequence.cs b/src/app/dev/DevToys.Tools/Models/EndOfLineSequence.cs
new file mode 100644
index 000000000..d2fcca659
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Models/EndOfLineSequence.cs
@@ -0,0 +1,26 @@
+namespace DevToys.Tools.Models;
+
+internal enum EndOfLineSequence
+{
+ Unknown = 0,
+ LineFeed = 1,
+ CarriageReturn = 2,
+ CarriageReturnLineFeed = 3,
+ Mixed = 4
+}
+
+internal static class EndOfLineSequenceExtensions
+{
+ internal static string ToLineBreakCharacters(this EndOfLineSequence lineBreakType)
+ {
+ return lineBreakType switch
+ {
+ EndOfLineSequence.Unknown => Environment.NewLine,
+ EndOfLineSequence.LineFeed => "\n",
+ EndOfLineSequence.CarriageReturn => "\r",
+ EndOfLineSequence.CarriageReturnLineFeed => "\r\n",
+ EndOfLineSequence.Mixed => Environment.NewLine,
+ _ => throw new ArgumentOutOfRangeException(nameof(lineBreakType)),
+ };
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilities.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilities.Designer.cs
new file mode 100644
index 000000000..8a0eb59e2
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilities.Designer.cs
@@ -0,0 +1,567 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace DevToys.Tools.Tools.Text.AnalyzerAndUtilities {
+ using System;
+
+
+ /// <summary>
+ /// A strongly-typed resource class, for looking up localized strings, etc.
+ /// </summary>
+ // This class was auto-generated by the StronglyTypedResourceBuilder
+ // class via a tool like ResGen or Visual Studio.
+ // To add or remove a member, edit your .ResX file then rerun ResGen
+ // with the /str option, or rebuild your VS project.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class AnalyzerAndUtilities {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal AnalyzerAndUtilities() {
+ }
+
+ /// <summary>
+ /// Returns the cached ResourceManager instance used by this class.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager {
+ get {
+ if (object.ReferenceEquals(resourceMan, null)) {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DevToys.Tools.Tools.Text.AnalyzerAndUtilities.AnalyzerAndUtilities", typeof(AnalyzerAndUtilities).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ /// <summary>
+ /// Overrides the current thread's CurrentUICulture property for all
+ /// resource lookups using this strongly typed resource class.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture {
+ get {
+ return resourceCulture;
+ }
+ set {
+ resourceCulture = value;
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Text analyzer, converter and utilities tool.
+ /// </summary>
+ internal static string AccessibleName {
+ get {
+ return ResourceManager.GetString("AccessibleName", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to A set of treatments to apply to the input text. Actions are performed in the order they&apos;re set..
+ /// </summary>
+ internal static string ActionsOptionDescription {
+ get {
+ return ResourceManager.GetString("ActionsOptionDescription", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Alphabetize.
+ /// </summary>
+ internal static string Alphabetize {
+ get {
+ return ResourceManager.GetString("Alphabetize", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Alphabetize by last word.
+ /// </summary>
+ internal static string AlphabetizeLast {
+ get {
+ return ResourceManager.GetString("AlphabetizeLast", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to aLtErNaTiNg cAsE.
+ /// </summary>
+ internal static string AlternatingCase {
+ get {
+ return ResourceManager.GetString("AlternatingCase", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Bytes.
+ /// </summary>
+ internal static string Bytes {
+ get {
+ return ResourceManager.GetString("Bytes", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to camelCase.
+ /// </summary>
+ internal static string CamelCase {
+ get {
+ return ResourceManager.GetString("CamelCase", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Character frequency.
+ /// </summary>
+ internal static string CharacterFrequency {
+ get {
+ return ResourceManager.GetString("CharacterFrequency", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Characters.
+ /// </summary>
+ internal static string Characters {
+ get {
+ return ResourceManager.GetString("Characters", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to COBOL-CASE.
+ /// </summary>
+ internal static string CobolCase {
+ get {
+ return ResourceManager.GetString("CobolCase", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to CONSTANT_CASE.
+ /// </summary>
+ internal static string ConstantCase {
+ get {
+ return ResourceManager.GetString("ConstantCase", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Convert case.
+ /// </summary>
+ internal static string ConvertCase {
+ get {
+ return ResourceManager.GetString("ConvertCase", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Convert line break.
+ /// </summary>
+ internal static string ConvertEndOfLineSequence {
+ get {
+ return ResourceManager.GetString("ConvertEndOfLineSequence", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Analyze text and provide some basic utility tools.
+ /// </summary>
+ internal static string Description {
+ get {
+ return ResourceManager.GetString("Description", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Line break.
+ /// </summary>
+ internal static string EndOfLineSequence {
+ get {
+ return ResourceManager.GetString("EndOfLineSequence", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to CR (\r).
+ /// </summary>
+ internal static string EndOfLineSequenceCR {
+ get {
+ return ResourceManager.GetString("EndOfLineSequenceCR", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to CRLF (\r\n).
+ /// </summary>
+ internal static string EndOfLineSequenceCRLF {
+ get {
+ return ResourceManager.GetString("EndOfLineSequenceCRLF", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to LF (\n).
+ /// </summary>
+ internal static string EndOfLineSequenceLF {
+ get {
+ return ResourceManager.GetString("EndOfLineSequenceLF", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Mixed.
+ /// </summary>
+ internal static string EndOfLineSequenceMixed {
+ get {
+ return ResourceManager.GetString("EndOfLineSequenceMixed", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Unknown.
+ /// </summary>
+ internal static string EndOfLineSequenceUnknown {
+ get {
+ return ResourceManager.GetString("EndOfLineSequenceUnknown", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Text or path to a file to treat..
+ /// </summary>
+ internal static string InputOptionDescription {
+ get {
+ return ResourceManager.GetString("InputOptionDescription", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to InVeRsE CaSe.
+ /// </summary>
+ internal static string InverseCase {
+ get {
+ return ResourceManager.GetString("InverseCase", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to kebab-case.
+ /// </summary>
+ internal static string KebabCase {
+ get {
+ return ResourceManager.GetString("KebabCase", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Lines.
+ /// </summary>
+ internal static string Lines {
+ get {
+ return ResourceManager.GetString("Lines", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Text Analyzer and Utilities.
+ /// </summary>
+ internal static string LongDisplayTitle {
+ get {
+ return ResourceManager.GetString("LongDisplayTitle", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to lower case.
+ /// </summary>
+ internal static string LowerCase {
+ get {
+ return ResourceManager.GetString("LowerCase", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to File where the result should be persisted..
+ /// </summary>
+ internal static string OutputFileOptionDescription {
+ get {
+ return ResourceManager.GetString("OutputFileOptionDescription", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Paragraphs.
+ /// </summary>
+ internal static string Paragraphs {
+ get {
+ return ResourceManager.GetString("Paragraphs", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to PascalCase.
+ /// </summary>
+ internal static string PascalCase {
+ get {
+ return ResourceManager.GetString("PascalCase", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Randomize.
+ /// </summary>
+ internal static string Randomize {
+ get {
+ return ResourceManager.GetString("Randomize", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Reverse.
+ /// </summary>
+ internal static string Reverse {
+ get {
+ return ResourceManager.GetString("Reverse", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Reverse alphabetize.
+ /// </summary>
+ internal static string ReverseAlphabetize {
+ get {
+ return ResourceManager.GetString("ReverseAlphabetize", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Reverse alphabetize by last word.
+ /// </summary>
+ internal static string ReverseAlphabetizeLast {
+ get {
+ return ResourceManager.GetString("ReverseAlphabetizeLast", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to string.
+ /// </summary>
+ internal static string SearchKeywords {
+ get {
+ return ResourceManager.GetString("SearchKeywords", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Column.
+ /// </summary>
+ internal static string SelectionColumnNumber {
+ get {
+ return ResourceManager.GetString("SelectionColumnNumber", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to End position.
+ /// </summary>
+ internal static string SelectionEndPosition {
+ get {
+ return ResourceManager.GetString("SelectionEndPosition", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Length.
+ /// </summary>
+ internal static string SelectionLength {
+ get {
+ return ResourceManager.GetString("SelectionLength", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Line.
+ /// </summary>
+ internal static string SelectionLineNumber {
+ get {
+ return ResourceManager.GetString("SelectionLineNumber", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Start position.
+ /// </summary>
+ internal static string SelectionStartPosition {
+ get {
+ return ResourceManager.GetString("SelectionStartPosition", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Selection.
+ /// </summary>
+ internal static string SelectionStatistics {
+ get {
+ return ResourceManager.GetString("SelectionStatistics", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Sentence case.
+ /// </summary>
+ internal static string SentenceCase {
+ get {
+ return ResourceManager.GetString("SentenceCase", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Sentences.
+ /// </summary>
+ internal static string Sentences {
+ get {
+ return ResourceManager.GetString("Sentences", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Analyzer &amp; Utilities.
+ /// </summary>
+ internal static string ShortDisplayTitle {
+ get {
+ return ResourceManager.GetString("ShortDisplayTitle", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Show original text.
+ /// </summary>
+ internal static string ShowOriginalText {
+ get {
+ return ResourceManager.GetString("ShowOriginalText", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to snake_case.
+ /// </summary>
+ internal static string SnakeCase {
+ get {
+ return ResourceManager.GetString("SnakeCase", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Sort lines.
+ /// </summary>
+ internal static string SortLines {
+ get {
+ return ResourceManager.GetString("SortLines", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Statistics.
+ /// </summary>
+ internal static string Statistics {
+ get {
+ return ResourceManager.GetString("Statistics", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Title.
+ /// </summary>
+ internal static string StatisticTitle {
+ get {
+ return ResourceManager.GetString("StatisticTitle", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Value.
+ /// </summary>
+ internal static string StatisticValue {
+ get {
+ return ResourceManager.GetString("StatisticValue", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Text.
+ /// </summary>
+ internal static string TextInput {
+ get {
+ return ResourceManager.GetString("TextInput", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Text.
+ /// </summary>
+ internal static string TextStatistics {
+ get {
+ return ResourceManager.GetString("TextStatistics", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Title Case.
+ /// </summary>
+ internal static string TitleCase {
+ get {
+ return ResourceManager.GetString("TitleCase", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Train-Case.
+ /// </summary>
+ internal static string TrainCase {
+ get {
+ return ResourceManager.GetString("TrainCase", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to UPPER CASE.
+ /// </summary>
+ internal static string UpperCase {
+ get {
+ return ResourceManager.GetString("UpperCase", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Word frequency.
+ /// </summary>
+ internal static string WordFrequency {
+ get {
+ return ResourceManager.GetString("WordFrequency", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Words.
+ /// </summary>
+ internal static string Words {
+ get {
+ return ResourceManager.GetString("Words", resourceCulture);
+ }
+ }
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilities.resx b/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilities.resx
new file mode 100644
index 000000000..5410adc0a
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilities.resx
@@ -0,0 +1,288 @@
+<?xml version="1.0" encoding="utf-8"?>
+<root>
+ <!--
+ Microsoft ResX Schema
+
+ Version 2.0
+
+ The primary goals of this format is to allow a simple XML format
+ that is mostly human readable. The generation and parsing of the
+ various data types are done through the TypeConverter classes
+ associated with the data types.
+
+ Example:
+
+ ... ado.net/XML headers & schema ...
+ <resheader name="resmimetype">text/microsoft-resx</resheader>
+ <resheader name="version">2.0</resheader>
+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+ <value>[base64 mime encoded serialized .NET Framework object]</value>
+ </data>
+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+ <comment>This is a comment</comment>
+ </data>
+
+ There are any number of "resheader" rows that contain simple
+ name/value pairs.
+
+ Each data row contains a name, and value. The row also contains a
+ type or mimetype. Type corresponds to a .NET class that support
+ text/value conversion through the TypeConverter architecture.
+ Classes that don't support this are serialized and stored with the
+ mimetype set.
+
+ The mimetype is used for serialized objects, and tells the
+ ResXResourceReader how to depersist the object. This is currently not
+ extensible. For a given mimetype the value must be set accordingly:
+
+ Note - application/x-microsoft.net.object.binary.base64 is the format
+ that the ResXResourceWriter will generate, however the reader can
+ read any of the formats listed below.
+
+ mimetype: application/x-microsoft.net.object.binary.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.soap.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.bytearray.base64
+ value : The object must be serialized into a byte array
+ : using a System.ComponentModel.TypeConverter
+ : and then encoded with base64 encoding.
+ -->
+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
+ <xsd:element name="root" msdata:IsDataSet="true">
+ <xsd:complexType>
+ <xsd:choice maxOccurs="unbounded">
+ <xsd:element name="metadata">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" />
+ </xsd:sequence>
+ <xsd:attribute name="name" use="required" type="xsd:string" />
+ <xsd:attribute name="type" type="xsd:string" />
+ <xsd:attribute name="mimetype" type="xsd:string" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="assembly">
+ <xsd:complexType>
+ <xsd:attribute name="alias" type="xsd:string" />
+ <xsd:attribute name="name" type="xsd:string" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="data">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="resheader">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" />
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:choice>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:schema>
+ <resheader name="resmimetype">
+ <value>text/microsoft-resx</value>
+ </resheader>
+ <resheader name="version">
+ <value>2.0</value>
+ </resheader>
+ <resheader name="reader">
+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <resheader name="writer">
+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <data name="AccessibleName" xml:space="preserve">
+ <value>Text analyzer, converter and utilities tool</value>
+ </data>
+ <data name="ActionsOptionDescription" xml:space="preserve">
+ <value>A set of treatments to apply to the input text. Actions are performed in the order they're set.</value>
+ </data>
+ <data name="Alphabetize" xml:space="preserve">
+ <value>Alphabetize</value>
+ </data>
+ <data name="AlphabetizeLast" xml:space="preserve">
+ <value>Alphabetize by last word</value>
+ </data>
+ <data name="AlternatingCase" xml:space="preserve">
+ <value>aLtErNaTiNg cAsE</value>
+ </data>
+ <data name="Bytes" xml:space="preserve">
+ <value>Bytes</value>
+ </data>
+ <data name="CamelCase" xml:space="preserve">
+ <value>camelCase</value>
+ </data>
+ <data name="CharacterFrequency" xml:space="preserve">
+ <value>Character frequency</value>
+ </data>
+ <data name="Characters" xml:space="preserve">
+ <value>Characters</value>
+ </data>
+ <data name="CobolCase" xml:space="preserve">
+ <value>COBOL-CASE</value>
+ </data>
+ <data name="ConstantCase" xml:space="preserve">
+ <value>CONSTANT_CASE</value>
+ </data>
+ <data name="ConvertCase" xml:space="preserve">
+ <value>Convert case</value>
+ </data>
+ <data name="ConvertEndOfLineSequence" xml:space="preserve">
+ <value>Convert line break</value>
+ </data>
+ <data name="Description" xml:space="preserve">
+ <value>Analyze text and provide some basic utility tools</value>
+ </data>
+ <data name="EndOfLineSequence" xml:space="preserve">
+ <value>Line break</value>
+ </data>
+ <data name="EndOfLineSequenceCR" xml:space="preserve">
+ <value>CR (\r)</value>
+ </data>
+ <data name="EndOfLineSequenceCRLF" xml:space="preserve">
+ <value>CRLF (\r\n)</value>
+ </data>
+ <data name="EndOfLineSequenceLF" xml:space="preserve">
+ <value>LF (\n)</value>
+ </data>
+ <data name="EndOfLineSequenceMixed" xml:space="preserve">
+ <value>Mixed</value>
+ </data>
+ <data name="EndOfLineSequenceUnknown" xml:space="preserve">
+ <value>Unknown</value>
+ </data>
+ <data name="InputOptionDescription" xml:space="preserve">
+ <value>Text or path to a file to treat.</value>
+ </data>
+ <data name="InverseCase" xml:space="preserve">
+ <value>InVeRsE CaSe</value>
+ </data>
+ <data name="KebabCase" xml:space="preserve">
+ <value>kebab-case</value>
+ </data>
+ <data name="Lines" xml:space="preserve">
+ <value>Lines</value>
+ </data>
+ <data name="LongDisplayTitle" xml:space="preserve">
+ <value>Text Analyzer and Utilities</value>
+ </data>
+ <data name="LowerCase" xml:space="preserve">
+ <value>lower case</value>
+ </data>
+ <data name="OutputFileOptionDescription" xml:space="preserve">
+ <value>File where the result should be persisted.</value>
+ </data>
+ <data name="Paragraphs" xml:space="preserve">
+ <value>Paragraphs</value>
+ </data>
+ <data name="PascalCase" xml:space="preserve">
+ <value>PascalCase</value>
+ </data>
+ <data name="Randomize" xml:space="preserve">
+ <value>Randomize</value>
+ </data>
+ <data name="Reverse" xml:space="preserve">
+ <value>Reverse</value>
+ </data>
+ <data name="ReverseAlphabetize" xml:space="preserve">
+ <value>Reverse alphabetize</value>
+ </data>
+ <data name="ReverseAlphabetizeLast" xml:space="preserve">
+ <value>Reverse alphabetize by last word</value>
+ </data>
+ <data name="SearchKeywords" xml:space="preserve">
+ <value>string</value>
+ </data>
+ <data name="SelectionColumnNumber" xml:space="preserve">
+ <value>Column</value>
+ </data>
+ <data name="SelectionEndPosition" xml:space="preserve">
+ <value>End position</value>
+ </data>
+ <data name="SelectionLength" xml:space="preserve">
+ <value>Length</value>
+ </data>
+ <data name="SelectionLineNumber" xml:space="preserve">
+ <value>Line</value>
+ </data>
+ <data name="SelectionStartPosition" xml:space="preserve">
+ <value>Start position</value>
+ </data>
+ <data name="SelectionStatistics" xml:space="preserve">
+ <value>Selection</value>
+ </data>
+ <data name="SentenceCase" xml:space="preserve">
+ <value>Sentence case</value>
+ </data>
+ <data name="Sentences" xml:space="preserve">
+ <value>Sentences</value>
+ </data>
+ <data name="ShortDisplayTitle" xml:space="preserve">
+ <value>Analyzer &amp; Utilities</value>
+ </data>
+ <data name="ShowOriginalText" xml:space="preserve">
+ <value>Show original text</value>
+ </data>
+ <data name="SnakeCase" xml:space="preserve">
+ <value>snake_case</value>
+ </data>
+ <data name="SortLines" xml:space="preserve">
+ <value>Sort lines</value>
+ </data>
+ <data name="Statistics" xml:space="preserve">
+ <value>Statistics</value>
+ </data>
+ <data name="StatisticTitle" xml:space="preserve">
+ <value>Title</value>
+ </data>
+ <data name="StatisticValue" xml:space="preserve">
+ <value>Value</value>
+ </data>
+ <data name="TextInput" xml:space="preserve">
+ <value>Text</value>
+ </data>
+ <data name="TextStatistics" xml:space="preserve">
+ <value>Text</value>
+ </data>
+ <data name="TitleCase" xml:space="preserve">
+ <value>Title Case</value>
+ </data>
+ <data name="TrainCase" xml:space="preserve">
+ <value>Train-Case</value>
+ </data>
+ <data name="UpperCase" xml:space="preserve">
+ <value>UPPER CASE</value>
+ </data>
+ <data name="WordFrequency" xml:space="preserve">
+ <value>Word frequency</value>
+ </data>
+ <data name="Words" xml:space="preserve">
+ <value>Words</value>
+ </data>
+</root>
\ No newline at end of file
diff --git a/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilitiesCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilitiesCommandLineTool.cs
new file mode 100644
index 000000000..dcf5330c7
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilitiesCommandLineTool.cs
@@ -0,0 +1,143 @@
+using DevToys.Api.Core;
+using DevToys.Tools.Helpers;
+using Microsoft.Extensions.Logging;
+using OneOf;
+
+namespace DevToys.Tools.Tools.Text.AnalyzerAndUtilities;
+
+[Export(typeof(ICommandLineTool))]
+[Name("AnalyzerAndUtilities")]
+[CommandName(
+ Name = "textutilities",
+ Alias = "txt",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Text.AnalyzerAndUtilities.AnalyzerAndUtilities",
+ DescriptionResourceName = nameof(AnalyzerAndUtilities.Description))]
+internal sealed class AnalyzerAndUtilitiesCommandLineTool : ICommandLineTool
+{
+ private enum OperationType
+ {
+ ConvertLineBreakToLF,
+ ConvertLineBreakToCRLF,
+ LowerCase,
+ UpperCase,
+ SentenceCase,
+ TitleCase,
+ CamelCase,
+ PascalCase,
+ SnakeCase,
+ ConstantCase,
+ KebabCase,
+ CobolCase,
+ TrainCase,
+ AlternatingCase,
+ InverseCase,
+ SortLinesAlphabetically,
+ SortLinesAlphabeticallyDescending,
+ SortLinesByLastWord,
+ SortLinesByLastWordDescending,
+ ReverseLines,
+ ShuffleLines,
+ }
+
+#pragma warning disable IDE0044 // Add readonly modifier
+ [Import]
+ private IFileStorage _fileStorage = null!;
+#pragma warning restore IDE0044 // Add readonly modifier
+
+ [CommandLineOption(
+ Name = "input",
+ Alias = "i",
+ IsRequired = true,
+ DescriptionResourceName = nameof(AnalyzerAndUtilities.InputOptionDescription))]
+ private OneOf<FileInfo, string>? Input { get; set; }
+
+ [CommandLineOption(
+ Name = "action",
+ Alias = "a",
+ IsRequired = true,
+ DescriptionResourceName = nameof(AnalyzerAndUtilities.ActionsOptionDescription))]
+ private OperationType[] Actions { get; set; } = Array.Empty<OperationType>();
+
+ [CommandLineOption(
+ Name = "outputFile",
+ Alias = "o",
+ DescriptionResourceName = nameof(AnalyzerAndUtilities.OutputFileOptionDescription))]
+ internal FileInfo? OutputFile { get; set; }
+
+ public async ValueTask<int> InvokeAsync(ILogger logger, CancellationToken cancellationToken)
+ {
+ string? input = null;
+
+ if (Input.HasValue)
+ {
+ input = await Input.Value.ReadAllTextAsync(_fileStorage, cancellationToken);
+ }
+
+ Guard.IsNotNull(input);
+
+ string newText = input;
+ for (int i = 0; i < Actions.Length; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+
+ OperationType action = Actions[i];
+ newText = action switch
+ {
+ OperationType.ConvertLineBreakToLF
+ => StringHelper.ConvertLineBreakToLF(newText),
+ OperationType.ConvertLineBreakToCRLF
+ => StringHelper.ConvertLineBreakToCRLF(newText),
+ OperationType.LowerCase
+ => newText.ToLowerInvariant(),
+ OperationType.UpperCase
+ => newText.ToUpperInvariant(),
+ OperationType.SentenceCase
+ => StringHelper.ConvertToSentenceCase(newText, cancellationToken),
+ OperationType.TitleCase
+ => StringHelper.ConvertToTitleCase(newText, cancellationToken),
+ OperationType.CamelCase
+ => StringHelper.ConvertToCamelCase(newText, cancellationToken),
+ OperationType.PascalCase
+ => StringHelper.ConvertToPascalCase(newText, cancellationToken),
+ OperationType.SnakeCase
+ => StringHelper.ConvertToSnakeCase(newText, cancellationToken),
+ OperationType.ConstantCase
+ => StringHelper.ConvertToConstantCase(newText, cancellationToken),
+ OperationType.KebabCase
+ => StringHelper.ConvertToKebabCase(newText, cancellationToken),
+ OperationType.CobolCase
+ => StringHelper.ConvertToCobolCase(newText, cancellationToken),
+ OperationType.TrainCase
+ => StringHelper.ConvertToTrainCase(newText, cancellationToken),
+ OperationType.AlternatingCase
+ => StringHelper.ConvertToAlternatingCase(newText, cancellationToken),
+ OperationType.InverseCase
+ => StringHelper.ConvertToInverseCase(newText, cancellationToken),
+ OperationType.SortLinesAlphabetically
+ => StringHelper.SortLinesAlphabetically(newText, StringHelper.DetectLineBreakKind(newText, cancellationToken)),
+ OperationType.SortLinesAlphabeticallyDescending
+ => StringHelper.SortLinesAlphabeticallyDescending(newText, StringHelper.DetectLineBreakKind(newText, cancellationToken)),
+ OperationType.SortLinesByLastWord
+ => StringHelper.SortLinesByLastWord(newText, StringHelper.DetectLineBreakKind(newText, cancellationToken)),
+ OperationType.SortLinesByLastWordDescending
+ => StringHelper.SortLinesByLastWordDescending(newText, StringHelper.DetectLineBreakKind(newText, cancellationToken)),
+ OperationType.ReverseLines
+ => StringHelper.ReverseLines(newText, StringHelper.DetectLineBreakKind(newText, cancellationToken)),
+ OperationType.ShuffleLines
+ => StringHelper.ShuffleLines(newText, StringHelper.DetectLineBreakKind(newText, cancellationToken)),
+ _ => throw new NotSupportedException(),
+ };
+ }
+
+ if (OutputFile is null)
+ {
+ Console.WriteLine(newText);
+ }
+ else
+ {
+ await File.WriteAllTextAsync(OutputFile.FullName, newText, cancellationToken);
+ }
+
+ return 0;
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilitiesGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilitiesGuiTool.cs
new file mode 100644
index 000000000..b030803ae
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Tools/Text/AnalyzerAndUtilities/AnalyzerAndUtilitiesGuiTool.cs
@@ -0,0 +1,478 @@
+using System.Text.RegularExpressions;
+using DevToys.Tools.Helpers;
+using DevToys.Tools.Models;
+
+namespace DevToys.Tools.Tools.Text.AnalyzerAndUtilities;
+
+[Export(typeof(IGuiTool))]
+[Name("TextAnalyzerAndUtilities")]
+[ToolDisplayInformation(
+ IconFontName = "DevToys-Tools-Icons",
+ IconGlyph = '\u0131',
+ GroupName = PredefinedCommonToolGroupNames.Text,
+ ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Text.AnalyzerAndUtilities.AnalyzerAndUtilities",
+ ShortDisplayTitleResourceName = nameof(AnalyzerAndUtilities.ShortDisplayTitle),
+ LongDisplayTitleResourceName = nameof(AnalyzerAndUtilities.LongDisplayTitle),
+ DescriptionResourceName = nameof(AnalyzerAndUtilities.Description),
+ AccessibleNameResourceName = nameof(AnalyzerAndUtilities.AccessibleName),
+ SearchKeywordsResourceName = nameof(AnalyzerAndUtilities.SearchKeywords))]
+[AcceptedDataTypeName(PredefinedCommonDataTypeNames.Text)]
+internal sealed class AnalyzerAndUtilitiesGuiTool : IGuiTool, IDisposable
+{
+ private enum GridRows
+ {
+ TopAuto,
+ Stretch,
+ }
+
+ private enum GridColumns
+ {
+ Stretch
+ }
+
+ private readonly IUIMultiLineTextInput _textInput = MultilineTextInput();
+ private readonly IUISelectDropDownList _endOfLineSequenceDropDownList = SelectDropDownList();
+ private readonly IUIButton _originalTextButton = Button();
+ private readonly IUIDataGrid _statisticsDataGrid = DataGrid();
+ private readonly DisposableSemaphore _updateSemaphore = new();
+
+ private string? _originalText;
+ private bool _forbidBackup;
+ private CancellationTokenSource? _selectionStatisticsCancellationTokenSource;
+ private CancellationTokenSource? _textStatisticsCancellationTokenSource;
+
+ private int _statisticSelectionLength;
+ private int _statisticSelectionStartPosition;
+ private int _statisticSelectionEndPosition;
+ private int _statisticSelectionLineNumber;
+ private int _statisticSelectionColumnNumber;
+ private int _statisticByteCount;
+ private int _statisticCharacterCount;
+ private int _statisticWordCount;
+ private int _statisticSentenceCount;
+ private int _statisticParagraphCount;
+ private int _statisticLineCount;
+ private EndOfLineSequence _statisticEndOfLineSequence;
+ private Dictionary<char, int>? _statisticCharacterFrequency;
+ private Dictionary<string, int>? _statisticWordFrequency;
+
+ [ImportingConstructor]
+ public AnalyzerAndUtilitiesGuiTool()
+ {
+ _textInput.SelectionChanged += OnTextInputSelectionChanged;
+ }
+
+ public UIToolView View
+ => new(
+ isScrollable: false,
+ Grid()
+ .ColumnMediumSpacing()
+
+ .Rows(
+ (GridRows.TopAuto, Auto),
+ (GridRows.Stretch, new UIGridLength(1, UIGridUnitType.Fraction)))
+
+ .Columns(
+ (GridColumns.Stretch, new UIGridLength(1, UIGridUnitType.Fraction)))
+
+ .Cells(
+ Cell(
+ GridRows.TopAuto,
+ GridColumns.Stretch,
+
+ Stack()
+ .Vertical()
+ .LargeSpacing()
+ .WithChildren(
+
+ // Convert line break
+ Stack()
+ .Vertical()
+ .SmallSpacing()
+ .WithChildren(
+
+ Label()
+ .Text(AnalyzerAndUtilities.ConvertEndOfLineSequence),
+ Wrap()
+ .SmallSpacing()
+ .WithChildren(
+ Button().Text(AnalyzerAndUtilities.EndOfLineSequenceLF).OnClick(OnEndOfLineSequenceLFButtonClick),
+ Button().Text(AnalyzerAndUtilities.EndOfLineSequenceCRLF).OnClick(OnEndOfLineSequenceCRLFButtonClick))),
+
+ // Convert case
+ Stack()
+ .Vertical()
+ .SmallSpacing()
+ .WithChildren(
+
+ Label()
+ .Text(AnalyzerAndUtilities.ConvertCase),
+ Wrap()
+ .SmallSpacing()
+ .WithChildren(
+ Button().Text(AnalyzerAndUtilities.LowerCase).OnClick(OnLowerCaseButtonClick),
+ Button().Text(AnalyzerAndUtilities.UpperCase).OnClick(OnUpperCaseButtonClick),
+ Button().Text(AnalyzerAndUtilities.SentenceCase).OnClick(OnSentenceCaseButtonClick),
+ Button().Text(AnalyzerAndUtilities.TitleCase).OnClick(OnTitleCaseButtonClick),
+ Button().Text(AnalyzerAndUtilities.CamelCase).OnClick(OnCamelCaseButtonClick),
+ Button().Text(AnalyzerAndUtilities.PascalCase).OnClick(OnPascalCaseButtonClick),
+ Button().Text(AnalyzerAndUtilities.SnakeCase).OnClick(OnSnakeCaseButtonClick),
+ Button().Text(AnalyzerAndUtilities.ConstantCase).OnClick(OnConstantCaseButtonClick),
+ Button().Text(AnalyzerAndUtilities.KebabCase).OnClick(OnKebabCaseButtonClick),
+ Button().Text(AnalyzerAndUtilities.CobolCase).OnClick(OnCobolCaseButtonClick),
+ Button().Text(AnalyzerAndUtilities.TrainCase).OnClick(OnTrainCaseButtonClick),
+ Button().Text(AnalyzerAndUtilities.AlternatingCase).OnClick(OnAlternatingCaseButtonClick),
+ Button().Text(AnalyzerAndUtilities.InverseCase).OnClick(OnInverseCaseButtonClick))),
+
+ // Sort lines
+ Stack()
+ .Vertical()
+ .SmallSpacing()
+ .WithChildren(
+
+ Label()
+ .Text(AnalyzerAndUtilities.SortLines),
+ Wrap()
+ .SmallSpacing()
+ .WithChildren(
+ Button().Text(AnalyzerAndUtilities.Alphabetize).OnClick(OnAlphabetizeButtonClick),
+ Button().Text(AnalyzerAndUtilities.ReverseAlphabetize).OnClick(OnReverseAlphabetizeButtonClick),
+ Button().Text(AnalyzerAndUtilities.AlphabetizeLast).OnClick(OnAlphabetizeLastButtonClick),
+ Button().Text(AnalyzerAndUtilities.ReverseAlphabetizeLast).OnClick(OnReverseAlphabetizeLastButtonClick),
+ Button().Text(AnalyzerAndUtilities.Reverse).OnClick(OnReverseButtonClick),
+ Button().Text(AnalyzerAndUtilities.Randomize).OnClick(OnRandomizeButtonClick))))),
+
+ Cell(
+ GridRows.Stretch,
+ GridColumns.Stretch,
+
+ SplitGrid()
+ .Vertical()
+ .RightPaneLength(new UIGridLength(250, UIGridUnitType.Pixel))
+
+ .WithLeftPaneChild(
+ _textInput
+ .Title(AnalyzerAndUtilities.TextInput)
+ .CanCopyWhenEditable()
+ .AlwaysWrap()
+ .OnTextChanged(OnInputTextChanged)
+ .CommandBarExtraContent(
+ _originalTextButton
+ .AccentAppearance()
+ .Text(AnalyzerAndUtilities.ShowOriginalText)
+ .OnClick(OnOriginalTextButtonClick)))
+
+ .WithRightPaneChild(
+ _statisticsDataGrid
+ .Title(AnalyzerAndUtilities.Statistics)
+ .ForbidSelectItem()
+ .WithColumns(AnalyzerAndUtilities.StatisticTitle, AnalyzerAndUtilities.StatisticValue)))));
+
+ public void Dispose()
+ {
+ _selectionStatisticsCancellationTokenSource?.Cancel();
+ _selectionStatisticsCancellationTokenSource?.Dispose();
+ _textStatisticsCancellationTokenSource?.Cancel();
+ _textStatisticsCancellationTokenSource?.Dispose();
+ _updateSemaphore.Dispose();
+ }
+
+ public void OnDataReceived(string dataTypeName, object? parsedData)
+ {
+ if (dataTypeName == PredefinedCommonDataTypeNames.Text && parsedData is string text)
+ {
+ _originalText = text;
+ OnOriginalTextButtonClick();
+ }
+ }
+
+ private void OnInputTextChanged(string newText)
+ {
+ if (!_forbidBackup)
+ {
+ _originalTextButton.Disable();
+ _originalText = newText;
+ }
+ else
+ {
+ _originalTextButton.Enable();
+ }
+
+ _textStatisticsCancellationTokenSource?.Cancel();
+ _textStatisticsCancellationTokenSource?.Dispose();
+ _textStatisticsCancellationTokenSource = new CancellationTokenSource();
+
+ ComputeTextStatisticsAsync(newText, _textStatisticsCancellationTokenSource.Token).ForgetSafely();
+ }
+
+ private void OnTextInputSelectionChanged(object? sender, EventArgs e)
+ {
+ _selectionStatisticsCancellationTokenSource?.Cancel();
+ _selectionStatisticsCancellationTokenSource?.Dispose();
+ _selectionStatisticsCancellationTokenSource = new CancellationTokenSource();
+
+ ComputeSelectionStatisticsAsync(_textInput.Text, _textInput.Selection, _selectionStatisticsCancellationTokenSource.Token).ForgetSafely();
+ }
+
+ private void OnEndOfLineSequenceLFButtonClick()
+ {
+ SetTextWithoutBackup(StringHelper.ConvertLineBreakToLF(_textInput.Text));
+ }
+
+ private void OnEndOfLineSequenceCRLFButtonClick()
+ {
+ SetTextWithoutBackup(StringHelper.ConvertLineBreakToCRLF(_textInput.Text));
+ }
+
+ private void OnLowerCaseButtonClick()
+ {
+ SetTextWithoutBackup(_textInput.Text?.ToLowerInvariant());
+ }
+
+ private void OnUpperCaseButtonClick()
+ {
+ SetTextWithoutBackup(_textInput.Text?.ToUpperInvariant());
+ }
+
+ private void OnSentenceCaseButtonClick()
+ {
+ SetTextWithoutBackup(StringHelper.ConvertToSentenceCase(_textInput.Text, CancellationToken.None));
+ }
+
+ private void OnTitleCaseButtonClick()
+ {
+ SetTextWithoutBackup(StringHelper.ConvertToTitleCase(_textInput.Text, CancellationToken.None));
+ }
+
+ private void OnCamelCaseButtonClick()
+ {
+ SetTextWithoutBackup(StringHelper.ConvertToCamelCase(_textInput.Text, CancellationToken.None));
+ }
+
+ private void OnPascalCaseButtonClick()
+ {
+ SetTextWithoutBackup(StringHelper.ConvertToPascalCase(_textInput.Text, CancellationToken.None));
+ }
+
+ private void OnSnakeCaseButtonClick()
+ {
+ SetTextWithoutBackup(StringHelper.ConvertToSnakeCase(_textInput.Text, CancellationToken.None));
+ }
+
+ private void OnConstantCaseButtonClick()
+ {
+ SetTextWithoutBackup(StringHelper.ConvertToConstantCase(_textInput.Text, CancellationToken.None));
+ }
+
+ private void OnKebabCaseButtonClick()
+ {
+ SetTextWithoutBackup(StringHelper.ConvertToKebabCase(_textInput.Text, CancellationToken.None));
+ }
+
+ private void OnCobolCaseButtonClick()
+ {
+ SetTextWithoutBackup(StringHelper.ConvertToCobolCase(_textInput.Text, CancellationToken.None));
+ }
+
+ private void OnTrainCaseButtonClick()
+ {
+ SetTextWithoutBackup(StringHelper.ConvertToTrainCase(_textInput.Text, CancellationToken.None));
+ }
+
+ private void OnAlternatingCaseButtonClick()
+ {
+ SetTextWithoutBackup(StringHelper.ConvertToAlternatingCase(_textInput.Text, CancellationToken.None));
+ }
+
+ private void OnInverseCaseButtonClick()
+ {
+ SetTextWithoutBackup(StringHelper.ConvertToInverseCase(_textInput.Text, CancellationToken.None));
+ }
+
+ private void OnAlphabetizeButtonClick()
+ {
+ SetTextWithoutBackup(StringHelper.SortLinesAlphabetically(_textInput.Text, _statisticEndOfLineSequence));
+ }
+
+ private void OnReverseAlphabetizeButtonClick()
+ {
+ SetTextWithoutBackup(StringHelper.SortLinesAlphabeticallyDescending(_textInput.Text, _statisticEndOfLineSequence));
+ }
+
+ private void OnAlphabetizeLastButtonClick()
+ {
+ SetTextWithoutBackup(StringHelper.SortLinesByLastWord(_textInput.Text, _statisticEndOfLineSequence));
+ }
+
+ private void OnReverseAlphabetizeLastButtonClick()
+ {
+ SetTextWithoutBackup(StringHelper.SortLinesByLastWordDescending(_textInput.Text, _statisticEndOfLineSequence));
+ }
+
+ private void OnReverseButtonClick()
+ {
+ SetTextWithoutBackup(StringHelper.ReverseLines(_textInput.Text, _statisticEndOfLineSequence));
+ }
+
+ private void OnRandomizeButtonClick()
+ {
+ SetTextWithoutBackup(StringHelper.ShuffleLines(_textInput.Text, _statisticEndOfLineSequence));
+ }
+
+ private void OnOriginalTextButtonClick()
+ {
+ SetTextWithoutBackup(_originalText);
+ _originalTextButton.Disable();
+ }
+
+ private void SetTextWithoutBackup(string? text)
+ {
+ _forbidBackup = true;
+ _textInput.Text(text ?? string.Empty);
+ _forbidBackup = false;
+ }
+
+ private async Task ComputeTextStatisticsAsync(string text, CancellationToken cancellationToken)
+ {
+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);
+
+ StringHelper.AnalyzeText(
+ text,
+ cancellationToken,
+ out int byteCount,
+ out int characterCount,
+ out int wordCount,
+ out int sentenceCount,
+ out int paragraphCount,
+ out int lineCount,
+ out EndOfLineSequence endOfLineSequence,
+ out Dictionary<char, int> characterFrequency,
+ out Dictionary<string, int> wordFrequency);
+
+ using (await _updateSemaphore.WaitAsync(cancellationToken))
+ {
+ _statisticByteCount = byteCount;
+ _statisticCharacterCount = characterCount;
+ _statisticWordCount = wordCount;
+ _statisticSentenceCount = sentenceCount;
+ _statisticParagraphCount = paragraphCount;
+ _statisticLineCount = lineCount;
+ _statisticEndOfLineSequence = endOfLineSequence;
+ _statisticCharacterFrequency = characterFrequency;
+ _statisticWordFrequency = wordFrequency;
+
+ DisplayStatisticsAndUpdateDetectedEndOfLineSequence();
+ }
+ }
+
+ private async Task ComputeSelectionStatisticsAsync(string text, TextSpan selection, CancellationToken cancellationToken)
+ {
+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);
+
+ StringHelper.AnalyzeSpan(
+ text,
+ selection,
+ cancellationToken,
+ out int spanLength,
+ out int spanStartPosition,
+ out int spanEndPosition,
+ out int spanLineNumber,
+ out int spanColumnNumber);
+
+ using (await _updateSemaphore.WaitAsync(cancellationToken))
+ {
+ _statisticSelectionLength = spanLength;
+ _statisticSelectionStartPosition = spanStartPosition;
+ _statisticSelectionEndPosition = spanEndPosition;
+ _statisticSelectionLineNumber = spanLineNumber;
+ _statisticSelectionColumnNumber = spanColumnNumber;
+
+ DisplayStatisticsAndUpdateDetectedEndOfLineSequence();
+ }
+ }
+
+ private void DisplayStatisticsAndUpdateDetectedEndOfLineSequence()
+ {
+ Guard.IsTrue(_updateSemaphore.IsBusy);
+
+ string endOfLineSequenceString
+ = _statisticEndOfLineSequence switch
+ {
+ EndOfLineSequence.CarriageReturn => AnalyzerAndUtilities.EndOfLineSequenceCR,
+ EndOfLineSequence.CarriageReturnLineFeed => AnalyzerAndUtilities.EndOfLineSequenceCRLF,
+ EndOfLineSequence.LineFeed => AnalyzerAndUtilities.EndOfLineSequenceLF,
+ EndOfLineSequence.Mixed => AnalyzerAndUtilities.EndOfLineSequenceMixed,
+ EndOfLineSequence.Unknown => AnalyzerAndUtilities.EndOfLineSequenceUnknown,
+ _ => string.Empty
+ };
+
+ var rows
+ = new List<IUIDataGridRow>
+ {
+ CreateStatisticTitleRow(AnalyzerAndUtilities.SelectionStatistics),
+ Row(null, Cell(AnalyzerAndUtilities.SelectionLength), Cell(_statisticSelectionLength.ToString())),
+ Row(null, Cell(AnalyzerAndUtilities.SelectionStartPosition), Cell(_statisticSelectionStartPosition.ToString())),
+ Row(null, Cell(AnalyzerAndUtilities.SelectionEndPosition), Cell(_statisticSelectionEndPosition.ToString())),
+ Row(null, Cell(AnalyzerAndUtilities.SelectionLineNumber), Cell(_statisticSelectionLineNumber.ToString())),
+ Row(null, Cell(AnalyzerAndUtilities.SelectionColumnNumber), Cell(_statisticSelectionColumnNumber.ToString())),
+ CreateStatisticTitleRow(AnalyzerAndUtilities.TextStatistics),
+ Row(null, Cell(AnalyzerAndUtilities.Bytes), Cell(_statisticByteCount.ToString())),
+ Row(null, Cell(AnalyzerAndUtilities.Characters), Cell(_statisticCharacterCount.ToString())),
+ Row(null, Cell(AnalyzerAndUtilities.Words), Cell(_statisticWordCount.ToString())),
+ Row(null, Cell(AnalyzerAndUtilities.Sentences), Cell(_statisticSentenceCount.ToString())),
+ Row(null, Cell(AnalyzerAndUtilities.Paragraphs), Cell(_statisticParagraphCount.ToString())),
+ Row(null, Cell(AnalyzerAndUtilities.Lines), Cell(_statisticLineCount.ToString())),
+ Row(null, Cell(AnalyzerAndUtilities.EndOfLineSequence), Cell(endOfLineSequenceString))
+ };
+
+ if (_statisticWordFrequency is not null)
+ {
+ if (_statisticWordFrequency.Count > 0)
+ {
+ rows.Add(CreateStatisticTitleRow(AnalyzerAndUtilities.WordFrequency));
+ }
+
+ foreach (KeyValuePair<string, int> word in _statisticWordFrequency.OrderByDescending(a => a.Value))
+ {
+ rows.Add(Row(null, Cell(word.Key), Cell(word.Value.ToString())));
+ }
+ }
+
+ if (_statisticCharacterFrequency is not null)
+ {
+ if (_statisticCharacterFrequency.Count > 0)
+ {
+ rows.Add(CreateStatisticTitleRow(AnalyzerAndUtilities.CharacterFrequency));
+ }
+
+ foreach (KeyValuePair<char, int> character in _statisticCharacterFrequency.OrderByDescending(a => a.Value))
+ {
+ string displayedKey = character.Key.ToString();
+ if (displayedKey == " ")
+ {
+ displayedKey = "⎵";
+ }
+ else
+ {
+ displayedKey = Regex.Escape(displayedKey);
+ }
+ rows.Add(Row(null, Cell(displayedKey), Cell(character.Value.ToString())));
+ }
+ }
+
+ _statisticsDataGrid.WithRows(rows.ToArray());
+
+ _endOfLineSequenceDropDownList.Select((int)_statisticEndOfLineSequence);
+ }
+
+ private static IUIDataGridRow CreateStatisticTitleRow(string title)
+ => Row(
+ null,
+ Cell(
+ Label()
+ .NeverWrap()
+ .Style(UILabelStyle.Subtitle)
+ .Text(title)),
+ Cell(Label()));
+}
diff --git a/src/app/dev/DevToys.Tools/Tools/Text/Compare/TextCompareGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/Text/Compare/TextCompareGuiTool.cs
index 4f9178279..023149c26 100644
--- a/src/app/dev/DevToys.Tools/Tools/Text/Compare/TextCompareGuiTool.cs
+++ b/src/app/dev/DevToys.Tools/Tools/Text/Compare/TextCompareGuiTool.cs
@@ -57,7 +57,7 @@ internal sealed class TextCompareGuiTool : IGuiTool
public UIToolView View
=> new(
- isScrollable: false,
+ isScrollable: true,
Grid()
.ColumnMediumSpacing()
diff --git a/src/app/dev/platforms/desktop/DevToys.CLI/Properties/launchSettings.json b/src/app/dev/platforms/desktop/DevToys.CLI/Properties/launchSettings.json
new file mode 100644
index 000000000..f54371f0f
--- /dev/null
+++ b/src/app/dev/platforms/desktop/DevToys.CLI/Properties/launchSettings.json
@@ -0,0 +1,8 @@
+{
+ "profiles": {
+ "DevToys.CLI": {
+ "commandName": "Project",
+ "commandLineArgs": "imageconverter -i \"C:\\Users\\ebaud\\Downloads\\Untitled - Copy.png\" \"C:\\Users\\ebaud\\Downloads\\Untitled.png\" -t webp"
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/app/tests/DevToys.UnitTests/Tools/Helpers/MemoryExtensionsTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Helpers/MemoryExtensionsTests.cs
new file mode 100644
index 000000000..04c971b39
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/Helpers/MemoryExtensionsTests.cs
@@ -0,0 +1,60 @@
+#nullable enable
+
+using DevToys.Tools.Helpers;
+using DevToys.Tools.Models;
+
+namespace DevToys.UnitTests.Tools.Helpers;
+public class MemoryExtensionsTests
+{
+ [Theory]
+ [InlineData(null, false, EndOfLineSequence.Unknown)]
+ [InlineData("", false, EndOfLineSequence.Unknown)]
+ [InlineData(" ", false, EndOfLineSequence.Unknown)]
+ [InlineData("\r", true, EndOfLineSequence.CarriageReturn)]
+ [InlineData("\n", true, EndOfLineSequence.LineFeed)]
+ [InlineData("\r\n", true, EndOfLineSequence.CarriageReturnLineFeed)]
+ [InlineData("\r ", true, EndOfLineSequence.CarriageReturn)]
+ [InlineData("\n\r", true, EndOfLineSequence.LineFeed)]
+ [InlineData("\n\r ", true, EndOfLineSequence.LineFeed)]
+ internal void IsLineBreak(string? input, bool expectedResult, EndOfLineSequence expectedLikeBreakType)
+ {
+ bool result = input.AsSpan().IsLineBreak(0, out EndOfLineSequence lineBreakType);
+
+ result.Should().Be(expectedResult);
+ lineBreakType.Should().Be(expectedLikeBreakType);
+ }
+
+ [Theory]
+ [InlineData(null, "")]
+ [InlineData("", "")]
+ [InlineData("Hello", "Hello")]
+ [InlineData("Hello world", "world")]
+ [InlineData("Hello world.", "world")]
+ [InlineData("Hello world...", "world")]
+ [InlineData("Hello world ...", "world")]
+ [InlineData("Hello world ... ", "world")]
+ [InlineData("Hello-world", "world")]
+ internal void GetLastWord(string? input, string? expectedResult)
+ {
+ ReadOnlySpan<char> result = input.AsSpan().GetLastWord();
+
+ new string(result).Should().Be(expectedResult);
+ }
+
+ [Theory]
+ [InlineData(null, "")]
+ [InlineData("", "")]
+ [InlineData("hello", "hello")]
+ [InlineData("hello\r", "hello", "")]
+ [InlineData("hello\n", "hello", "")]
+ [InlineData("hello\r\n", "hello", "")]
+ [InlineData("hello\n\r", "hello", "", "")]
+ [InlineData("hello\nworld\rhi", "hello", "world", "hi")]
+ [InlineData("hello \n world \r hi \r\n ", "hello ", " world ", " hi ", " ")]
+ internal void ToLines(string? input, params string[] expectLines)
+ {
+ List<ReadOnlyMemory<char>> result = input.AsMemory().ToLines();
+
+ result.Select(x => new string(x.Span)).Should().BeEquivalentTo(expectLines);
+ }
+}
diff --git a/src/app/tests/DevToys.UnitTests/Tools/Helpers/StringHelperTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Helpers/StringHelperTests.cs
new file mode 100644
index 000000000..d38972f0c
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/Helpers/StringHelperTests.cs
@@ -0,0 +1,269 @@
+#nullable enable
+
+using System.Threading;
+using DevToys.Tools.Helpers;
+using DevToys.Tools.Models;
+
+namespace DevToys.UnitTests.Tools.Helpers;
+
+public class StringHelperTests
+{
+ private const string Text = "Lorem ipsum dolor sit amet takimata sit.\r\n Placerat sed duis clita nonumy tincidunt est facilisis.\r Cum ea elitr consectetuer nonumy diam.\n Eos ut diam laoreet amet minim dolor dolores dolore amet lorem consetetur dolor clita.";
+ private const string Text2 = "Lorem ipsum dolor sit amet takimata sit.\r\nPlacerat sed duis clita nonumy tincidunt est facilisis.\rCum ea elitr consectetuer nonumy diam.\nEos ut diam laoreet amet minim dolor dolores dolore amet lorem consetetur dolor clita.";
+
+ [Theory]
+ [InlineData("", 0, 0, 1, 0)]
+ [InlineData(Text, 0, 0, 1, 0)]
+ [InlineData(Text, 1, 0, 1, 1)]
+ [InlineData(Text, 2, 0, 1, 2)]
+ [InlineData(Text, 2, 1, 1, 2)]
+ [InlineData(Text, 51, 1, 2, 9)]
+ [InlineData(Text, 49, 1, 2, 7)]
+ internal void AnalyzeSpan(string input, int selectionStart, int length, int expectLine, int expectedColumn)
+ {
+ StringHelper.AnalyzeSpan(
+ input,
+ new TextSpan(selectionStart, length),
+ CancellationToken.None,
+ out int _,
+ out int _,
+ out int _,
+ out int spanLineNumber,
+ out int spanColumnNumber);
+
+ spanLineNumber.Should().Be(expectLine);
+ spanColumnNumber.Should().Be(expectedColumn);
+ }
+
+ [Theory]
+ [InlineData("", 0, 0, 0, 0, 1, 1, EndOfLineSequence.Unknown)]
+ [InlineData(Text, 226, 226, 35, 4, 1, 4, EndOfLineSequence.Mixed)]
+ [InlineData("Lorem ipsum dolor sit amet takimata sit.", 40, 40, 7, 1, 1, 1, EndOfLineSequence.Unknown)]
+ [InlineData("Lorem \nipsum \ndolor \nsit \namet takimata sit.", 44, 44, 7, 1, 1, 5, EndOfLineSequence.LineFeed)]
+ [InlineData("Lorem \ripsum \rdolor \rsit \ramet takimata sit.", 44, 44, 7, 1, 1, 5, EndOfLineSequence.CarriageReturn)]
+ [InlineData("Lorem \r\nipsum \r\ndolor \r\nsit \r\namet takimata sit.", 48, 48, 7, 1, 1, 5, EndOfLineSequence.CarriageReturnLineFeed)]
+ [InlineData("Lorem \n\ripsum \n\rdolor \n\rsit \n\ramet takimata sit.", 48, 48, 7, 1, 5, 9, EndOfLineSequence.Mixed)]
+ internal void AnalyzeText(
+ string input,
+ int expectedByteCount,
+ int expectedCharacterCount,
+ int expectedWordCount,
+ int expectedSentenceCount,
+ int expectedParagraphCount,
+ int expectedLineCount,
+ EndOfLineSequence expectedOverallLineBreakType)
+ {
+ StringHelper.AnalyzeText(
+ input,
+ CancellationToken.None,
+ out int byteCount,
+ out int characterCount,
+ out int wordCount,
+ out int sentenceCount,
+ out int paragraphCount,
+ out int lineCount,
+ out EndOfLineSequence overallLineBreakType,
+ out Dictionary<char, int>? _,
+ out Dictionary<string, int>? _);
+
+ byteCount.Should().Be(expectedByteCount);
+ characterCount.Should().Be(expectedCharacterCount);
+ wordCount.Should().Be(expectedWordCount);
+ sentenceCount.Should().Be(expectedSentenceCount);
+ paragraphCount.Should().Be(expectedParagraphCount);
+ lineCount.Should().Be(expectedLineCount);
+ overallLineBreakType.Should().Be(expectedOverallLineBreakType);
+ }
+
+ [Fact]
+ internal void SentenceCase()
+ {
+ string result = StringHelper.ConvertToSentenceCase(Text, CancellationToken.None);
+ result
+ .Should()
+ .Be("Lorem ipsum dolor sit amet takimata sit.\r\n Placerat sed duis clita nonumy tincidunt est facilisis.\r Cum ea elitr consectetuer nonumy diam.\n Eos ut diam laoreet amet minim dolor dolores dolore amet lorem consetetur dolor clita.");
+ }
+
+ [Fact]
+ internal void TitleCase()
+ {
+ string result = StringHelper.ConvertToTitleCase(Text, CancellationToken.None);
+ result
+ .Should()
+ .Be("Lorem Ipsum Dolor Sit Amet Takimata Sit.\r\n Placerat Sed Duis Clita Nonumy Tincidunt Est Facilisis.\r Cum Ea Elitr Consectetuer Nonumy Diam.\n Eos Ut Diam Laoreet Amet Minim Dolor Dolores Dolore Amet Lorem Consetetur Dolor Clita.");
+ }
+
+ [Fact]
+ internal void PascalCase()
+ {
+ string result = StringHelper.ConvertToPascalCase(Text, CancellationToken.None);
+ result
+ .Should()
+ .Be("LoremIpsumDolorSitAmetTakimataSit\r\nPlaceratSedDuisClitaNonumyTinciduntEstFacilisis\rCumEaElitrConsectetuerNonumyDiam\nEosUtDiamLaoreetAmetMinimDolorDoloresDoloreAmetLoremConseteturDolorClita");
+ }
+
+ [Fact]
+ internal void SnakeCase()
+ {
+ string result = StringHelper.ConvertToSnakeCase(Text, CancellationToken.None);
+ result
+ .Should()
+ .Be("lorem_ipsum_dolor_sit_amet_takimata_sit\r\nplacerat_sed_duis_clita_nonumy_tincidunt_est_facilisis\rcum_ea_elitr_consectetuer_nonumy_diam\neos_ut_diam_laoreet_amet_minim_dolor_dolores_dolore_amet_lorem_consetetur_dolor_clita");
+ }
+
+ [Fact]
+ internal void ConstantCase()
+ {
+ string result = StringHelper.ConvertToConstantCase(Text, CancellationToken.None);
+ result
+ .Should()
+ .Be("LOREM_IPSUM_DOLOR_SIT_AMET_TAKIMATA_SIT\r\nPLACERAT_SED_DUIS_CLITA_NONUMY_TINCIDUNT_EST_FACILISIS\rCUM_EA_ELITR_CONSECTETUER_NONUMY_DIAM\nEOS_UT_DIAM_LAOREET_AMET_MINIM_DOLOR_DOLORES_DOLORE_AMET_LOREM_CONSETETUR_DOLOR_CLITA");
+ }
+
+ [Fact]
+ internal void KebabCase()
+ {
+ string result = StringHelper.ConvertToKebabCase(Text, CancellationToken.None);
+ result
+ .Should()
+ .Be("lorem-ipsum-dolor-sit-amet-takimata-sit\r\nplacerat-sed-duis-clita-nonumy-tincidunt-est-facilisis\rcum-ea-elitr-consectetuer-nonumy-diam\neos-ut-diam-laoreet-amet-minim-dolor-dolores-dolore-amet-lorem-consetetur-dolor-clita");
+ }
+
+ [Fact]
+ internal void CobolCase()
+ {
+ string result = StringHelper.ConvertToCobolCase(Text, CancellationToken.None);
+ result
+ .Should()
+ .Be("LOREM-IPSUM-DOLOR-SIT-AMET-TAKIMATA-SIT\r\nPLACERAT-SED-DUIS-CLITA-NONUMY-TINCIDUNT-EST-FACILISIS\rCUM-EA-ELITR-CONSECTETUER-NONUMY-DIAM\nEOS-UT-DIAM-LAOREET-AMET-MINIM-DOLOR-DOLORES-DOLORE-AMET-LOREM-CONSETETUR-DOLOR-CLITA");
+ }
+
+ [Fact]
+ internal void TrainCase()
+ {
+ string result = StringHelper.ConvertToTrainCase(Text, CancellationToken.None);
+ result
+ .Should()
+ .Be("Lorem-Ipsum-Dolor-Sit-Amet-Takimata-Sit\r\nPlacerat-Sed-Duis-Clita-Nonumy-Tincidunt-Est-Facilisis\rCum-Ea-Elitr-Consectetuer-Nonumy-Diam\nEos-Ut-Diam-Laoreet-Amet-Minim-Dolor-Dolores-Dolore-Amet-Lorem-Consetetur-Dolor-Clita");
+ }
+
+ [Fact]
+ internal void AlternatingCase()
+ {
+ string result = StringHelper.ConvertToAlternatingCase(Text, CancellationToken.None);
+ result
+ .Should()
+ .Be("lOrEm iPsUm dOlOr sIt aMeT TaKiMaTa sIt.\r\n PlAcErAt sEd dUiS ClItA NoNuMy tInCiDuNt eSt fAcIlIsIs.\r cUm eA ElItR CoNsEcTeTuEr nOnUmY DiAm.\n eOs uT DiAm lAoReEt aMeT MiNiM DoLoR DoLoReS DoLoRe aMeT LoReM CoNsEtEtUr dOlOr cLiTa.");
+ }
+
+ [Fact]
+ internal void InverseCase()
+ {
+ string result = StringHelper.ConvertToInverseCase(Text, CancellationToken.None);
+ result
+ .Should()
+ .Be("LoReM IpSuM DoLoR SiT AmEt tAkImAtA SiT.\r\n pLaCeRaT SeD DuIs cLiTa nOnUmY TiNcIdUnT EsT FaCiLiSiS.\r CuM Ea eLiTr cOnSeCtEtUeR NoNuMy dIaM.\n EoS Ut dIaM LaOrEeT AmEt mInIm dOlOr dOlOrEs dOlOrE AmEt lOrEm cOnSeTeTuR DoLoR ClItA.");
+ }
+
+ [Theory]
+ [InlineData("", EndOfLineSequence.Unknown)]
+ [InlineData(Text, EndOfLineSequence.Mixed)]
+ [InlineData("Lorem ipsum dolor sit amet takimata sit.", EndOfLineSequence.Unknown)]
+ [InlineData("Lorem \nipsum \ndolor \nsit \namet takimata sit.", EndOfLineSequence.LineFeed)]
+ [InlineData("Lorem \ripsum \rdolor \rsit \ramet takimata sit.", EndOfLineSequence.CarriageReturn)]
+ [InlineData("Lorem \r\nipsum \r\ndolor \r\nsit \r\namet takimata sit.", EndOfLineSequence.CarriageReturnLineFeed)]
+ [InlineData("Lorem \n\ripsum \n\rdolor \n\rsit \n\ramet takimata sit.", EndOfLineSequence.Mixed)]
+ internal void DetectLineBreakKind(string input, EndOfLineSequence expectedLineBreak)
+ {
+ EndOfLineSequence result = StringHelper.DetectLineBreakKind(input, CancellationToken.None);
+ result
+ .Should()
+ .Be(expectedLineBreak);
+ }
+
+ [Theory]
+ [InlineData("", "")]
+ [InlineData(Text, "Lorem ipsum dolor sit amet takimata sit.\n Placerat sed duis clita nonumy tincidunt est facilisis.\n Cum ea elitr consectetuer nonumy diam.\n Eos ut diam laoreet amet minim dolor dolores dolore amet lorem consetetur dolor clita.")]
+ [InlineData("Lorem ipsum dolor sit amet takimata sit.", "Lorem ipsum dolor sit amet takimata sit.")]
+ [InlineData("Lorem \nipsum \ndolor \nsit \namet takimata sit.", "Lorem \nipsum \ndolor \nsit \namet takimata sit.")]
+ [InlineData("Lorem \ripsum \rdolor \rsit \ramet takimata sit.", "Lorem \nipsum \ndolor \nsit \namet takimata sit.")]
+ [InlineData("Lorem \r\nipsum \r\ndolor \r\nsit \r\namet takimata sit.", "Lorem \nipsum \ndolor \nsit \namet takimata sit.")]
+ [InlineData("Lorem \n\ripsum \n\rdolor \n\rsit \n\ramet takimata sit.", "Lorem \n\nipsum \n\ndolor \n\nsit \n\namet takimata sit.")]
+ internal void ConvertLineBreakToLF(string input, string expectedResult)
+ {
+ string result = StringHelper.ConvertLineBreakToLF(input);
+ result
+ .Should()
+ .Be(expectedResult);
+ }
+
+ [Theory]
+ [InlineData("", "")]
+ [InlineData(Text, "Lorem ipsum dolor sit amet takimata sit.\r\n Placerat sed duis clita nonumy tincidunt est facilisis.\r\n Cum ea elitr consectetuer nonumy diam.\r\n Eos ut diam laoreet amet minim dolor dolores dolore amet lorem consetetur dolor clita.")]
+ [InlineData("Lorem ipsum dolor sit amet takimata sit.", "Lorem ipsum dolor sit amet takimata sit.")]
+ [InlineData("Lorem \nipsum \ndolor \nsit \namet takimata sit.", "Lorem \r\nipsum \r\ndolor \r\nsit \r\namet takimata sit.")]
+ [InlineData("Lorem \ripsum \rdolor \rsit \ramet takimata sit.", "Lorem \r\nipsum \r\ndolor \r\nsit \r\namet takimata sit.")]
+ [InlineData("Lorem \r\nipsum \r\ndolor \r\nsit \r\namet takimata sit.", "Lorem \r\nipsum \r\ndolor \r\nsit \r\namet takimata sit.")]
+ [InlineData("Lorem \n\ripsum \n\rdolor \n\rsit \n\ramet takimata sit.", "Lorem \r\n\r\nipsum \r\n\r\ndolor \r\n\r\nsit \r\n\r\namet takimata sit.")]
+ internal void ConvertLineBreakToCRLF(string input, string expectedResult)
+ {
+ string result = StringHelper.ConvertLineBreakToCRLF(input);
+ result
+ .Should()
+ .Be(expectedResult);
+ }
+
+ [Fact]
+ internal void SortLinesAlphabetically()
+ {
+ string result = StringHelper.SortLinesAlphabetically(Text2, EndOfLineSequence.CarriageReturnLineFeed);
+ result
+ .Should()
+ .Be("Cum ea elitr consectetuer nonumy diam.\r\nEos ut diam laoreet amet minim dolor dolores dolore amet lorem consetetur dolor clita.\r\nLorem ipsum dolor sit amet takimata sit.\r\nPlacerat sed duis clita nonumy tincidunt est facilisis.");
+ }
+
+ [Fact]
+ internal void SortLinesAlphabeticallyDescending()
+ {
+ string result = StringHelper.SortLinesAlphabeticallyDescending(Text2, EndOfLineSequence.CarriageReturnLineFeed);
+ result
+ .Should()
+ .Be("Placerat sed duis clita nonumy tincidunt est facilisis.\r\nLorem ipsum dolor sit amet takimata sit.\r\nEos ut diam laoreet amet minim dolor dolores dolore amet lorem consetetur dolor clita.\r\nCum ea elitr consectetuer nonumy diam.");
+ }
+
+ [Fact]
+ internal void SortLinesByLastWord()
+ {
+ string result = StringHelper.SortLinesByLastWord(Text2, EndOfLineSequence.CarriageReturnLineFeed);
+ result
+ .Should()
+ .Be("Eos ut diam laoreet amet minim dolor dolores dolore amet lorem consetetur dolor clita.\r\nCum ea elitr consectetuer nonumy diam.\r\nPlacerat sed duis clita nonumy tincidunt est facilisis.\r\nLorem ipsum dolor sit amet takimata sit.");
+ }
+
+ [Fact]
+ internal void SortLinesByLastWordDescending()
+ {
+ string result = StringHelper.SortLinesByLastWordDescending(Text2, EndOfLineSequence.CarriageReturnLineFeed);
+ result
+ .Should()
+ .Be("Lorem ipsum dolor sit amet takimata sit.\r\nPlacerat sed duis clita nonumy tincidunt est facilisis.\r\nCum ea elitr consectetuer nonumy diam.\r\nEos ut diam laoreet amet minim dolor dolores dolore amet lorem consetetur dolor clita.");
+ }
+
+ [Fact]
+ internal void ReverseLines()
+ {
+ string result = StringHelper.ReverseLines(Text2, EndOfLineSequence.CarriageReturnLineFeed);
+ result
+ .Should()
+ .Be("Eos ut diam laoreet amet minim dolor dolores dolore amet lorem consetetur dolor clita.\r\nCum ea elitr consectetuer nonumy diam.\r\nPlacerat sed duis clita nonumy tincidunt est facilisis.\r\nLorem ipsum dolor sit amet takimata sit.");
+ }
+
+ [Fact]
+ internal void ShuffleLines()
+ {
+ string result = StringHelper.ShuffleLines(Text2, EndOfLineSequence.CarriageReturnLineFeed);
+ result
+ .Should()
+ .NotBe(Text2);
+ }
+}