Skip to content

Commit

Permalink
Customizable colors for ls, help and prnt commands, fixes #525
Browse files Browse the repository at this point in the history
  • Loading branch information
mattirn committed Apr 30, 2020
1 parent 5cf8f03 commit b7ae0ea
Show file tree
Hide file tree
Showing 6 changed files with 122 additions and 44 deletions.
43 changes: 25 additions & 18 deletions builtins/src/main/java/org/jline/builtins/Completers.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import org.jline.utils.AttributedString;
import org.jline.utils.AttributedStringBuilder;
import org.jline.utils.AttributedStyle;
import org.jline.utils.StyleResolver;

public class Completers {

Expand Down Expand Up @@ -330,6 +331,7 @@ protected String getSeparator(boolean useForwardSlash) {
*/
public static class FileNameCompleter implements org.jline.reader.Completer
{
protected static StyleResolver resolver = Styles.lsStyle();

public void complete(LineReader reader, ParsedLine commandLine, final List<Candidate> candidates) {
assert commandLine != null;
Expand Down Expand Up @@ -363,10 +365,10 @@ public void complete(LineReader reader, ParsedLine commandLine, final List<Candi
if (Files.isDirectory(p)) {
candidates.add(
new Candidate(value + (reader.isSet(LineReader.Option.AUTO_PARAM_SLASH) ? sep : ""),
getDisplay(reader.getTerminal(), p), null, null,
getDisplay(reader.getTerminal(), p, resolver), null, null,
reader.isSet(LineReader.Option.AUTO_REMOVE_SLASH) ? sep : null, null, false));
} else {
candidates.add(new Candidate(value, getDisplay(reader.getTerminal(), p), null, null, null, null,
candidates.add(new Candidate(value, getDisplay(reader.getTerminal(), p, resolver), null, null, null, null,
true));
}
});
Expand Down Expand Up @@ -395,24 +397,28 @@ protected Path getUserHome() {
}

protected String getSeparator(boolean useForwardSlash) {
return useForwardSlash ? "/" :getUserDir().getFileSystem().getSeparator();
return useForwardSlash ? "/" : getUserDir().getFileSystem().getSeparator();
}

protected String getDisplay(Terminal terminal, Path p) {
// TODO: use $LS_COLORS for output
protected String getDisplay(Terminal terminal, Path p, StyleResolver resolver) {
AttributedStringBuilder sb = new AttributedStringBuilder();
String name = p.getFileName().toString();
if (Files.isDirectory(p)) {
AttributedStringBuilder sb = new AttributedStringBuilder();
sb.styled(AttributedStyle.BOLD.foreground(AttributedStyle.RED), name);
sb.append("/");
name = sb.toAnsi(terminal);
} else if (Files.isSymbolicLink(p)) {
AttributedStringBuilder sb = new AttributedStringBuilder();
sb.styled(AttributedStyle.BOLD.foreground(AttributedStyle.RED), name);
sb.append("@");
name = sb.toAnsi(terminal);
int idx = name.lastIndexOf(".");
String type = idx != -1 ? ".*" + name.substring(idx): null;
if (Files.isSymbolicLink(p)) {
sb.styled(resolver.resolve(".ln"), name).append("@");
} else if (Files.isDirectory(p)) {
sb.styled(resolver.resolve(".di"), name).append("/");
} else if (Files.isExecutable(p)) {
sb.styled(resolver.resolve(".ex"), name).append("*");
} else if (type != null && resolver.resolve(type).getStyle() != 0) {
sb.styled(resolver.resolve(type), name);
} else if (Files.isRegularFile(p)) {
sb.styled(resolver.resolve(".fi"), name);
} else {
sb.append(name);
}
return name;
return sb.toAnsi(terminal);
}

}
Expand Down Expand Up @@ -688,8 +694,9 @@ protected boolean completeValue(LineReader reader, final ParsedLine commandLine,
if (v.startsWith(partialValue)) {
out = true;
String val = c.value();
if (valueCompleter instanceof Completers.FileNameCompleter) {
val = ((Completers.FileNameCompleter)valueCompleter).getDisplay(reader.getTerminal(), Paths.get(c.value()));
if (valueCompleter instanceof FileNameCompleter) {
FileNameCompleter cc = (FileNameCompleter)valueCompleter;
val = cc.getDisplay(reader.getTerminal(), Paths.get(c.value()), FileNameCompleter.resolver);
}
candidates.add(new Candidate(curBuf + v, val, null, null, null, null, c.complete()));
}
Expand Down
17 changes: 3 additions & 14 deletions builtins/src/main/java/org/jline/builtins/ConsoleEngineImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ public enum Command {SHOW
private static final String[] OPTION_HELP = {"-?", "--help"};
private static final String OPTION_VERBOSE = "-v";
private static final String END_HELP = "END_HELP";
private static final String PRNT_COLORS = "th=1;34:rn=1;34:mk=1;34:em=31:vs=32";
private static final int HELP_MAX_SIZE = 30;
private static final int PRNT_MAX_ROWS = 100000;
private static final int PRNT_MAX_DEPTH = 1;
Expand Down Expand Up @@ -130,17 +129,7 @@ public ConsoleEngineImpl(Set<Command> commands, ScriptEngine engine
aliases.putAll((Map<String,String>)slurp(aliasFile));
}
registerCommands(commandName, commandExecute);
}

private static StyleResolver prntStyle() {
return style(PRNT_COLORS);
}

private static StyleResolver style(String str) {
Map<String, String> colors = Arrays.stream(str.split(":"))
.collect(Collectors.toMap(s -> s.substring(0, s.indexOf('=')),
s -> s.substring(s.indexOf('=') + 1)));
return new StyleResolver(colors::get);
prntStyle = Styles.prntStyle();
}

/**
Expand Down Expand Up @@ -965,7 +954,7 @@ private void internalPrintln(Map<String, Object> options, Object object) {
if (options.containsKey(Printer.VALUE_STYLE)) {
options.put(Printer.VALUE_STYLE, valueHighlighter(valueStyle));
}
prntStyle = prntStyle();
prntStyle = Styles.prntStyle();
options.putIfAbsent(Printer.WIDTH, terminal().getSize().getColumns());
String style = (String) options.getOrDefault(Printer.STYLE, "");
int width = (int) options.get(Printer.WIDTH);
Expand Down Expand Up @@ -1013,7 +1002,7 @@ private AttributedString highlight(CmdDesc cmdDesc) {
}
sb.append(asb.toString());
}
return Options.HelpException.highlight(sb.toString(), Options.HelpException.defaultStyle());
return Options.HelpException.highlight(sb.toString(), Styles.helpStyle());
}

private SyntaxHighlighter valueHighlighter(String style) {
Expand Down
11 changes: 1 addition & 10 deletions builtins/src/main/java/org/jline/builtins/Options.java
Original file line number Diff line number Diff line change
Expand Up @@ -525,17 +525,8 @@ public HelpException(String message) {
super(message);
}

public static final String DEFAULT_COLORS = "ti=1;34:co=1:ar=3:op=33";

public static StyleResolver defaultStyle() {
return style(DEFAULT_COLORS);
}

public static StyleResolver style(String str) {
Map<String, String> colors = Arrays.stream(str.split(":"))
.collect(Collectors.toMap(s -> s.substring(0, s.indexOf('=')),
s -> s.substring(s.indexOf('=') + 1)));
return new StyleResolver(colors::get);
return Styles.helpStyle();
}

public static AttributedString highlight(String msg, StyleResolver resolver) {
Expand Down
73 changes: 73 additions & 0 deletions builtins/src/main/java/org/jline/builtins/Styles.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* Copyright (c) 2002-2020, the original author or authors.
*
* This software is distributable under the BSD license. See the terms of the
* BSD license in the documentation provided with this software.
*
* https://opensource.org/licenses/BSD-3-Clause
*/
package org.jline.builtins;

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

import org.jline.utils.StyleResolver;

public class Styles {
private static final String DEFAULT_LS_COLORS = "di=1;91:ex=1;92:ln=1;96:fi=";
private static final String DEFAULT_HELP_COLORS = "ti=1;34:co=1:ar=3:op=33";
private static final String DEFAULT_PRNT_COLORS = "th=1;34:rn=1;34:mk=1;34:em=31:vs=32";
private static final String LS_COLORS = "LS_COLORS";
private static final String HELP_COLORS = "HELP_COLORS";
private static final String PRNT_COLORS = "PRNT_COLORS";

private static final String KEY = "([a-z]{2}|\\*\\.[a-zA-Z0-9]+)";
private static final String VALUE = "[0-9]*(;[0-9]+){0,2}";
private static final String ANSI_STYLE_PATTERN = KEY + "=" + VALUE + "(:" + KEY + "=" + VALUE + ")*(:|)";

public static StyleResolver lsStyle() {
return style(LS_COLORS, DEFAULT_LS_COLORS);
}

public static StyleResolver helpStyle() {
return style(HELP_COLORS, DEFAULT_HELP_COLORS);
}

public static StyleResolver prntStyle() {
return style(PRNT_COLORS, DEFAULT_PRNT_COLORS);
}

private static StyleResolver style(String name, String defStyle) {
String style = consoleOption(name);
if (style == null) {
style = defStyle;
}
return style(style);
}

private static String consoleOption(String name) {
String out = null;
SystemRegistry sr = SystemRegistry.get();
if (sr != null) {
out = (String)sr.consoleOption(name);
if (out != null && !out.matches(ANSI_STYLE_PATTERN)) {
out = null;
}
}
if (out == null) {
out = System.getenv(name);
if (out != null && !out.matches(ANSI_STYLE_PATTERN)) {
out = null;
}
}
return out;
}

private static StyleResolver style(String style) {
Map<String, String> colors = Arrays.stream(style.split(":"))
.collect(Collectors.toMap(s -> s.substring(0, s.indexOf('=')),
s -> s.substring(s.indexOf('=') + 1)));
return new StyleResolver(colors::get);
}
}
7 changes: 7 additions & 0 deletions builtins/src/main/java/org/jline/builtins/SystemRegistry.java
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,13 @@ public interface SystemRegistry extends CommandRegistry {
*/
void trace(boolean stack, Exception exception);

/**
* Return console option value
* @param name the option name
* @return option value
*/
Object consoleOption(String name);

/**
* @return terminal
*/
Expand Down
15 changes: 13 additions & 2 deletions builtins/src/main/java/org/jline/builtins/SystemRegistryImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -157,11 +157,21 @@ public Map<String, String> commandAliases() {
return out;
}

@Override
public Object consoleOption(String name) {
Object out = null;
if (consoleId != null) {
out = consoleEngine().consoleOption(name, null);
}
return out;
}

/**
* Register subcommand registry
* @param command main command
* @param subcommandRegistry subcommand registry
*/
@Override
public void register(String command, CommandRegistry subcommandRegistry) {
subcommands.put(command, subcommandRegistry);
commandExecute.put(command, new CommandMethods(this::subcommand, this::emptyCompleter));
Expand Down Expand Up @@ -296,9 +306,10 @@ public CmdDesc commandDescription(List<String> args) {
private CmdDesc commandDescription(CommandRegistry subreg) {
List<AttributedString> main = new ArrayList<>();
Map<String, List<AttributedString>> options = new HashMap<>();
StyleResolver helpStyle = Styles.helpStyle();
for (String sc : new TreeSet<String>(subreg.commandNames())) {
for (String info : subreg.commandInfo(sc)) {
main.add(HelpException.highlightSyntax(sc + " - " + info, HelpException.defaultStyle(), true));
main.add(HelpException.highlightSyntax(sc + " - " + info, helpStyle, true));
break;
}
}
Expand Down Expand Up @@ -1227,7 +1238,7 @@ public void trace(Exception exception) {
@Override
public void trace(boolean stack, Exception exception) {
if (exception instanceof Options.HelpException) {
Options.HelpException.highlight((exception).getMessage(), Options.HelpException.defaultStyle()).print(terminal());
Options.HelpException.highlight((exception).getMessage(), Styles.helpStyle()).print(terminal());
} else if (stack) {
exception.printStackTrace();
} else {
Expand Down

0 comments on commit b7ae0ea

Please sign in to comment.