/
LineReaderImpl.java
6146 lines (5635 loc) · 218 KB
/
LineReaderImpl.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-2020, 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.reader.impl;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Flushable;
import java.io.IOError;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.lang.reflect.Constructor;
import java.time.Instant;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.jline.keymap.BindingReader;
import org.jline.keymap.KeyMap;
import org.jline.reader.*;
import org.jline.reader.Parser.ParseContext;
import org.jline.reader.impl.history.DefaultHistory;
import org.jline.terminal.*;
import org.jline.terminal.Attributes.ControlChar;
import org.jline.terminal.Terminal.Signal;
import org.jline.terminal.Terminal.SignalHandler;
import org.jline.terminal.impl.AbstractWindowsTerminal;
import org.jline.utils.AttributedString;
import org.jline.utils.AttributedStringBuilder;
import org.jline.utils.AttributedStyle;
import org.jline.utils.Curses;
import org.jline.utils.Display;
import org.jline.utils.InfoCmp.Capability;
import org.jline.utils.Levenshtein;
import org.jline.utils.Log;
import org.jline.utils.Status;
import org.jline.utils.WCWidth;
import static org.jline.keymap.KeyMap.alt;
import static org.jline.keymap.KeyMap.ctrl;
import static org.jline.keymap.KeyMap.del;
import static org.jline.keymap.KeyMap.esc;
import static org.jline.keymap.KeyMap.range;
import static org.jline.keymap.KeyMap.translate;
/**
* A reader for terminal applications. It supports custom tab-completion,
* saveable command history, and command line editing.
*
* @author <a href="mailto:mwp1@cornell.edu">Marc Prud'hommeaux</a>
* @author <a href="mailto:jason@planet57.com">Jason Dillon</a>
* @author <a href="mailto:gnodet@gmail.com">Guillaume Nodet</a>
*/
@SuppressWarnings("StatementWithEmptyBody")
public class LineReaderImpl implements LineReader, Flushable
{
public static final char NULL_MASK = 0;
public static final int TAB_WIDTH = 4;
public static final String DEFAULT_WORDCHARS = "*?_-.[]~=/&;!#$%^(){}<>";
public static final String DEFAULT_REMOVE_SUFFIX_CHARS = " \t\n;&|";
public static final String DEFAULT_COMMENT_BEGIN = "#";
public static final String DEFAULT_SEARCH_TERMINATORS = "\033\012";
public static final String DEFAULT_BELL_STYLE = "";
public static final int DEFAULT_LIST_MAX = 100;
public static final int DEFAULT_ERRORS = 2;
public static final long DEFAULT_BLINK_MATCHING_PAREN = 500L;
public static final long DEFAULT_AMBIGUOUS_BINDING = 1000L;
public static final String DEFAULT_SECONDARY_PROMPT_PATTERN = "%M> ";
public static final String DEFAULT_OTHERS_GROUP_NAME = "others";
public static final String DEFAULT_ORIGINAL_GROUP_NAME = "original";
public static final String DEFAULT_COMPLETION_STYLE_STARTING = "36"; // cyan
public static final String DEFAULT_COMPLETION_STYLE_DESCRIPTION = "90"; // dark gray
public static final String DEFAULT_COMPLETION_STYLE_GROUP = "35;1"; // magenta
public static final String DEFAULT_COMPLETION_STYLE_SELECTION = "7"; // inverted
public static final int DEFAULT_INDENTATION = 0;
public static final int DEFAULT_FEATURES_MAX_BUFFER_SIZE = 1000;
private static final int MIN_ROWS = 3;
public static final String BRACKETED_PASTE_ON = "\033[?2004h";
public static final String BRACKETED_PASTE_OFF = "\033[?2004l";
public static final String BRACKETED_PASTE_BEGIN = "\033[200~";
public static final String BRACKETED_PASTE_END = "\033[201~";
public static final String FOCUS_IN_SEQ = "\033[I";
public static final String FOCUS_OUT_SEQ = "\033[O";
/**
* Possible states in which the current readline operation may be in.
*/
protected enum State {
/**
* The user is just typing away
*/
NORMAL,
/**
* readLine should exit and return the buffer content
*/
DONE,
/**
* readLine should exit and return empty String
*/
IGNORE,
/**
* readLine should exit and throw an EOFException
*/
EOF,
/**
* readLine should exit and throw an UserInterruptException
*/
INTERRUPT
}
protected enum ViMoveMode {
NORMAL,
YANK,
DELETE,
CHANGE
}
protected enum BellType {
NONE,
AUDIBLE,
VISIBLE
}
//
// Constructor variables
//
/** The terminal to use */
protected final Terminal terminal;
/** The application name */
protected final String appName;
/** The terminal keys mapping */
protected final Map<String, KeyMap<Binding>> keyMaps;
//
// Configuration
//
protected final Map<String, Object> variables;
protected History history = new DefaultHistory();
protected Completer completer = null;
protected Highlighter highlighter = new DefaultHighlighter();
protected Parser parser = new DefaultParser();
protected Expander expander = new DefaultExpander();
//
// State variables
//
protected final Map<Option, Boolean> options = new HashMap<>();
protected final Buffer buf = new BufferImpl();
protected String tailTip = "";
protected SuggestionType autosuggestion = SuggestionType.NONE;
protected final Size size = new Size();
protected AttributedString prompt = AttributedString.EMPTY;
protected AttributedString rightPrompt = AttributedString.EMPTY;
protected MaskingCallback maskingCallback;
protected Map<Integer, String> modifiedHistory = new HashMap<>();
protected Buffer historyBuffer = null;
protected CharSequence searchBuffer;
protected StringBuffer searchTerm = null;
protected boolean searchFailing;
protected boolean searchBackward;
protected int searchIndex = -1;
protected boolean doAutosuggestion;
// Reading buffers
protected final BindingReader bindingReader;
/**
* VI character find
*/
protected int findChar;
protected int findDir;
protected int findTailAdd;
/**
* VI history string search
*/
private int searchDir;
private String searchString;
/**
* Region state
*/
protected int regionMark;
protected RegionType regionActive;
private boolean forceChar;
private boolean forceLine;
/**
* The vi yank buffer
*/
protected String yankBuffer = "";
protected ViMoveMode viMoveMode = ViMoveMode.NORMAL;
protected KillRing killRing = new KillRing();
protected UndoTree<Buffer> undo = new UndoTree<>(this::setBuffer);
protected boolean isUndo;
/**
* State lock
*/
protected final ReentrantLock lock = new ReentrantLock();
/*
* Current internal state of the line reader
*/
protected State state = State.DONE;
protected final AtomicBoolean startedReading = new AtomicBoolean();
protected boolean reading;
protected Supplier<AttributedString> post;
protected Map<String, Widget> builtinWidgets;
protected Map<String, Widget> widgets;
protected int count;
protected int mult;
protected int universal = 4;
protected int repeatCount;
protected boolean isArgDigit;
protected ParsedLine parsedLine;
protected boolean skipRedisplay;
protected Display display;
protected boolean overTyping = false;
protected String keyMap;
protected int smallTerminalOffset = 0;
/*
* accept-and-infer-next-history, accept-and-hold & accept-line-and-down-history
*/
protected boolean nextCommandFromHistory = false;
protected int nextHistoryId = -1;
/*
* execute commands from commandsBuffer
*/
protected List<String> commandsBuffer = new ArrayList<>();
public LineReaderImpl(Terminal terminal) throws IOException {
this(terminal, null, null);
}
public LineReaderImpl(Terminal terminal, String appName) throws IOException {
this(terminal, appName, null);
}
public LineReaderImpl(Terminal terminal, String appName, Map<String, Object> variables) {
Objects.requireNonNull(terminal, "terminal can not be null");
this.terminal = terminal;
if (appName == null) {
appName = "JLine";
}
this.appName = appName;
if (variables != null) {
this.variables = variables;
} else {
this.variables = new HashMap<>();
}
this.keyMaps = defaultKeyMaps();
builtinWidgets = builtinWidgets();
widgets = new HashMap<>(builtinWidgets);
bindingReader = new BindingReader(terminal.reader());
doDisplay();
}
public Terminal getTerminal() {
return terminal;
}
public String getAppName() {
return appName;
}
public Map<String, KeyMap<Binding>> getKeyMaps() {
return keyMaps;
}
public KeyMap<Binding> getKeys() {
return keyMaps.get(keyMap);
}
@Override
public Map<String, Widget> getWidgets() {
return widgets;
}
@Override
public Map<String, Widget> getBuiltinWidgets() {
return Collections.unmodifiableMap(builtinWidgets);
}
@Override
public Buffer getBuffer() {
return buf;
}
@Override
public void setAutosuggestion(SuggestionType type) {
this.autosuggestion = type;
}
@Override
public SuggestionType getAutosuggestion() {
return autosuggestion;
}
@Override
public String getTailTip() {
return tailTip;
}
@Override
public void setTailTip(String tailTip) {
this.tailTip = tailTip;
}
@Override
public void runMacro(String macro) {
bindingReader.runMacro(macro);
}
@Override
public MouseEvent readMouseEvent() {
return terminal.readMouseEvent(bindingReader::readCharacter);
}
/**
* Set the completer.
*
* @param completer the completer to use
*/
public void setCompleter(Completer completer) {
this.completer = completer;
}
/**
* Returns the completer.
*
* @return the completer
*/
public Completer getCompleter() {
return completer;
}
//
// History
//
public void setHistory(final History history) {
Objects.requireNonNull(history);
this.history = history;
}
public History getHistory() {
return history;
}
//
// Highlighter
//
public void setHighlighter(Highlighter highlighter) {
this.highlighter = highlighter;
}
public Highlighter getHighlighter() {
return highlighter;
}
public Parser getParser() {
return parser;
}
public void setParser(Parser parser) {
this.parser = parser;
}
@Override
public Expander getExpander() {
return expander;
}
public void setExpander(Expander expander) {
this.expander = expander;
}
//
// Line Reading
//
/**
* Read the next line and return the contents of the buffer.
*
* @return A line that is read from the terminal, can never be null.
*/
public String readLine() throws UserInterruptException, EndOfFileException {
return readLine(null, null, (MaskingCallback) null, null);
}
/**
* Read the next line with the specified character mask. If null, then
* characters will be echoed. If 0, then no characters will be echoed.
*
* @param mask The mask character, <code>null</code> or <code>0</code>.
* @return A line that is read from the terminal, can never be null.
*/
public String readLine(Character mask) throws UserInterruptException, EndOfFileException {
return readLine(null, null, mask, null);
}
/**
* Read a line from the <i>in</i> {@link InputStream}, and return the line
* (without any trailing newlines).
*
* @param prompt The prompt to issue to the terminal, may be null.
* @return A line that is read from the terminal, can never be null.
*/
public String readLine(String prompt) throws UserInterruptException, EndOfFileException {
return readLine(prompt, null, (MaskingCallback) null, null);
}
/**
* Read a line from the <i>in</i> {@link InputStream}, and return the line
* (without any trailing newlines).
*
* @param prompt The prompt to issue to the terminal, may be null.
* @param mask The mask character, <code>null</code> or <code>0</code>.
* @return A line that is read from the terminal, can never be null.
*/
public String readLine(String prompt, Character mask) throws UserInterruptException, EndOfFileException {
return readLine(prompt, null, mask, null);
}
/**
* Read a line from the <i>in</i> {@link InputStream}, and return the line
* (without any trailing newlines).
*
* @param prompt The prompt to issue to the terminal, may be null.
* @param mask The mask character, <code>null</code> or <code>0</code>.
* @param buffer A string that will be set for editing.
* @return A line that is read from the terminal, can never be null.
*/
public String readLine(String prompt, Character mask, String buffer) throws UserInterruptException, EndOfFileException {
return readLine(prompt, null, mask, buffer);
}
/**
* Read a line from the <i>in</i> {@link InputStream}, and return the line
* (without any trailing newlines).
*
* @param prompt The prompt to issue to the terminal, may be null.
* @param rightPrompt The prompt to issue to the right of the terminal, may be null.
* @param mask The mask character, <code>null</code> or <code>0</code>.
* @param buffer A string that will be set for editing.
* @return A line that is read from the terminal, can never be null.
*/
public String readLine(String prompt, String rightPrompt, Character mask, String buffer) throws UserInterruptException, EndOfFileException {
return readLine(prompt, rightPrompt, mask != null ? new SimpleMaskingCallback(mask) : null, buffer);
}
/**
* Read a line from the <i>in</i> {@link InputStream}, and return the line
* (without any trailing newlines).
*
* @param prompt The prompt to issue to the terminal, may be null.
* @param rightPrompt The prompt to issue to the right of the terminal, may be null.
* @param maskingCallback The callback used to mask parts of the edited line.
* @param buffer A string that will be set for editing.
* @return A line that is read from the terminal, can never be null.
*/
public String readLine(String prompt, String rightPrompt, MaskingCallback maskingCallback, String buffer) throws UserInterruptException, EndOfFileException {
// prompt may be null
// maskingCallback may be null
// buffer may be null
if (!commandsBuffer.isEmpty()) {
String cmd = commandsBuffer.remove(0);
boolean done = false;
do {
try {
parser.parse(cmd, cmd.length() + 1, ParseContext.ACCEPT_LINE);
done = true;
} catch (EOFError e) {
if (commandsBuffer.isEmpty()) {
throw new IllegalArgumentException("Incompleted command: \n" + cmd);
}
cmd += "\n";
cmd += commandsBuffer.remove(0);
} catch (SyntaxError e) {
done = true;
} catch (Exception e) {
commandsBuffer.clear();
throw new IllegalArgumentException(e.getMessage());
}
} while (!done);
AttributedStringBuilder sb = new AttributedStringBuilder();
sb.styled(AttributedStyle::bold, cmd);
sb.toAttributedString().println(terminal);
terminal.flush();
return finish(cmd);
}
if (!startedReading.compareAndSet(false, true)) {
throw new IllegalStateException();
}
Thread readLineThread = Thread.currentThread();
SignalHandler previousIntrHandler = null;
SignalHandler previousWinchHandler = null;
SignalHandler previousContHandler = null;
Attributes originalAttributes = null;
boolean dumb = isTerminalDumb();
try {
this.maskingCallback = maskingCallback;
/*
* This is the accumulator for VI-mode repeat count. That is, while in
* move mode, if you type 30x it will delete 30 characters. This is
* where the "30" is accumulated until the command is struck.
*/
repeatCount = 0;
mult = 1;
regionActive = RegionType.NONE;
regionMark = -1;
smallTerminalOffset = 0;
state = State.NORMAL;
modifiedHistory.clear();
setPrompt(prompt);
setRightPrompt(rightPrompt);
buf.clear();
if (buffer != null) {
buf.write(buffer);
}
if (nextCommandFromHistory && nextHistoryId > 0) {
if (history.size() > nextHistoryId) {
history.moveTo(nextHistoryId);
} else {
history.moveTo(history.last());
}
buf.write(history.current());
} else {
nextHistoryId = -1;
}
nextCommandFromHistory = false;
undo.clear();
parsedLine = null;
keyMap = MAIN;
if (history != null) {
history.attach(this);
}
try {
lock.lock();
this.reading = true;
previousIntrHandler = terminal.handle(Signal.INT, signal -> readLineThread.interrupt());
previousWinchHandler = terminal.handle(Signal.WINCH, this::handleSignal);
previousContHandler = terminal.handle(Signal.CONT, this::handleSignal);
originalAttributes = terminal.enterRawMode();
doDisplay();
// Move into application mode
if (!dumb) {
terminal.puts(Capability.keypad_xmit);
if (isSet(Option.AUTO_FRESH_LINE))
callWidget(FRESH_LINE);
if (isSet(Option.MOUSE))
terminal.trackMouse(Terminal.MouseTracking.Normal);
if (isSet(Option.BRACKETED_PASTE))
terminal.writer().write(BRACKETED_PASTE_ON);
} else {
// For dumb terminals, we need to make sure that CR are ignored
Attributes attr = new Attributes(originalAttributes);
attr.setInputFlag(Attributes.InputFlag.IGNCR, true);
terminal.setAttributes(attr);
}
callWidget(CALLBACK_INIT);
undo.newState(buf.copy());
// Draw initial prompt
redrawLine();
redisplay();
} finally {
lock.unlock();
}
while (true) {
KeyMap<Binding> local = null;
if (isInViCmdMode() && regionActive != RegionType.NONE) {
local = keyMaps.get(VISUAL);
}
Binding o = readBinding(getKeys(), local);
if (o == null) {
throw new EndOfFileException();
}
Log.trace("Binding: ", o);
if (buf.length() == 0 && getLastBinding().charAt(0) == originalAttributes.getControlChar(ControlChar.VEOF)) {
throw new EndOfFileException();
}
// If this is still false after handling the binding, then
// we reset our repeatCount to 0.
isArgDigit = false;
// Every command that can be repeated a specified number
// of times, needs to know how many times to repeat, so
// we figure that out here.
count = ((repeatCount == 0) ? 1 : repeatCount) * mult;
// Reset undo/redo flag
isUndo = false;
// Reset region after a paste
if (regionActive == RegionType.PASTE) {
regionActive = RegionType.NONE;
}
try {
lock.lock();
// Get executable widget
Buffer copy = buf.length() <= getInt(FEATURES_MAX_BUFFER_SIZE, DEFAULT_FEATURES_MAX_BUFFER_SIZE) ? buf.copy() : null;
Widget w = getWidget(o);
if (!w.apply()) {
beep();
}
if (!isUndo && copy != null && buf.length() <= getInt(FEATURES_MAX_BUFFER_SIZE, DEFAULT_FEATURES_MAX_BUFFER_SIZE)
&& !copy.toString().equals(buf.toString())) {
undo.newState(buf.copy());
}
switch (state) {
case DONE:
return finishBuffer();
case IGNORE:
return "";
case EOF:
throw new EndOfFileException();
case INTERRUPT:
throw new UserInterruptException(buf.toString());
}
if (!isArgDigit) {
/*
* If the operation performed wasn't a vi argument
* digit, then clear out the current repeatCount;
*/
repeatCount = 0;
mult = 1;
}
if (!dumb) {
redisplay();
}
} finally {
lock.unlock();
}
}
} catch (IOError e) {
if (e.getCause() instanceof InterruptedIOException) {
throw new UserInterruptException(buf.toString());
} else {
throw e;
}
}
finally {
try {
lock.lock();
this.reading = false;
cleanup();
if (originalAttributes != null) {
terminal.setAttributes(originalAttributes);
}
if (previousIntrHandler != null) {
terminal.handle(Signal.INT, previousIntrHandler);
}
if (previousWinchHandler != null) {
terminal.handle(Signal.WINCH, previousWinchHandler);
}
if (previousContHandler != null) {
terminal.handle(Signal.CONT, previousContHandler);
}
} finally {
lock.unlock();
}
startedReading.set(false);
}
}
private boolean isTerminalDumb() {
return Terminal.TYPE_DUMB.equals(terminal.getType())
|| Terminal.TYPE_DUMB_COLOR.equals(terminal.getType());
}
private void doDisplay() {
// Cache terminal size for the duration of the call to readLine()
// It will eventually be updated with WINCH signals
size.copy(terminal.getBufferSize());
display = new Display(terminal, false);
if (size.getRows() == 0 || size.getColumns() == 0) {
display.resize(1, Integer.MAX_VALUE);
} else {
display.resize(size.getRows(), size.getColumns());
}
if (isSet(Option.DELAY_LINE_WRAP))
display.setDelayLineWrap(true);
}
@Override
public void printAbove(String str) {
try {
lock.lock();
boolean reading = this.reading;
if (reading) {
display.update(Collections.emptyList(), 0);
}
if (str.endsWith("\n") || str.endsWith("\n\033[m") || str.endsWith("\n\033[0m")) {
terminal.writer().print(str);
} else {
terminal.writer().println(str);
}
if (reading) {
redisplay(false);
}
terminal.flush();
} finally {
lock.unlock();
}
}
@Override
public void printAbove(AttributedString str) {
printAbove(str.toAnsi(terminal));
}
@Override
public boolean isReading() {
try {
lock.lock();
return reading;
} finally {
lock.unlock();
}
}
/* Make sure we position the cursor on column 0 */
protected boolean freshLine() {
boolean wrapAtEol = terminal.getBooleanCapability(Capability.auto_right_margin);
boolean delayedWrapAtEol = wrapAtEol && terminal.getBooleanCapability(Capability.eat_newline_glitch);
AttributedStringBuilder sb = new AttributedStringBuilder();
sb.style(AttributedStyle.DEFAULT.foreground(AttributedStyle.BLACK + AttributedStyle.BRIGHT));
sb.append("~");
sb.style(AttributedStyle.DEFAULT);
if (!wrapAtEol || delayedWrapAtEol) {
for (int i = 0; i < size.getColumns() - 1; i++) {
sb.append(" ");
}
sb.append(KeyMap.key(terminal, Capability.carriage_return));
sb.append(" ");
sb.append(KeyMap.key(terminal, Capability.carriage_return));
} else {
// Given the terminal will wrap automatically,
// we need to print one less than needed.
// This means that the last character will not
// be overwritten, and that's why we're using
// a clr_eol first if possible.
String el = terminal.getStringCapability(Capability.clr_eol);
if (el != null) {
Curses.tputs(sb, el);
}
for (int i = 0; i < size.getColumns() - 2; i++) {
sb.append(" ");
}
sb.append(KeyMap.key(terminal, Capability.carriage_return));
sb.append(" ");
sb.append(KeyMap.key(terminal, Capability.carriage_return));
}
sb.print(terminal);
return true;
}
@Override
public void callWidget(String name) {
try {
lock.lock();
if (!reading) {
throw new IllegalStateException("Widgets can only be called during a `readLine` call");
}
try {
Widget w;
if (name.startsWith(".")) {
w = builtinWidgets.get(name.substring(1));
} else {
w = widgets.get(name);
}
if (w != null) {
w.apply();
}
} catch (Throwable t) {
Log.debug("Error executing widget '", name, "'", t);
}
} finally {
lock.unlock();
}
}
/**
* Clear the line and redraw it.
* @return <code>true</code>
*/
public boolean redrawLine() {
display.reset();
return true;
}
/**
* Write out the specified string to the buffer and the output stream.
* @param str the char sequence to write in the buffer
*/
public void putString(final CharSequence str) {
buf.write(str, overTyping);
}
/**
* Flush the terminal output stream. This is important for printout out single
* characters (like a buf.backspace or keyboard) that we want the terminal to
* handle immediately.
*/
public void flush() {
terminal.flush();
}
public boolean isKeyMap(String name) {
return keyMap.equals(name);
}
/**
* Read a character from the terminal.
*
* @return the character, or -1 if an EOF is received.
*/
public int readCharacter() {
if (lock.isHeldByCurrentThread()) {
try {
lock.unlock();
return bindingReader.readCharacter();
} finally {
lock.lock();
}
} else {
return bindingReader.readCharacter();
}
}
public int peekCharacter(long timeout) {
return bindingReader.peekCharacter(timeout);
}
protected <T> T doReadBinding(KeyMap<T> keys, KeyMap<T> local) {
if (lock.isHeldByCurrentThread()) {
try {
lock.unlock();
return bindingReader.readBinding(keys, local);
} finally {
lock.lock();
}
} else {
return bindingReader.readBinding(keys, local);
}
}
protected String doReadStringUntil(String sequence) {
if (lock.isHeldByCurrentThread()) {
try {
lock.unlock();
return bindingReader.readStringUntil(sequence);
} finally {
lock.lock();
}
} else {
return bindingReader.readStringUntil(sequence);
}
}
/**
* Read from the input stream and decode an operation from the key map.
*
* The input stream will be read character by character until a matching
* binding can be found. Characters that can't possibly be matched to
* any binding will be discarded.
*
* @param keys the KeyMap to use for decoding the input stream
* @return the decoded binding or <code>null</code> if the end of
* stream has been reached
*/
public Binding readBinding(KeyMap<Binding> keys) {
return readBinding(keys, null);
}
public Binding readBinding(KeyMap<Binding> keys, KeyMap<Binding> local) {
Binding o = doReadBinding(keys, local);
/*
* The kill ring keeps record of whether or not the
* previous command was a yank or a kill. We reset
* that state here if needed.
*/
if (o instanceof Reference) {
String ref = ((Reference) o).name();
if (!YANK_POP.equals(ref) && !YANK.equals(ref)) {
killRing.resetLastYank();
}
if (!KILL_LINE.equals(ref) && !KILL_WHOLE_LINE.equals(ref)
&& !BACKWARD_KILL_WORD.equals(ref) && !KILL_WORD.equals(ref)) {
killRing.resetLastKill();
}
}
return o;
}
@Override
public ParsedLine getParsedLine() {
return parsedLine;
}
@Override
public String getLastBinding() {
return bindingReader.getLastBinding();
}
@Override
public String getSearchTerm() {
return searchTerm != null ? searchTerm.toString() : null;
}
@Override
public RegionType getRegionActive() {
return regionActive;
}
@Override
public int getRegionMark() {
return regionMark;
}
//
// Key Bindings
//
/**
* Sets the current keymap by name. Supported keymaps are "emacs",
* "viins", "vicmd".
* @param name The name of the keymap to switch to
* @return true if the keymap was set, or false if the keymap is
* not recognized.
*/