Coder Social home page Coder Social logo

dialex / jcolor Goto Github PK

View Code? Open in Web Editor NEW
477.0 24.0 54.0 3.25 MB

An easy syntax to format your strings with colored fonts and backgrounds.

License: MIT License

Java 100.00%
java log color-font java-library utilities ascii-art ansi-colors cross-platform ansi

jcolor's People

Contributors

codedojoofficial avatar dialex avatar elegantshock2258 avatar extollite avatar flawedspirit avatar robertcsakany avatar xafero avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jcolor's Issues

Update screenshots

Review the demo code for clarity

  • Windows 10:
    • Powershell6
    • Windows Terminal
  • macOS (iTerm)
  • IntelliJ

Import in java program

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 ?

How to print unicode ?

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";

BACK_COLOR for True colors doesn't seem to work when I try with 5.0.0

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.

Code

consoleOut

Screenshots
If applicable, add screenshots to help explain your problem.

Environment
Windows 10 using JColor version 5.0.0. Java Version 13.0

Windows Command Line and Powershell display ANSI escape codes instead of expected formatting

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

  1. In a Win 10 clean machine setup create / compile https://github.com/dialex/JColor-Sandbox.
  2. Run the generated jar file in a Windows CMD terminal

Expected behavior
Show colored output of the application.

Screenshots
N / A

Environment

  • OS: Windows 10 21H1 (19043.1348)
  • Version 5.0.0, 5.0.2

ColoredPrinter.print does not behave like System.out.print

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?

Colors don't work in Windows 10 command prompt + powershell

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:

  1. Make a new Java project or edit an existing one.
  2. Add a simple line of code that will log colorized text into console.
  3. Run the project in the command prompt or in powershell.
  4. The colorized text will have gibberish around it.

Expected behavior
I expected the text to be colorized, which I have seen some programs doing.

Screenshots
Powershell:
image
Command prompt:
image
Windows Terminal (expected behavior):
image

Environment

  • OS: Windows
  • Version: 10

Simple formatter like Color.format("text") with BB Codes or Markdown Syntax?

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:

  • [BB Code style] Color.format("My custom text has [b]bold[/b] and [i]italic[/I] texts which you also can combine [b][I]combined[/I[/b]")
  • [Markdown style] Color.format("My custom text has bold and italic texts which you also can combine combined")

Environment

  • OS: MacOS/Linux

README.md code samples are confusing

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)).

Probably Trailing new lines not supported/Line Break Issue

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

Review Javadoc (specially ColoredPrinter)

Describe the bug
Methods need

    /**
     * {@inheritDoc}
     */

To Reproduce
Check UnixColoredPrinter

  • review javadoc, adding missing documentation
  • generate javadoc and publish it
  • document how to generate javadoc, in runbook.md

Doesn't work on command prompt

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();

bug report: CLEAR_SCREEN is not portable

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.

Source: https://stackoverflow.com/a/5367075

Feature: Drop Jansi since Windows 10 now supports ANSI escape codes

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!

Fluent print syntax

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:

  1. use System.out.println with a string including several generateCode(Ansi.Attribute, Ansi.FColor, Ansi.BColor) calls (maybe stored as constants)
  2. use several ColoredPrinter.print(Object, Ansi.Attribute, Ansi.FColor, Ansi.BColor) calls for the individual parts of the line

How 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();
  • New class FluentColoredPrinter (instantiated e.g. via coloredPrinter.fluent()) that delegates the real printing to ColoredPrinter.
  • push() pushes a new state object to an internal stack
  • pop() returns to the previous state
  • set() 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.

Cygwin not showing colors but has ANSI support

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();

Link to the ANSI codes can be found here

Improve pipeline

  • Run tests on travis ✅
  • Show results of running travis on each PR created by maintainer ✅
  • Show results of running travis on each PR created by contributor ❓(TBC)

Publish on JCenter and Maven Central

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.

A Suggestion About Clearing the Color

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!

Debugging Output in Eclipse IDE Does not format the markup

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

Feature: allow dev to display color without printers

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()

Refactor: foreground and background words

  • 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

Which escape code to use?

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 + "[";

Feature: Support of clear screen

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

Color not printed if BColor not specified

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

First word not printed properly

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'
;

image

image

The first Word is distorted and I do not know why.

AnsiConsole class not found? Can't compile or include.. fusesource..

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!

Feature: refactor ANSI formatting into single class

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.