athari / csconsoleformat Goto Github PK
View Code? Open in Web Editor NEW.NET C# library for advanced formatting of console output [Apache]
License: Other
.NET C# library for advanced formatting of console output [Apache]
License: Other
Calling Console.Write
for every line seems to be unoptimal compared to writing one big block of text. Probably caused by too much interop. See #21 (comment).
Optimize number of API calls in ConsoleRenderTarget
for specific cases, like lack of color formating in the document or disabled formatting like discussed in #22.
Optimizations from #11 should make that unnecessary for modern platforms, but generic fallback console writing should be fast too.
Windows 10 supports 256 colors now, see Orange text color in C# console application?
For *nix, it depends on the used terminal app(?). The flags are kinda standard though, so bold-italic-underline-blink flags are either supported or ignored, so should be supported by the library. The fact that "bold" often means "brigher set of forecolors" kinda sucks though.
If I output chinese words,the grid will broken,I think the problem is in the character calculation of Chinese characters.
My code is like this:
static void Main(string[] args)
{
var headerThickness = new LineThickness(LineWidth.Double, LineWidth.Single);
Console.WriteLine("outpt Chinese");
var doc = new Document(
new Span("Order #") { Color = Yellow }, "Id", "\n",
new Span("Customer: ") { Color = Yellow }, "Name",
new Grid
{
Color = Gray,
Columns = { GridLength.Char(10), GridLength.Char(20), GridLength.Char(70) },
Children = {
new Cell("Id") { Stroke = headerThickness ,TextAlign =TextAlign.Center},
new Cell("Name") { Stroke = headerThickness ,TextAlign =TextAlign.Center},
new Cell("Assembly") { Stroke = headerThickness,TextAlign =TextAlign.Center },
new[] {
new Cell("AAAAA"),
new Cell("这里是中文,有错误!"),
new Cell("BBBBBBBBBBBBBBBBBBBBBBBB"),
}
}
}
);
ConsoleRenderer.RenderDocument(doc);
Console.WriteLine("outpt English");
doc = new Document(
new Span("Order #") { Color = Yellow }, "Id", "\n",
new Span("Customer: ") { Color = Yellow }, "Name",
new Grid
{
Color = Gray,
Columns = { GridLength.Char(10), GridLength.Char(20), GridLength.Char(70) },
Children = {
new Cell("Id") { Stroke = headerThickness ,TextAlign =TextAlign.Center},
new Cell("Name") { Stroke = headerThickness ,TextAlign =TextAlign.Center},
new Cell("Assembly") { Stroke = headerThickness,TextAlign =TextAlign.Center },
new[] {
new Cell("AAAAA"),
new Cell("This is English,And it is OK"),
new Cell("BBBBBBBBBBBBBBBBBBBBBBBB"),
}
}
}
);
ConsoleRenderer.RenderDocument(doc);
}
FluentAssertins is switching from 1.4 back to 1.3 fluentassertions/fluentassertions#779, so we can do to.
Should happen on 5.2 release.
There're probably quite a few questions on StackOverflow about formatting in console, tables, colors and word wrap. Find them and help people find the one and only correct solution.
And don't copy-paste answers like the last time. Don't be that stupid, you dirty rep whore. You have 25K rep, it's time to pretend you have brains.
Add CodeCov badge. As a bonus, it shows pretty diagrams of code coverage.
Use example CodeCov C# repository as an example.
Code coverage apparently requires debug(?) build with full non-portable PDBs, so switch to Build Debug -> Test & Coverage -> Build Release -> Deploy sequence? There're no parallel builds on free AppVeyour plan, so no point in separating build jobs even if it's possible. Symbol Packages for .NET Standard libraries are probably supposed to contain portable PDBs, so there's no way around double build, I guess.
Could also be a good time to find out why the heck only 1 set of tests is executed on AppVeyor instead of 6 ( { XAML, No-XAML } x { Core 1.1, Core 2.0, .NET 4.6 } ).
Related:
P. S. Coveralls to CodeCov is like SensioLabs Insight to Scrutinizer. Don't bother with it. Not worth the badge. Well, maybe. If it's one line of code in the build script.
Integrate with popular command-line parsers to allow:
Zero-effort improvement to formatting of help texts. Should match the original tool's formatting closely, but improve upon it.
Easy customization options like colors, offsets, headers, padding etc.
Deep customization by providing source data in a ready-to-use form if the original tool doesn't. Code for generating documents from the points above should serve as a sample in this case.
Likely candidates:
Evaluate command line packages:
Colors module extends string prototype with color properties which generate escape sequences, which creates conscise API for colored console output.
Something like this can be done with CsConsoleFormat. A dirty hacky version can be found in my answer Using colors in console, how to store in a simplified notation, but it doesn't support background colors. Supporting both foreground and background colors would require extension methods for both strings and spans.
Looks like it's a very common use case, so implement this API properly.
Check arguments of all constructors and methods that accept object
and params object[]
as an argument and check values only at runtime. Check block-inline hierarchy, check elements that can't have children etc.
Suggesting to always set Color
and BackgroundColor
on Document
may also be a good idea.
Avoid use of LineWidth.Heavy
(limited font support). Check that combinations on line widths in LineChar
are valid (heavy and double can't be combined).
Double assignment of the same attached property (the last assignment wins).
If Roslyn can access XAML, check element hierarchy there too.
Currently LineChar
supports only 4 bits of information which isn't enough to completely describe all box-drawing characters. While it works for separate tables, it requires guessing and causes lines of two adjacent tables to join.
LineChar
to None
/Single
/Wide
in all 4 directions.ConsoleBuffer
line-drawing methods to allow specifying sub-character lengths.TextAlign=Right
seems to be ignored if text is shorter than width available for containing block.
<Div TextAlign="Right">
<Span Text="Hello world!">
</Div>
The workaround is to add Align=Right
, but it shouldn't be this way. Block should always occupy all available width to make text alignment work in this case. Look like for some reason it doesn't.
Apparently FIGlet font implementation from Colorful.Console is a joke which doesn't support any FIGlet features like smushing and transforms. Slanted fonts look like crap because they're designed to be smushed. All FIGlet implementations in C# and Java seem to be based on the same ancestor from which Colorful.Console's implementation descended too (also almost nobody cares about linking to source, apparently). There're forks with basic smushing, but they're far from complete.
According to FIGlet,org, the reference imlementation is FIGlet for Unix (ftp://ftp.figlet.org/pub/figlet/program/unix/) written in C, which also includes FIGlet specification (which is anything but OSS thanks to non-commercial requirements btw) and "intergation-y" tests. There's also FIGwin (ftp://ftp.figlet.org/pub/figlet/program/windows/) written in VB (and compiled to 16-bit NE .exe file) with a somewhat different feature set (see feature comparison in the "spec"), sources of which are lost in the nether.
The whole FIGlet program is 2K LOC of C, half of which are low-level C utilities, so no longer relevant. Should be pretty easy to port. FIGlet also switched to normal open-source license, New BSD. (It contradicts the requirements from the "spec"... Let's assume it's dual-licensed. Nobody is going to sue over FIGlet anyway.)
I need to generate a table to be used in a fixed lines per page scenario. If the table should continue onto multiple pages, I want to repeat the header at the top of those pages:
| header1 | header2 | header 3 |
--------------------------------------------------
| one | two | three |
| 1 | 2 | 3 |
| this line should be longer | yes it is | oh |
...more rows
--------------------------------------------------
--page 2---
| header1 | header2 | header 3 |
--------------------------------------------------
Can CsConsoleFormat do this?
Also, I don't want any delimiters, like "|" and "----------------------". Can the table be configured to output no column and row delimiters?
Customizing borders of tables is a mess. Removing table outer borders requires customizing every cell.
Look into supporting table styles like in Microsoft Word, at least for borders, but possibly for colors and alignment.
Example Word style:
<w:style w:type="table" w:styleId="InfoTable">
<w:pPr>
<w:spacing w:after="0pt" w:line="12pt" w:lineRule="auto"/>
</w:pPr>
<w:rPr>
<w:rFonts w:ascii="Arial Narrow" w:hAnsi="Arial Narrow"/>
<w:sz w:val="19"/>
</w:rPr>
<w:tblPr>
<w:tblBorders>
<w:top w:val="single" w:sz="4" w:space="0" w:color="auto"/>
<w:start w:val="single" w:sz="4" w:space="0" w:color="auto"/>
<w:bottom w:val="single" w:sz="4" w:space="0" w:color="auto"/>
<w:end w:val="single" w:sz="4" w:space="0" w:color="auto"/>
<w:insideH w:val="single" w:sz="4" w:space="0" w:color="auto"/>
</w:tblBorders>
</w:tblPr>
<w:tcPr>
<w:vAlign w:val="center"/>
</w:tcPr>
<w:tblStylePr w:type="firstCol">
<w:pPr>
<w:jc w:val="start"/>
</w:pPr>
<w:rPr>
<w:b/>
</w:rPr>
<w:tblPr/>
<w:tcPr>
<w:tcBorders>
<w:top w:val="nil"/>
<w:start w:val="nil"/>
<w:bottom w:val="nil"/>
<w:end w:val="single" w:sz="4" w:space="0" w:color="auto"/>
<w:insideH w:val="nil"/>
<w:insideV w:val="nil"/>
<w:tl2br w:val="nil"/>
<w:tr2bl w:val="nil"/>
</w:tcBorders>
<w:vAlign w:val="top"/>
</w:tcPr>
</w:tblStylePr>
</w:style>
Example Word style usage:
<w:tblPr>
<w:tblStyle w:val="InfoTable"/>
<w:tblLook w:firstRow="0" w:lastRow="0" w:firstColumn="1" w:lastColumn="0" w:noHBand="1" w:noVBand="1"/>
</w:tblPr>
I need to generate tables in text, but not for writing to the console. Can CsConsoleFormat render to a string or stream, instead of the console?
In the version 1.0 if foreground or background colors are not specified, the white and black colors are used for them. It looks unnatural if other colors are used in the terminal by default, like in Mas OS X Terminal.
It would be nice if it is possible to render the user interface using default colors.
As a workaround, it is possible to set Color
to Console.ForegroundColor
and Background
to Console.BackgroundColor
but it works only on Windows. On Linux and Mas OS these properties return (ConsoleColor)(-1)
and it looks like there is no easy and universal way to determine the actual colors.
I have been trying to render a grid with no border and it seems to resort to using LineThickness.Single
instead.
I have tried the following:
Stroke = LineThickness.None;
Stroke = new LineThickness(0);
It will render with a border every time.
Hi,
Trying to compile examples in VS2012 and have an errors : first project won't load looking for .net 4.6 framework installed, then it shows a list of errors:
Error 15 Identifier expected; 'static' is a keyword C:\Users\Administrator\Documents\Visual Studio 2012\Projects\CsConsoleFormat-master\CsConsoleFormat-master\Alba.CsConsoleFormat\Converters\GridLengthConverter.cs 4 7 Alba.CsConsoleFormat
Error 16 Identifier expected; 'static' is a keyword C:\Users\Administrator\Documents\Visual Studio 2012\Projects\CsConsoleFormat-master\CsConsoleFormat-master\Alba.CsConsoleFormat\Converters\ConsoleColorConverter.cs 4 7 Alba.CsConsoleFormat
Error 17 Expected class, delegate, enum, interface, or struct C:\Users\Administrator\Documents\Visual Studio 2012\Projects\CsConsoleFormat-master\CsConsoleFormat-master\Alba.CsConsoleFormat\Converters\VectorConverter.cs 4 14 Alba.CsConsoleFormat
Error 18 Expected class, delegate, enum, interface, or struct C:\Users\Administrator\Documents\Visual Studio 2012\Projects\CsConsoleFormat-master\CsConsoleFormat-master\Alba.CsConsoleFormat\Converters\ThicknessConverter.cs 4 14 Alba.CsConsoleFormat
Error 19 Expected class, delegate, enum, interface, or struct C:\Users\Administrator\Documents\Visual Studio 2012\Projects\CsConsoleFormat-master\CsConsoleFormat-master\Alba.CsConsoleFormat\Converters\SizeConverter.cs 4 14 Alba.CsConsoleFormat
Error 20 Expected class, delegate, enum, interface, or struct C:\Users\Administrator\Documents\Visual Studio 2012\Projects\CsConsoleFormat-master\CsConsoleFormat-master\Alba.CsConsoleFormat\Converters\RectConverter.cs 4 14 Alba.CsConsoleFormat
Error 21 Expected class, delegate, enum, interface, or struct C:\Users\Administrator\Documents\Visual Studio 2012\Projects\CsConsoleFormat-master\CsConsoleFormat-master\Alba.CsConsoleFormat\Converters\PointConverter.cs 4 14 Alba.CsConsoleFormat
Error 22 Expected class, delegate, enum, interface, or struct C:\Users\Administrator\Documents\Visual Studio 2012\Projects\CsConsoleFormat-master\CsConsoleFormat-master\Alba.CsConsoleFormat\Converters\LineThicknessConverter.cs 4 14 Alba.CsConsoleFormat
Error 23 Expected class, delegate, enum, interface, or struct C:\Users\Administrator\Documents\Visual Studio 2012\Projects\CsConsoleFormat-master\CsConsoleFormat-master\Alba.CsConsoleFormat\Converters\LengthConverter.cs 4 14 Alba.CsConsoleFormat
Error 24 Expected class, delegate, enum, interface, or struct C:\Users\Administrator\Documents\Visual Studio 2012\Projects\CsConsoleFormat-master\CsConsoleFormat-master\Alba.CsConsoleFormat\Converters\GridLengthConverter.cs 4 14 Alba.CsConsoleFormat
Error 25 Expected class, delegate, enum, interface, or struct C:\Users\Administrator\Documents\Visual Studio 2012\Projects\CsConsoleFormat-master\CsConsoleFormat-master\Alba.CsConsoleFormat\Converters\ConsoleColorConverter.cs 4 14 Alba.CsConsoleFormat
Error 26 ; expected C:\Users\Administrator\Documents\Visual Studio 2012\Projects\CsConsoleFormat-master\CsConsoleFormat-master\Alba.CsConsoleFormat\Core\LayoutInfo.cs 12 35 Alba.CsConsoleFormat
Error 27 Invalid token ')' in class, struct, or interface member declaration C:\Users\Administrator\Documents\Visual Studio 2012\Projects\CsConsoleFormat-master\CsConsoleFormat-master\Alba.CsConsoleFormat\Core\LayoutInfo.cs 12 49 Alba.CsConsoleFormat
Error 28 Method must have a return type C:\Users\Administrator\Documents\Visual Studio 2012\Projects\CsConsoleFormat-master\CsConsoleFormat-master\Alba.CsConsoleFormat\Core\LayoutInfo.cs 12 50 Alba.CsConsoleFormat
Error 29 ; expected C:\Users\Administrator\Documents\Visual Studio 2012\Projects\CsConsoleFormat-master\CsConsoleFormat-master\Alba.CsConsoleFormat\Converters\XmlLanguageConverter.cs 16 94 Alba.CsConsoleFormat
Error 30 Invalid token '==' in class, struct, or interface member declaration C:\Users\Administrator\Documents\Visual Studio 2012\Projects\CsConsoleFormat-master\CsConsoleFormat-master\Alba.CsConsoleFormat\Converters\XmlLanguageConverter.cs 16 108 Alba.CsConsoleFormat
Error 31 Invalid token ')' in class, struct, or interface member declaration C:\Users\Administrator\Documents\Visual Studio 2012\Projects\CsConsoleFormat-master\CsConsoleFormat-master\Alba.CsConsoleFormat\Converters\XmlLanguageConverter.cs 16 124 Alba.CsConsoleFormat
Error 32 ; expected C:\Users\Administrator\Documents\Visual Studio 2012\Projects\CsConsoleFormat-master\CsConsoleFormat-master\Alba.CsConsoleFormat\Core\Enums\LineWidth.cs 17 61 Alba.CsConsoleFormat
Error 33 Invalid token '==' in class, struct, or interface member declaration C:\Users\Administrator\Documents\Visual Studio 2012\Projects\CsConsoleFormat-master\CsConsoleFormat-master\Alba.CsConsoleFormat\Core\Enums\LineWidth.cs 17 70 Alba.CsConsoleFormat
Error 34 Invalid token '0' in class, struct, or interface member declaration C:\Users\Administrator\Documents\Visual Studio 2012\Projects\CsConsoleFormat-master\CsConsoleFormat-master\Alba.CsConsoleFormat\Core\Enums\LineWidth.cs 17 90 Alba.CsConsoleFormat
Error 35 ; expected C:\Users\Administrator\Documents\Visual Studio 2012\Projects\CsConsoleFormat-master\CsConsoleFormat-master\Alba.CsConsoleFormat\Converters\LengthConverter.cs 17 94 Alba.CsConsoleFormat
Error 36 ; expected C:\Users\Administrator\Documents\Visual Studio 2012\Projects\CsConsoleFormat-master\CsConsoleFormat-master\Alba.CsConsoleFormat\Converters\ConsoleColorConverter.cs 17 94 Alba.CsConsoleFormat
Error 37 Method must have a return type C:\Users\Administrator\Documents\Visual Studio 2012\Projects\CsConsoleFormat-master\CsConsoleFormat-master\Alba.CsConsoleFormat\Converters\LengthConverter.cs 17 97 Alba.CsConsoleFormat
Was wondering what might be causing this issue.
Thanks
Alex
If I do this ConsoleRenderer.RenderDocument(doc);
I get the output as expected.
But if I do this:
StringWriter sw = new StringWriter();
vs ConsoleRenderer.RenderDocumentAsText(doc, sw);
and then Console.WriteLine(sw.StringBuilder().toString());
There is an extra "\r\n"
between each line.
I needed to get a nice table fast but CsConsoleFormat appeared too complicated. It would help a lot if there was a simple fully working and copy-pastable example to start with, right on the front page. Something like this:
using ConsoleTables;
public class Color
{
public string Name { get; set; }
public string Code { get; set; }
}
public class Program
{
public static void Main()
{
var colors = new[] {
new Color { Name = "Blue", Code = "#0000FF" },
new Color { Name = "Yellow", Code = "#FFFF00" },
new Color { Name = "Cyan", Code = "#00FFFF" }};
var table = new ConsoleTable(
"Name",
"Code");
foreach (var color in colors)
{
table.AddRow(color.Name, color.Code);
}
table.Write();
}
}
And the result of the program, of course:
--------------------
| Name | Code |
--------------------
| Blue | #0000FF |
--------------------
| Yellow | #FFFF00 |
--------------------
| Cyan | #00FFFF |
--------------------
Count: 3
Free Coverity seems to be down. When it isn't, check out whether it's possible to get it to do something useful, like providing a badge for ReadMe.
Last time I checked, it was ages late on supporting a recent version of Visual Studio, so don't expect much, especially with Core stuff being not 10 years old and the project being built on the latest VS with the latest C#. Even ReSharper fails.
I've tried using a negative top margin on a block element like this:
var div = new Div { Margin = new Thickness(0, -1, 0, 0) };
I've added some children to this element that should span 6 lines in height. Using the -1 top margin causes the element to only have a height of 1 line and the other lines are missing.
It will only render with the correct height if I remove the negative margin. It also seems to work okay if I use a bottom margin like this, but this causes an extra line to render after my div which is not what I want:
var div = new Div { Margin = new Thickness(0, -1, 0, 1) };
Will this library compile well with dotnet core? Is there a newer dotnet core version of this library? Thanks for your attention
More modes of displaying images:
More image sources:
Also make image sources pluggable instead of current weird internal dependencies.
See also Display a Image in a console application.
See elw00d/consoleframework#45 for more details.
Fixed in ConsoleFramework by elw00d/consoleframework@bde72d5.
Hello,
I was able to execute the ConsoleTest application to see how it performed with the new Windows Terminal. It appears you are setting the terminal width prior to rendering the text which is not being honored by the new Windows Terminal. Because of that the text rendering does not line up properly and word wraps. Do you expect this library to work well in the new Windows Terminal? Can any tweaks be done to make it compatible? Classic command console seems to be fine.
Also, do you expect the library to perform well in a dotnet core / linux environment?
My goal is to add this library to a console application I am building which will run on dotnet core and non-windows machines. I have a lot of tables and formatting in my output and would very much like to use a library like this.
Thank you.
The current choice of escape codes used by AnsiRenderTarget
is pretty much random. Try detecting current system's/terminal's actual escape codes. Investigate what .NET Core does to detect them for switching console colors.
Windows 10 supports escape codes too now. Needs to be enabled with ENABLE_VIRTUAL_TERMINAL_PROCESSING
flag in SetConsoleMode
. Find out what codes are supported. All related issues are discussed in symfony/symfony#19520.
Also give meaningful names to the commented out color maps and allow to customize them.
I'm new to programming, dunno if there are good tools for this out there but most things I'm finding has all this HTML stuff that I don't want to learn or fuss with.
Instead of .Yellow(), can I just use markdown instead?
Look into using WriteConsoleOutput
Windows API. Sample code on Stack Overflow: How can I write fast colored output to Console?
Similarly, writing ANSI escape sequences may be faster on *nix.
File templates for XAML files could be useful as it isn't easy to add them and put all namespaces.
If it requires adding adding VS extensions, that's probably too much hassle both on development and consumption side, but R# seems to have lightweight code templates, maybe at least this can be used. That new common project system may have extensibility points too.
I want to render the grid on test output context, but there is nothing.
I wrote a sample with xunit.
public class DocumentDraftServiceTests
{
private readonly ITestOutputHelper _output;
public DocumentDraftServiceTests(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public async Task Test()
{
_output.WriteLine("--------- Console Info -----------");
_output.WriteLine($"WindowWidth={Console.WindowWidth}");
_output.WriteLine($"WindowHeight={Console.WindowHeight}");
_output.WriteLine($"WindowLeft={Console.WindowLeft}");
_output.WriteLine($"WindowTop={Console.WindowTop}");
var document = new Alba.CsConsoleFormat.Document(
new Grid
{
Columns = { GridLength.Auto },
Children =
{
new Cell("ID"),
new Cell("1")
}
}
);
// I want to render the grid on test output context, but there is nothing.
_output.WriteLine("--------- Grid -----------");
_output.WriteLine(ConsoleRenderer.RenderDocumentToText(document, new TextRenderTarget()));
_output.WriteLine("--------------------------");
}
}
Output:
--------- Console Info -----------
WindowWidth=0
WindowHeight=0
WindowLeft=0
WindowTop=0
--------- Grid -----------
--------------------------
But it's well on terminal.
dotnet test --logger:"console;verbosity=detailed"
--------- Console Info -----------
WindowWidth=217
WindowHeight=16
WindowLeft=0
WindowTop=0
--------- Grid -----------
╔══╗
║ID║
╟──╢
║1 ║
╚══╝
--------------------------
I want to show rendered text on the Rider IDE unit test.
Are these bugs?
Hi,
Is it possible to display colors for text on Linux (RHEL)?
I formatted some documents with colored text on Windows and everything works fine
This is how it looks on Windows
but when I run it on Linux (Redhat Enterprise Linux) no colors are displayed as you can see in the following picture.
To note, the system is able to show colors, as seen in the above picture, with the ls command files and directories are listed using colors.
So why it does not show correctly the colors? Do I have to do something special?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.