Skip to content

Highlighting and parsing

mattirn edited this page May 12, 2020 · 11 revisions

The LineReader can be given an implementation of the Highlighter and Parser interfaces which are responsible for highlighting and parsing of the command line.

Builtin highlighters

DefaultHighlighter

DefaultHighlighter is JLine provided implementation of Highlighter interface.

Nano SyntaxHighlighter

SyntaxHighlighter is a JLine implementation of nanorc syntax highlighter that works with standard nanorc syntaxfiles.

JLine supported keywords: the syntax, color, and icolor are used to define syntax highlighting rules for different text patterns. Other nanorc keywords are quietly ignored.

JLine extension:

To the commands color and icolor first parameter has been added style field. For fields fgcolor and bgcolor in addition to the color names (see below) SyntaxHighlighter support also number codes 0-255.

color fgcolor,bgcolor,style ...

Fields fgcolor and bgcolor defines foreground and background colors respectively. Valid color names are: white, black, blue, green, red, cyan, yellow, magenta, and normal -- where normal means the default foreground or background color. You may use the prefix bright for the foreground color to get a stronger highlight. If your terminal supports transparency, not specifying a bgcolor it will try to use a transparent background. Field style defines an additional style to the foreground text. Valid style names are blink, bold, conceal, faint, hidden, inverse, italic and underline.

Note:

SyntaxHighlighter does not implement Highlighter interface but it might be useful for implementing one or it can be just used to highlight command output and/or descriptions.

Usage:

ConfigurationPath configPath = new ConfigurationPath(Paths.get("/pub/myApp"),   // application-wide settings
                       Paths.get(System.getProperty("user.home"), ".myApp"));   // user-specific settings
SyntaxHighlighter javaSyntax = SyntaxHighlighter.build(configPath.getConfig("jnanorc"), "Java");
AttributedString as = javaSyntax.highlight("public AttributedString highlight(String string)")
//
// to highlight a long string you should split it in order to avoid StackOverFlowError
// https://bugs.java.com/bugdatabase/view_bug.do?bug_id=6337993 
//
SyntaxHighlighter jsonSyntax = SyntaxHighlighter.build(configPath.getConfig("jnanorc"), "JSON");
for (String s: longString.split("\n")) {
    jsonSyntax.highlight(s).println(terminal);
}
Clone this wiki locally