org.jline.reader.Candidate Java Examples
The following examples show how to use
org.jline.reader.Candidate.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CompletionTest.java From sqlline with BSD 3-Clause "New" or "Revised" License | 6 votes |
@ParameterizedTest @MethodSource("stringsForSchemaTableColumnCompletions") public void testSchemaTableColumnCompletions(String expected, String input) { try { final LineReaderCompletionImpl lineReader = getDummyLineReader(); lineReader.setCompleter(new SqlCompleter(sqlLine, false)); // need for rehash as test data created after sql completer init sqlLine.runCommands(new DispatchCallback(), "!rehash"); os.reset(); final Collection<String> actual = getLineReaderCompletedList(lineReader, input).stream() .map(Candidate::value).collect(Collectors.toList()); assertIterableEquals(Collections.singleton(expected), actual); assertEquals(1, actual.size()); } catch (Exception e) { // fail throw new RuntimeException(e); } }
Example #2
Source File: OperationCompleter.java From rug-cli with GNU General Public License v3.0 | 6 votes |
private void completeBasedOnJsonpathMatches(String kind, List<String> words, List<Candidate> candidates) { if (ctx != null) { try { List<String> names = ctx.read(String.format("$.%s[*].name", kind)); Optional<String> name = names.stream().filter(words::contains).map(String::toString) .findFirst(); if (name.isPresent()) { List<String> parameterNames = ctx.read(String .format("$.%s[?(@.name=='%s')].parameters[*].name", kind, name.get())); completeParameters(kind, words, candidates, parameterNames); parameterNames = ctx.read(String .format("$.%s[?(@.name=='%s')].mapped_parameters[*].local_key", kind, name.get())); completeParameters(kind, words, candidates, parameterNames); } else { names.forEach(n -> candidates.add(new Candidate(n))); } } catch (PathNotFoundException e) { // This is ok as it means we don't have the matching operation in the cache } } }
Example #3
Source File: CommandInfoCompleter.java From rug-cli with GNU General Public License v3.0 | 6 votes |
private void completeOptions(Collection<Option> options, List<Candidate> candidates, List<String> words, boolean highlight) { options.stream().filter(o -> { if (o.hasLongOpt() && words.contains("--" + o.getLongOpt())) { return false; } if (o.getOpt() != null && words.contains("-" + o.getOpt())) { return false; } return true; }).forEach(o -> { if (o.hasLongOpt()) { candidates .add(new Candidate("--" + o.getLongOpt(), (highlight ? Style.underline("--" + o.getLongOpt()) : "--" + o.getLongOpt()), null, null, null, o.toString(), true)); } if (o.getOpt() != null) { candidates.add(new Candidate("-" + o.getOpt(), (highlight ? Style.underline("-" + o.getOpt()) : "-" + o.getOpt()), null, null, null, o.toString(), true)); } }); }
Example #4
Source File: PicocliJLineCompleter.java From picocli with Apache License 2.0 | 6 votes |
/** * Populates <i>candidates</i> with a list of possible completions for the <i>command line</i>. * * The list of candidates will be sorted and filtered by the LineReader, so that * the list of candidates displayed to the user will usually be smaller than * the list given by the completer. Thus it is not necessary for the completer * to do any matching based on the current buffer. On the contrary, in order * for the typo matcher to work, all possible candidates for the word being * completed should be returned. * * @param reader The line reader * @param line The parsed command line * @param candidates The {@link List} of candidates to populate */ //@Override public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) { // let picocli generate completion candidates for the token where the cursor is at String[] words = new String[line.words().size()]; words = line.words().toArray(words); List<CharSequence> cs = new ArrayList<CharSequence>(); AutoComplete.complete(spec, words, line.wordIndex(), 0, line.cursor(), cs); for(CharSequence c: cs){ candidates.add(new Candidate((String)c)); } }
Example #5
Source File: SqlCompleter.java From flink with Apache License 2.0 | 6 votes |
public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) { String statement = line.line(); // remove ';' at the end if (statement.endsWith(";")) { statement = statement.substring(0, statement.length() - 1); } // handle SQL client specific commands final String statementNormalized = statement.toUpperCase().trim(); for (String commandHint : COMMAND_HINTS) { if (commandHint.startsWith(statementNormalized) && line.cursor() < commandHint.length()) { candidates.add(createCandidate(getCompletionHint(statementNormalized, commandHint))); } } // fallback to Table API hinting try { executor.completeStatement(sessionId, statement, line.cursor()) .forEach(hint -> candidates.add(createCandidate(hint))); } catch (SqlExecutionException e) { LOG.debug("Could not complete statement at " + line.cursor() + ":" + statement, e); } }
Example #6
Source File: ConnectionCompleter.java From sqlline with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public void complete( LineReader lineReader, ParsedLine parsedLine, List<Candidate> list) { DatabaseConnections databaseConnections = sqlLine.getDatabaseConnections(); if (databaseConnections.size() == 0) { return; } int i = 0; for (DatabaseConnection dbConnection: databaseConnections) { String strValue = String.valueOf(i); list.add(new SqlLineCommandCompleter.SqlLineCandidate( sqlLine, strValue, strValue, sqlLine.loc("connections"), dbConnection.getNickname() == null ? dbConnection.getUrl() : dbConnection.getNickname(), null, null, true)); i++; } }
Example #7
Source File: CompletionTest.java From sqlline with BSD 3-Clause "New" or "Revised" License | 6 votes |
@ParameterizedTest(name = "Check completions like input + one symbol") @ValueSource(strings = {"!", " \t\t !", "\t \t!"}) public void testCommandCompletions(String input) { final LineReaderCompletionImpl lineReader = getDummyLineReader(); TreeSet<String> commandSet = getCommandSet(sqlLine); for (char c = 'a'; c <= 'z'; c++) { final Set<String> expectedSubSet = filterSet(commandSet, SqlLine.COMMAND_PREFIX + c); final List<Candidate> actualCandidates = getLineReaderCompletedList(lineReader, input + c); assertEquals(expectedSubSet.size(), actualCandidates.size()); for (Candidate candidate : actualCandidates) { assertTrue(expectedSubSet.contains(candidate.value())); } } }
Example #8
Source File: SqlCompleter.java From Flink-CEPplus with Apache License 2.0 | 6 votes |
public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) { String statement = line.line(); // remove ';' at the end if (statement.endsWith(";")) { statement = statement.substring(0, statement.length() - 1); } // handle SQL client specific commands final String statementNormalized = statement.toUpperCase().trim(); for (String commandHint : COMMAND_HINTS) { if (commandHint.startsWith(statementNormalized) && line.cursor() < commandHint.length()) { candidates.add(createCandidate(commandHint)); } } // fallback to Table API hinting try { executor.completeStatement(context, statement, line.cursor()) .forEach(hint -> candidates.add(createCandidate(hint))); } catch (SqlExecutionException e) { LOG.debug("Could not complete statement at " + line.cursor() + ":" + statement, e); } }
Example #9
Source File: Shell.java From joinery with GNU General Public License v3.0 | 6 votes |
@Override public void complete(final LineReader reader, final ParsedLine line, final List<Candidate> candidates) { final String expr = line.word().substring(0, line.wordCursor()); final int dot = expr.lastIndexOf('.') + 1; if (dot > 1) { final String sym = expr.substring(0, dot - 1); final Object value = get(sym, Repl.this); if (value instanceof ScriptableObject) { ScriptableObject so = (ScriptableObject)value; final Object[] ids = so.getAllIds(); for (final Object id : ids) { final String candidate = sym + "." + id; candidates.add(new Candidate( candidate, candidate, null, null, null, null, false )); } } } }
Example #10
Source File: CommandCompleter.java From batfish with Apache License 2.0 | 6 votes |
@Override public void complete(LineReader lineReader, ParsedLine parsedLine, List<Candidate> candidates) { String buffer = parsedLine.word().trim(); if (Strings.isNullOrEmpty(buffer)) { candidates.addAll(_commandStrs.stream().map(Candidate::new).collect(Collectors.toList())); } else { for (String match : _commandStrs.tailSet(buffer)) { if (!match.startsWith(buffer)) { break; } candidates.add(new Candidate(match)); } } // if the match was unique and the complete command was specified, print the command usage if (candidates.size() == 1 && candidates.get(0).displ().equals(buffer)) { candidates.clear(); candidates.add( new Candidate( " " + Command.getUsageMap().get(Command.getNameMap().get(buffer)).getUsage())); } }
Example #11
Source File: CompletionTest.java From sqlline with BSD 3-Clause "New" or "Revised" License | 6 votes |
@ParameterizedTest @MethodSource("sqlKeywordCompletionProvider") public void testSqlCompletions(String input, String expected) { try { LineReader lineReader = sqlLine.getLineReader(); LineReaderCompletionImpl lineReaderCompletion = new LineReaderCompletionImpl(lineReader.getTerminal()); lineReaderCompletion.setCompleter( sqlLine.getDatabaseConnection().getSqlCompleter()); final List<Candidate> actual = getLineReaderCompletedList(lineReaderCompletion, input); assertEquals(1, actual.size()); assertEquals(expected, actual.iterator().next().value()); } catch (Exception e) { // fail throw new RuntimeException(e); } }
Example #12
Source File: VelocityConsole.java From Velocity with MIT License | 6 votes |
@Override protected LineReader buildReader(LineReaderBuilder builder) { return super.buildReader(builder .appName("Velocity") .completer((reader, parsedLine, list) -> { try { boolean isCommand = parsedLine.line().indexOf(' ') == -1; List<String> offers = this.server.getCommandManager() .offerSuggestions(this, parsedLine.line()); for (String offer : offers) { if (isCommand) { list.add(new Candidate(offer.substring(1))); } else { list.add(new Candidate(offer)); } } } catch (Exception e) { logger.error("An error occurred while trying to perform tab completion.", e); } }) ); }
Example #13
Source File: DynamicCompleter.java From super-cloudops with Apache License 2.0 | 6 votes |
@Override public void complete(LineReader reader, ParsedLine parsedLine, List<Candidate> candidates) { List<String> commands = LineUtils.parse(parsedLine.line()); // Primary level frist arguments if (commands.isEmpty()) { new StringsCompleter(registry.getHelpOptions().keySet()).complete(reader, parsedLine, candidates); } // Secondary primary arguments else { HelpOptions options = registry.getHelpOptions().get(commands.get(0)); // Continue before completion if (completingCompleted(commands, options)) { List<String> candes = new ArrayList<>(); for (Option opt : options.getOptions()) { candes.add(GNU_CMD_SHORT + opt.getOpt()); candes.add(GNU_CMD_LONG + opt.getLongOpt()); } new StringsCompleter(candes).complete(reader, parsedLine, candidates); } } }
Example #14
Source File: Command.java From Launcher with GNU General Public License v3.0 | 6 votes |
/** * Returns a list of available options for the next word for the current command. * * @param words list all user words * @param wordIndex current word index * @param word current word * @return list of available Candidate */ public List<Candidate> complete(List<String> words, int wordIndex, String word) { if (wordIndex == 0) { List<Candidate> candidates = new ArrayList<>(); childCommands.forEach((k, v) -> { if (k.startsWith(word)) { candidates.add(new Candidate(k)); } }); return candidates; } else { Command cmd = childCommands.get(words.get(0)); if (cmd == null) return new ArrayList<>(); return cmd.complete(words.subList(1, words.size()), wordIndex - 1, word); } }
Example #15
Source File: JLineCompleter.java From jsqsh with Apache License 2.0 | 6 votes |
@Override public void complete(LineReader lineReader, ParsedLine parsedLine, List<Candidate> list) { Session session = ctx.getCurrentSession(); ConnectionContext conn = session.getConnectionContext(); if (conn != null) { Completer completer = conn.getTabCompleter(session, parsedLine.line(), parsedLine.cursor(), parsedLine.word()); String name = completer.next(); while (name != null) { list.add(new Candidate(name)); name = completer.next(); } } }
Example #16
Source File: TestCLICompleter.java From nifi with Apache License 2.0 | 6 votes |
@Test public void testCompletionWithFileArguments() { final String topCommand = NiFiRegistryCommandGroup.REGISTRY_COMMAND_GROUP; final String subCommand = "list-buckets"; final DefaultParser.ArgumentList parsedLine = new DefaultParser.ArgumentList( "", Arrays.asList(topCommand, subCommand, "-p", "src/test/resources/"), 3, -1, -1); final List<Candidate> candidates = new ArrayList<>(); completer.complete(lineReader, parsedLine, candidates); assertTrue(candidates.size() > 0); boolean found = false; for (Candidate candidate : candidates) { if (candidate.value().equals("src/test/resources/test.properties")) { found = true; break; } } assertTrue(found); }
Example #17
Source File: CompletionTest.java From sqlline with BSD 3-Clause "New" or "Revised" License | 6 votes |
@ParameterizedTest @MethodSource("noSchemaSqlCompletionsWithFastConnect") public void testNoSchemaSqlCompletionsWithFastConnect( String expected, String input) { try { final LineReaderCompletionImpl lineReader = getDummyLineReader(); lineReader.setCompleter(new SqlCompleter(sqlLine, true)); // need for rehash as test data created after sql completer init sqlLine.runCommands(new DispatchCallback(), "!set fastconnect true"); sqlLine.runCommands(new DispatchCallback(), "!rehash"); os.reset(); final Collection<String> actual = getLineReaderCompletedList(lineReader, input).stream() .map(Candidate::value).collect(Collectors.toList()); assertFalse(actual.stream().allMatch(t -> t.startsWith(expected))); sqlLine.runCommands(new DispatchCallback(), "!set fastconnect false"); sqlLine.runCommands(new DispatchCallback(), "!rehash"); } catch (Exception e) { // fail throw new RuntimeException(e); } }
Example #18
Source File: SqlCompleter.java From flink with Apache License 2.0 | 6 votes |
public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) { String statement = line.line(); // remove ';' at the end if (statement.endsWith(";")) { statement = statement.substring(0, statement.length() - 1); } // handle SQL client specific commands final String statementNormalized = statement.toUpperCase().trim(); for (String commandHint : COMMAND_HINTS) { if (commandHint.startsWith(statementNormalized) && line.cursor() < commandHint.length()) { candidates.add(createCandidate(commandHint)); } } // fallback to Table API hinting try { executor.completeStatement(context, statement, line.cursor()) .forEach(hint -> candidates.add(createCandidate(hint))); } catch (SqlExecutionException e) { LOG.debug("Could not complete statement at " + line.cursor() + ":" + statement, e); } }
Example #19
Source File: ArchiveNameCompleter.java From rug-cli with GNU General Public License v3.0 | 6 votes |
@Override public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) { if (line.words().size() == 2) { String cmd = line.words().get(0); String word = line.word(); if (COMMANDS.contains(cmd)) { // group is already specified; only provide artifacts now if (word.contains(":")) { String group = word.split(":")[0] + ":"; archivesFromCache().stream().filter(a -> a.startsWith(group)) .collect(Collectors.toSet()) .forEach(a -> candidates.add(new Candidate(a))); } // sill completing group else { archivesFromCache().stream().map(a -> a.split(":")[0]) .collect(Collectors.toSet()).forEach(a -> candidates .add(new Candidate(a + ":", a, null, null, null, null, false))); } } } }
Example #20
Source File: TestCLICompleter.java From nifi with Apache License 2.0 | 5 votes |
@Test public void testCompletionForSessionVariableWithFiles() { final String topCommand = "session"; final String subCommand = "set"; final DefaultParser.ArgumentList parsedLine = new DefaultParser.ArgumentList("", Arrays.asList( topCommand, subCommand, SessionVariable.NIFI_CLIENT_PROPS.getVariableName(), "src/test/resources/"), 3, -1, -1); final List<Candidate> candidates = new ArrayList<>(); completer.complete(lineReader, parsedLine, candidates); assertTrue(candidates.size() > 0); boolean found = false; for (Candidate candidate : candidates) { if (candidate.value().equals("src/test/resources/test.properties")) { found = true; break; } } assertTrue(found); }
Example #21
Source File: CompletionTest.java From sqlline with BSD 3-Clause "New" or "Revised" License | 5 votes |
@ParameterizedTest @MethodSource("stringsForSchemaTableColumnCompletionsForSquareBrackets") public void testSchemaTableColumnCompletionsForSquareBracketsDialect( String expected, String input) { try { new MockUp<DialectImpl>() { @Mock public char getOpenQuote() { return '['; } @Mock public char getCloseQuote() { return ']'; } }; final LineReaderCompletionImpl lineReader = getDummyLineReader(); lineReader.setCompleter(new SqlCompleter(sqlLine, false)); // need for rehash as test data created after sql completer init sqlLine.runCommands(new DispatchCallback(), "!rehash"); os.reset(); final Collection<String> actual = getLineReaderCompletedList(lineReader, input).stream() .map(Candidate::value).collect(Collectors.toList()); assertIterableEquals(Collections.singleton(expected), actual); assertEquals(1, actual.size()); } catch (Exception e) { // fail throw new RuntimeException(e); } }
Example #22
Source File: CompletionTest.java From sqlline with BSD 3-Clause "New" or "Revised" License | 5 votes |
@ParameterizedTest(name = "Property with defined available values " + "should be autocompleted only with values from the defined ranges") @MethodSource("propertyCompletionProvider") public void testSetPropertyCompletions(String input, String expected) { final LineReaderCompletionImpl lineReader = getDummyLineReader(); final Collection<Candidate> actual = getLineReaderCompletedList(lineReader, input); assertEquals(1, actual.size()); assertEquals(expected, actual.iterator().next().value()); }
Example #23
Source File: CompletionTest.java From sqlline with BSD 3-Clause "New" or "Revised" License | 5 votes |
@ParameterizedTest @MethodSource("stringsForSchemaTableColumnCompletionsForMySql") public void testSchemaTableColumnCompletionsForMySqlDialect( String expected, String input) { try { new MockUp<DialectImpl>() { @Mock public char getOpenQuote() { return '`'; } @Mock public char getCloseQuote() { return '`'; } }; final LineReaderCompletionImpl lineReader = getDummyLineReader(); lineReader.setCompleter(new SqlCompleter(sqlLine, false)); // need for rehash as test data created after sql completer init sqlLine.runCommands(new DispatchCallback(), "!rehash"); os.reset(); final Collection<String> actual = getLineReaderCompletedList(lineReader, input).stream() .map(Candidate::value).collect(Collectors.toList()); assertIterableEquals(Collections.singleton(expected), actual); assertEquals(1, actual.size()); } catch (Exception e) { // fail throw new RuntimeException(e); } }
Example #24
Source File: TestCLICompleter.java From nifi with Apache License 2.0 | 5 votes |
@Test public void testCompletionWithWordIndexOneAndMatching() { final String topCommand = NiFiRegistryCommandGroup.REGISTRY_COMMAND_GROUP; final DefaultParser.ArgumentList parsedLine = new DefaultParser.ArgumentList( "", Collections.singletonList(topCommand), 1, -1, -1); final List<Candidate> candidates = new ArrayList<>(); completer.complete(lineReader, parsedLine, candidates); assertEquals(completer.getSubCommands(topCommand).size(), candidates.size()); }
Example #25
Source File: TestCLICompleter.java From nifi with Apache License 2.0 | 5 votes |
@Test public void testCompletionForSessionVariableNames() { final String topCommand = "session"; final String subCommand = "set"; final DefaultParser.ArgumentList parsedLine = new DefaultParser.ArgumentList( "", Arrays.asList(topCommand, subCommand), 2, -1, -1); final List<Candidate> candidates = new ArrayList<>(); completer.complete(lineReader, parsedLine, candidates); assertTrue(candidates.size() > 0); assertEquals(SessionVariable.values().length, candidates.size()); }
Example #26
Source File: TestCLICompleter.java From nifi with Apache License 2.0 | 5 votes |
@Test public void testCompletionWithMultipleArguments() { final String topCommand = NiFiRegistryCommandGroup.REGISTRY_COMMAND_GROUP; final String subCommand = "list-buckets"; final DefaultParser.ArgumentList parsedLine = new DefaultParser.ArgumentList( "", Arrays.asList(topCommand, subCommand, "-ks", "foo", "-kst", "JKS"), 6, -1, -1); final List<Candidate> candidates = new ArrayList<>(); completer.complete(lineReader, parsedLine, candidates); assertTrue(candidates.size() > 0); assertEquals(completer.getOptions(subCommand).size(), candidates.size()); }
Example #27
Source File: TestCLICompleter.java From nifi with Apache License 2.0 | 5 votes |
@Test public void testCompletionWithWordIndexTwoAndNotMatching() { final String topCommand = NiFiRegistryCommandGroup.REGISTRY_COMMAND_GROUP; final String subCommand = "NOT-A-TOP-LEVEL-COMMAND"; final DefaultParser.ArgumentList parsedLine = new DefaultParser.ArgumentList( "", Arrays.asList(topCommand, subCommand), 2, -1, -1); final List<Candidate> candidates = new ArrayList<>(); completer.complete(lineReader, parsedLine, candidates); assertEquals(0, candidates.size()); }
Example #28
Source File: TestCLICompleter.java From nifi with Apache License 2.0 | 5 votes |
@Test public void testCompletionWithWordIndexTwoAndMatching() { final String topCommand = NiFiRegistryCommandGroup.REGISTRY_COMMAND_GROUP; final String subCommand = "list-buckets"; final DefaultParser.ArgumentList parsedLine = new DefaultParser.ArgumentList( "", Arrays.asList(topCommand, subCommand), 2, -1, -1); final List<Candidate> candidates = new ArrayList<>(); completer.complete(lineReader, parsedLine, candidates); assertTrue(candidates.size() > 0); assertEquals(completer.getOptions(subCommand).size(), candidates.size()); }
Example #29
Source File: TestCLICompleter.java From nifi with Apache License 2.0 | 5 votes |
@Test public void testCompletionWithWordIndexOneAndNotMatching() { final String topCommand = "NOT-A-TOP-LEVEL-COMMAND"; final DefaultParser.ArgumentList parsedLine = new DefaultParser.ArgumentList( "", Collections.singletonList(topCommand), 1, -1, -1); final List<Candidate> candidates = new ArrayList<>(); completer.complete(lineReader, parsedLine, candidates); assertEquals(0, candidates.size()); }
Example #30
Source File: CliClientTest.java From flink with Apache License 2.0 | 5 votes |
private void verifySqlCompletion(String statement, int position, List<String> expectedHints, List<String> notExpectedHints) throws IOException { final SessionContext context = new SessionContext("test-session", new Environment()); final MockExecutor mockExecutor = new MockExecutor(); String sessionId = mockExecutor.openSession(context); final SqlCompleter completer = new SqlCompleter(sessionId, mockExecutor); final SqlMultiLineParser parser = new SqlMultiLineParser(); try (Terminal terminal = TerminalUtils.createDummyTerminal()) { final LineReader reader = LineReaderBuilder.builder().terminal(terminal).build(); final ParsedLine parsedLine = parser.parse(statement, position, Parser.ParseContext.COMPLETE); final List<Candidate> candidates = new ArrayList<>(); final List<String> results = new ArrayList<>(); completer.complete(reader, parsedLine, candidates); candidates.forEach(item -> results.add(item.value())); assertTrue(results.containsAll(expectedHints)); assertEquals(statement, mockExecutor.receivedStatement); assertEquals(context, mockExecutor.receivedContext); assertEquals(position, mockExecutor.receivedPosition); assertTrue(results.contains("HintA")); assertTrue(results.contains("Hint B")); results.retainAll(notExpectedHints); assertEquals(0, results.size()); } }