dialex / jcolor Goto Github PK
View Code? Open in Web Editor NEWAn easy syntax to format your strings with colored fonts and backgrounds.
License: MIT License
An easy syntax to format your strings with colored fonts and backgrounds.
License: MIT License
Review the demo code for clarity
Hello, I can't seem to find an easy import to display your README example...
With import com.diogonunes.jcolor.Ansi;
, I am forced to use Ansi.colorize()
and in your example you are using colorize()
directly (same for Attribute.YELLOW_TEXT()
and YELLOW_TEXT()
).
Are you using this ?
import com.diogonunes.jcolor.Attribute;
import com.diogonunes.jcolor.AnsiFormat;
import static com.diogonunes.jcolor.Ansi.*;
import static com.diogonunes.jcolor.Attribute.*;
or is there a simpler way ?
I try print unicode:
cp.print(" ███╗ ", Attribute.NONE, FColor.CYAN, BColor.BLACK);
but the result is: ???? (in cyan color)
My full sample here
note: unicode sqare is:
String unicodeMessage = "\u25A0";
Describe the bug
BACK_COLOR doesn't seem to work when I tried for True Colours RGB.
To Reproduce
See screenshot
Expected behavior
BACK_COLOR should display correctly.
Screenshots
If applicable, add screenshots to help explain your problem.
Environment
Windows 10 using JColor version 5.0.0. Java Version 13.0
Describe the bug
Hi, I've setup a simple maven project with your library to test the example code included in the README.md of the project, but unfortunately running the application does not show the text with colors and other attributes but the plain escape sequences. Trying to figure it out the problem, I also tested https://github.com/dialex/JColor-Sandbox with the same result.
Seems that during the migration process from JCDP to JColor you removed too much code, in particular the code included in baa3b95 that actually uses JNA to enable the ENABLE_VIRTUAL_TERMINAL_PROCESSING flag.
Adding the enableWindows10AnsiSupport() method from the commit and the OS versions checks from that commit into the JColor-Sanbox project make it to work ok again.
Also, the pom.xml has a JNA as a compile time dependency but I can't find where it is used. Besides, xstream dependency is neither used, did I miss something ?
I suggest to at least add a section to the README.md with the boilerplate code required to activate the feature.
PS: congrats for your project
To Reproduce
Expected behavior
Show colored output of the application.
Screenshots
N / A
Environment
The Javadoc says ColoredPrinter.print
is a
Usual System.out.print
This is not the case for me. Calling it does not immediately print my string; System.out.print
correctly does in its place. Instead, my string appears with the next output made with ColoredPrinter.print
or ColoredPrinter.println
(or their equivalents from System.out
).
For now I am using regular System.out
in its place - I'd rather use ColoredPrinter
as in the rest of my code though.
Is this a known and fixable error?
Describe the bug
This works fine everywhere else for me except in the command prompt and powershell in Windows 10. I am not talking about the Windows Terminal app, it works fine in there.
To Reproduce
Steps to reproduce the behavior:
Expected behavior
I expected the text to be colorized, which I have seen some programs doing.
Screenshots
Powershell:
Command prompt:
Windows Terminal (expected behavior):
Environment
If the maven-compiler-plugin were changed to source 1.7 target 1.7 the JCDP jar wouldn't require Java 8
Discovered as part of #26
Does not happen on IntelliJ.
Does happen on iTerm, running directly with java -jar
.
Describe the feature
I wish to have a simple and modern formatter same as String.format to format variable text input.
Something simple, similar to BB Codes or Markdown?
With the current solution/structure, it's way too much effort.
Expected behavior
My wish would be something like:
Environment
Hello. Just reading over the README.md
file, and there is one issue: where do the static imports come from?
Like, where is the colorize method (colorize(" ", bkgColor)
) from?
Same thing for BACK_COLOR(randomInt(255), randomInt(255), randomInt(255))
.
Describe the bug
In pom.xml maven-bundle-plugin must not be a project dependecy, just a plugin.
To Reproduce
Steps to reproduce the behavior:
v5.3.1 classpath
I browsed the code on github and think colorize(String text, String ansiCode) will not handle trailing new lines correctly, because split will not return them. See https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
" ... Trailing empty strings are therefore not included in the resulting array. ... "
I think the code gets in trouble with:
"a\n\n\n" because split will result in ["a"]
"a\n\n\b" because endsWithLine is set to false and therefore no new lines are added in the loop
Describe the bug
Methods need
/**
* {@inheritDoc}
*/
To Reproduce
Check UnixColoredPrinter
runbook.md
Describe the bug
the printlines do not show color when running the program from a compiled jar via command prompt. java -jar jcolor.jar
it printlines the escape characters but not the color
I noticed calling echo with an ansi escape sequence seems to fix this. If the terminal is command prompt you should apply a fix similar to this
new ProcessBuilder(new String[]{"cmd", "/c", "echo", "\u001B[42m A TEST�[0m"}).inheritIO().start().waitFor();
Current implementation of the CLEAR_SCREEN command returns only \033[2J
which works on Windows but on not in many other modern terminals.
Most of the terminals used today are VT terminals, which includes most of the modern Linux and Mac terminals and the Windows Terminal available since Windows 10+. The escape sequence for clearing the screen and the scroll-back in a VT terminal is \033c
. This should also work in the Windows Command Prompt if VT (support for ANSI) is enabled. This works exactly like calling clear
in Linux or cls
in Windows.
Some other Linux terminals, like the KDE Console (Konsole) and XTerm support \033[3J
for clearing the screen and resetting the scroll-back.
In my opinion, \033c
will be the most platform-independent implementation. But users should be able to provide custom escape sequence implementation for the CLEAR_SCREEN command.
I read that Windows 10 now supports ANSI escape codes natively. (sources: 1, 2)
We currently depend on Jansi precisely because it allowed us to bypass that limitation on Windows. If that's no longer the case, we can drop that dependency. Even better, we can merge our current NixColoredPrinter
and WinColoredPrinter
into a single class!
Using ColoredPrinter
, I always have to specify all three parameters (foreground, background, attributes) even when I want to change only one of them. This makes the calling code quite verbose.
Furthermore, when changing the colors inside a line, I see the following options:
System.out.println
with a string including several generateCode(Ansi.Attribute, Ansi.FColor, Ansi.BColor)
calls (maybe stored as constants)ColoredPrinter.print(Object, Ansi.Attribute, Ansi.FColor, Ansi.BColor)
calls for the individual parts of the lineHow about adding a fluent alternative, maybe something like the following (indendation for illustrative purposes)?
fluentColoredPrinter
.print("Hello, ")
.push()
.set(Ansi.FColor.BLUE)
.set(Ansi.Attribute.BOLD)
.print("World")
.pop()
.print("!")
.println();
FluentColoredPrinter
(instantiated e.g. via coloredPrinter.fluent()
) that delegates the real printing to ColoredPrinter
.push()
pushes a new state object to an internal stackpop()
returns to the previous stateset()
has three overloads (one for FColor
, BColor
and Attribute
) to make the method calls more compact. One could even go so far to add (Attribute, FColor)
, (Attribute, BColor)
,(FColor, BColor)
, and (Attribute, FColor, BColor)
overrides.If you're interested, I could write this and create a PR.
I've tested the library with Cygwin on Windows 10. It did not show the colors of the text however Cygwin has ANSI support.
Here is an example code to try out and replicate the issue:
ColoredPrinter coloredPrinter = new ColoredPrinter.Builder(1, false).build();
coloredPrinter.println("test", Attribute.NONE, FColor.CYAN, BColor.NONE);
System.out.println("\u001B[31m" + "TEST" + "\u001B[0m");
coloredPrinter.print("test scan:", Attribute.NONE, FColor.RED, BColor.NONE);
System.out.print("\u001B[35m");
Scanner scan = new Scanner(System.in);
scan.nextLine();
System.out.println("\u001B[0m");
coloredPrinter.clear();
Hi! Great job with this library.
Is there any reason why you don't publish the library on JCenter or Maven Central?
If you need help with that, let me know... I usually publish on Bintray's JCenter, which is fairly simple, and recently started using its automatic push to Maven Central which simplifies life a lot and lets people using Maven to get your lib without adding any repositories.
I know it may seem like you'll have to have the user call clear(), but even then, you can help them even further. It is just a small bit of code you can add to help your users that extra step. Here is the code:
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
clear();
}
}));
All this code does is say that while the program is exiting, run clear. This way, the terminal won't look like a mess after running the code. This is kind of the opposite of a static block, where the contents of a static { ... }
block are run as the JVM is starting, not ending. So if you wanted to, you can use that as well!
Hello,
I believe this is a limitation of the eclipse console but when I'm trying to build an app using JCDP the output in the console shows up something like the snippet below. Does anyone know if there is a workaround to seeing your formatted output in a IDE without having to build/export the compiled jar of my app every-time? Thanks. - Krebznet
�[37;44mColoredPrinter | level: 0 | timestamping: false | Attribute: NONE | Foreground color: WHITE | Background color: BLUE�[0m
�[37;44mThis printer will always format text with WHITE font on BLUE background.�[0m
�[7;37;44mFrom now on, that format is reversed.�[0m
ColoredPrinters do not affect System.* format.
�[7;37;44mEven if�[0m you mix �[7;37;44mthe two.�[0m
�[33m2020-06-09 12:29:15 This printer displays timestamps and warning messages.�[0m
�[36m2020-06-09 12:29:15 And this printer can be used for info messages.�[0m
�[mThis example used JCDP 4.0.0 �[0m�[1;33;42m MADE �[0m�[1;33;41mIN PORTUGAL�[0m
�[mI hope you find it useful ;)�[0m
Just like Jansi, using system.out.println
and passing the generated code from our Ansi
class, the dev should be able to print color without our printers. This is less prescriptive.
// (this is pseudocode)
Ansi.Attribute.RED_TEXT
Ansi.Attribute.YELLOW_BACK
Ansi.Attribute.BRIGHT
// option 1: simple format
AnsiFormat fError = new AnsiFormat(Attribute.RED_TEXT);
System.out.println(fError.format("This text will be red"));
// option 2: composite format
AnsiFormat fWarning = new AnsiFormat(Attribute.RED_TEXT, Attribute.YELLOW_BACK, Attribute.BRIGHT);
System.out.println(fWarning.format("This text will be bright red with yellow background"));
// option 3: inline format
System.out.println(Ansi.colorize("This text will be cyan", Attribute.CYAN_TEXT));
AnsiFormat.format("message") -> calls Ansi.colorize() with internal state
Ansi.colorize("message", Ansi.Attribute[1 or more]) -> String with AnsiCodes, ready for Sys.out
Ansi.makeItFabulous() -> alias to .colorize()
ColoredPrinter println(Object msg, Attribute attr, FColor fg, BColor bg) api is calling getImpl().print rather than getImpl().println.
/src/main/java/com/diogonunes/jcdp/color/ColoredPrinter.java#L345
@Override
public void println(Object msg, Attribute attr, FColor fg, BColor bg) {
getImpl().print(msg, attr, fg, bg);
}
withForeground -> withText
withBackground -> withBack
it would make the text shorter and more intuitive... but it would be breaking change (is it worth it?)
doesn't have to be a hard rename, it can be just an alias
Currently I use 33
because that's what I found on StackOverflow, back in the days. But the more I research about Windows ANSI codes, everything references 27
(examples: jansi, wiki, ascii)
I tried a quick replace in the code. All Unix units passed, but the visual test failed... not good I was trying "\027["
but when I used a proper char ESC = 27;
which is then appended to a string, all tests passed (unit and acceptance)
public static final char ESC = 27;
/**
* Every Ansi escape code begins with this PREFIX.
*/
public static final String PREFIX = ESC + "[";
First: Thx, a lot for this nice toolkit!!!!
Sometimes I want to start with a clear screen and the ANSI support this feature:
see: https://en.wikipedia.org/wiki/ANSI_escape_code (look for Erase in Display
)
StringBuilder clearScreenEscBuilder = new StringBuilder();
char c = 27;
char c2 = '[';
clearScreenEscBuilder.append(c);
clearScreenEscBuilder.append(c2);
clearScreenEscBuilder.append("2");
clearScreenEscBuilder.append("J");
String clear = clearScreenEscBuilder.toString();
String text = "�[34mMy Super Duper blue text on a clear screen�[0m";
System.out.println(clear);
System.out.println(text);
What do you think?
BR
Olli
The JNA dependency is now redundant. It should be removed.
Color printing isn't working unless BColor is specified.
For example, I'd expect this to work:
final ColoredPrinter cp = new ColoredPrinter.Builder(1, false)
.foreground(Ansi.FColor.GREEN)
.build();
But it will just print text regularly, until BColor is set as well:
final ColoredPrinter cp = new ColoredPrinter.Builder(1, false)
.foreground(Ansi.FColor.GREEN).background(Ansi.BColor.BLACK)
.build();
Setting BColor.None gives same no-op results
that way, they can always run, without the need of a human eye
Dear developers, I love this lib but I face a small challenge
private static final AnsiFormat KEYWORD_FORMAT = new AnsiFormat(BLUE_TEXT(), BOLD());
private static final void appendKeyWord(
StringBuilder builder, OutputFormat format, String keyword, String before, String after) {
switch (format) {
case PLAIN:
builder.append(before).append(keyword).append(after);
break;
case ANSI:
builder.append(before).append(KEYWORD_FORMAT.format(keyword)).append(after);
break;
default:
builder.append(before).append(keyword).append(after);
break;
}
}
appendKeyWord(builder, outputFormat, "DELETE", "", " ");
Produces output like this
are@ryzen ~/d/s/jsqlformatter (main) [1]> /usr/lib/jvm/java-11-graalvm/bin/java -jar dist/JSQLFormatter.jar "DELETE FROM a where b='c';" [34;47;1m DELETE FROM a WHERE b = 'c' ;
The first Word is distorted and I do not know why.
Tried building the source as well as grabbing the artifacts from MVNrepos. Both have the same result. Am I missing a reference or not structuring my project with meta-inf right?
This is the error I get when including the .jar:
Exception in thread "main" java.lang.NoClassDefFoundError: org/fusesource/jansi/AnsiConsole
at com.diogonunes.jcdp.color.impl.WindowsColoredPrinter.println(WindowsColoredPrinter.java:197)
at com.diogonunes.jcdp.color.ColoredPrinter.println(ColoredPrinter.java:225)
at Program.main(Program.java:36)
Caused by: java.lang.ClassNotFoundException: org.fusesource.jansi.AnsiConsole
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 3 more
Process finished with exit code 1
When trying to compile the source
import org.fusesource.jansi.AnsiConsole;
Error:(9, 28) java: package org.fusesource.jansi does not exist
Error:(152, 20) java: package AnsiConsole does not exist
Error:(160, 20) java: package AnsiConsole does not exist
Error:(203, 24) java: package AnsiConsole does not exist
Error:(205, 20) java: package AnsiConsole does not exist
Error:(216, 24) java: package AnsiConsole does not exist
Error:(218, 20) java: package AnsiConsole does not exist
Error:(229, 24) java: package AnsiConsole does not exist
Error:(231, 20) java: package AnsiConsole does not exist
Error:(242, 24) java: package AnsiConsole does not exist
Error:(244, 20) java: package AnsiConsole does not exist
Error:(333, 20) java: package AnsiConsole does not exist
An immediate response would be appreciated as I am hoping to use this in a project that I am wrapping up soon. Thanks for you work sir!
class AnsiCode {
PREFIX
SUFFIX
SEPARATOR
//builder pattern
constructor().withTextColor(...).withBackColor(...).build()
String generateCode() {
//returns ansi escape code (for printing)
}
String generateEscapedCode() {
//returns escaped ansi escape code (for unit tests and debugging)
}
}
// NEW - creation
AnsiCode format = new AnsiCode().withTextColor(FColor.Red).build()
ColoredPrinter cp = new ColoredPrinter().withFormat(format).build()
// OLD - usage
//ColoredPrinter.println("message", Attr.Bold, FColor.Blue, BColor.Red)
// NEW
AnsiCode warning = new AnsiCode().withTextColor(FColor.Yellow).build()
ColoredPrinter.println("message", warning)
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.