2

I've been trying to display formatted texts on CLI. I tried the exact same code provided in picocli docs (doc link), but the formatting does not seem to be applied.

Please help me to identify my mistake.

Expected output

Example of the formatting

My code

import java.util.concurrent.Callable;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Help.Ansi;

@Command(name = "test", mixinStandardHelpOptions = true, version = "test 1.0",
   description = "Custom @|bold,underline styles|@ and @|fg(red) colors|@.")
public class Interpreter  implements Callable<Integer> {
    @Override
    public Integer call() throws Exception { // your business logic goes here...
        String str = Ansi.AUTO.string("@|red Hello, colored world!|@");
        System.out.println(str);
        return 0;
    }

    public static void main (String[] args) {
            
        CommandLine prompt = new CommandLine(new Interpreter());
        int exitCode = prompt.execute(args);
        
        System.exit(exitCode);
    }

My output (formatting is not getting applied)

my output

PS. Im using picocli v 4.5.2, exporting the project as runnable jar, and building it to .exe using Launch4j. Executing the result exe in command prompt of windows 10.

curiousredoC
  • 51
  • 1
  • 7

1 Answers1

3

To get ANSI colors in Windows, you need to do some extra work. The best way is to add the Jansi library to your classpath.

To use Jansi, you need to enable it in your application:

import org.fusesource.jansi.AnsiConsole;
// ...
public static void main(String[] args) {
    AnsiConsole.systemInstall(); // enable colors on Windows
    new CommandLine(new Interpreter()).execute(args);
    AnsiConsole.systemUninstall(); // cleanup when done
}

If you are interested in creating a native Windows CLI executable with GraalVM (instead of using Launch4j), then be aware that Jansi by itself is insufficient to show colors. This is partly because GraalVM requires configuration and partly because Jansi internally depends on non-standard system properties, without a graceful fallback if these properties are absent (as is the case in GraalVM).

You may be interested in combining Jansi with picocli-jansi-graalvm until this issue is fixed. Example usage:

import picocli.jansi.graalvm.AnsiConsole; // not org.fusesource.jansi.AnsiConsole
// ...
public static void main(String[] args) {
    int exitCode;
    try (AnsiConsole ansi = AnsiConsole.windowsInstall()) {
        exitCode = new CommandLine(new Interpreter()).execute(args);
    }
    System.exit(exitCode);
}

See also the picocli user manual section on ANSI colors in Windows.

Remko Popma
  • 35,130
  • 11
  • 92
  • 114