org.jline.reader.LineReader Java Examples
The following examples show how to use
org.jline.reader.LineReader.
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: 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 #2
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 #3
Source File: SqshConsole.java From jsqsh with Apache License 2.0 | 6 votes |
@Override public boolean apply() { final Buffer buffer = reader.getBuffer(); if (context.getCurrentSession().isInputComplete(buffer.toString(), buffer.cursor())) { acceptCause = AcceptCause.NORMAL; reader.callWidget(LineReader.ACCEPT_LINE); } else { buffer.write('\n'); } return true; }
Example #4
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 #5
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 #6
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 #7
Source File: SimpleTerminalConsole.java From TerminalConsoleAppender with MIT License | 6 votes |
private void readCommands(Terminal terminal) { LineReader reader = buildReader(LineReaderBuilder.builder().terminal(terminal)); TerminalConsoleAppender.setReader(reader); try { String line; while (isRunning()) { try { line = reader.readLine("> "); } catch (EndOfFileException ignored) { // Continue reading after EOT continue; } if (line == null) { break; } processInput(line); } } catch (UserInterruptException e) { shutdown(); } finally { TerminalConsoleAppender.setReader(null); } }
Example #8
Source File: LoginCommand.java From rug-cli with GNU General Public License v3.0 | 6 votes |
private void postForTokenAndHandleResponse(String username, String password, String code, Settings settings, LineReader reader) { Status status = new LoginOperations().postForToken(username, password, code, settings); if (status == Status.OK) { log.newline(); log.info(Style.green( "Successfully logged in to GitHub and stored token in ~/.atomist/cli.yml")); } else if (status == Status.BAD_CREDENTIALS) { throw new CommandException( "Provided credentials are invalid. Please try again with correct credentials.", "login"); } else if (status == Status.MFA_REQUIRED) { log.newline(); log.info(" Please provide a MFA code"); code = reader.readLine(getPrompt("MFA code")); postForTokenAndHandleResponse(username, password, code, settings, reader); } }
Example #9
Source File: DemoCommandTest.java From ssh-shell-spring-boot with Apache License 2.0 | 6 votes |
@BeforeAll static void prepare() { cmd = new DemoCommand(new SshShellHelper()); terminal = mock(Terminal.class); when(terminal.getSize()).thenReturn(size); PrintWriter writer = mock(PrintWriter.class); lr = mock(LineReader.class); ParsedLine line = mock(ParsedLine.class); when(line.line()).thenReturn("y"); when(lr.getParsedLine()).thenReturn(line); when(lr.getTerminal()).thenReturn(terminal); when(terminal.writer()).thenReturn(writer); reader = mock(NonBlockingReader.class); when(terminal.reader()).thenReturn(reader); when(terminal.getType()).thenReturn("osx"); auth = new SshAuthentication("user", "user", null, null, null); SshContext ctx = new SshContext(new SshShellRunnable(new SshShellProperties(), null, null, null, null, null, null, null, null, null, null, null, null, null), terminal, lr, auth); SshShellCommandFactory.SSH_THREAD_CONTEXT.set(ctx); }
Example #10
Source File: TestCLICompleter.java From nifi with Apache License 2.0 | 6 votes |
@BeforeClass public static void setupCompleter() { Assume.assumeTrue("Test only runs on *nix", !SystemUtils.IS_OS_WINDOWS); final Session session = new InMemorySession(); final ClientFactory<NiFiClient> niFiClientFactory = new NiFiClientFactory(); final ClientFactory<NiFiRegistryClient> nifiRegClientFactory = new NiFiRegistryClientFactory(); final Context context = new StandardContext.Builder() .output(System.out) .session(session) .nifiClientFactory(niFiClientFactory) .nifiRegistryClientFactory(nifiRegClientFactory) .build(); final Map<String,Command> commands = CommandFactory.createTopLevelCommands(context); final Map<String,CommandGroup> commandGroups = CommandFactory.createCommandGroups(context); completer = new CLICompleter(commands.values(), commandGroups.values()); lineReader = Mockito.mock(LineReader.class); }
Example #11
Source File: AbstractShellHelperTest.java From ssh-shell-spring-boot with Apache License 2.0 | 6 votes |
@BeforeEach public void each() { h = new SshShellHelper(); List<String> auth = Collections.singletonList("ROLE_ACTUATOR"); lr = mock(LineReader.class); ter = mock(Terminal.class); writer = mock(PrintWriter.class); when(ter.writer()).thenReturn(writer); reader = mock(NonBlockingReader.class); when(ter.reader()).thenReturn(reader); when(lr.getTerminal()).thenReturn(ter); SshContext ctx = new SshContext(new SshShellRunnable(new SshShellProperties(), mockChannelSession(4L), null, null, null, null, null, null, null, null, null, null, null, null), ter, lr, new SshAuthentication("user", "user", null, null, auth)); SshShellCommandFactory.SSH_THREAD_CONTEXT.set(ctx); when(ter.getType()).thenReturn("osx"); when(ter.getSize()).thenReturn(new Size(123, 40)); }
Example #12
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 #13
Source File: SqlLineParser.java From sqlline with BSD 3-Clause "New" or "Revised" License | 6 votes |
private String getPaddedPrompt(String waitingPattern) { if (sqlLine.getOpts().getShowLineNumbers() && sqlLine.getLineReader() != null) { sqlLine.getLineReader() .setVariable(LineReader.SECONDARY_PROMPT_PATTERN, "%N%P.%M> "); return waitingPattern; } else { if (sqlLine.getLineReader() != null) { sqlLine.getLineReader().setVariable(LineReader.SECONDARY_PROMPT_PATTERN, LineReaderImpl.DEFAULT_SECONDARY_PROMPT_PATTERN); } int length = sqlLine.getPromptHandler().getPrompt().columnLength(); StringBuilder prompt = new StringBuilder(length); for (int i = 0; i < length - "> ".length() - waitingPattern.length(); i++) { prompt.append(i % 2 == 0 ? '.' : ' '); } prompt.append(waitingPattern); return prompt.toString(); } }
Example #14
Source File: PutToLogCommand.java From ratis with Apache License 2.0 | 6 votes |
@Override public void run(Terminal terminal, LineReader lineReader, LogServiceClient client, String[] args) { if (args.length != 2) { terminal.writer().println("ERROR - Usage: put <name> <value>"); return; } String name = args[0]; String value = args[1]; try (LogStream stream = client.getLog(LogName.of(name)); LogWriter writer = stream.createWriter()) { writer.write(ByteBuffer.wrap(value.getBytes(StandardCharsets.UTF_8))); } catch (Exception e) { terminal.writer().println("Error writing to log"); e.printStackTrace(terminal.writer()); } }
Example #15
Source File: PutToLogCommand.java From incubator-ratis with Apache License 2.0 | 6 votes |
@Override public void run(Terminal terminal, LineReader lineReader, LogServiceClient client, String[] args) { if (args.length != 2) { terminal.writer().println("ERROR - Usage: put <name> <value>"); return; } String name = args[0]; String value = args[1]; try (LogStream stream = client.getLog(LogName.of(name)); LogWriter writer = stream.createWriter()) { writer.write(ByteBuffer.wrap(value.getBytes(StandardCharsets.UTF_8))); } catch (Exception e) { terminal.writer().println("Error writing to log"); e.printStackTrace(terminal.writer()); } }
Example #16
Source File: ListLogsCommand.java From ratis with Apache License 2.0 | 6 votes |
@Override public void run(Terminal terminal, LineReader lineReader, LogServiceClient client, String[] args) { if (args.length != 0) { terminal.writer().println("ERROR - Usage: list"); return; } try { List<LogInfo> logs = client.listLogs(); StringBuilder sb = new StringBuilder(); for (LogInfo log : logs) { if (sb.length() > 0) { sb.append("\n"); } sb.append(log.getLogName().getName()); } terminal.writer().println(sb.toString()); } catch (IOException e) { terminal.writer().println("Failed to list available logs"); e.printStackTrace(terminal.writer()); } }
Example #17
Source File: ExportLogCommand.java From incubator-ratis with Apache License 2.0 | 6 votes |
@Override public void run(Terminal terminal, LineReader lineReader, LogServiceClient client, String[] args) { if (args.length != 3) { terminal.writer().println("ERROR - Usage: export <name> <location> <recordId>"); return; } String logName = args[0]; String location = args[1]; long recordId = Long.parseLong(args[2]); try { client.exportLog(LogName.of(logName), location,recordId); terminal.writer().println("Export Log request is submitted successfully!!"); } catch (Exception e) { terminal.writer().println("Failed to export log!!"); e.printStackTrace(terminal.writer()); } }
Example #18
Source File: SqlLineArgsTest.java From sqlline with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void testAnsiConsoleFormatWithNonExistingTerminalAndSmallWidth() { new MockUp<SqlLine>() { @Mock LineReader getLineReader() { return null; } }; final String script = "!set maxwidth 0\n" + "!set incremental true \n" + "!set outputformat ansiconsole \n" + "values (1, '2');\n"; final String line1 = "" + "\n" + "\n"; checkScriptFile(script, true, equalTo(SqlLine.Status.OK), containsString(line1)); }
Example #19
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 #20
Source File: CliHighlighter.java From samza with Apache License 2.0 | 6 votes |
public AttributedString highlight(LineReader reader, String buffer) { AttributedStringBuilder builder = new AttributedStringBuilder(); List<String> tokens = splitWithSpace(buffer); for (String token : tokens) { if (isKeyword(token)) { builder.style(AttributedStyle.BOLD.foreground(AttributedStyle.YELLOW)) .append(token); } else { builder.style(AttributedStyle.DEFAULT) .append(token); } } return builder.toAttributedString(); }
Example #21
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 #22
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 #23
Source File: LoginCommand.java From rug-cli with GNU General Public License v3.0 | 6 votes |
private void login(String username, String code, Settings settings) { printBanner(); LineReader reader = ShellUtils.lineReader(null, Optional.empty()); try { if (username == null) { username = reader.readLine(getPrompt("Username")); } String password = reader.readLine(getPrompt("Password"), new Character('*')); postForTokenAndHandleResponse(username, password, code, settings, reader); } catch (EndOfFileException | UserInterruptException e) { log.error("Canceled!"); } finally { ShellUtils.shutdown(reader); } }
Example #24
Source File: ListLogsCommand.java From incubator-ratis with Apache License 2.0 | 6 votes |
@Override public void run(Terminal terminal, LineReader lineReader, LogServiceClient client, String[] args) { if (args.length != 0) { terminal.writer().println("ERROR - Usage: list"); return; } try { List<LogInfo> logs = client.listLogs(); StringBuilder sb = new StringBuilder(); for (LogInfo log : logs) { if (sb.length() > 0) { sb.append("\n"); } sb.append(log.getLogName().getName()); } terminal.writer().println(sb.toString()); } catch (IOException e) { terminal.writer().println("Failed to list available logs"); e.printStackTrace(terminal.writer()); } }
Example #25
Source File: SqlLineOpts.java From sqlline with BSD 3-Clause "New" or "Revised" License | 6 votes |
public void setMode(String mode) { final LineReader reader = sqlLine.getLineReader(); if (reader == null || reader.getKeyMaps() == null) { return; } final Map<String, KeyMap<Binding>> keyMaps = reader.getKeyMaps(); switch (mode) { case LineReader.EMACS: case SqlLineProperty.DEFAULT: set(BuiltInProperty.MODE, LineReader.EMACS); keyMaps.put(LineReader.MAIN, keyMaps.get(LineReader.EMACS)); break; case "vi": set(BuiltInProperty.MODE, mode); keyMaps.put(LineReader.MAIN, keyMaps.get(LineReader.VIINS)); break; default: sqlLine.error( sqlLine.loc("unknown-value", MODE.propertyName(), mode, Arrays.asList(LineReader.EMACS, "vi"))); } }
Example #26
Source File: CommandsCompleter.java From Arend with Apache License 2.0 | 5 votes |
@Override public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) { if (line.cursor() >= 1 && ':' == line.line().charAt(0) && line.wordIndex() < 1) { for (var string : CommandHandler.INSTANCE.commandMap.keySet()) candidates.add(new Candidate(":" + string)); } }
Example #27
Source File: LogServiceShell.java From incubator-ratis with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { final Terminal terminal = TerminalBuilder.builder() .system(true) .build(); History defaultHistory = new DefaultHistory(); // Register a shutdown-hook per JLine documentation to save history Runtime.getRuntime().addShutdownHook(new Thread(() -> { try { defaultHistory.save(); } catch (IOException e) { LOG.debug("Failed to save terminal history", e); } })); final LineReader lineReader = LineReaderBuilder.builder() .terminal(terminal) .highlighter(new DefaultHighlighter()) .history(defaultHistory) .build(); LogServiceShellOpts opts = new LogServiceShellOpts(); JCommander.newBuilder() .addObject(opts) .build() .parse(args); try (LogServiceClient logServiceClient = new LogServiceClient(opts.getMetaQuorum())) { LogServiceShell client = new LogServiceShell(terminal, lineReader, logServiceClient); client.run(); } }
Example #28
Source File: NukkitConsole.java From Nukkit with GNU General Public License v3.0 | 5 votes |
@Override protected LineReader buildReader(LineReaderBuilder builder) { builder.completer(new NukkitConsoleCompleter(server)); builder.appName("Nukkit"); builder.option(LineReader.Option.HISTORY_BEEP, false); builder.option(LineReader.Option.HISTORY_IGNORE_DUPS, true); builder.option(LineReader.Option.HISTORY_IGNORE_SPACE, true); return super.buildReader(builder); }
Example #29
Source File: SqlCompleter.java From sqlline with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public void complete( LineReader reader, ParsedLine commandLine, List<Candidate> candidates) { String sql = commandLine.line().substring(0, commandLine.cursor()); SqlLineParser.SqlLineArgumentList argumentList = ((SqlLineParser) sqlLine.getLineReader().getParser()) .parseState(sql, sql.length(), Parser.ParseContext.UNSPECIFIED); final String supplierMsg = argumentList.getSupplier().get(); final char openQuote = sqlLine.getDialect().getOpenQuote(); if (argumentList.getState() == SqlLineParser.SqlParserState.MULTILINE_COMMENT || (argumentList.getState() == SqlLineParser.SqlParserState.QUOTED && ((openQuote == '"' && !supplierMsg.endsWith("dquote")) || (openQuote == '`' && !supplierMsg.endsWith("`"))))) { return; } if (!skipMeta) { Deque<String> lastWords = getSchemaTableColumn(argumentList.word()); candidates.addAll(getSchemaBasedCandidates(new ArrayDeque<>(lastWords))); candidates.addAll(getTableBasedCandidates(new ArrayDeque<>(lastWords))); } // suggest other candidates if not quoted // and previous word not finished with '.' if (argumentList.getState() != SqlLineParser.SqlParserState.QUOTED && ((argumentList.getState() != SqlLineParser.SqlParserState.SEMICOLON_REQUIRED && argumentList.getState() != SqlLineParser.SqlParserState.ROUND_BRACKET_BALANCE_FAILED) || sql.isEmpty() || sql.charAt(sql.length() - 1) != '.')) { candidates.addAll(this.candidates); } }
Example #30
Source File: TerminalProcessor.java From sshd-shell-spring-boot with Apache License 2.0 | 5 votes |
private void processInputs(LineReader reader, IntConsumer exitCallback) { try { processUserInput(reader, exitCallback); } catch (UserInterruptException ex) { // Need not concern with this exception log.warn("[{}] Ctrl-C interrupt", SshSessionContext.<String>get(Constants.USER)); exitCallback.accept(1); } }