Search in sources :

Example 1 with AttributedStringBuilder

use of org.jline.utils.AttributedStringBuilder in project karaf by apache.

the class AnsiColumn method getContent.

@Override
public String getContent(String content) {
    String in = super.getContent(content);
    AttributedStringBuilder sb = new AttributedStringBuilder();
    sb.style(sb.style().foreground(color));
    if (bold)
        sb.style(sb.style().bold());
    sb.append(in);
    if (bold)
        sb.style(sb.style().boldOff());
    sb.style(sb.style().foregroundOff());
    return sb.toAnsi();
}
Also used : AttributedStringBuilder(org.jline.utils.AttributedStringBuilder)

Example 2 with AttributedStringBuilder

use of org.jline.utils.AttributedStringBuilder in project felix by apache.

the class Highlighter method highlight.

public AttributedString highlight(LineReader reader, String buffer) {
    try {
        Program program = null;
        List<Token> tokens = null;
        List<Statement> statements = null;
        String repaired = buffer;
        while (program == null) {
            try {
                org.apache.felix.gogo.runtime.Parser parser = new org.apache.felix.gogo.runtime.Parser(repaired);
                program = parser.program();
                tokens = parser.tokens();
                statements = parser.statements();
            } catch (EOFError e) {
                repaired = repaired + " " + e.repair();
                // Make sure we don't loop forever
                if (repaired.length() > buffer.length() + 1024) {
                    return new AttributedStringBuilder().append(buffer).toAttributedString();
                }
            }
        }
        Map<String, String> colors = Posix.getColorMap(session, "HIGHLIGHTER", DEFAULT_HIGHLIGHTER_COLORS);
        int underlineStart = -1;
        int underlineEnd = -1;
        int negativeStart = -1;
        int negativeEnd = -1;
        String search = reader.getSearchTerm();
        if (search != null && search.length() > 0) {
            underlineStart = buffer.indexOf(search);
            if (underlineStart >= 0) {
                underlineEnd = underlineStart + search.length() - 1;
            }
        }
        if (reader.getRegionActive() != RegionType.NONE) {
            negativeStart = reader.getRegionMark();
            negativeEnd = reader.getBuffer().cursor();
            if (negativeStart > negativeEnd) {
                int x = negativeEnd;
                negativeEnd = negativeStart;
                negativeStart = x;
            }
            if (reader.getRegionActive() == RegionType.LINE) {
                while (negativeStart > 0 && reader.getBuffer().atChar(negativeStart - 1) != '\n') {
                    negativeStart--;
                }
                while (negativeEnd < reader.getBuffer().length() - 1 && reader.getBuffer().atChar(negativeEnd + 1) != '\n') {
                    negativeEnd++;
                }
            }
        }
        Type[] types = new Type[repaired.length()];
        Arrays.fill(types, Type.Unknown);
        int cur = 0;
        for (Token token : tokens) {
            // We're on the repair side, so exit now
            if (token.start() >= buffer.length()) {
                break;
            }
            if (token.start() > cur) {
                cur = token.start();
            }
            // Find corresponding statement
            Statement statement = null;
            for (int i = statements.size() - 1; i >= 0; i--) {
                Statement s = statements.get(i);
                if (s.start() <= cur && cur < s.start() + s.length()) {
                    statement = s;
                    break;
                }
            }
            // Reserved tokens
            Type type = Type.Unknown;
            if (Token.eq(token, "{") || Token.eq(token, "}") || Token.eq(token, "(") || Token.eq(token, ")") || Token.eq(token, "[") || Token.eq(token, "]") || Token.eq(token, "|") || Token.eq(token, ";") || Token.eq(token, "=")) {
                type = Type.Reserved;
            } else if (token.charAt(0) == '\'' || token.charAt(0) == '"') {
                type = Type.String;
            } else if (token.toString().matches("^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$")) {
                type = Type.Number;
            } else if (token.charAt(0) == '$') {
                type = Type.Variable;
            } else if (((Set) session.get(CommandSessionImpl.CONSTANTS)).contains(token.toString()) || Token.eq(token, "null") || Token.eq(token, "false") || Token.eq(token, "true")) {
                type = Type.Constant;
            } else {
                boolean isFirst = statement != null && statement.tokens().size() > 0 && token == statement.tokens().get(0);
                boolean isThirdWithNext = statement != null && statement.tokens().size() > 3 && token == statement.tokens().get(2);
                boolean isAssign = statement != null && statement.tokens().size() > 1 && Token.eq(statement.tokens().get(1), "=");
                if (isFirst && isAssign) {
                    type = Type.VariableName;
                }
                if (isFirst && !isAssign || isAssign && isThirdWithNext) {
                    Object v = session.get(Shell.resolve(session, token.toString()));
                    type = (v instanceof Function) ? Type.Function : Type.BadFunction;
                }
            }
            Arrays.fill(types, token.start(), Math.min(token.start() + token.length(), types.length), type);
            cur = Math.min(token.start() + token.length(), buffer.length());
        }
        if (buffer.length() < repaired.length()) {
            Arrays.fill(types, buffer.length(), repaired.length(), Type.Repair);
        }
        AttributedStringBuilder sb = new AttributedStringBuilder();
        for (int i = 0; i < repaired.length(); i++) {
            sb.style(AttributedStyle.DEFAULT);
            applyStyle(sb, colors, types[i]);
            if (i >= underlineStart && i <= underlineEnd) {
                sb.style(sb.style().underline());
            }
            if (i >= negativeStart && i <= negativeEnd) {
                sb.style(sb.style().inverse());
            }
            char c = repaired.charAt(i);
            if (c == '\t' || c == '\n') {
                sb.append(c);
            } else if (c < 32) {
                sb.style(sb.style().inverseNeg()).append('^').append((char) (c + '@')).style(sb.style().inverseNeg());
            } else {
                int w = WCWidth.wcwidth(c);
                if (w > 0) {
                    sb.append(c);
                }
            }
        }
        return sb.toAttributedString();
    } catch (SyntaxError e) {
        return super.highlight(reader, buffer);
    }
}
Also used : Program(org.apache.felix.gogo.runtime.Parser.Program) Statement(org.apache.felix.gogo.runtime.Parser.Statement) Token(org.apache.felix.gogo.runtime.Token) AttributedStringBuilder(org.jline.utils.AttributedStringBuilder) AttributedString(org.jline.utils.AttributedString) Function(org.apache.felix.service.command.Function) RegionType(org.jline.reader.LineReader.RegionType) SyntaxError(org.apache.felix.gogo.runtime.SyntaxError) EOFError(org.apache.felix.gogo.runtime.EOFError)

Example 3 with AttributedStringBuilder

use of org.jline.utils.AttributedStringBuilder in project felix by apache.

the class Posix method grep.

protected void grep(CommandSession session, Process process, String[] argv) throws Exception {
    final String[] usage = { "grep -  search for PATTERN in each FILE or standard input.", "Usage: grep [OPTIONS] PATTERN [FILES]", "  -? --help                Show help", "  -i --ignore-case         Ignore case distinctions", "  -n --line-number         Prefix each line with line number within its input file", "  -q --quiet, --silent     Suppress all normal output", "  -v --invert-match        Select non-matching lines", "  -w --word-regexp         Select only whole words", "  -x --line-regexp         Select only whole lines", "  -c --count               Only print a count of matching lines per file", "     --color=WHEN          Use markers to distinguish the matching string, may be `always', `never' or `auto'", "  -B --before-context=NUM  Print NUM lines of leading context before matching lines", "  -A --after-context=NUM   Print NUM lines of trailing context after matching lines", "  -C --context=NUM         Print NUM lines of output context", "     --pad-lines           Pad line numbers" };
    Options opt = parseOptions(session, usage, argv);
    List<String> args = opt.args();
    if (args.isEmpty()) {
        throw new IllegalArgumentException("no pattern supplied");
    }
    String regex = args.remove(0);
    String regexp = regex;
    if (opt.isSet("word-regexp")) {
        regexp = "\\b" + regexp + "\\b";
    }
    if (opt.isSet("line-regexp")) {
        regexp = "^" + regexp + "$";
    } else {
        regexp = ".*" + regexp + ".*";
    }
    Pattern p;
    Pattern p2;
    if (opt.isSet("ignore-case")) {
        p = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE);
        p2 = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    } else {
        p = Pattern.compile(regexp);
        p2 = Pattern.compile(regex);
    }
    int after = opt.isSet("after-context") ? opt.getNumber("after-context") : -1;
    int before = opt.isSet("before-context") ? opt.getNumber("before-context") : -1;
    int context = opt.isSet("context") ? opt.getNumber("context") : 0;
    String lineFmt = opt.isSet("pad-lines") ? "%6d" : "%d";
    if (after < 0) {
        after = context;
    }
    if (before < 0) {
        before = context;
    }
    List<String> lines = new ArrayList<>();
    boolean invertMatch = opt.isSet("invert-match");
    boolean lineNumber = opt.isSet("line-number");
    boolean count = opt.isSet("count");
    String color = opt.isSet("color") ? opt.get("color") : "auto";
    boolean colored;
    switch(color) {
        case "always":
        case "yes":
        case "force":
            colored = true;
            break;
        case "never":
        case "no":
        case "none":
            colored = false;
            break;
        case "auto":
        case "tty":
        case "if-tty":
            colored = process.isTty(1);
            break;
        default:
            throw new IllegalArgumentException("invalid argument ‘" + color + "’ for ‘--color’");
    }
    Map<String, String> colors = colored ? getColorMap(session, "GREP", DEFAULT_GREP_COLORS) : Collections.emptyMap();
    List<Source> sources = new ArrayList<>();
    if (opt.args().isEmpty()) {
        opt.args().add("-");
    }
    for (String arg : opt.args()) {
        if ("-".equals(arg)) {
            sources.add(new StdInSource(process));
        } else {
            sources.add(new PathSource(session.currentDir().resolve(arg), arg));
        }
    }
    boolean match = false;
    for (Source source : sources) {
        boolean firstPrint = true;
        int nb = 0;
        int lineno = 1;
        String line;
        int lineMatch = 0;
        try (BufferedReader r = new BufferedReader(new InputStreamReader(source.read()))) {
            while ((line = r.readLine()) != null) {
                if (line.length() == 1 && line.charAt(0) == '\n') {
                    break;
                }
                boolean matches = p.matcher(line).matches();
                AttributedStringBuilder sbl = new AttributedStringBuilder();
                if (!count) {
                    if (sources.size() > 1) {
                        if (colored) {
                            applyStyle(sbl, colors, "fn");
                        }
                        sbl.append(source.getName());
                        if (colored) {
                            applyStyle(sbl, colors, "se");
                        }
                        sbl.append(":");
                    }
                    if (lineNumber) {
                        if (colored) {
                            applyStyle(sbl, colors, "ln");
                        }
                        sbl.append(String.format(lineFmt, lineno));
                        if (colored) {
                            applyStyle(sbl, colors, "se");
                        }
                        sbl.append((matches ^ invertMatch) ? ":" : "-");
                    }
                    String style = matches ^ invertMatch ^ (invertMatch && colors.containsKey("rv")) ? "sl" : "cx";
                    if (colored) {
                        applyStyle(sbl, colors, style);
                    }
                    AttributedString aLine = AttributedString.fromAnsi(line);
                    Matcher matcher2 = p2.matcher(aLine.toString());
                    int cur = 0;
                    while (matcher2.find()) {
                        int index = matcher2.start(0);
                        AttributedString prefix = aLine.subSequence(cur, index);
                        sbl.append(prefix);
                        cur = matcher2.end();
                        if (colored) {
                            applyStyle(sbl, colors, invertMatch ? "mc" : "ms", "mt");
                        }
                        sbl.append(aLine.subSequence(index, cur));
                        if (colored) {
                            applyStyle(sbl, colors, style);
                        }
                        nb++;
                    }
                    sbl.append(aLine.subSequence(cur, aLine.length()));
                }
                if (matches ^ invertMatch) {
                    lines.add(sbl.toAnsi(Shell.getTerminal(session)));
                    lineMatch = lines.size();
                } else {
                    if (lineMatch != 0 & lineMatch + after + before <= lines.size()) {
                        if (!count) {
                            if (!firstPrint && before + after > 0) {
                                AttributedStringBuilder sbl2 = new AttributedStringBuilder();
                                if (colored) {
                                    applyStyle(sbl2, colors, "se");
                                }
                                sbl2.append("--");
                                process.out().println(sbl2.toAnsi(Shell.getTerminal(session)));
                            } else {
                                firstPrint = false;
                            }
                            for (int i = 0; i < lineMatch + after; i++) {
                                process.out().println(lines.get(i));
                            }
                        }
                        while (lines.size() > before) {
                            lines.remove(0);
                        }
                        lineMatch = 0;
                    }
                    lines.add(sbl.toAnsi(Shell.getTerminal(session)));
                    while (lineMatch == 0 && lines.size() > before) {
                        lines.remove(0);
                    }
                }
                lineno++;
            }
            if (!count && lineMatch > 0) {
                if (!firstPrint && before + after > 0) {
                    AttributedStringBuilder sbl2 = new AttributedStringBuilder();
                    if (colored) {
                        applyStyle(sbl2, colors, "se");
                    }
                    sbl2.append("--");
                    process.out().println(sbl2.toAnsi(Shell.getTerminal(session)));
                } else {
                    firstPrint = false;
                }
                for (int i = 0; i < lineMatch + after && i < lines.size(); i++) {
                    process.out().println(lines.get(i));
                }
            }
            if (count) {
                process.out().println(nb);
            }
            match |= nb > 0;
        }
    }
    Process.Utils.current().error(match ? 0 : 1);
}
Also used : Options(org.jline.builtins.Options) Pattern(java.util.regex.Pattern) InputStreamReader(java.io.InputStreamReader) Matcher(java.util.regex.Matcher) PathSource(org.jline.builtins.Source.PathSource) ArrayList(java.util.ArrayList) AttributedStringBuilder(org.jline.utils.AttributedStringBuilder) AttributedString(org.jline.utils.AttributedString) PathSource(org.jline.builtins.Source.PathSource) Source(org.jline.builtins.Source) AttributedString(org.jline.utils.AttributedString) BufferedReader(java.io.BufferedReader)

Example 4 with AttributedStringBuilder

use of org.jline.utils.AttributedStringBuilder in project karaf by apache.

the class AnsiSplitter method splitLines.

public static List<String> splitLines(String text, int maxLength, int tabs) throws IOException {
    AttributedStringBuilder sb = new AttributedStringBuilder();
    sb.tabs(tabs);
    sb.appendAnsi(text);
    return sb.columnSplitLength(maxLength).stream().map(AttributedString::toAnsi).collect(Collectors.toList());
}
Also used : AttributedStringBuilder(org.jline.utils.AttributedStringBuilder)

Example 5 with AttributedStringBuilder

use of org.jline.utils.AttributedStringBuilder in project karaf by apache.

the class AnsiSplitter method length.

public static int length(String text, int tabs) throws IOException {
    AttributedStringBuilder sb = new AttributedStringBuilder();
    sb.tabs(tabs);
    sb.appendAnsi(text);
    return sb.columnLength();
}
Also used : AttributedStringBuilder(org.jline.utils.AttributedStringBuilder)

Aggregations

AttributedStringBuilder (org.jline.utils.AttributedStringBuilder)10 AttributedString (org.jline.utils.AttributedString)3 Matcher (java.util.regex.Matcher)2 Pattern (java.util.regex.Pattern)2 Terminal (org.jline.terminal.Terminal)2 BufferedReader (java.io.BufferedReader)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 ArrayList (java.util.ArrayList)1 LinkedHashMap (java.util.LinkedHashMap)1 Map (java.util.Map)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 IntBinaryOperator (java.util.function.IntBinaryOperator)1 EOFError (org.apache.felix.gogo.runtime.EOFError)1 Program (org.apache.felix.gogo.runtime.Parser.Program)1 Statement (org.apache.felix.gogo.runtime.Parser.Statement)1 SyntaxError (org.apache.felix.gogo.runtime.SyntaxError)1 Token (org.apache.felix.gogo.runtime.Token)1 Function (org.apache.felix.service.command.Function)1 Job (org.apache.felix.service.command.Job)1