0
# Console Integration
1
2
Advanced console features including syntax highlighting, auto-completion, custom command registration, and integration with JLine3 terminal capabilities. These components provide the rich interactive experience of the Groovy shell.
3
4
## Capabilities
5
6
### Console Engine
7
8
Enhanced console engine with Groovy-specific printing capabilities and command support.
9
10
```groovy { .api }
11
/**
12
* Enhanced console engine extending JLine's ConsoleEngineImpl
13
*/
14
class GroovyConsoleEngine {
15
/**
16
* Enhanced printing with formatting options
17
* @param options Map of printing options for formatting control
18
* @param object Object to print
19
*/
20
void println(Map<String, Object> options, Object object)
21
22
/**
23
* Set console configuration option
24
* @param option Option name
25
* @param value Option value
26
*/
27
void setConsoleOption(String option, Object value)
28
}
29
```
30
31
**Usage Examples:**
32
33
```groovy
34
import org.apache.groovy.groovysh.jline.GroovyConsoleEngine
35
36
// Create console engine
37
GroovyConsoleEngine console = new GroovyConsoleEngine(
38
scriptEngine, printer, workDir, configPath, reader
39
)
40
41
// Configure console options
42
console.setConsoleOption("docs", new DocFinder())
43
44
// Enhanced printing with options
45
Map<String, Object> printOptions = [
46
color: true,
47
format: "json",
48
indent: 2
49
]
50
console.println(printOptions, ["name": "Alice", "age": 25])
51
```
52
53
### System Registry
54
55
Enhanced command execution system with Groovy syntax support and custom operators.
56
57
```groovy { .api }
58
/**
59
* System registry extending SystemRegistryImpl with Groovy enhancements
60
*/
61
class GroovySystemRegistry {
62
/**
63
* Execute command or script with Groovy enhancements
64
* @param line Command/script line to execute
65
* @return Execution result
66
*/
67
Object execute(String line)
68
69
/**
70
* Determine if input is command or script
71
* @param command Input string to analyze
72
* @return true if command, false if script
73
*/
74
boolean isCommandOrScript(String command)
75
76
/**
77
* Set command registries for the system
78
* @param registries Command registry instances
79
*/
80
void setCommandRegistries(CommandRegistry... registries)
81
82
/**
83
* Add completer for auto-completion
84
* @param completer Completer instance
85
*/
86
void addCompleter(Completer completer)
87
88
/**
89
* Set script description provider
90
* @param provider Function to provide script descriptions
91
*/
92
void setScriptDescription(Function<String, String> provider)
93
94
/**
95
* Group commands in help display
96
* @param group Whether to group commands
97
*/
98
void groupCommandsInHelp(boolean group)
99
100
/**
101
* Rename local command
102
* @param oldName Current command name
103
* @param newName New command name
104
*/
105
void renameLocal(String oldName, String newName)
106
107
/**
108
* Create command alias
109
* @param aliasName Alias name
110
* @param targetName Target command name
111
*/
112
void invoke(String aliasCommand, String aliasName, String targetName)
113
114
/**
115
* Set console option
116
* @param option Option name
117
* @param value Option value
118
*/
119
void setConsoleOption(String option, Object value)
120
}
121
```
122
123
**Usage Examples:**
124
125
```groovy
126
import org.apache.groovy.groovysh.jline.GroovySystemRegistry
127
128
// Create system registry
129
GroovySystemRegistry systemRegistry = new GroovySystemRegistry(
130
parser, terminal, workDir, configPath
131
)
132
133
// Configure registry
134
systemRegistry.groupCommandsInHelp(false)
135
systemRegistry.setCommandRegistries(extraCommands, consoleEngine, builtins, groovyCommands)
136
systemRegistry.addCompleter(scriptEngine.getScriptCompleter())
137
systemRegistry.setScriptDescription(scriptEngine::scriptDescription)
138
139
// Set up command aliases
140
systemRegistry.renameLocal('exit', '/exit')
141
systemRegistry.renameLocal('help', '/help')
142
systemRegistry.invoke('/alias', '/x', '/exit')
143
systemRegistry.invoke('/alias', '/q', '/exit')
144
145
// Configure options
146
systemRegistry.setConsoleOption("ignoreUnknownPipes", true)
147
148
// Execute commands/scripts
149
Object result = systemRegistry.execute("def x = 42; x * 2")
150
boolean isCommand = systemRegistry.isCommandOrScript("/help")
151
```
152
153
### Custom Pipe Operators
154
155
Support for enhanced pipe operations beyond standard shell pipes.
156
157
```groovy { .api }
158
// Conditional execution pipe
159
command1 |&& command2 // Execute command2 only if command1 succeeds
160
161
// Alternative execution pipe
162
command1 ||| command2 // Execute command2 only if command1 fails
163
164
// Output redirection pipes
165
command |> filename // Redirect output to file (overwrite)
166
command |>> filename // Redirect output to file (append)
167
```
168
169
**Usage Examples:**
170
171
```bash
172
groovy> def result = calculate() |&& processResult()
173
groovy> loadConfig() ||| useDefaults()
174
groovy> /vars |> variables.txt
175
groovy> getCurrentState() |>> state.log
176
```
177
178
### Command Registration
179
180
Register custom commands and command handlers within the shell environment.
181
182
```groovy { .api }
183
/**
184
* Command registry for managing custom commands
185
*/
186
class ExtraConsoleCommands {
187
/**
188
* Register custom command methods
189
* @param commands Map of command names to method implementations
190
*/
191
void registerCommands(Map<String, CommandMethods> commands)
192
193
/**
194
* Get current working directory
195
* @return Current directory path
196
*/
197
Path currentDir()
198
}
199
200
/**
201
* Command methods wrapper for command implementations
202
*/
203
class CommandMethods {
204
/**
205
* Create command methods
206
* @param function Command execution function
207
* @param completer Command completer function
208
*/
209
CommandMethods(Function function, Function completer)
210
}
211
```
212
213
**Usage Examples:**
214
215
```groovy
216
// Create custom command registry
217
ExtraConsoleCommands extraCommands = new ExtraConsoleCommands(
218
workDir, scriptEngine, reader
219
)
220
221
// Define custom commands
222
Map<String, CommandMethods> customCommands = [
223
'/mycommand': new CommandMethods(
224
this::myCommandHandler,
225
this::myCommandCompleter
226
)
227
]
228
229
// Register commands
230
extraCommands.registerCommands(customCommands)
231
```
232
233
### Syntax Highlighting
234
235
Advanced syntax highlighting system with support for multiple languages and contexts.
236
237
```groovy { .api }
238
/**
239
* System syntax highlighter with context-aware highlighting
240
*/
241
class SystemHighlighter {
242
/**
243
* Set highlighter for specific commands
244
* @param command Command name
245
* @param highlighter Syntax highlighter instance
246
*/
247
void setSpecificHighlighter(String command, SyntaxHighlighter highlighter)
248
249
/**
250
* Add file highlighting for commands
251
* @param commands Commands that work with files
252
*/
253
void addFileHighlight(String... commands)
254
255
/**
256
* Add external highlighter refresh callback
257
* @param refreshCallback Callback function for refresh
258
*/
259
void addExternalHighlighterRefresh(Runnable refreshCallback)
260
}
261
```
262
263
**Usage Examples:**
264
265
```groovy
266
SystemHighlighter highlighter = new SystemHighlighter(
267
commandHighlighter, argsHighlighter, groovyHighlighter
268
)
269
270
// Configure specific command highlighting
271
if (!OSUtils.IS_WINDOWS) {
272
highlighter.setSpecificHighlighter("/!",
273
SyntaxHighlighter.build(jnanorc, "SH-REPL"))
274
}
275
276
// Add file highlighting for file operations
277
highlighter.addFileHighlight('/nano', '/less', '/slurp', '/load', '/save')
278
highlighter.addFileHighlight('/classloader', null, ['-a', '--add'])
279
280
// Set up refresh callbacks
281
highlighter.addExternalHighlighterRefresh(printer::refresh)
282
highlighter.addExternalHighlighterRefresh(scriptEngine::refresh)
283
```
284
285
### Auto-completion System
286
287
Comprehensive auto-completion system with context-aware suggestions and multi-level completion.
288
289
```groovy { .api }
290
/**
291
* Get completer for the system registry
292
* @return Combined completer for all registered completers
293
*/
294
Completer completer()
295
296
/**
297
* Maven coordinate completer for dependency management
298
*/
299
class MavenCoordinateCompleter {
300
// Auto-completion for Maven artifact coordinates
301
}
302
303
/**
304
* Option completer for command options
305
*/
306
class OptionCompleter {
307
/**
308
* Create option completer
309
* @param fileCompleter Base file completer
310
* @param optionProvider Function providing command options
311
* @param maxOptions Maximum number of options to show
312
*/
313
OptionCompleter(Completer fileCompleter, Function optionProvider, int maxOptions)
314
}
315
```
316
317
**Usage Examples:**
318
319
```groovy
320
// Set up reader with completion
321
LineReader reader = LineReaderBuilder.builder()
322
.terminal(terminal)
323
.parser(parser)
324
.build()
325
326
// Configure completion
327
reader.setCompleter(systemRegistry.completer())
328
329
// Completion will work for:
330
// - Command names and options
331
// - File paths
332
// - Maven coordinates
333
// - Variable names
334
// - Groovy language constructs
335
```
336
337
### Terminal Integration
338
339
Deep integration with JLine3 terminal capabilities for cross-platform compatibility.
340
341
```groovy { .api }
342
// Terminal configuration
343
Terminal terminal = TerminalBuilder.builder()
344
.type(terminalType)
345
.encoding(encoding)
346
.color(colorEnabled)
347
.name('groovysh')
348
.build()
349
350
// Configure terminal size for redirected output
351
if (terminal.width == 0 || terminal.height == 0) {
352
terminal.size = new Size(120, 40)
353
}
354
355
// Handle interrupt signals
356
Thread executeThread = Thread.currentThread()
357
terminal.handle(Signal.INT, signal -> executeThread.interrupt())
358
```
359
360
### Widget System
361
362
Advanced widgets for enhanced user interaction including suggestions and tooltips.
363
364
```groovy { .api }
365
/**
366
* Tail tip widgets for command descriptions
367
*/
368
class TailTipWidgets {
369
/**
370
* Create tail tip widgets
371
* @param reader Line reader instance
372
* @param descriptionProvider Function providing descriptions
373
* @param maxTips Maximum number of tips to show
374
* @param tipType Type of tips to display
375
*/
376
TailTipWidgets(LineReader reader, Function descriptionProvider,
377
int maxTips, TipType tipType)
378
}
379
380
/**
381
* Auto-suggestion widgets for completion
382
*/
383
class AutosuggestionWidgets {
384
/**
385
* Create auto-suggestion widgets
386
* @param reader Line reader instance
387
*/
388
AutosuggestionWidgets(LineReader reader)
389
}
390
```
391
392
**Usage Examples:**
393
394
```groovy
395
// Set up widgets
396
new TailTipWidgets(reader, systemRegistry::commandDescription, 5, TipType.COMPLETER)
397
new AutosuggestionWidgets(reader)
398
399
// Bind widget toggle keys
400
KeyMap<Binding> keyMap = reader.getKeyMaps().get("main")
401
keyMap.bind(new Reference(Widgets.TAILTIP_TOGGLE), KeyMap.alt("s"))
402
keyMap.bind(new Reference(Widgets.AUTOSUGGEST_TOGGLE), KeyMap.alt("v"))
403
```