Skip to content

Commit

Permalink
Merge pull request #69 from hbre/hbre/issue68
Browse files Browse the repository at this point in the history
Fix Issue 68 - Special Characters break alignment
  • Loading branch information
khalidabuhakmeh authored Sep 25, 2024
2 parents c93523a + 93ddac9 commit e928d39
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
33 changes: 33 additions & 0 deletions ConsoleTables.Tests/ConsoleTableTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,39 @@ public void ShouldBeAvoidErrorOnToStringFromAddRows()
Count: 2", table);
}

[Fact]
public void SpecialCharactersShouldNotBreakTable()
{
var users = new List<User>
{
new() { Name = "René", Age = 59 },
new() { Name = "Otto", Age = 52 }
};
var table = ConsoleTable
.From(users)
.Configure(o => o.NumberAlignment = Alignment.Right)
.ToString();

Assert.Equal(
$@" --------------
| Name | Age |
--------------
| René | 59 |
--------------
| Otto | 52 |
--------------
Count: 2", table);
}

[Fact]
public void TestGetTextWidth()
{
Assert.Equal(3, ConsoleTable.GetTextWidth("abc"));
Assert.Equal(3, ConsoleTable.GetTextWidth("äöü"));
Assert.Equal(4, ConsoleTable.GetTextWidth("René"));
}

[Fact]
public void NumberShouldBeRightAligned()
{
Expand Down
5 changes: 3 additions & 2 deletions src/ConsoleTables/ConsoleTable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Wcwidth;

namespace ConsoleTables
{
Expand Down Expand Up @@ -206,7 +207,7 @@ public static int GetTextWidth(string value)
if (value == null)
return 0;

var length = value.ToCharArray().Sum(c => c > 127 ? 2 : 1);
var length = value.ToCharArray().Sum(c => UnicodeCalculator.GetWidth(c));
return length;
}

Expand Down Expand Up @@ -305,7 +306,7 @@ private List<int> ColumnLengths()
.Select((t, i) => Rows.Select(x => x[i])
.Union(new[] { Columns[i] })
.Where(x => x != null)
.Select(x => x.ToString().ToCharArray().Sum(c => c > 127 ? 2 : 1)).Max())
.Select(x => x.ToString().ToCharArray().Sum(c => UnicodeCalculator.GetWidth(c))).Max())
.ToList();
return columnLengths;
}
Expand Down
4 changes: 4 additions & 0 deletions src/ConsoleTables/ConsoleTables.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Wcwidth" Version="1.0.0" />
</ItemGroup>

<PropertyGroup>
<MinVerMinimumMajorMinor>2.2</MinVerMinimumMajorMinor>
</PropertyGroup>
Expand Down

0 comments on commit e928d39

Please sign in to comment.