Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/ConsoleTables/ConsoleTable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ public class ConsoleTable
public IList<object> Columns { get; }
public IList<object[]> Rows { get; }

public int MaxWidth { get; set; } = 40;
public char WordBreakDelimiter { get; private set; }

public ConsoleTableOptions Options { get; }
public Type[] ColumnTypes { get; private set; }

Expand All @@ -36,6 +39,7 @@ public ConsoleTable(ConsoleTableOptions options)
{
Options = options ?? throw new ArgumentNullException("options");
Rows = new List<object[]>();
WordBreakDelimiter = ' ';
Columns = new List<object>(options.Columns);
}

Expand All @@ -46,6 +50,12 @@ public ConsoleTable AddColumn(IEnumerable<string> names)
return this;
}

public ConsoleTable SetWordBreakDelimiter(char delimiter)
{
WordBreakDelimiter = delimiter;
return this;
}

public ConsoleTable AddRow(params object[] values)
{
if (values == null)
Expand Down Expand Up @@ -187,6 +197,38 @@ private void SetFormats(List<int> columnLengths, List<string> columnAlignment)
{
var allLines = new List<object[]>();
allLines.Add(Columns.ToArray());

for (var i = 0; i < Rows.Count; i++)
{
var row = Rows[i];

if (row.Any(o => o != null && o.ToString().Length > MaxWidth)) //checks if any column exceeds the MaxWidth
{
var newRow = new object[row.Length];
for (var j = 0; j < row.Length; j++) //loop through cells
{
var cellStr = row[j]?.ToString() ?? "";
if (cellStr.Length > MaxWidth) //if cell exceeds MaxWidth
{
var cutCell = cellStr[..MaxWidth]; //cut the cell
var leftOver = cellStr[MaxWidth..]; //into two parts
if (cutCell[^1] != ' ' && cutCell[0] != ' ') //if the cut is in the middle of a word
{
var lastSpace = cutCell.LastIndexOf(WordBreakDelimiter); //find the last WordBreak Delimiter of the first cell
if (lastSpace > 0) //if there is a space
{
cutCell = cellStr[..lastSpace]; //cut the cell at the last space
leftOver = cellStr[lastSpace..]; //the leftover is the rest of the cell
}//if there is no space, the cell will be cut at MaxWidth
}
newRow[j] = leftOver.Trim();
Rows[i][j] = cutCell.Trim();
}
}
Rows.Insert(i + 1, newRow);
}
}

allLines.AddRange(Rows);

Formats = allLines.Select(d =>
Expand Down