Skip to content

Commit

Permalink
Merge branch 'master' into help-printer
Browse files Browse the repository at this point in the history
Conflicts:
	builtins/src/test/java/org/jline/example/Example.java
  • Loading branch information
mattirn committed Mar 16, 2019
2 parents acb9342 + 05b89e4 commit cb027ad
Show file tree
Hide file tree
Showing 14 changed files with 454 additions and 58 deletions.
132 changes: 112 additions & 20 deletions builtins/src/main/java/org/jline/builtins/Commands.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
import java.io.InputStream;
import java.io.PrintStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
Expand All @@ -24,13 +26,15 @@
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

import org.jline.builtins.Completers.CompletionData;
import org.jline.builtins.Options;
import org.jline.builtins.Source.StdInSource;
import org.jline.builtins.Source.URLSource;
import org.jline.keymap.KeyMap;
Expand Down Expand Up @@ -157,54 +161,142 @@ public static void less(Terminal terminal, InputStream in, PrintStream out, Prin
}

public static void history(LineReader reader, PrintStream out, PrintStream err,
String[] argv) throws IOException {
String[] argv) throws IOException, IllegalArgumentException {
final String[] usage = {
"history - list history of commands",
"Usage: history [OPTIONS]",
"Usage: history [-dnrfEi] [-m match] [first] [last]",
" history -ARWI [filename]",
" history --clear",
" history --save",
" -? --help Displays command help",
" --clear Clear history",
" --save Save history",
" -d Print timestamps for each event"};

" -m match If option -m is present the first argument is taken as a pattern",
" and only the history events matching the pattern will be shown",
" -d Print timestamps for each event",
" -f Print full time-date stamps in the US format",
" -E Print full time-date stamps in the European format",
" -i Print full time-date stamps in ISO8601 format",
" -n Suppresses command numbers",
" -r Reverses the order of the commands",
" -A Appends the history out to the given file",
" -R Reads the history from the given file",
" -W Writes the history out to the given file",
" -I If added to -R, only the events that are not contained within the internal list are added",
" If added to -W/A, only the events that are new since the last incremental operation to",
" the file are added",
" [first] [last] These optional arguments are numbers. A negative number is",
" used as an offset to the current history event number"};
Options opt = Options.compile(usage).parse(argv);

if (opt.isSet("help")) {
opt.usage(err);
return;
}
if (!opt.args().isEmpty()) {
err.println("usage: history [OPTIONS]");
return;
}

History history = reader.getHistory();
boolean done = true;
boolean increment = opt.isSet("I") ? true : false;
if (opt.isSet("clear")) {
history.purge();
}
if (opt.isSet("save")) {
} else if (opt.isSet("save")) {
history.save();
} else if (opt.isSet("A")) {
Path file = opt.args().size() > 0 ? Paths.get(opt.args().get(0)) : null;
history.append(file, increment);
} else if (opt.isSet("R")) {
Path file = opt.args().size() > 0 ? Paths.get(opt.args().get(0)) : null;
history.read(file, increment);
} else if (opt.isSet("W")) {
Path file = opt.args().size() > 0 ? Paths.get(opt.args().get(0)) : null;
history.write(file, increment);
} else {
done = false;
}
if (opt.isSet("clear") || opt.isSet("save")) {
if (done) {
return;
}
int argId = 0;
Pattern pattern = null;
if (opt.isSet("m")) {
if (opt.args().size() == 0) {
throw new IllegalArgumentException();
}
String sp = opt.args().get(argId++);
pattern = Pattern.compile(sp.toString());
}
int firstId = opt.args().size() > argId ? parseInteger(opt.args().get(argId++)) : -17;
int lastId = opt.args().size() > argId ? parseInteger(opt.args().get(argId++)) : -1;
firstId = historyId(firstId, history.size() - 1);
lastId = historyId(lastId, history.size() - 1);
if (firstId > lastId) {
throw new IllegalArgumentException();
}
int tot = lastId - firstId + 1;
int listed = 0;
final Highlighter highlighter = reader.getHighlighter();
for (History.Entry entry : history) {
Iterator<History.Entry> iter = null;
if (opt.isSet("r")) {
iter = history.reverseIterator(lastId);
} else {
iter = history.iterator(firstId);
}
while (iter.hasNext() && listed < tot) {
History.Entry entry = iter.next();
listed++;
if (pattern != null && !pattern.matcher(entry.line()).matches()) {
continue;
}
AttributedStringBuilder sb = new AttributedStringBuilder();
sb.append(" ");
sb.styled(AttributedStyle::bold, String.format("%3d", entry.index() + 1));
if (opt.isSet("d")) {
if (!opt.isSet("n")) {
sb.append(" ");
LocalTime lt = LocalTime.from(entry.time().atZone(ZoneId.systemDefault()))
.truncatedTo(ChronoUnit.SECONDS);
DateTimeFormatter.ISO_LOCAL_TIME.formatTo(lt, sb);
sb.styled(AttributedStyle::bold, String.format("%3d", entry.index()));
}
if (opt.isSet("d") || opt.isSet("f") || opt.isSet("E") || opt.isSet("i")) {
sb.append(" ");
if (opt.isSet("d")) {
LocalTime lt = LocalTime.from(entry.time().atZone(ZoneId.systemDefault()))
.truncatedTo(ChronoUnit.SECONDS);
DateTimeFormatter.ISO_LOCAL_TIME.formatTo(lt, sb);
} else {
LocalDateTime lt = LocalDateTime.from(entry.time().atZone(ZoneId.systemDefault())
.truncatedTo(ChronoUnit.MINUTES));
String format = "yyyy-MM-dd hh:mm";
if (opt.isSet("f")) {
format = "MM/dd/yy hh:mm";
} else if (opt.isSet("E")) {
format = "dd.MM.yyyy hh:mm";
}
DateTimeFormatter.ofPattern(format).formatTo(lt, sb);
}
}
sb.append(" ");
sb.append(highlighter.highlight(reader, entry.line()));
out.println(sb.toAnsi(reader.getTerminal()));
}
}

public static void complete(LineReader reader, PrintStream out, PrintStream err,
private static int historyId(int id, int maxId) {
int out = id;
if (id < 0) {
out = maxId + id + 1;
}
if (out < 0) {
out = 0;
} else if (out > maxId) {
out = maxId;
}
return out;
}

private static int parseInteger(String s) throws IllegalArgumentException {
try {
return Integer.parseInt(s);
} catch (NumberFormatException ex) {
throw new IllegalArgumentException();
}
}

public static void complete(LineReader reader, PrintStream out, PrintStream err,
Map<String, List<CompletionData>> completions,
String[] argv) {
final String[] usage = {
Expand Down
2 changes: 1 addition & 1 deletion builtins/src/main/java/org/jline/builtins/Options.java
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,7 @@ else if (needArg != null) {
needArg = null;
needOpt = null;
}
else if (!arg.startsWith("-") || "-".equals(oarg)) {
else if (!arg.startsWith("-") || (arg.length() > 1 && Character.isDigit(arg.charAt(1))) || "-".equals(oarg)) {
if (optionsFirst)
endOpt = true;
xargs.add(oarg);
Expand Down
6 changes: 3 additions & 3 deletions builtins/src/test/java/org/jline/example/Example.java
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ public static void main(String[] args) throws IOException {
case "brackets":
prompt = "long-prompt> ";
DefaultParser p2 = new DefaultParser();
p2.eofOnUnclosedBracket(Bracket.CURLY,Bracket.ROUND,Bracket.SQUARE);
p2.setEofOnUnclosedBracket(Bracket.CURLY, Bracket.ROUND, Bracket.SQUARE);
parser = p2;
break label;
case "foo":
Expand Down Expand Up @@ -316,8 +316,8 @@ public void complete(LineReader reader, ParsedLine line, List<Candidate> candida
if (line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("exit")) {
break;
}
ParsedLine pl = reader.getParser().parse(line, 0);
String[] argv = pl.words().toArray(new String[0]);
ParsedLine pl = reader.getParser().parse(line, 0);
String[] argv = pl.words().subList(1, pl.words().size()).toArray(new String[0]);
if ("set".equals(pl.word())) {
if (pl.words().size() == 3) {
reader.setVariable(pl.words().get(1), pl.words().get(2));
Expand Down
21 changes: 21 additions & 0 deletions reader/src/main/java/org/jline/reader/History.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
package org.jline.reader;

import java.io.IOException;
import java.nio.file.Path;
import java.time.Instant;
import java.util.Iterator;
import java.util.ListIterator;
Expand Down Expand Up @@ -41,6 +42,26 @@ public interface History extends Iterable<History.Entry>
*/
void save() throws IOException;

/**
* Write history to the file. If incremental only the events that are new since the last incremental operation to
* the file are added.
* @throws IOException if a problem occurs
*/
void write(Path file, boolean incremental) throws IOException;

/**
* Append history to the file. If incremental only the events that are new since the last incremental operation to
* the file are added.
* @throws IOException if a problem occurs
*/
void append(Path file, boolean incremental) throws IOException;

/**
* Read history from the file. If incremental only the events that are not contained within the internal list are added.
* @throws IOException if a problem occurs
*/
void read(Path file, boolean incremental) throws IOException;

/**
* Purge history.
* @throws IOException if a problem occurs
Expand Down
3 changes: 3 additions & 0 deletions reader/src/main/java/org/jline/reader/LineReader.java
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,10 @@ public interface LineReader {
String CALLBACK_FINISH = "callback-finish";
String CALLBACK_KEYMAP = "callback-keymap";

String ACCEPT_AND_INFER_NEXT_HISTORY = "accept-and-infer-next-history";
String ACCEPT_AND_HOLD = "accept-and-hold";
String ACCEPT_LINE = "accept-line";
String ACCEPT_LINE_AND_DOWN_HISTORY = "accept-line-and-down-history";
String ARGUMENT_BASE = "argument-base";
String BACKWARD_CHAR = "backward-char";
String BACKWARD_DELETE_CHAR = "backward-delete-char";
Expand Down
26 changes: 14 additions & 12 deletions reader/src/main/java/org/jline/reader/impl/DefaultParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -209,18 +209,20 @@ public ParsedLine parse(final String line, final int cursor, ParseContext contex
rawWordLength = rawWordCursor;
}

if (eofOnEscapedNewLine && isEscapeChar(line, line.length() - 1)) {
throw new EOFError(-1, -1, "Escaped new line", "newline");
}
if (eofOnUnclosedQuote && quoteStart >= 0 && context != ParseContext.COMPLETE) {
throw new EOFError(-1, -1, "Missing closing quote", line.charAt(quoteStart) == '\''
? "quote" : "dquote");
}
if (bracketChecker.isOpeningBracketMissing() && context != ParseContext.COMPLETE) {
throw new EOFError(-1, -1, "Missing opening bracket", "missing: " + bracketChecker.getMissingOpeningBracket());
}
if (bracketChecker.isClosingBracketMissing() && context != ParseContext.COMPLETE) {
throw new EOFError(-1, -1, "Missing closing brackets", "add: " + bracketChecker.getMissingClosingBrackets());
if (context != ParseContext.COMPLETE) {
if (eofOnEscapedNewLine && isEscapeChar(line, line.length() - 1)) {
throw new EOFError(-1, -1, "Escaped new line", "newline");
}
if (eofOnUnclosedQuote && quoteStart >= 0) {
throw new EOFError(-1, -1, "Missing closing quote", line.charAt(quoteStart) == '\''
? "quote" : "dquote");
}
if (bracketChecker.isOpeningBracketMissing()) {
throw new EOFError(-1, -1, "Missing opening bracket", "missing: " + bracketChecker.getMissingOpeningBracket());
}
if (bracketChecker.isClosingBracketMissing()) {
throw new EOFError(-1, -1, "Missing closing brackets", "add: " + bracketChecker.getMissingClosingBrackets());
}
}

String openingQuote = quotedWord ? line.substring(quoteStart, quoteStart + 1) : null;
Expand Down

0 comments on commit cb027ad

Please sign in to comment.