0
# Autocompletion
1
2
TAB completion script generation and completion candidate suggestion for creating shell autocompletion functionality that enhances user experience with intelligent command line completion.
3
4
## Capabilities
5
6
### AutoComplete Class
7
8
Main class for generating shell completion scripts and providing completion suggestions.
9
10
```java { .api }
11
public class AutoComplete {
12
// Exit codes for the AutoComplete main method
13
public static final int EXIT_CODE_SUCCESS = 0;
14
public static final int EXIT_CODE_INVALID_INPUT = 1;
15
public static final int EXIT_CODE_COMMAND_SCRIPT_EXISTS = 2;
16
public static final int EXIT_CODE_COMPLETION_SCRIPT_EXISTS = 3;
17
public static final int EXIT_CODE_EXECUTION_ERROR = 4;
18
19
/**
20
* Main entry point for autocompletion script generation
21
* Usage: java -cp myapp.jar picocli.AutoComplete [-f] [-o completionFile] [--] commandLineClass
22
* @param args command line arguments for script generation
23
*/
24
public static void main(String... args);
25
26
/**
27
* Generates bash completion script and writes to file
28
* @param scriptName name of the script/command
29
* @param out output file for the completion script
30
* @param command file containing the command class
31
* @param commandLine CommandLine instance for the command
32
* @throws IOException if file operations fail
33
*/
34
public static void bash(String scriptName, File out, File command, CommandLine commandLine) throws IOException;
35
36
/**
37
* Generates bash completion script as string
38
* @param scriptName name of the script/command
39
* @param commandLine CommandLine instance for the command
40
* @return bash completion script as string
41
*/
42
public static String bash(String scriptName, CommandLine commandLine);
43
44
/**
45
* Provides completion candidates for interactive completion
46
* @param spec command specification
47
* @param args current command line arguments
48
* @param argIndex index of argument being completed
49
* @param positionInArg cursor position within the argument
50
* @param cursor absolute cursor position
51
* @param candidates list to populate with completion candidates
52
* @return number of completion candidates found
53
*/
54
public static int complete(CommandSpec spec, String[] args, int argIndex, int positionInArg, int cursor, List<CharSequence> candidates);
55
}
56
```
57
58
**Usage Examples:**
59
60
```java
61
// Generate completion script for a command
62
@Command(name = "myapp", subcommands = {SubCmd1.class, SubCmd2.class})
63
class MyApp implements Runnable {
64
@Option(names = {"-v", "--verbose"}) boolean verbose;
65
@Parameters String[] files;
66
67
public void run() { /* implementation */ }
68
}
69
70
// Generate bash completion script
71
CommandLine cmd = new CommandLine(new MyApp());
72
String completionScript = AutoComplete.bash("myapp", cmd);
73
74
// Write to file
75
try (FileWriter writer = new FileWriter("myapp_completion.bash")) {
76
writer.write(completionScript);
77
}
78
79
// Or use the file-based method
80
AutoComplete.bash("myapp",
81
new File("myapp_completion.bash"),
82
new File("myapp.jar"),
83
cmd);
84
```
85
86
### Command Line Generation
87
88
Using the AutoComplete main method to generate completion scripts from command line.
89
90
**Command Line Usage:**
91
92
```bash
93
# Generate completion script
94
java -cp myapp.jar picocli.AutoComplete com.example.MyApp
95
96
# Generate to specific file
97
java -cp myapp.jar picocli.AutoComplete -o myapp_completion.bash com.example.MyApp
98
99
# Force overwrite if file exists
100
java -cp myapp.jar picocli.AutoComplete -f -o myapp_completion.bash com.example.MyApp
101
102
# Install the generated completion (example for bash)
103
source myapp_completion.bash
104
# or
105
sudo cp myapp_completion.bash /etc/bash_completion.d/
106
```
107
108
### Interactive Completion
109
110
Programmatic completion for building custom completion systems or integrating with shells.
111
112
```java { .api }
113
/**
114
* Completion method for interactive use
115
* @param spec the command specification to complete against
116
* @param args the current command line arguments
117
* @param argIndex index of the argument being completed (0-based)
118
* @param positionInArg position within the current argument being completed
119
* @param cursor absolute cursor position in the command line
120
* @param candidates list to be populated with completion candidates
121
* @return number of candidates found
122
*/
123
public static int complete(CommandSpec spec, String[] args, int argIndex, int positionInArg, int cursor, List<CharSequence> candidates);
124
```
125
126
**Usage Examples:**
127
128
```java
129
@Command(name = "app")
130
class MyApp {
131
@Option(names = {"-f", "--file"}) File file;
132
@Option(names = {"-t", "--type"},
133
completionCandidates = "text,binary,xml,json")
134
String type;
135
@Parameters String[] inputs;
136
}
137
138
CommandLine cmd = new CommandLine(new MyApp());
139
CommandSpec spec = cmd.getCommandSpec();
140
141
// Complete for: "app -t "
142
String[] args = {"app", "-t", ""};
143
List<CharSequence> candidates = new ArrayList<>();
144
int count = AutoComplete.complete(spec, args, 2, 0, 7, candidates);
145
146
// candidates now contains: [text, binary, xml, json]
147
System.out.println("Completion candidates: " + candidates);
148
149
// Complete for: "app --f"
150
args = new String[]{"app", "--f"};
151
candidates.clear();
152
count = AutoComplete.complete(spec, args, 1, 3, 6, candidates);
153
154
// candidates now contains: [--file]
155
System.out.println("Option completions: " + candidates);
156
```
157
158
### Completion Candidates Configuration
159
160
Configuring completion candidates for options and parameters through annotations.
161
162
```java { .api }
163
// In @Option annotation:
164
String completionCandidates() default "";
165
166
// In @Parameters annotation:
167
String completionCandidates() default "";
168
```
169
170
**Usage Examples:**
171
172
```java
173
@Command(name = "processor")
174
class DataProcessor {
175
// Static completion candidates
176
@Option(names = {"-f", "--format"},
177
completionCandidates = "json,xml,csv,yaml",
178
description = "Output format")
179
String format;
180
181
// File path completion (automatic)
182
@Option(names = {"-i", "--input"},
183
description = "Input file")
184
File inputFile;
185
186
// Enum completion (automatic)
187
@Option(names = {"-l", "--level"},
188
description = "Log level")
189
LogLevel logLevel;
190
191
// Directory completion
192
@Option(names = {"-o", "--output-dir"},
193
description = "Output directory")
194
File outputDir;
195
196
// Custom completion candidates class
197
@Option(names = {"-e", "--encoding"},
198
completionCandidates = "EncodingCandidates",
199
description = "Character encoding")
200
String encoding;
201
}
202
203
enum LogLevel { TRACE, DEBUG, INFO, WARN, ERROR }
204
205
// Custom completion candidates provider
206
class EncodingCandidates extends ArrayList<String> {
207
EncodingCandidates() {
208
addAll(Arrays.asList("UTF-8", "UTF-16", "ASCII", "ISO-8859-1"));
209
}
210
}
211
```
212
213
### Advanced Completion Features
214
215
Advanced completion features for complex command structures and dynamic candidates.
216
217
**Subcommand Completion:**
218
219
```java
220
@Command(name = "git", subcommands = {GitAdd.class, GitCommit.class, GitPush.class})
221
class Git {
222
// Subcommands are automatically completed
223
}
224
225
@Command(name = "add")
226
class GitAdd {
227
@Parameters(description = "Files to add") File[] files;
228
}
229
230
// Completion works for: git <TAB> -> [add, commit, push]
231
// And for: git add <TAB> -> [file completions]
232
```
233
234
**Dynamic Completion with Custom Logic:**
235
236
```java
237
// Custom completion through ICompletionCandidates interface
238
public class DatabaseTableCandidates implements Iterable<String> {
239
@Override
240
public Iterator<String> iterator() {
241
// Connect to database and get table names
242
List<String> tables = getDatabaseTables();
243
return tables.iterator();
244
}
245
246
private List<String> getDatabaseTables() {
247
// Implementation to fetch table names from database
248
return Arrays.asList("users", "orders", "products", "categories");
249
}
250
}
251
252
@Option(names = "--table",
253
completionCandidates = "DatabaseTableCandidates",
254
description = "Database table name")
255
String tableName;
256
```
257
258
### Installation and Integration
259
260
Setting up completion scripts in different shell environments.
261
262
**Bash Installation:**
263
264
```bash
265
# Generate the completion script
266
java -cp myapp.jar picocli.AutoComplete com.example.MyApp > myapp_completion.bash
267
268
# Install globally
269
sudo cp myapp_completion.bash /etc/bash_completion.d/
270
271
# Or install for current user
272
mkdir -p ~/.bash_completion.d
273
cp myapp_completion.bash ~/.bash_completion.d/
274
echo "source ~/.bash_completion.d/myapp_completion.bash" >> ~/.bashrc
275
276
# Test completion
277
source ~/.bashrc
278
myapp <TAB><TAB>
279
```
280
281
**Integration with Build Tools:**
282
283
```xml
284
<!-- Maven plugin configuration -->
285
<plugin>
286
<groupId>org.codehaus.mojo</groupId>
287
<artifactId>exec-maven-plugin</artifactId>
288
<version>3.1.0</version>
289
<executions>
290
<execution>
291
<id>generate-completion</id>
292
<phase>package</phase>
293
<goals>
294
<goal>java</goal>
295
</goals>
296
<configuration>
297
<mainClass>picocli.AutoComplete</mainClass>
298
<commandlineArgs>-o ${project.build.directory}/myapp_completion.bash com.example.MyApp</commandlineArgs>
299
</configuration>
300
</execution>
301
</executions>
302
</plugin>
303
```
304
305
```gradle
306
// Gradle task for completion generation
307
task generateCompletion(type: JavaExec) {
308
classpath = sourceSets.main.runtimeClasspath
309
main = 'picocli.AutoComplete'
310
args = ['-o', "$buildDir/myapp_completion.bash", 'com.example.MyApp']
311
}
312
313
build.dependsOn generateCompletion
314
```
315
316
### Completion Script Customization
317
318
The generated bash completion scripts can be customized for specific needs.
319
320
**Generated Script Structure:**
321
322
```bash
323
# Example generated completion script structure
324
_myapp() {
325
local cur prev opts
326
COMPREPLY=()
327
cur="${COMP_WORDS[COMP_CWORD]}"
328
prev="${COMP_WORDS[COMP_CWORD-1]}"
329
330
# Command completion logic generated by picocli
331
# Handles options, subcommands, and file completion
332
333
# Custom completion logic can be added here
334
}
335
336
complete -F _myapp myapp
337
```
338
339
**Custom Enhancement Example:**
340
341
```bash
342
# Enhanced completion with additional logic
343
_myapp_enhanced() {
344
local cur prev opts
345
COMPREPLY=()
346
cur="${COMP_WORDS[COMP_CWORD]}"
347
prev="${COMP_WORDS[COMP_CWORD-1]}"
348
349
# Generated picocli completion
350
_myapp
351
352
# Add custom hostname completion for --host option
353
if [[ ${prev} == "--host" ]]; then
354
COMPREPLY=( $(compgen -W "$(cat ~/.ssh/known_hosts | cut -d' ' -f1)" -- ${cur}) )
355
return 0
356
fi
357
}
358
359
complete -F _myapp_enhanced myapp
360
```