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 Project: Flink-CEPplus   Author: ljygz   File: SqlCompleter.java    License: Apache License 2.0 6 votes vote down vote up
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 #2
Source Project: flink   Author: flink-tpc-ds   File: SqlCompleter.java    License: Apache License 2.0 6 votes vote down vote up
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 #3
Source Project: Launcher   Author: GravitLauncher   File: Command.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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 #4
Source Project: super-cloudops   Author: wl4g   File: DynamicCompleter.java    License: Apache License 2.0 6 votes vote down vote up
@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 #5
Source Project: Velocity   Author: VelocityPowered   File: VelocityConsole.java    License: MIT License 6 votes vote down vote up
@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 #6
Source Project: picocli   Author: remkop   File: PicocliJLineCompleter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #7
Source Project: rug-cli   Author: atomist-attic   File: OperationCompleter.java    License: GNU General Public License v3.0 6 votes vote down vote up
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 #8
Source Project: rug-cli   Author: atomist-attic   File: ArchiveNameCompleter.java    License: GNU General Public License v3.0 6 votes vote down vote up
@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 #9
Source Project: rug-cli   Author: atomist-attic   File: CommandInfoCompleter.java    License: GNU General Public License v3.0 6 votes vote down vote up
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 #10
Source Project: flink   Author: apache   File: SqlCompleter.java    License: Apache License 2.0 6 votes vote down vote up
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 #11
Source Project: joinery   Author: cardillo   File: Shell.java    License: GNU General Public License v3.0 6 votes vote down vote up
@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 #12
Source Project: batfish   Author: batfish   File: CommandCompleter.java    License: Apache License 2.0 6 votes vote down vote up
@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 #13
Source Project: jsqsh   Author: scgray   File: JLineCompleter.java    License: Apache License 2.0 6 votes vote down vote up
@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 #14
Source Project: nifi   Author: apache   File: TestCLICompleter.java    License: Apache License 2.0 6 votes vote down vote up
@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 #15
Source Project: sqlline   Author: julianhyde   File: ConnectionCompleter.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 #16
Source Project: sqlline   Author: julianhyde   File: CompletionTest.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 #17
Source Project: sqlline   Author: julianhyde   File: CompletionTest.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 #18
Source Project: sqlline   Author: julianhyde   File: CompletionTest.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 #19
Source Project: sqlline   Author: julianhyde   File: CompletionTest.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 #20
Source Project: Flink-CEPplus   Author: ljygz   File: CliClientTest.java    License: Apache License 2.0 5 votes vote down vote up
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();

	final SqlCompleter completer = new SqlCompleter(context, 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());
	}
}
 
Example #21
Source Project: flink   Author: flink-tpc-ds   File: CliClientTest.java    License: Apache License 2.0 5 votes vote down vote up
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();

	final SqlCompleter completer = new SqlCompleter(context, 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());
	}
}
 
Example #22
Source Project: rdflint   Author: imas   File: InteractiveModeTest.java    License: MIT License 5 votes vote down vote up
@Test
public void interactiveCompleterCommand() throws Exception {
  ParsedLine pl = mock(ParsedLine.class);
  when(pl.line()).thenReturn(":ex");
  when(pl.word()).thenReturn(":ex");
  Model m = mock(Model.class);
  when(m.getNsPrefixMap()).thenReturn(new HashMap<String, String>());
  InteractiveMode.InteractiveCompleter completer = new InteractiveMode.InteractiveCompleter(m);
  List<Candidate> candidates = new LinkedList<>();
  completer.complete(null, pl, candidates);
  assertEquals(":exit", candidates.get(0).value());
}
 
Example #23
Source Project: rdflint   Author: imas   File: InteractiveModeTest.java    License: MIT License 5 votes vote down vote up
@Test
public void interactiveCompleterQuery() throws Exception {
  ParsedLine pl = mock(ParsedLine.class);
  when(pl.line()).thenReturn("se");
  when(pl.word()).thenReturn("se");
  Model m = mock(Model.class);
  when(m.getNsPrefixMap()).thenReturn(new HashMap<String, String>());
  InteractiveMode.InteractiveCompleter completer = new InteractiveMode.InteractiveCompleter(m);
  List<Candidate> candidates = new LinkedList<>();
  completer.complete(null, pl, candidates);
  assertEquals("SELECT", candidates.get(0).value());
}
 
Example #24
Source Project: rdflint   Author: imas   File: InteractiveModeTest.java    License: MIT License 5 votes vote down vote up
@Test
public void interactiveCompleterPrefixAlias() throws Exception {
  ParsedLine pl = mock(ParsedLine.class);
  when(pl.line()).thenReturn("PREFIX foa");
  when(pl.words()).thenReturn(Arrays.asList("PREFIX", "foa"));
  when(pl.word()).thenReturn("foa");
  Model m = mock(Model.class);
  Map<String, String> prefixMap = new HashMap<String, String>();
  prefixMap.put("foaf", "http://xmlns.com/foaf/spec/");
  when(m.getNsPrefixMap()).thenReturn(prefixMap);
  InteractiveMode.InteractiveCompleter completer = new InteractiveMode.InteractiveCompleter(m);
  List<Candidate> candidates = new LinkedList<>();
  completer.complete(null, pl, candidates);
  assertEquals("foaf:", candidates.get(0).value());
}
 
Example #25
Source Project: rdflint   Author: imas   File: InteractiveModeTest.java    License: MIT License 5 votes vote down vote up
@Test
public void interactiveCompleterPrefixUri() throws Exception {
  ParsedLine pl = mock(ParsedLine.class);
  when(pl.line()).thenReturn("PREFIX rdfs: ");
  when(pl.words()).thenReturn(Arrays.asList("PREFIX", "rdfs:", ""));
  when(pl.word()).thenReturn("");
  Model m = mock(Model.class);
  Map<String, String> prefixMap = new HashMap<String, String>();
  prefixMap.put("rdfs", "http://www.w3.org/2000/01/rdf-schema#");
  when(m.getNsPrefixMap()).thenReturn(prefixMap);
  InteractiveMode.InteractiveCompleter completer = new InteractiveMode.InteractiveCompleter(m);
  List<Candidate> candidates = new LinkedList<>();
  completer.complete(null, pl, candidates);
  assertEquals("<http://www.w3.org/2000/01/rdf-schema#>", candidates.get(0).value());
}
 
Example #26
Source Project: picocli   Author: remkop   File: PicocliCommands.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void complete(LineReader reader, ParsedLine commandLine, List<Candidate> candidates) {
    assert commandLine != null;
    assert candidates != null;
    String word = commandLine.word();
    List<String> words = commandLine.words();
    CommandLine sub = findSubcommandLine(words, commandLine.wordIndex());
    if (sub == null) {
        return;
    }
    if (word.startsWith("-")) {
        String buffer = word.substring(0, commandLine.wordCursor());
        int eq = buffer.indexOf('=');
        for (OptionSpec option : sub.getCommandSpec().options()) {
            if (option.arity().max() == 0 && eq < 0) {
                addCandidates(candidates, Arrays.asList(option.names()));
            } else {
                if (eq > 0) {
                    String opt = buffer.substring(0, eq);
                    if (Arrays.asList(option.names()).contains(opt) && option.completionCandidates() != null) {
                        addCandidates(candidates, option.completionCandidates(), buffer.substring(0, eq + 1), "", true);
                    }
                } else {
                    addCandidates(candidates, Arrays.asList(option.names()), "", "=", false);
                }
            }
        }
    } else {
        addCandidates(candidates, sub.getSubcommands().keySet());
        for (CommandLine s : sub.getSubcommands().values()) {
            addCandidates(candidates, Arrays.asList(s.getCommandSpec().aliases()));
        }
    }
}
 
Example #27
Source Project: rug-cli   Author: atomist-attic   File: OperationCompleter.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void completeParameters(String kind, List<String> words, List<Candidate> candidates,
        List<String> parameterNames) {
    parameterNames.stream()
            .filter(p -> words.stream().noneMatch(w -> w.startsWith(p + "=")))
            .forEach(n -> candidates
                    .add(new Candidate(n + "=", Style.underline(n), null, null, null, null, false)));
}
 
Example #28
Source Project: rug-cli   Author: atomist-attic   File: FileAndDirectoryNameCompleter.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void complete(LineReader reader, ParsedLine commandLine, List<Candidate> candidates) {
    if (commandLine.words().size() > 1) {
        String word = commandLine.words().get(commandLine.words().size() - 2);
        if ("-C".equals(word) || "--change-dir".equals(word)) {
            super.complete(reader, commandLine, candidates);
        }
        else if (commandLine.line().startsWith(Constants.SHELL_ESCAPE)) {
            super.complete(reader, commandLine, candidates);
        }
    }
}
 
Example #29
Source Project: Arend   Author: JetBrains   File: SpecialCommandCompleter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) {
  int cursor = line.cursor();
  var command = CommandHandler.splitCommand(line.line());
  if (command.proj1 != null && cursor > command.proj1.length() && CommandHandler.INSTANCE
    .determineEntries(command.proj1)
    .map(Map.Entry::getValue)
    .anyMatch(commandClass::isInstance)
  ) completer.complete(reader, line, candidates);
}
 
Example #30
Source Project: Arend   Author: JetBrains   File: KeywordCompleter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) {
  if (!line.word().startsWith("\\")) return;
  String command = CommandHandler.splitCommand(line.line()).proj1;
  if (command != null && CommandHandler.INSTANCE
    .determineEntries(command)
    .noneMatch(entry -> entry.getValue() instanceof ExpressionArgumentCommand)
  ) return;
  for (var arendKeyword : arendKeywords) candidates.add(new Candidate("\\" + arendKeyword));
}