### Basic JLine Quick Start Example Source: https://github.com/jline/jline3/blob/master/README.md A simple Java example demonstrating how to initialize JLine, create a line reader, and read user input from the console. ```java import org.jline.reader.*; import org.jline.reader.impl.*; import org.jline.terminal.*; import org.jline.terminal.impl.*; public class HelloJLine { public static void main(String[] args) { try { // Create a terminal Terminal terminal = TerminalBuilder.builder() .system(true) .build(); // Create line reader LineReader reader = LineReaderBuilder.builder() .terminal(terminal) .build(); // Prompt and read input String line = reader.readLine("JLine > "); // Print the result System.out.println("You entered: " + line); } catch (Exception e) { e.printStackTrace(); } } } ``` -------------------------------- ### Start Development Server with Snippets Source: https://github.com/jline/jline3/blob/master/website/README.md Starts the development server after extracting code snippets from the demo directory. ```bash $ npm run start-with-snippets ``` -------------------------------- ### REPL Console Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/repl-console.md This is a placeholder for a REPL console example. It demonstrates the basic setup and usage of the JLine REPL console. ```java System.out.println("This is a placeholder for a REPL console example."); System.out.println("It demonstrates the basic setup and usage of the JLine REPL console."); ``` -------------------------------- ### Picocli Command Integration Example Source: https://github.com/jline/jline3/blob/master/website/docs/shell-picocli.md This example demonstrates how to integrate picocli commands with JLine's shell. It shows the basic setup for exposing picocli commands as JLine commands. ```java import org.jline.console.CommandRegistry; import org.jline.console.CommandRegistry.CommandDescription; import org.jline.console.impl.PicocliCommandRegistry; import org.jline.terminal.Terminal; import org.jline.terminal.TerminalBuilder; import picocli.CommandLine; import picocli.CommandLine.Command; import picocli.CommandLine.Option; import picocli.CommandLine.Parameters; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; @Command(name = "myapp", mixinStandardHelpOptions = true, subcommands = { Echo.class, Hello.class }) public class PicocliJLineExample implements Callable { @Override public Void call() throws Exception { return null; } @Command(name = "echo", description = "Echo back arguments") static class Echo implements Runnable { @Parameters(arity = "0..*") List params; public void run() { System.out.println(String.join(" ", params)); } } @Command(name = "hello", description = "Greet someone") static class Hello implements Runnable { @Option(names = {"-n", "--name"}, required = true) String name; public void run() { System.out.println("Hello " + name); } } public static void main(String[] args) throws IOException { Terminal terminal = TerminalBuilder.builder() .system(true) .build(); CommandRegistry registry = new PicocliCommandRegistry(new CommandLine(new PicocliJLineExample())); Map commands = registry.commands(); System.out.println("Available commands:"); commands.forEach((name, description) -> System.out.println(" " + name + " - " + description.description())); // Example of executing a command System.out.println("Executing 'echo hello world':"); registry.execute(Arrays.asList("echo", "hello", "world")); System.out.println("Executing 'hello --name=JLine':"); registry.execute(Arrays.asList("hello", "--name=JLine")); } } ``` -------------------------------- ### Example Theme System Configuration File Source: https://github.com/jline/jline3/wiki/Theme-System An example of a complete theme system configuration file, demonstrating token type styles, mixins, and parser configurations. ```nanorc BOOLEAN brightwhite NUMBER blue CONSTANT yellow COMMENT brightblack DOC_COMMENT white TODO brightwhite,yellow WHITESPACE ,green # # mixin # +LINT WHITESPACE: "[[:space:]]+" WHITESPACE: "\t*" # # parser # $LINE_COMMENT COMMENT TODO: "(FIXME|TODO|XXX)" $BLOCK_COMMENT COMMENT DOC_COMMENT: startWith=/** TODO: "(FIXME|TODO|XXX)" ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/jline/jline3/blob/master/website/README.md Run this command to install all necessary project dependencies using npm. ```bash $ npm install ``` -------------------------------- ### NanoLessCustomizationExample Source: https://github.com/jline/jline3/blob/master/website/docs/advanced/nano-less-customization.md This is a placeholder for a NanoLessCustomization example. ```java import org.jline.builtins.ConfigurationPath; import org.jline.builtins.Builtins; import org.jline.utils.InfoCmp; import org.jline.terminal.Terminal; import org.jline.reader.Parser; import org.jline.reader.impl.SystemReader; import org.jline.reader.impl.completer.AggregateCompleter; import org.jline.reader.impl.completer.ArgumentCompleter; import org.jline.reader.impl.completer.NullCompleter; import org.jline.reader.impl.completer.StringsCompleter; import org.jline.reader.impl.history.DefaultHistory; import org.jline.terminal.impl.DumbTerminal; import org.jline.utils.OSUtils; import java.nio.file.Paths; import java.util.function.Supplier; public class NanoLessCustomizationExample { public static void main(String[] args) throws Exception { Parser parser = new Parser() { @Override public ParsedLine parse(String line, int cursor, ParseContext context) { return null; } @Override public boolean isQuoted(String s, int cursor) { return false; } }; Terminal terminal = new DumbTerminal(System.in, System.out, System.err); Supplier workDir = () -> Paths.get(""); ConfigurationPath configPath = new ConfigurationPath( Paths.get("/pub/myApp"), // application-wide settings Paths.get(System.getProperty("user.home"), ".myApp") // user-specific settings ); Builtins builtins = new Builtins(workDir, configPath, null); SystemRegistry systemRegistry = new SystemRegistry(parser, terminal, workDir, configPath); systemRegistry.setCommandRegistries(builtins); // Example of how to use the configuration path System.out.println("Configuration Path:"); System.out.println(" App-wide: " + configPath.appSettings()); System.out.println(" User-specific: " + configPath.userSettings()); } } ``` -------------------------------- ### Start Local Development Server Source: https://github.com/jline/jline3/blob/master/website/README.md Starts the development server for local testing without extracting code snippets. ```bash $ npm start ``` -------------------------------- ### Basic ConsoleUI Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/console-ui.md A simple example demonstrating the basic usage of ConsoleUI to create interactive prompts. ```java ConsolePrompt prompt = new ConsolePrompt(); PromptBuilder builder = prompt.getPromptBuilder(); builder.addPrompt("name", "What is your name? ", "John Doe"); builder.addPrompt("age", "Your age? ", "30"); Map result = prompt.prompt(builder.build()); System.out.println("Hello " + result.get("name") + ", you are " + result.get("age") + " years old."); ``` -------------------------------- ### Configuration Path Setup Source: https://github.com/jline/jline3/blob/master/website/docs/advanced/nano-less-customization.md Specify application-wide and user-specific configuration directories for nano and less. ```java ConfigurationPath configPath = new ConfigurationPath( Paths.get("/pub/myApp"), // application-wide settings Paths.get(System.getProperty("user.home"), ".myApp") // user-specific settings ); Supplier workDir = () -> Paths.get(""); Builtins builtins = new Builtins(workDir, configPath, null); SystemRegistry systemRegistry = new SystemRegistry(parser, terminal, workDir, configPath); systemRegistry.setCommandRegistries(builtins); ``` -------------------------------- ### Install backport CLI tool Source: https://github.com/jline/jline3/blob/master/BACKPORT_CANDIDATES.md Install the backport CLI tool globally using npm. ```bash npm install -g backport ``` -------------------------------- ### Running JLine Examples with Maven Source: https://github.com/jline/jline3/blob/master/demo/src/main/java/org/jline/demo/examples/README.md Execute JLine example classes directly using the Maven exec plugin, specifying the main class with the -Dexec.mainClass argument. ```bash mvn exec:java -Dexec.mainClass="org.jline.demo.examples.PrintAboveExample" ``` -------------------------------- ### Basic JLine Usage Example Source: https://github.com/jline/jline3/blob/master/website/docs/intro.md A simple example demonstrating how to create a terminal, build a line reader, and read user input with a prompt. ```java import org.jline.reader.LineReader; import org.jline.reader.LineReaderBuilder; import org.jline.reader.impl.history.DefaultHistory; import org.jline.terminal.Terminal; import org.jline.terminal.TerminalBuilder; public class JLineExample { public static void main(String[] args) throws Exception { // Build a terminal instance Terminal terminal = TerminalBuilder.builder() .system(true) .build(); // Build a line reader LineReader reader = LineReaderBuilder.builder() .terminal(terminal) .history(new DefaultHistory()) .build(); // Read input from the user with a prompt String line = reader.readLine("\u001B[32m\u276f\u001B[0m "); // Green prompt System.out.println("You entered: " + line); } } ``` -------------------------------- ### Console Script Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/repl-console.md This is a placeholder for a console script example. It shows how to define and execute a console script within the JLine REPL. ```bash echo "This is a placeholder for a console script example." echo "It shows how to define and execute a console script within the JLine REPL." ``` -------------------------------- ### SystemCompleter Example Source: https://github.com/jline/jline3/blob/master/website/docs/tab-completion.md Manage completers for different commands using SystemCompleter. ```java SystemCompleter systemCompleter = new SystemCompleter(); systemCompleter.add("command1", new StringsCompleter("arg1", "arg2")); systemCompleter.add("command2", new FileNameCompleter()); ``` -------------------------------- ### Minimal jline-shell Example Source: https://github.com/jline/jline3/blob/master/website/docs/shell-getting-started.md A basic example demonstrating the core functionality of jline-shell for creating an interactive command-line interface. ```java LineReader lineReader = LineReaderBuilder.builder().build(); String line; while ((line = lineReader.readLine("myapp> ")) != null) { if (line.equals("exit")) { break; } System.out.println("You entered: " + line); } ``` -------------------------------- ### Running Application with JLine Jars Module Path Source: https://github.com/jline/jline3/blob/master/website/docs/modules/jpms.md Example of launching an application using the JLine JARs located in a specific directory on the module path, without special setup for the JNI provider. ```bash java --module-path jline-jars/ --module your.app/your.Main ``` -------------------------------- ### Multi-Column Layout Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/prompt.md Demonstrates automatic calculation of optimal multi-column layouts based on terminal width. ```java Prompter prompter = PrompterFactory.create(TerminalBuilder.builder().build()); String choice = prompter.prompt(builder -> builder.message("Choose an option") .choices("Short", "Medium length", "A much longer option", "Another one") .multiColumn(2)); System.out.println("Selected: " + choice); ``` -------------------------------- ### Basic Prompt Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/prompt.md Demonstrates the fluent builder API for creating a basic prompt. ```java Prompter prompter = PrompterFactory.create(TerminalBuilder.builder().build()); String name = prompter.prompt(builder -> builder.message("What is your name?")); System.out.println("Hello, " + name); String color = prompter.prompt(builder -> builder.message("What is your favorite color?") .choices("Red", "Green", "Blue")); System.out.println("Your favorite color is " + color); boolean confirm = prompter.prompt(builder -> builder.message("Do you want to continue?") .confirm()); System.out.println("Confirmation: " + confirm); ``` -------------------------------- ### Styler Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/style.md Demonstrates how the Styler combines style expressions and text for styling. ```java Styler styler = new DefaultStyler(); String styledText = styler.style("This text is green.", "green"); System.out.println(styledText); ``` -------------------------------- ### JLine ConsoleEngine and Command Registry Setup Source: https://github.com/jline/jline3/wiki/Command-Registries This snippet demonstrates the setup of JLine's ConsoleEngine, script engine integration (Groovy), and command registries. It configures the system registry, registers built-in commands, and initializes the LineReader for interactive use. This is typically used for creating REPL-like applications. ```java // // ScriptEngine and command registeries // ConfigurationPath configPath = new ConfigurationPath(appConfig, userConfig); GroovyEngine scriptEngine = new GroovyEngine(); Printer printer = new DefaultPrinter(scriptEngine, configPath); ConsoleEngineImpl consoleEngine = new ConsoleEngineImpl(scriptEngine , printer , Repl::workDir, configPath); Builtins builtins = new Builtins(Repl::workDir, configPath , (String fun)-> {return new ConsoleEngine.WidgetCreator(consoleEngine, fun);}); MyCommands myCommands = new MyCommands(Repl::workDir); SystemRegistryImpl systemRegistry = new SystemRegistryImpl(parser, terminal, Repl::workDir, configPath); systemRegistry.register("groovy", new GroovyCommand(scriptEngine, consoleEngine)); systemRegistry.setCommandRegistries(consoleEngine, builtins, myCommands); // // set scriptEngine statement completer and description method to systemRegistry (JLine version > 3.15.0) // systemRegistry.addCompleter(scriptEngine.getScriptCompleter()); systemRegistry.setScriptDescription(scriptEngine::scriptDescription); // // LineReader // LineReader reader = LineReaderBuilder.builder() .terminal(terminal) .completer(systemRegistry.completer()) .parser(parser) .variable(LineReader.SECONDARY_PROMPT_PATTERN, "%M%P > ") .variable(LineReader.INDENTATION, 2) .variable(LineReader.HISTORY_FILE, Paths.get(root, "history")) .option(Option.INSERT_BRACKET, true) .option(Option.DISABLE_EVENT_EXPANSION, true) .build(); // // complete command registeries // consoleEngine.setLineReader(reader); builtins.setLineReader(reader); myCommands.setLineReader(reader); // // widgets and console initialization // new TailTipWidgets(reader, systemRegistry::commandDescription, 5, TipType.COMPLETER); KeyMap keyMap = reader.getKeyMaps().get("main"); keyMap.bind(new Reference(Widgets.TAILTIP_TOGGLE), KeyMap.alt("s")); systemRegistry.initialize(Paths.get(root, "init.jline").toFile()); // // REPL-loop // consoleEngine.println(terminal.getName() + ": " + terminal.getType()); while (true) { try { systemRegistry.cleanUp(); // delete temporary variables and reset output streams String line = reader.readLine("groovy-repl> "); Object result = systemRegistry.execute(line); consoleEngine.println(result); // print command result } catch (UserInterruptException e) { // Ignore } catch (EndOfFileException e) { break; } catch (Exception e) { systemRegistry.trace(e); // print exception and save it to console variable } } systemRegistry.close(); // persist pipeline names for completer etc ``` -------------------------------- ### JNI Terminal Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/terminal-providers.md Shows how to use the JNI provider for native terminal functionality. ```java import org.jline.terminal.TerminalBuilder; import org.jline.terminal.Terminal; import java.io.IOException; public class JniTerminalExample { public static void main(String[] args) throws IOException { // The JNI provider is a common choice for native terminal access try (Terminal terminal = TerminalBuilder.builder().provider("jni").build()) { System.out.println("Using JNI provider: " + terminal.getProvider()); System.out.println("Terminal type: " + terminal.getType()); // Interact with the terminal... terminal.writer().println("Hello from JNI terminal!"); terminal.flush(); } } } ``` -------------------------------- ### Input Prompt Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/console-ui.md Demonstrates an input prompt with optional masking and completion capabilities. ```java ConsolePrompt prompt = new ConsolePrompt(); PromptBuilder builder = prompt.getPromptBuilder(); builder.createInputPrompt("password", "Enter password: ", "", "*", "Enter your password"); Map result = prompt.prompt(builder.build()); System.out.println("Password entered: " + result.get("password")); ``` -------------------------------- ### Confirmation Prompt Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/console-ui.md Shows a confirmation prompt for a yes/no answer. ```java ConsolePrompt prompt = new ConsolePrompt(); PromptBuilder builder = prompt.getPromptBuilder(); builder.createConfirmPrompt("confirm", "Are you sure? ", false); Map result = prompt.prompt(builder.build()); System.out.println("Confirmation: " + result.get("confirm")); ``` -------------------------------- ### Preview Website with Code Snippets Source: https://github.com/jline/jline3/blob/master/website/README.md Extracts code snippets and starts a local development server for previewing the website. ```bash $ npm run preview ``` -------------------------------- ### Style Expression Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/style.md Shows how to define styles concisely using style expressions. ```java StyleExpression expression = StyleExpression.parse("red bold"); AttributedStyle style = expression.resolve(null); System.out.println(style.apply("This is red and bold text.")); ``` -------------------------------- ### Context-Aware Completer Example Source: https://github.com/jline/jline3/blob/master/website/docs/tab-completion.md Create completers that adapt suggestions based on the current command context. ```java public class ContextAwareCompleter implements Completer { @Override public void complete(LineReader reader, ParsedLine line, List candidates) { if (line.wordIndex() == 1) { // If completing the second word candidates.add(new SimpleCompletionCandidate("contextual_option1")); candidates.add(new SimpleCompletionCandidate("contextual_option2")); } } } ``` -------------------------------- ### Toggle Prompt Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/prompt.md Presents a binary choice between two options, navigable with arrow keys. ```java Prompter prompter = PrompterFactory.create(TerminalBuilder.builder().build()); String status = prompter.prompt(builder -> builder.message("Select status") .choices("Active", "Inactive") .toggle()); System.out.println("Selected status: " + status); ``` -------------------------------- ### Pre-checked Checkboxes Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/prompt.md Illustrates how to pre-check specific items in a checkbox prompt. ```java Prompter prompter = PrompterFactory.create(TerminalBuilder.builder().build()); List selections = prompter.prompt(builder -> builder.message("Select options") .choices("Option 1", "Option 2", "Option 3") .checked("Option 1", "Option 3") .checkbox()); System.out.println("Selected: " + selections); ``` -------------------------------- ### Search Prompt Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/prompt.md Enables dynamic search with type-ahead filtering for selecting items. ```java Prompter prompter = PrompterFactory.create(TerminalBuilder.builder().build()); String selection = prompter.prompt(builder -> builder.message("Search for a user") .choices("Alice", "Bob", "Charlie", "David") .search()); System.out.println("Selected user: " + selection); ``` -------------------------------- ### Confirm Prompt Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/prompt.md Creates a Yes/No confirmation prompt with a default value. ```java Prompter prompter = PrompterFactory.create(TerminalBuilder.builder().build()); boolean deploy = prompter.prompt(builder -> builder.message("Deploy to production?") .defaultValue("y") .confirm()); System.out.println("Deployment confirmed: " + deploy); ``` -------------------------------- ### Choice Prompt Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/prompt.md Implements a key-based selection prompt with character shortcuts. ```java Prompter prompter = PrompterFactory.create(TerminalBuilder.builder().build()); String color = prompter.prompt(builder -> builder.message("Pick a color") .choices("Red", "Green", "Blue") .key("rgb") .choice()); System.out.println("Picked color: " + color); ``` -------------------------------- ### Bash List Selection Source: https://github.com/jline/jline3/blob/master/website/docs/modules/prompt.md Example of using the 'prompt' command-line tool for list selection. ```bash prompt list "Choose environment" "Development" "Staging" "Production" ``` -------------------------------- ### List Prompt Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/prompt.md Creates a single-selection list prompt with multi-column layout support. ```java Prompter prompter = PrompterFactory.create(TerminalBuilder.builder().build()); String choice = prompter.prompt(builder -> builder.message("Choose an option") .choices("Option 1", "Option 2", "Option 3", "Option 4", "Option 5") .multiColumn(3)); System.out.println("Selected: " + choice); ``` -------------------------------- ### Editor Prompt Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/prompt.md Opens an inline editor (like Nano) for multi-line text input. ```java Prompter prompter = PrompterFactory.create(TerminalBuilder.builder().build()); String text = prompter.prompt(builder -> builder.message("Enter description") .editor()); System.out.println("Description entered: " + text); ``` -------------------------------- ### Exec Terminal Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/terminal-providers.md Demonstrates the Exec provider, which relies on external commands for terminal functionality. ```java import org.jline.terminal.TerminalBuilder; import org.jline.terminal.Terminal; import java.io.IOException; public class ExecTerminalExample { public static void main(String[] args) throws IOException { // The Exec provider is used as a fallback when native providers are unavailable try (Terminal terminal = TerminalBuilder.builder().provider("exec").build()) { System.out.println("Using Exec provider: " + terminal.getProvider()); System.out.println("Terminal type: " + terminal.getType()); // Interact with the terminal... terminal.writer().println("Hello from Exec terminal!"); terminal.flush(); } } } ``` -------------------------------- ### Example jnanorc Configuration File Source: https://github.com/jline/jline3/wiki/Nano-and-Less-Customization Demonstrates basic configuration options for nano/less using a jnanorc file. Includes including external syntax files and setting common options like tab conversion and history logging. ```properties include /usr/share/nano/*.nanorc set tabstospaces set autoindent set tempfile set historylog search.log ``` -------------------------------- ### Handle Ctrl+C on Windows Source: https://github.com/jline/jline3/blob/master/website/docs/troubleshooting.md To prevent Ctrl+C from terminating the application on Windows, install a custom signal handler. This example shows how to catch the INT signal and provide a custom message. ```java terminal.handle(Signal.INT, signal -> { // Handle Ctrl+C gracefully terminal.writer().println("Ctrl+C pressed, type 'exit' to quit"); terminal.flush(); }); ``` -------------------------------- ### Handle Unix Signals Source: https://github.com/jline/jline3/blob/master/website/docs/troubleshooting.md Properly handle common Unix signals like INT, WINCH, TSTP, and CONT for a better user experience. This example shows how to install signal handlers for these events. ```java terminal.handle(Signal.INT, signal -> { // Handle Ctrl+C }); terminal.handle(Signal.WINCH, signal -> { // Handle terminal resize }); terminal.handle(Signal.TSTP, signal -> { // Handle Ctrl+Z (suspend) terminal.pause(); }); terminal.handle(Signal.CONT, signal -> { // Handle resume from suspension terminal.resume(); }); ``` -------------------------------- ### Example nanorc Syntax File Using Theme System Source: https://github.com/jline/jline3/wiki/Theme-System Demonstrates how a nanorc syntax file can reference theme system configurations for token types, comments, and mixins. ```nanorc BOOLEAN: "\b(true|false)\b" CONSTANT: "\b[A-Z]+([_]{1}[A-Z]+){0,}\b" ~NUMBER: "\b(([1-9][0-9]+)|0+)\.[0-9]+\b" "\b[1-9][0-9]*\b" "\b0[0-7]*\b" "\b0x[1-9a-f][0-9a-f]*\b" $LINE_COMMENT: "//" $BLOCK_COMMENT: "/*, */" +LINT ``` -------------------------------- ### Choice Prompt Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/console-ui.md Demonstrates an expandable choice prompt where each option is assigned a single keystroke. ```java ConsolePrompt prompt = new ConsolePrompt(); PromptBuilder builder = prompt.getPromptBuilder(); builder.createChoicePrompt("choice", "Choose an option: ", Arrays.asList("Yes", "No", "Maybe")); Map result = prompt.prompt(builder.build()); System.out.println("Your choice: " + result.get("choice")); ``` -------------------------------- ### Input Prompt Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/prompt.md Provides a text input prompt with support for default values and masking. ```java Prompter prompter = PrompterFactory.create(TerminalBuilder.builder().build()); String name = prompter.prompt(builder -> builder.message("Enter your name") .defaultValue("John Doe")); System.out.println("Name entered: " + name); String maskedInput = prompter.prompt(builder -> builder.message("Enter a secret") .mask('*')); System.out.println("Secret entered (masked): " + maskedInput); ``` -------------------------------- ### JLine History Expansion Example Source: https://github.com/jline/jline3/blob/master/website/docs/history.md Demonstrates how JLine supports history expansion similar to Bash. ```java ``` -------------------------------- ### Apache Commons CLI Integration Example Source: https://github.com/jline/jline3/blob/master/website/docs/advanced/library-integration.md Shows how to combine JLine with Apache Commons CLI for an interactive shell that parses commands using Commons CLI. This setup allows for structured command-line argument parsing within an interactive environment. ```java import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Options; import org.jline.reader.LineReader; import org.jline.reader.LineReaderBuilder; import org.jline.reader.impl.history.DefaultHistory; import org.jline.terminal.Terminal; import org.jline.terminal.TerminalBuilder; import java.io.IOException; public class CommonsCliJLineExample { public static void main(String[] args) throws IOException { Terminal terminal = TerminalBuilder.builder() .system(true) .build(); LineReader reader = LineReaderBuilder.builder() .terminal(terminal) .history(new DefaultHistory()) .build(); Options options = new Options(); options.addOption("h", "help", false, "Show help message"); options.addOption("f", "file", true, "Input file path"); String line; while ((line = reader.readLine("> ")) != null) { CommandLineParser parser = new DefaultParser(); try { CommandLine cmd = parser.parse(options, line.split(" ")); if (cmd.hasOption("help")) { System.out.println("Help message..."); } else if (cmd.hasOption("file")) { String filePath = cmd.getOptionValue("file"); System.out.println("Processing file: " + filePath); } else { System.out.println("Unknown command or options."); } } catch (Exception e) { System.err.println("Error parsing command: " + e.getMessage()); } reader.getHistory().add(line); } } } ``` -------------------------------- ### Preview Website with Processed Documentation Source: https://github.com/jline/jline3/blob/master/website/docs/examples/README.md Navigate to the website directory and run this script to start a development server. This allows you to preview the documentation with processed code snippets. ```bash cd website ./scripts/preview-website.sh ``` -------------------------------- ### AttributedString Basics Example Source: https://github.com/jline/jline3/blob/master/website/docs/advanced/attributed-strings.md Demonstrates creating AttributedString objects with various styles and displaying them in the terminal. ```java AttributedStringBasicsExample ``` -------------------------------- ### Create and Use a Basic List Prompt Source: https://github.com/jline/jline3/blob/master/prompt/README.md Demonstrates how to create a Prompter instance, build a list prompt with options, and display it to the user to get their selection. ```java Terminal terminal = TerminalBuilder.builder().build(); Prompter prompter = PrompterFactory.create(terminal); PromptBuilder promptBuilder = prompter.newBuilder(); promptBuilder.createListPrompt() .name("choice") .message("Choose an option:") .newItem("option1") .text("Option 1") .add() .newItem("option2") .text("Option 2") .add() .addPrompt(); Map result = prompter.prompt(header, promptBuilder.build()); ``` -------------------------------- ### FFM Terminal Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/terminal-providers.md Illustrates using the FFM provider, which requires Java 22+ and specific native access permissions. ```java import org.jline.terminal.TerminalBuilder; import org.jline.terminal.Terminal; import java.io.IOException; public class FfmTerminalExample { public static void main(String[] args) throws IOException { // The FFM provider is automatically selected if available and compatible try (Terminal terminal = TerminalBuilder.builder().provider("ffm").build()) { System.out.println("Using FFM provider: " + terminal.getProvider()); System.out.println("Terminal type: " + terminal.getType()); // Interact with the terminal... terminal.writer().println("Hello from FFM terminal!"); terminal.flush(); } } } ``` -------------------------------- ### Example Usage with Custom Timeouts Source: https://github.com/jline/jline3/blob/master/website/docs/advanced/terminal-graphics.md Launch an application with specific timeout configurations for Kitty and Sixel graphics protocols. ```bash java -Dorg.jline.terminal.graphics.kitty.timeout=50 \ -Dorg.jline.terminal.graphics.sixel.timeout=100 \ MyApplication ``` -------------------------------- ### Build and Highlight with SyntaxHighlighter Source: https://github.com/jline/jline3/wiki/Highlighting-and-parsing Demonstrates how to build a SyntaxHighlighter instance with custom configuration paths and use it to highlight a given string. ```java ConfigurationPath configPath = new ConfigurationPath(Paths.get("/pub/myApp"), // application-wide settings Paths.get(System.getProperty("user.home"), ".myApp")); // user-specific settings SyntaxHighlighter javaSyntax = SyntaxHighlighter.build(configPath.getConfig("jnanorc"), "Java"); javaSyntax.highlight("public AttributedString highlight(String string)").println(terminal); ``` -------------------------------- ### Variable Expansion Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/repl-console.md Demonstrates variable expansion in the REPL console, showing how to create a map and print it using different syntaxes. ```groovy groovy-repl> # create a map and print it groovy-repl> user=[name:'Pippo',age:10] groovy-repl> prnt $user name Pippo age 10 groovy-repl> prnt ${user}.name Pippo ``` -------------------------------- ### Custom Widgets Example Source: https://github.com/jline/jline3/blob/master/website/docs/advanced/key-bindings.md Provides an example of creating and registering a custom widget to extend JLine's functionality. ```java import org.jline.keyρέssion.KeyMap; import org.jline.reader.LineReader; import org.jline.reader.LineReaderBuilder; import org.jline.reader.Widget; import org.jline.terminal.Terminal; import org.jline.terminal.TerminalBuilder; import java.io.IOException; public class CustomWidgetsExample { // Define a custom widget static class MyCustomWidget implements Widget { @Override public void widget(LineReader reader) { System.out.println("\n--- Custom Widget Executed ---"); // In a real widget, you might manipulate the buffer, display info, etc. } } public static void main(String[] args) throws Exception { Terminal terminal = TerminalBuilder.builder().build(); LineReader reader = LineReaderBuilder.builder().terminal(terminal).build(); KeyMap keyMap = reader.getKeyMaps().get(KeyMap.EMACS); // Register the custom widget reader.addWidget("my-widget", new MyCustomWidget()); // Bind Ctrl+W to the custom widget keyMap.bind(KeyMap.ctrl('w'), "my-widget"); System.out.println("Custom widget 'my-widget' registered and bound to Ctrl+W."); System.out.println("Press Ctrl+W to execute the custom widget."); String line; while ((line = reader.readLine("> ")) != null) { System.out.println("You entered: " + line); if (line.equals("exit")) { break; } } terminal.close(); } } ``` -------------------------------- ### Variable Expansion Examples Source: https://github.com/jline/jline3/blob/master/website/docs/shell-features.md Illustrates different syntaxes for variable expansion, including session and environment variables, home directory expansion, quoted strings, and default value fallbacks. ```shell echo $HOME → /home/user echo ${HOME}/docs → /home/user/docs echo ~/docs → /home/user/docs echo '$HOME' → $HOME (no expansion) echo "$HOME" → /home/user echo ${MISSING:-hello} → hello echo ${NAME:+yes} → yes (if NAME is set) ``` -------------------------------- ### Groovy Script Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/repl-console.md This is a placeholder for a Groovy script example. It demonstrates executing application commands from within a Groovy script in the JLine REPL. ```groovy System.out.println("This is a placeholder for a Groovy script example."); System.out.println("It demonstrates executing application commands from within a Groovy script in the JLine REPL."); System.Registry.get().invoke('prnt', '-s', 'JSON', map) ``` -------------------------------- ### List Prompt Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/console-ui.md Shows how to create a list prompt for single item selection from a given list of options. ```java ConsolePrompt prompt = new ConsolePrompt(); PromptBuilder builder = prompt.getPromptBuilder(); builder.createListPrompt("color", "Choose a color: ", Arrays.asList("Red", "Green", "Blue"), "Red"); Map result = prompt.prompt(builder.build()); System.out.println("You chose: " + result.get("color")); ``` -------------------------------- ### Bash Quick Choice with Keys Source: https://github.com/jline/jline3/blob/master/website/docs/modules/prompt.md Example of using the 'prompt' command-line tool for quick choice selection with defined keys. ```bash prompt choice "Pick color" "Red" "Green" "Blue" -k "rgb" ``` -------------------------------- ### JLine Diagnostic Output Example Source: https://github.com/jline/jline3/blob/master/website/docs/reference/diagnostic.md This is an example of the output generated by the JLine diagnostic tool, showing system properties, OS details, and terminal provider support status. ```text System properties ================= os.name = Mac OS X OSTYPE = null MSYSTEM = null PWD = /Users/gnodet/work/git/jline3 ConEmuPID = null WSL_DISTRO_NAME = null WSL_INTEROP = null OSUtils ================= IS_WINDOWS = false IS_CYGWIN = false IS_MSYSTEM = false IS_WSL = false IS_WSL1 = false IS_WSL2 = false IS_CONEMU = false IS_OSX = true FFM Support ================= FFM support not available: java.io.IOException: Unable to load terminal provider ffm: null JnaSupport ================= JNA support not available: java.io.IOException: Unable to load terminal provider jna: Provider removed in JLine 4.x Jansi2Support ================= Jansi 2 support not available: java.io.IOException: Unable to load terminal provider jansi: Provider removed in JLine 4.x JniSupport ================= StdIn stream = true StdOut stream = true StdErr stream = true StdIn stream name = /dev/ttys007 StdOut stream name = /dev/ttys007 StdErr stream name = /dev/ttys007 Terminal size: Size[cols=184, rows=47] The terminal seems to work: terminal org.jline.terminal.impl.PosixSysTerminal with pty org.jline.terminal.impl.jni.osx.OsXNativePty Exec Support ================= StdIn stream = true StdOut stream = true StdErr stream = true StdIn stream name = /dev/ttys007 StdOut stream name = /dev/ttys007 StdErr stream name = /dev/ttys007 Terminal size: Size[cols=184, rows=47] The terminal seems to work: terminal org.jline.terminal.impl.PosixSysTerminal with pty org.jline.terminal.impl.exec.ExecPty ``` -------------------------------- ### Interactive Remote Shell Example Source: https://github.com/jline/jline3/blob/master/website/docs/remote-terminals.md An example demonstrating how to create an interactive shell for remote terminals using JLine. This snippet showcases the integration of JLine's features for networked terminal applications. ```java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jline.example; import org.jline.terminal.Terminal; import org.jline.terminal.TerminalBuilder; import org.jline.utils.InfoCmp; import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class RemoteShellExample { public static void main(String[] args) { int port = 12345; try (ServerSocket serverSocket = new ServerSocket(port)) { System.out.println("Server started on port " + port); while (true) { Socket clientSocket = serverSocket.accept(); System.out.println("Client connected: " + clientSocket.getInetAddress()); new Thread(() -> { try { Terminal terminal = TerminalBuilder.builder() .system(false) .streams(clientSocket.getInputStream(), clientSocket.getOutputStream()) .build(); PrintWriter writer = terminal.writer(); writer.println("Welcome to the remote shell!"); writer.flush(); // Example: Print terminal capabilities writer.println("Terminal type: " + terminal.getType()); writer.println("Number of columns: " + terminal.getWidth()); writer.println("Number of rows: " + terminal.getHeight()); writer.flush(); // Example: Read and echo input String line; while ((line = terminal.reader().readLine("> ")) != null) { writer.println("You entered: " + line); writer.flush(); if (line.equalsIgnoreCase("exit")) { break; } } writer.println("Goodbye!"); writer.flush(); terminal.close(); } catch (IOException e) { System.err.println("Error handling client: " + e.getMessage()); } }).start(); } } catch (IOException e) { System.err.println("Could not start server: " + e.getMessage()); } } } ``` -------------------------------- ### Basic WebTerminal Usage Source: https://github.com/jline/jline3/blob/master/website/docs/advanced/web-swing-terminals.md Demonstrates how to create, start, and manage a WebTerminal instance. Includes initial content writing and a loop for processing I/O. Ensure to handle potential exceptions like InterruptedException. ```java WebTerminal webTerminal = new WebTerminal("localhost", 8080, 24, 80); webTerminal.write("Welcome to JLine WebTerminal!\n"); webTerminal.write("$ "); webTerminal.start(); while (webTerminal.isRunning()) { String output = webTerminal.read(); if (output != null && !output.isEmpty()) { // Process output } Thread.sleep(100); } webTerminal.stop(); ``` -------------------------------- ### JLine Diagnostic Output Example Source: https://github.com/jline/jline3/wiki/Diagnostic This is an example of the output you can expect when running the JLine diagnostic tool. It includes system properties, OS utility information, and support status for various terminal providers. ```text System properties ================= os.name = Mac OS X OSTYPE = null MSYSTEM = null PWD = /Users/gnodet/work/git/jline3 ConEmuPID = null WSL_DISTRO_NAME = null WSL_INTEROP = null OSUtils ================= IS_WINDOWS = false IS_CYGWIN = false IS_MSYSTEM = false IS_WSL = false IS_WSL1 = false IS_WSL2 = false IS_CONEMU = false IS_OSX = true FFM Support ================= FFM support not available: java.io.IOException: Unable to load terminal provider ffm: null JnaSupport ================= JNA support not available: java.io.IOException: Unable to load terminal provider jna: null Jansi2Support ================= Jansi 2 support not available: java.io.IOException: Unable to load terminal provider jansi: null JniSupport ================= StdIn stream = true StdOut stream = true StdErr stream = true StdIn stream name = /dev/ttys007 StdOut stream name = /dev/ttys007 StdErr stream name = /dev/ttys007 Terminal size: Size[cols=184, rows=47] The terminal seems to work: terminal org.jline.terminal.impl.PosixSysTerminal with pty org.jline.terminal.impl.jni.osx.OsXNativePty Exec Support ================= StdIn stream = true StdOut stream = true StdErr stream = true StdIn stream name = /dev/ttys007 StdOut stream name = /dev/ttys007 StdErr stream name = /dev/ttys007 Terminal size: Size[cols=184, rows=47] The terminal seems to work: terminal org.jline.terminal.impl.PosixSysTerminal with pty org.jline.terminal.impl.exec.ExecPty ``` -------------------------------- ### Install Gogh for Nanorc Themes Source: https://github.com/jline/jline3/wiki/Theme-System This command sequence downloads and executes a script to install Gogh, which can be used to apply color themes to nanorc files. Ensure you are in the correct directory and have the necessary build tools. ```bash > cd git/jline3 > ./build rebuild > cd demo/target/nanorc > bash -c "$(wget -qO- https://git.io/vQgMr)" ``` -------------------------------- ### Theme System File Example Source: https://github.com/jline/jline3/blob/master/website/docs/advanced/theme-system.md Demonstrates the syntax for defining token types, mixins, and parser configurations within a JLine theme system file. ```nanorc BOOLEAN brightwhite NUMBER blue CONSTANT yellow COMMENT brightblack DOC_COMMENT white TODO brightwhite,yellow WHITESPACE ,green # # mixin # +LINT WHITESPACE: "[[:space:]]+$" WHITESPACE: "\t*" # # parser # $LINE_COMMENT COMMENT TODO: "(FIXME|TODO|XXX)" $BLOCK_COMMENT COMMENT DOC_COMMENT: startWith=/** TODO: "(FIXME|TODO|XXX)" ``` -------------------------------- ### Build Documentation Site Source: https://github.com/jline/jline3/blob/master/CLAUDE.md Command to build the JLine3 documentation website. ```bash ./mvx website build ``` -------------------------------- ### EnumCompleter Example Source: https://github.com/jline/jline3/blob/master/website/docs/tab-completion.md Complete enum values using EnumCompleter. ```java Completer completer = new EnumCompleter(MyEnum.class); ``` -------------------------------- ### DirectoriesCompleter Example Source: https://github.com/jline/jline3/blob/master/website/docs/tab-completion.md Use DirectoriesCompleter to complete only directory names. ```java Completer completer = new DirectoriesCompleter(); ``` -------------------------------- ### Configure Prompter with Custom Settings Source: https://github.com/jline/jline3/blob/master/prompt/README.md Shows how to initialize the Prompter with either platform-specific default configurations or a completely custom set of display elements for prompts. ```java PrompterConfig config = PrompterConfig.defaults(); PrompterConfig customConfig = PrompterConfig.custom( "->", // indicator "[ ]", // unchecked box "[x]", // checked box "[-]", // unavailable item null, // style resolver (optional) false // cancellable first prompt ); Prompter prompter = PrompterFactory.create(terminal, customConfig); ``` -------------------------------- ### NullCompleter Example Source: https://github.com/jline/jline3/blob/master/website/docs/tab-completion.md Use NullCompleter to explicitly terminate a chain of completers. ```java Completer completer = new AggregateCompleter( new StringsCompleter("first"), NullCompleter.INSTANCE ); ``` -------------------------------- ### Basic Key Binding Example Source: https://github.com/jline/jline3/blob/master/website/docs/advanced/key-bindings.md Demonstrates the fundamental concept of mapping keyboard input to actions using JLine's key binding system. ```java import org.jline.keyρέssion.KeyMap; import org.jline.terminal.Terminal; import org.jline.terminal.TerminalBuilder; public class KeyBindingBasicsExample { public static void main(String[] args) throws Exception { Terminal terminal = TerminalBuilder.builder().build(); KeyMap keyMap = new KeyMap<>("main", terminal); // Bind 'a' to the action "do-a" keyMap.bind(KeyMap.key(terminal, "a"), "do-a"); // Bind Ctrl+X to the action "do-ctrl-x" keyMap.bind(KeyMap.ctrl('x'), "do-ctrl-x"); System.out.println("Key bindings set. Try typing 'a' or Ctrl+X."); // In a real application, you would typically use a LineReader to process input // For this example, we just show the binding setup. terminal.close(); } } ``` -------------------------------- ### TreeCompleter Example Source: https://github.com/jline/jline3/blob/master/website/docs/tab-completion.md Define a hierarchical structure of completions using TreeCompleter. ```java Node root = new Node("command", new Node("subcommand1"), new Node("subcommand2")); Completer completer = new TreeCompleter(root); ``` -------------------------------- ### FileNameCompleter Example Source: https://github.com/jline/jline3/blob/master/website/docs/tab-completion.md Use FileNameCompleter for autocompleting file and directory names. ```java Completer completer = new FileNameCompleter(); ``` -------------------------------- ### RegexCompleter Example Source: https://github.com/jline/jline3/blob/master/website/docs/tab-completion.md Define completion patterns using regular expressions with RegexCompleter. ```java Completer completer = new RegexCompleter("^(?:command|option)-\d+$"); ``` -------------------------------- ### Basic Styling Example Source: https://github.com/jline/jline3/blob/master/website/docs/modules/style.md Demonstrates how to add basic colors and formatting to text using the JLine Style module. ```java AttributedStyle style = new AttributedStyle().foreground(AttributedStyle.RED).bold(true); System.out.println(style.apply("This is red and bold text.")); ``` -------------------------------- ### FilesCompleter Example Source: https://github.com/jline/jline3/blob/master/website/docs/tab-completion.md Use FilesCompleter to complete file names with optional filtering. ```java Completer completer = new FilesCompleter(); ``` -------------------------------- ### Colored Completer Example Source: https://github.com/jline/jline3/blob/master/website/docs/tab-completion.md Add colors to completion suggestions to visually distinguish them. ```java List candidates = new ArrayList<>(); candidates.add(new SimpleCompletionCandidate("command", "\u001b[32mExecutes the command\u001b[0m")); // Green color ``` -------------------------------- ### Completion Behavior Example Source: https://github.com/jline/jline3/blob/master/website/docs/tab-completion.md Configure how tab completion behaves, such as case sensitivity. ```java LineReader lineReader = LineReaderBuilder.builder() .completer(new StringsCompleter("OptionA", "OptionB")) .option(LineReaderBuilder.Option.CASE_INSENSITIVE, true) .build(); ``` -------------------------------- ### Start Basic SSH Server Source: https://github.com/jline/jline3/blob/master/website/docs/remote-terminals.md This code snippet shows how to launch a basic SSH server for secure remote terminal access. ```java ssh.sshd(System.out, System.err, new String[]{ "--port=2222", // Default is 8022 "--ip=0.0.0.0", // Default is 127.0.0.1 (localhost only) "start" }); ``` -------------------------------- ### Configuring Init Script for Shell Startup Source: https://github.com/jline/jline3/blob/master/website/docs/shell-features.md Sets up the shell to automatically run a specified script file upon startup. This is useful for initializing shell environment or running setup commands. ```java Shell.builder() .scriptRunner(new DefaultScriptRunner()) .initScript(new File("~/.myapprc")) .build(); ``` -------------------------------- ### AggregateCompleter Example Source: https://github.com/jline/jline3/blob/master/website/docs/tab-completion.md Combine multiple completers into a single one using AggregateCompleter. ```java Completer completer = new AggregateCompleter( new StringsCompleter("option1", "option2"), new FileNameCompleter() ); ``` -------------------------------- ### Disabled Items in Prompts Source: https://github.com/jline/jline3/blob/master/website/docs/modules/console-ui.md Example of how to disable an item in a prompt and provide a reason. ```java .newItem("premium").text("Premium Feature").disabledText("Requires subscription").add() ```