-
Notifications
You must be signed in to change notification settings - Fork 212
/
Commands.java
1558 lines (1502 loc) · 65.5 KB
/
Commands.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2002-2021, the original author or authors.
*
* This software is distributable under the BSD license. See the terms of the
* BSD license in the documentation provided with this software.
*
* https://opensource.org/licenses/BSD-3-Clause
*/
package org.jline.builtins;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.jline.builtins.Completers.CompletionData;
import org.jline.builtins.Options.HelpException;
import org.jline.builtins.Source.StdInSource;
import org.jline.builtins.Source.URLSource;
import org.jline.keymap.KeyMap;
import org.jline.reader.Binding;
import org.jline.reader.Highlighter;
import org.jline.reader.History;
import org.jline.reader.LineReader;
import org.jline.reader.LineReader.Option;
import org.jline.reader.Macro;
import org.jline.reader.Reference;
import org.jline.reader.Widget;
import org.jline.terminal.Terminal;
import org.jline.utils.AttributedStringBuilder;
import org.jline.utils.AttributedStyle;
import org.jline.utils.StyleResolver;
public class Commands {
public static void tmux(Terminal terminal, PrintStream out, PrintStream err,
Supplier<Object> getter,
Consumer<Object> setter,
Consumer<Terminal> runner,
String[] argv) throws Exception {
final String[] usage = {
"tmux - terminal multiplexer",
"Usage: tmux [command]",
" -? --help Show help",
};
Options opt = Options.compile(usage).parse(argv);
if (opt.isSet("help")) {
throw new HelpException(opt.usage());
}
// Tmux with no args
if (argv.length == 0) {
Object instance = getter.get();
if (instance != null) {
err.println("tmux: can't run tmux inside itself");
} else {
Tmux tmux = new Tmux(terminal, err, runner);
setter.accept(tmux);
try {
tmux.run();
} finally {
setter.accept(null);
}
}
} else {
Object instance = getter.get();
if (instance != null) {
((Tmux) instance).execute(out, err, Arrays.asList(argv));
} else {
err.println("tmux: no instance running");
}
}
}
public static void nano(Terminal terminal, PrintStream out, PrintStream err,
Path currentDir,
String[] argv) throws Exception {
nano(terminal, out, err, currentDir, argv, null);
}
public static void nano(Terminal terminal, PrintStream out, PrintStream err,
Path currentDir,
String[] argv,
ConfigurationPath configPath) throws Exception {
Options opt = Options.compile(Nano.usage()).parse(argv);
if (opt.isSet("help")) {
throw new HelpException(opt.usage());
}
Nano edit = new Nano(terminal, currentDir, opt, configPath);
edit.open(opt.args());
edit.run();
}
public static void less(Terminal terminal, InputStream in, PrintStream out, PrintStream err,
Path currentDir,
String[] argv) throws Exception {
less(terminal, in, out, err, currentDir, argv, null);
}
public static void less(Terminal terminal, InputStream in, PrintStream out, PrintStream err,
Path currentDir,
String[] argv,
ConfigurationPath configPath) throws Exception {
Options opt = Options.compile(Less.usage()).parse(argv);
if (opt.isSet("help")) {
throw new HelpException(opt.usage());
}
Less less = new Less(terminal, currentDir, opt, configPath);
List<Source> sources = new ArrayList<>();
if (opt.args().isEmpty()) {
opt.args().add("-");
}
for (String arg : opt.args()) {
arg = arg.startsWith("~") ? arg.replace("~", System.getProperty("user.home")) : arg;
if ("-".equals(arg)) {
sources.add(new StdInSource(in));
} else if (arg.contains("*") || arg.contains("?")) {
for (Path p: findFiles(currentDir, arg)) {
sources.add(new URLSource(p.toUri().toURL(), p.toString()));
}
} else {
sources.add(new URLSource(currentDir.resolve(arg).toUri().toURL(), arg));
}
}
less.run(sources);
}
protected static List<Path> findFiles(Path root, String files) throws IOException{
files = files.startsWith("~") ? files.replace("~", System.getProperty("user.home")) : files;
String regex = files;
Path searchRoot = Paths.get("/");
if (new File(files).isAbsolute()) {
regex = regex.replaceAll("\\\\", "/").replaceAll("//", "/");
if (regex.contains("/")) {
String sr = regex.substring(0, regex.lastIndexOf("/") + 1);
while (sr.contains("*") || sr.contains("?")) {
sr = sr.substring(0, sr.lastIndexOf("/"));
}
searchRoot = Paths.get(sr + "/");
}
} else {
regex = (root.toString().length() == 0 ? "" : root.toString() + "/") + files;
regex = regex.replaceAll("\\\\", "/").replaceAll("//", "/");
searchRoot = root;
}
PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:"+regex);
return Files.find(searchRoot, Integer.MAX_VALUE, (path, f)->pathMatcher.matches(path)).collect(Collectors.toList());
}
public static void history(LineReader reader, PrintStream out, PrintStream err, Path currentDir,
String[] argv) throws Exception {
final String[] usage = {
"history - list history of commands",
"Usage: history [-dnrfEie] [-m match] [first] [last]",
" history -ARWI [filename]",
" history -s [old=new] [command]",
" history --clear",
" history --save",
" -? --help Displays command help",
" --clear Clear history",
" --save Save history",
" -m match If option -m is present the first argument is taken as a pattern",
" and only the history events matching the pattern will be shown",
" -d Print timestamps for each event",
" -f Print full time date stamps in the US format",
" -E Print full time date stamps in the European format",
" -i Print full time date stamps in ISO8601 format",
" -n Suppresses command numbers",
" -r Reverses the order of the commands",
" -A Appends the history out to the given file",
" -R Reads the history from the given file",
" -W Writes the history out to the given file",
" -I If added to -R, only the events that are not contained within the internal list are added",
" If added to -W or -A, only the events that are new since the last incremental operation",
" to the file are added",
" [first] [last] These optional arguments may be specified as a number or as a string. A negative number",
" is used as an offset to the current history event number. A string specifies the most",
" recent event beginning with the given string.",
" -e Uses the nano editor to edit the commands before executing",
" -s Re-executes the command without invoking an editor"};
Options opt = Options.compile(usage).parse(argv);
if (opt.isSet("help")) {
throw new HelpException(opt.usage());
}
History history = reader.getHistory();
boolean done = true;
boolean increment = opt.isSet("I");
if (opt.isSet("clear")) {
history.purge();
} else if (opt.isSet("save")) {
history.save();
} else if (opt.isSet("A")) {
Path file = opt.args().size() > 0 ? currentDir.resolve(opt.args().get(0)) : null;
history.append(file, increment);
} else if (opt.isSet("R")) {
Path file = opt.args().size() > 0 ? currentDir.resolve(opt.args().get(0)) : null;
history.read(file, increment);
} else if (opt.isSet("W")) {
Path file = opt.args().size() > 0 ? currentDir.resolve(opt.args().get(0)) : null;
history.write(file, increment);
} else {
done = false;
}
if (done) {
return;
}
ReExecute execute = new ReExecute(history, opt);
int argId = execute.getArgId();
Pattern pattern = null;
if (opt.isSet("m") && opt.args().size() > argId) {
StringBuilder sb = new StringBuilder();
char prev = '0';
for (char c: opt.args().get(argId++).toCharArray()) {
if (c == '*' && prev != '\\' && prev != '.') {
sb.append('.');
}
sb.append(c);
prev = c;
}
pattern = Pattern.compile(sb.toString(), Pattern.DOTALL);
}
boolean reverse = opt.isSet("r") || (opt.isSet("s") && opt.args().size() <= argId);
int firstId = opt.args().size() > argId ? retrieveHistoryId(history, opt.args().get(argId++)) : -17;
int lastId = opt.args().size() > argId ? retrieveHistoryId(history, opt.args().get(argId++)) : -1;
firstId = historyId(firstId, history.first(), history.last());
lastId = historyId(lastId, history.first(), history.last());
if (firstId > lastId) {
int tmpId = firstId;
firstId = lastId;
lastId = tmpId;
reverse = !reverse;
}
int tot = lastId - firstId + 1;
int listed = 0;
final Highlighter highlighter = reader.getHighlighter();
Iterator<History.Entry> iter = null;
if (reverse) {
iter = history.reverseIterator(lastId);
} else {
iter = history.iterator(firstId);
}
while (iter.hasNext() && listed < tot) {
History.Entry entry = iter.next();
listed++;
if (pattern != null && !pattern.matcher(entry.line()).matches()) {
continue;
}
if (execute.isExecute()) {
if (execute.isEdit()) {
execute.addCommandInFile(entry.line());
} else {
execute.addCommandInBuffer(reader, entry.line());
break;
}
} else {
AttributedStringBuilder sb = new AttributedStringBuilder();
if (!opt.isSet("n")) {
sb.append(" ");
sb.styled(AttributedStyle::bold, String.format("%3d", entry.index()));
}
if (opt.isSet("d") || opt.isSet("f") || opt.isSet("E") || opt.isSet("i")) {
sb.append(" ");
if (opt.isSet("d")) {
LocalTime lt = LocalTime.from(entry.time().atZone(ZoneId.systemDefault()))
.truncatedTo(ChronoUnit.SECONDS);
DateTimeFormatter.ISO_LOCAL_TIME.formatTo(lt, sb);
} else {
LocalDateTime lt = LocalDateTime.from(entry.time().atZone(ZoneId.systemDefault())
.truncatedTo(ChronoUnit.MINUTES));
String format = "yyyy-MM-dd hh:mm";
if (opt.isSet("f")) {
format = "MM/dd/yy hh:mm";
} else if (opt.isSet("E")) {
format = "dd.MM.yyyy hh:mm";
}
DateTimeFormatter.ofPattern(format).formatTo(lt, sb);
}
}
sb.append(" ");
sb.append(highlighter.highlight(reader, entry.line()));
out.println(sb.toAnsi(reader.getTerminal()));
}
}
execute.editCommandsAndClose(reader);
}
private static class ReExecute {
private final boolean execute;
private final boolean edit;
private String oldParam;
private String newParam;
private FileWriter cmdWriter;
private File cmdFile;
private int argId = 0;
public ReExecute(History history, Options opt) throws IOException {
execute = opt.isSet("e") || opt.isSet("s");
edit = opt.isSet("e");
if (execute) {
Iterator<History.Entry> iter = history.reverseIterator(history.last());
if (iter.hasNext()) {
iter.next();
iter.remove();
}
if (edit) {
cmdFile = File.createTempFile("jline-history-", null);
cmdWriter = new FileWriter(cmdFile);
} else if (opt.args().size() > 0 ) {
String[] s = opt.args().get(argId).split("=");
if (s.length == 2) {
argId = argId + 1;
oldParam = s[0];
newParam = s[1];
}
}
}
}
public int getArgId() {
return argId;
}
public boolean isEdit() {
return edit;
}
public boolean isExecute() {
return execute;
}
public void addCommandInFile(String command) throws IOException {
cmdWriter.write(command + "\n");
}
public void addCommandInBuffer(LineReader reader, String command) {
reader.addCommandsInBuffer(Arrays.asList(replaceParam(command)));
}
private String replaceParam(String command) {
String out = command;
if (oldParam != null && newParam != null) {
out = command.replaceAll(oldParam, newParam);
}
return out;
}
public void editCommandsAndClose(LineReader reader) throws Exception {
if (edit) {
cmdWriter.close();
try {
reader.editAndAddInBuffer(cmdFile);
} finally {
cmdFile.delete();
}
}
}
}
private static int historyId(int id, int minId, int maxId) {
int out = id;
if (id < 0) {
out = maxId + id + 1;
}
if (out < minId) {
out = minId;
} else if (out > maxId) {
out = maxId;
}
return out;
}
private static int retrieveHistoryId(History history, String s) throws IllegalArgumentException {
try {
return Integer.parseInt(s);
} catch (NumberFormatException ex) {
Iterator<History.Entry> iter = history.iterator();
while (iter.hasNext()) {
History.Entry entry = iter.next();
if (entry.line().startsWith(s)) {
return entry.index();
}
}
throw new IllegalArgumentException("history: event not found: " + s);
}
}
public static void complete(LineReader reader, PrintStream out, PrintStream err,
Map<String, List<CompletionData>> completions,
String[] argv) throws HelpException {
final String[] usage = {
"complete - edit command specific tab-completions",
"Usage: complete",
" -? --help Displays command help",
" -c --command=COMMAND Command to add completion to",
" -d --description=DESCRIPTION Description of this completions",
" -e --erase Erase the completions",
" -s --short-option=SHORT_OPTION Posix-style option to complete",
" -l --long-option=LONG_OPTION GNU-style option to complete",
" -a --argument=ARGUMENTS A list of possible arguments",
" -n --condition=CONDITION The completion should only be used if the",
" specified command has a zero exit status"};
Options opt = Options.compile(usage).parse(argv);
if (opt.isSet("help")) {
throw new HelpException(opt.usage());
}
String command = opt.get("command");
if (opt.isSet("erase")) {
completions.remove(command);
return;
}
List<CompletionData> cmdCompletions = completions.computeIfAbsent(command, s -> new ArrayList<>());
List<String> options = null;
if (opt.isSet("short-option")) {
for (String op : opt.getList("short-option")) {
if (options == null) {
options = new ArrayList<>();
}
options.add("-" + op);
}
}
if (opt.isSet("long-option")) {
for (String op : opt.getList("long-option")) {
if (options == null) {
options = new ArrayList<>();
}
options.add("--" + op);
}
}
String description = opt.isSet("description") ? opt.get("description") : null;
String argument = opt.isSet("argument") ? opt.get("argument") : null;
String condition = opt.isSet("condition") ? opt.get("condition") : null;
cmdCompletions.add(new CompletionData(options, description, argument, condition));
}
public static void widget(LineReader reader, PrintStream out, PrintStream err,
Function<String, Widget> widgetCreator,
String[] argv) throws Exception {
final String[] usage = {
"widget - manipulate widgets",
"Usage: widget -N new-widget [function-name]",
" widget -D widget ...",
" widget -A old-widget new-widget",
" widget -U string ...",
" widget -l [options]",
" -? --help Displays command help",
" -A Create alias to widget",
" -N Create new widget",
" -D Delete widgets",
" -U Push characters to the stack",
" -l List user-defined widgets",
" -a With -l, list all widgets"
};
Options opt = Options.compile(usage).parse(argv);
if (opt.isSet("help")) {
throw new HelpException(opt.usage());
}
int actions = (opt.isSet("N") ? 1 : 0)
+ (opt.isSet("D") ? 1 : 0)
+ (opt.isSet("U") ? 1 : 0)
+ (opt.isSet("l") ? 1 : 0)
+ (opt.isSet("A") ? 1 : 0);
if (actions > 1) {
err.println("widget: incompatible operation selection options");
return;
}
if (opt.isSet("l")) {
TreeSet<String> ws = new TreeSet<>(reader.getWidgets().keySet());
if (opt.isSet("a")) {
Set<String> temp = new HashSet<>(ws);
for (String s: temp) {
ws.add(reader.getWidgets().get(s).toString());
}
}
for (String s : ws) {
if (opt.isSet("a")) {
out.println(s);
} else if (!reader.getWidgets().get(s).toString().startsWith(".")) {
out.println(s + " (" + reader.getWidgets().get(s) + ")");
}
}
}
else if (opt.isSet("N")) {
if (opt.args().size() < 1) {
err.println("widget: not enough arguments for -N");
return;
}
if (opt.args().size() > 2) {
err.println("widget: too many arguments for -N");
return;
}
final String name = opt.args().get(0);
final String func = opt.args().size() == 2 ? opt.args().get(1) : name;
reader.getWidgets().put(name, widgetCreator.apply(func));
} else if (opt.isSet("D")) {
for (String name : opt.args()) {
reader.getWidgets().remove(name);
}
} else if (opt.isSet("A")) {
if (opt.args().size() < 2) {
err.println("widget: not enough arguments for -A");
return;
}
if (opt.args().size() > 2) {
err.println("widget: too many arguments for -A");
return;
}
Widget org = null;
if (opt.args().get(0).startsWith(".")) {
org = reader.getBuiltinWidgets().get(opt.args().get(0).substring(1));
} else {
org = reader.getWidgets().get(opt.args().get(0));
}
if (org == null) {
err.println("widget: no such widget `" + opt.args().get(0) + "'");
return;
}
reader.getWidgets().put(opt.args().get(1), org);
}
else if (opt.isSet("U")) {
for (String arg : opt.args()) {
reader.runMacro(KeyMap.translate(arg));
}
}
else if (opt.args().size() == 1) {
reader.callWidget(opt.args().get(0));
}
}
public static void keymap(LineReader reader,
PrintStream out,
PrintStream err,
String[] argv) throws HelpException {
final String[] usage = {
"keymap - manipulate keymaps",
"Usage: keymap [options] -l [-L] [keymap ...]",
" keymap [options] -d",
" keymap [options] -D keymap ...",
" keymap [options] -A old-keymap new-keymap",
" keymap [options] -N new-keymap [old-keymap]",
" keymap [options] -m",
" keymap [options] -r in-string ...",
" keymap [options] -s in-string out-string ...",
" keymap [options] in-string command ...",
" keymap [options] [in-string]",
" -? --help Displays command help",
" -A Create alias to keymap",
" -D Delete named keymaps",
" -L Output in form of keymap commands",
" -M (default=main) Specify keymap to select",
" -N Create new keymap",
" -R Interpret in-strings as ranges",
" -a Select vicmd keymap",
" -d Delete existing keymaps and reset to default state",
" -e Select emacs keymap and bind it to main",
" -l List existing keymap names",
" -p List bindings which have given key sequence as a a prefix",
" -r Unbind specified in-strings ",
" -s Bind each in-string to each out-string ",
" -v Select viins keymap and bind it to main",
};
Options opt = Options.compile(usage).parse(argv);
if (opt.isSet("help")) {
throw new HelpException(opt.usage());
}
Map<String, KeyMap<Binding>> keyMaps = reader.getKeyMaps();
int actions = (opt.isSet("N") ? 1 : 0)
+ (opt.isSet("d") ? 1 : 0)
+ (opt.isSet("D") ? 1 : 0)
+ (opt.isSet("l") ? 1 : 0)
+ (opt.isSet("r") ? 1 : 0)
+ (opt.isSet("s") ? 1 : 0)
+ (opt.isSet("A") ? 1 : 0);
if (actions > 1) {
err.println("keymap: incompatible operation selection options");
return;
}
if (opt.isSet("l")) {
boolean commands = opt.isSet("L");
// TODO: handle commands
if (opt.args().size() > 0) {
for (String arg : opt.args()) {
KeyMap<Binding> map = keyMaps.get(arg);
if (map == null) {
err.println("keymap: no such keymap: `" + arg + "'");
} else {
out.println(arg);
}
}
} else {
keyMaps.keySet().forEach(out::println);
}
}
else if (opt.isSet("N")) {
if (opt.isSet("e") || opt.isSet("v") || opt.isSet("a") || opt.isSet("M")) {
err.println("keymap: keymap can not be selected with -N");
return;
}
if (opt.args().size() < 1) {
err.println("keymap: not enough arguments for -N");
return;
}
if (opt.args().size() > 2) {
err.println("keymap: too many arguments for -N");
return;
}
KeyMap<Binding> org = null;
if (opt.args().size() == 2) {
org = keyMaps.get(opt.args().get(1));
if (org == null) {
err.println("keymap: no such keymap `" + opt.args().get(1) + "'");
return;
}
}
KeyMap<Binding> map = new KeyMap<>();
if (org != null) {
for (Map.Entry<String, Binding> bound : org.getBoundKeys().entrySet()) {
map.bind(bound.getValue(), bound.getKey());
}
}
keyMaps.put(opt.args().get(0), map);
}
else if (opt.isSet("A")) {
if (opt.isSet("e") || opt.isSet("v") || opt.isSet("a") || opt.isSet("M")) {
err.println("keymap: keymap can not be selected with -N");
return;
}
if (opt.args().size() < 2) {
err.println("keymap: not enough arguments for -A");
return;
}
if (opt.args().size() > 2) {
err.println("keymap: too many arguments for -A");
return;
}
KeyMap<Binding> org = keyMaps.get(opt.args().get(0));
if (org == null) {
err.println("keymap: no such keymap `" + opt.args().get(0) + "'");
return;
}
keyMaps.put(opt.args().get(1), org);
}
else if (opt.isSet("d")) {
if (opt.isSet("e") || opt.isSet("v") || opt.isSet("a") || opt.isSet("M")) {
err.println("keymap: keymap can not be selected with -N");
return;
}
if (opt.args().size() > 0) {
err.println("keymap: too many arguments for -d");
return;
}
keyMaps.clear();
keyMaps.putAll(reader.defaultKeyMaps());
}
else if (opt.isSet("D")) {
if (opt.isSet("e") || opt.isSet("v") || opt.isSet("a") || opt.isSet("M")) {
err.println("keymap: keymap can not be selected with -N");
return;
}
if (opt.args().size() < 1) {
err.println("keymap: not enough arguments for -A");
return;
}
for (String name : opt.args()) {
if (keyMaps.remove(name) == null) {
err.println("keymap: no such keymap `" + name + "'");
return;
}
}
}
else if (opt.isSet("r")) {
// Select keymap
String keyMapName = LineReader.MAIN;
int sel = (opt.isSet("a") ? 1 : 0)
+ (opt.isSet("e") ? 1 : 0)
+ (opt.isSet("v") ? 1 : 0)
+ (opt.isSet("M") ? 1 : 0);
if (sel > 1) {
err.println("keymap: incompatible keymap selection options");
return;
} else if (opt.isSet("a")) {
keyMapName = LineReader.VICMD;
} else if (opt.isSet("e")) {
keyMapName = LineReader.EMACS;
} else if (opt.isSet("v")) {
keyMapName = LineReader.VIINS;
} else if (opt.isSet("M")) {
if (opt.args().isEmpty()) {
err.println("keymap: argument expected: -M");
return;
}
keyMapName = opt.args().remove(0);
}
KeyMap<Binding> map = keyMaps.get(keyMapName);
if (map == null) {
err.println("keymap: no such keymap `" + keyMapName + "'");
return;
}
// Unbind
boolean range = opt.isSet("R");
boolean prefix = opt.isSet("p");
Set<String> toRemove = new HashSet<>();
Map<String, Binding> bound = map.getBoundKeys();
for (String arg : opt.args()) {
if (range) {
Collection<String> r = KeyMap.range(opt.args().get(0));
if (r == null) {
err.println("keymap: malformed key range `" + opt.args().get(0) + "'");
return;
}
toRemove.addAll(r);
} else {
String seq = KeyMap.translate(arg);
for (String k : bound.keySet()) {
if (prefix && k.startsWith(seq) && k.length() > seq.length()
|| !prefix && k.equals(seq)) {
toRemove.add(k);
}
}
}
}
for (String seq : toRemove) {
map.unbind(seq);
}
if (opt.isSet("e") || opt.isSet("v")) {
keyMaps.put(LineReader.MAIN, map);
}
}
else if (opt.isSet("s") || opt.args().size() > 1) {
// Select keymap
String keyMapName = LineReader.MAIN;
int sel = (opt.isSet("a") ? 1 : 0)
+ (opt.isSet("e") ? 1 : 0)
+ (opt.isSet("v") ? 1 : 0)
+ (opt.isSet("M") ? 1 : 0);
if (sel > 1) {
err.println("keymap: incompatible keymap selection options");
return;
} else if (opt.isSet("a")) {
keyMapName = LineReader.VICMD;
} else if (opt.isSet("e")) {
keyMapName = LineReader.EMACS;
} else if (opt.isSet("v")) {
keyMapName = LineReader.VIINS;
} else if (opt.isSet("M")) {
if (opt.args().isEmpty()) {
err.println("keymap: argument expected: -M");
return;
}
keyMapName = opt.args().remove(0);
}
KeyMap<Binding> map = keyMaps.get(keyMapName);
if (map == null) {
err.println("keymap: no such keymap `" + keyMapName + "'");
return;
}
// Bind
boolean range = opt.isSet("R");
if (opt.args().size() % 2 == 1) {
err.println("keymap: even number of arguments required");
return;
}
for (int i = 0; i < opt.args().size(); i += 2) {
Binding bout = opt.isSet("s")
? new Macro(KeyMap.translate(opt.args().get(i + 1)))
: new Reference(opt.args().get(i + 1));
if (range) {
Collection<String> r = KeyMap.range(opt.args().get(i));
if (r == null) {
err.println("keymap: malformed key range `" + opt.args().get(i) + "'");
return;
}
map.bind(bout, r);
} else {
String in = KeyMap.translate(opt.args().get(i));
map.bind(bout, in);
}
}
if (opt.isSet("e") || opt.isSet("v")) {
keyMaps.put(LineReader.MAIN, map);
}
}
else {
// Select keymap
String keyMapName = LineReader.MAIN;
int sel = (opt.isSet("a") ? 1 : 0)
+ (opt.isSet("e") ? 1 : 0)
+ (opt.isSet("v") ? 1 : 0)
+ (opt.isSet("M") ? 1 : 0);
if (sel > 1) {
err.println("keymap: incompatible keymap selection options");
return;
} else if (opt.isSet("a")) {
keyMapName = LineReader.VICMD;
} else if (opt.isSet("e")) {
keyMapName = LineReader.EMACS;
} else if (opt.isSet("v")) {
keyMapName = LineReader.VIINS;
} else if (opt.isSet("M")) {
if (opt.args().isEmpty()) {
err.println("keymap: argument expected: -M");
return;
}
keyMapName = opt.args().remove(0);
}
KeyMap<Binding> map = keyMaps.get(keyMapName);
if (map == null) {
err.println("keymap: no such keymap `" + keyMapName + "'");
return;
}
// Display
boolean prefix = opt.isSet("p");
boolean commands = opt.isSet("L");
if (prefix && opt.args().isEmpty()) {
err.println("keymap: option -p requires a prefix string");
return;
}
if (opt.args().size() > 0 || !opt.isSet("e") && !opt.isSet("v")) {
Map<String, Binding> bound = map.getBoundKeys();
String seq = opt.args().size() > 0 ? KeyMap.translate(opt.args().get(0)) : null;
Map.Entry<String, Binding> begin = null;
String last = null;
Iterator<Entry<String, Binding>> iterator = bound.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Binding> entry = iterator.next();
String key = entry.getKey();
if (seq == null
|| prefix && key.startsWith(seq) && !key.equals(seq)
|| !prefix && key.equals(seq)) {
if (begin != null || !iterator.hasNext()) {
String n = (last.length() > 1 ? last.substring(0, last.length() - 1) : "") + (char) (last.charAt(last.length() - 1) + 1);
if (key.equals(n) && entry.getValue().equals(begin.getValue())) {
last = key;
} else {
// We're not in a range, so we need to close the previous range
StringBuilder sb = new StringBuilder();
if (commands) {
sb.append("keymap -M ");
sb.append(keyMapName);
sb.append(" ");
}
if (begin.getKey().equals(last)) {
sb.append(KeyMap.display(last));
sb.append(" ");
displayValue(sb, begin.getValue());
out.println(sb.toString());
} else {
if (commands) {
sb.append("-R ");
}
sb.append(KeyMap.display(begin.getKey()));
sb.append("-");
sb.append(KeyMap.display(last));
sb.append(" ");
displayValue(sb, begin.getValue());
out.println(sb.toString());
}
begin = entry;
last = key;
}
} else {
begin = entry;
last = key;
}
}
}
}
if (opt.isSet("e") || opt.isSet("v")) {
keyMaps.put(LineReader.MAIN, map);
}
}
}
public static void setopt(LineReader reader,
PrintStream out,
PrintStream err,
String[] argv) throws HelpException {
final String[] usage = {
"setopt - set options",
"Usage: setopt [-m] option ...",
" setopt",
" -? --help Displays command help",
" -m Use pattern matching"
};
Options opt = Options.compile(usage).parse(argv);
if (opt.isSet("help")) {
throw new HelpException(opt.usage());
}
if (opt.args().isEmpty()) {
for (Option option : Option.values()) {
if (reader.isSet(option) != option.isDef()) {
out.println((option.isDef() ? "no-" : "") + option.toString().toLowerCase().replace('_', '-'));
}
}
}
else {
boolean match = opt.isSet("m");
doSetOpts(reader, out, err, opt.args(), match, true);
}
}
public static void unsetopt(LineReader reader,
PrintStream out,
PrintStream err,
String[] argv) throws HelpException {
final String[] usage = {
"unsetopt - unset options",
"Usage: unsetopt [-m] option ...",
" unsetopt",
" -? --help Displays command help",
" -m Use pattern matching"
};
Options opt = Options.compile(usage).parse(argv);
if (opt.isSet("help")) {
throw new HelpException(opt.usage());
}
if (opt.args().isEmpty()) {
for (Option option : Option.values()) {
if (reader.isSet(option) == option.isDef()) {
out.println((option.isDef() ? "no-" : "") + option.toString().toLowerCase().replace('_', '-'));
}
}
}
else {
boolean match = opt.isSet("m");
doSetOpts(reader, out, err, opt.args(), match, false);
}
}
private static void doSetOpts(LineReader reader, PrintStream out, PrintStream err, List<String> options, boolean match, boolean set) {
for (String name : options) {
String tname = name.toLowerCase().replaceAll("[-_]", "");
if (match) {
tname = tname.replaceAll("\\*", "[a-z]*");
tname = tname.replaceAll("\\?", "[a-z]");
}
boolean found = false;
for (LineReader.Option option : LineReader.Option.values()) {
String optName = option.name().toLowerCase().replaceAll("[-_]", "");
if (match ? optName.matches(tname) : optName.equals(tname)) {
if (set) {
reader.setOpt(option);
} else {
reader.unsetOpt(option);
}
found = true;
if (!match) {
break;
}
} else if (match ? ("no" + optName).matches(tname) : ("no" + optName).equals(tname)) {
if (set) {
reader.unsetOpt(option);
} else {
reader.setOpt(option);
}
if (!match) {
found = true;
}
break;
}
}
if (!found) {
err.println("No matching option: " + name);
}