/
ConsoleReader.java
2185 lines (1849 loc) · 67.2 KB
/
ConsoleReader.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-2007, Marc Prud'hommeaux. All rights reserved.
*
* This software is distributable under the BSD license. See the terms of the
* BSD license in the documentation provided with this software.
*/
package scala.tools.jline.console;
import scala.tools.jline.Terminal;
import scala.tools.jline.TerminalFactory;
import scala.tools.jline.console.completer.CandidateListCompletionHandler;
import scala.tools.jline.console.completer.Completer;
import scala.tools.jline.console.completer.CompletionHandler;
import scala.tools.jline.console.history.History;
import scala.tools.jline.console.history.MemoryHistory;
import scala.tools.jline.internal.Configuration;
import scala.tools.jline.internal.Log;
import org.fusesource.jansi.AnsiOutputStream;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
/**
* A reader for console applications. It supports custom tab-completion,
* saveable command history, and command line editing. On some platforms,
* platform-specific commands will need to be issued before the reader will
* function properly. See {@link jline.Terminal#init} for convenience
* methods for issuing platform-specific setup commands.
*
* @author <a href="mailto:mwp1@cornell.edu">Marc Prud'hommeaux</a>
* @author <a href="mailto:jason@planet57.com">Jason Dillon</a>
*/
public class ConsoleReader
{
public static final String JLINE_NOBELL = "jline.nobell";
public static final String JLINE_EXPANDEVENTS = "jline.expandevents";
public static final char BACKSPACE = '\b';
public static final char RESET_LINE = '\r';
public static final char KEYBOARD_BELL = '\07';
public static final char NULL_MASK = 0;
public static final int TAB_WIDTH = 4;
private static final ResourceBundle
resources = ResourceBundle.getBundle(CandidateListCompletionHandler.class.getName());
private final Terminal terminal;
private InputStream in;
private final Writer out;
private final CursorBuffer buf = new CursorBuffer();
private String prompt;
private boolean bellEnabled = true;
private boolean expandEvents = false;
private Character mask;
private Character echoCharacter;
private StringBuffer searchTerm = null;
private String previousSearchTerm = "";
private int searchIndex = -1;
public ConsoleReader(final InputStream in, final OutputStream out, final InputStream bindings, final Terminal term) throws
IOException
{
this.in = in;
this.terminal = term != null ? term : TerminalFactory.get();
this.out = new PrintWriter(getTerminal().wrapOutIfNeeded(out));
this.keyBindings = loadKeyBindings(bindings);
setBellEnabled(!Configuration.getBoolean(JLINE_NOBELL, false));
setExpandEvents(Configuration.getBoolean(JLINE_EXPANDEVENTS, false));
}
/**
* @deprecated use {@link #ConsoleReader(InputStream, OutputStream, InputStream, Terminal)}
* to let the terminal wrap the output stream if needed.
*/
public ConsoleReader(final InputStream in, final Writer out, final InputStream bindings, final Terminal term) throws
IOException
{
this.in = in;
this.out = out;
this.terminal = term != null ? term : TerminalFactory.get();
this.keyBindings = loadKeyBindings(bindings);
setBellEnabled(!Configuration.getBoolean(JLINE_NOBELL, false));
}
/**
* @deprecated use {@link #ConsoleReader(InputStream, OutputStream, InputStream, Terminal)}
* to let the terminal wrap the output stream if needed.
*/
public ConsoleReader(final InputStream in, final Writer out, final Terminal term) throws IOException {
this(in, out, null, term);
}
/**
* @deprecated use {@link #ConsoleReader(InputStream, OutputStream, InputStream, Terminal)}
* to let the terminal wrap the output stream if needed.
*/
public ConsoleReader(final InputStream in, final Writer out) throws IOException
{
this(in, out, null, null);
}
/**
* Create a new reader using {@link FileDescriptor#in} for input and
* {@link System#out} for output.
* <p/>
* {@link FileDescriptor#in} is used because it has a better chance of not being buffered.
*/
public ConsoleReader() throws IOException {
this(new FileInputStream(FileDescriptor.in), System.out, null, null );
}
// FIXME: Only used for tests
void setInput(final InputStream in) {
this.in = in;
}
public InputStream getInput() {
return in;
}
public Writer getOutput() {
return out;
}
public Terminal getTerminal() {
return terminal;
}
public CursorBuffer getCursorBuffer() {
return buf;
}
public void setBellEnabled(final boolean enabled) {
this.bellEnabled = enabled;
}
public boolean isBellEnabled() {
return bellEnabled;
}
public void setExpandEvents(final boolean expand) {
this.expandEvents = expand;
}
public boolean getExpandEvents() {
return expandEvents;
}
public void setPrompt(final String prompt) {
this.prompt = prompt;
}
public String getPrompt() {
return prompt;
}
/**
* Set the echo character. For example, to have "*" entered when a password is typed:
* <p/>
* <pre>
* myConsoleReader.setEchoCharacter(new Character('*'));
* </pre>
* <p/>
* Setting the character to
* <p/>
* <pre>
* null
* </pre>
* <p/>
* will restore normal character echoing. Setting the character to
* <p/>
* <pre>
* new Character(0)
* </pre>
* <p/>
* will cause nothing to be echoed.
*
* @param c the character to echo to the console in place of the typed character.
*/
public void setEchoCharacter(final Character c) {
this.echoCharacter = c;
}
/**
* Returns the echo character.
*/
public Character getEchoCharacter() {
return echoCharacter;
}
/**
* Erase the current line.
*
* @return false if we failed (e.g., the buffer was empty)
*/
protected final boolean resetLine() throws IOException {
if (buf.cursor == 0) {
return false;
}
backspaceAll();
return true;
}
int getCursorPosition() {
// FIXME: does not handle anything but a line with a prompt absolute position
String prompt = getPrompt();
return ((prompt == null) ? 0 : stripAnsi(lastLine(prompt)).length()) + buf.cursor;
}
/**
* Returns the text after the last '\n'.
* prompt is returned if no '\n' characters are present.
* null is returned if prompt is null.
*/
private String lastLine(String str) {
if (str == null) return "";
int last = str.lastIndexOf("\n");
if (last >= 0) {
return str.substring(last + 1, str.length());
}
return str;
}
private String stripAnsi(String str) {
if (str == null) return "";
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
AnsiOutputStream aos = new AnsiOutputStream(baos);
aos.write(str.getBytes());
aos.flush();
return baos.toString();
} catch (IOException e) {
return str;
}
}
/**
* Move the cursor position to the specified absolute index.
*/
public final boolean setCursorPosition(final int position) throws IOException {
return moveCursor(position - buf.cursor) != 0;
}
/**
* Set the current buffer's content to the specified {@link String}. The
* visual console will be modified to show the current buffer.
*
* @param buffer the new contents of the buffer.
*/
private void setBuffer(final String buffer) throws IOException {
// don't bother modifying it if it is unchanged
if (buffer.equals(buf.buffer.toString())) {
return;
}
// obtain the difference between the current buffer and the new one
int sameIndex = 0;
for (int i = 0, l1 = buffer.length(), l2 = buf.buffer.length(); (i < l1)
&& (i < l2); i++) {
if (buffer.charAt(i) == buf.buffer.charAt(i)) {
sameIndex++;
}
else {
break;
}
}
int diff = buf.cursor - sameIndex;
if (diff < 0) { // we can't backspace here so try from the end of the buffer
moveToEnd();
diff = buf.buffer.length() - sameIndex;
}
backspace(diff); // go back for the differences
killLine(); // clear to the end of the line
buf.buffer.setLength(sameIndex); // the new length
putString(buffer.substring(sameIndex)); // append the differences
}
private void setBuffer(final CharSequence buffer) throws IOException {
setBuffer(String.valueOf(buffer));
}
/**
* Output put the prompt + the current buffer
*/
public final void drawLine() throws IOException {
String prompt = getPrompt();
if (prompt != null) {
print(prompt);
}
print(buf.buffer.toString());
if (buf.length() != buf.cursor) { // not at end of line
back(buf.length() - buf.cursor - 1);
}
// force drawBuffer to check for weird wrap (after clear screen)
drawBuffer();
}
/**
* Clear the line and redraw it.
*/
public final void redrawLine() throws IOException {
print(RESET_LINE);
// flush();
drawLine();
}
/**
* Clear the buffer and add its contents to the history.
*
* @return the former contents of the buffer.
*/
final String finishBuffer() throws IOException { // FIXME: Package protected because used by tests
String str = buf.buffer.toString();
if (expandEvents) {
str = expandEvents(str);
}
// we only add it to the history if the buffer is not empty
// and if mask is null, since having a mask typically means
// the string was a password. We clear the mask after this call
if (str.length() > 0) {
if (mask == null && isHistoryEnabled()) {
history.add(str);
}
else {
mask = null;
}
}
history.moveToEnd();
buf.buffer.setLength(0);
buf.cursor = 0;
return str;
}
/**
* Expand event designator such as !!, !#, !3, etc...
* See http://www.gnu.org/software/bash/manual/html_node/Event-Designators.html
*
* @param str
* @return
*/
protected String expandEvents(String str) throws IOException {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
switch (c) {
case '!':
if (i + 1 < str.length()) {
c = str.charAt(++i);
boolean neg = false;
String rep = null;
int i1, idx;
switch (c) {
case '!':
if (history.size() == 0) {
throw new IllegalArgumentException("!!: event not found");
}
rep = history.get(history.index() - 1).toString();
break;
case '#':
sb.append(sb.toString());
break;
case '?':
i1 = str.indexOf('?', i + 1);
if (i1 < 0) {
i1 = str.length();
}
String sc = str.substring(i + 1, i1);
i = i1;
idx = searchBackwards(sc);
if (idx < 0) {
throw new IllegalArgumentException("!?" + sc + ": event not found");
} else {
rep = history.get(idx).toString();
}
break;
case ' ':
case '\t':
sb.append('!');
sb.append(c);
break;
case '-':
neg = true;
i++;
// fall through
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
i1 = i;
for (; i < str.length(); i++) {
c = str.charAt(i);
if (c < '0' || c > '9') {
break;
}
}
idx = 0;
try {
idx = Integer.parseInt(str.substring(i1, i));
} catch (NumberFormatException e) {
throw new IllegalArgumentException((neg ? "!-" : "!") + str.substring(i1, i) + ": event not found");
}
if (neg) {
if (idx < history.size()) {
rep = (history.get(history.index() - idx)).toString();
} else {
throw new IllegalArgumentException((neg ? "!-" : "!") + str.substring(i1, i) + ": event not found");
}
} else {
if (idx >= history.index() - history.size() && idx < history.index()) {
rep = (history.get(idx)).toString();
} else {
throw new IllegalArgumentException((neg ? "!-" : "!") + str.substring(i1, i) + ": event not found");
}
}
break;
default:
String ss = str.substring(i);
i = str.length();
idx = searchBackwards(ss, history.index(), true);
if (idx < 0) {
throw new IllegalArgumentException("!" + ss + ": event not found");
} else {
rep = history.get(idx).toString();
}
break;
}
if (rep != null) {
sb.append(rep);
}
} else {
sb.append(c);
}
break;
case '^':
if (i == 0) {
int i1 = str.indexOf('^', i + 1);
int i2 = str.indexOf('^', i1 + 1);
if (i2 < 0) {
i2 = str.length();
}
if (i1 > 0 && i2 > 0) {
String s1 = str.substring(i + 1, i1);
String s2 = str.substring(i1 + 1, i2);
String s = history.get(history.index() - 1).toString().replace(s1, s2);
sb.append(s);
i = i2 + 1;
break;
}
}
sb.append(c);
break;
default:
sb.append(c);
break;
}
}
String result = sb.toString();
if (!str.equals(result)) {
print(result);
println();
flush();
}
return result;
}
/**
* Write out the specified string to the buffer and the output stream.
*/
public final void putString(final CharSequence str) throws IOException {
buf.write(str);
print(str);
drawBuffer();
}
/**
* Output the specified character, both to the buffer and the output stream.
*/
private void putChar(final int c, final boolean print) throws IOException {
buf.write((char) c);
if (print) {
if (mask == null) {
// no masking
print(c);
}
else if (mask == NULL_MASK) {
// Don't print anything
}
else {
print(mask);
}
drawBuffer();
}
}
/**
* Redraw the rest of the buffer from the cursor onwards. This is necessary
* for inserting text into the buffer.
*
* @param clear the number of characters to clear after the end of the buffer
*/
private void drawBuffer(final int clear) throws IOException {
// debug ("drawBuffer: " + clear);
if (buf.cursor == buf.length() && clear == 0) {
} else {
char[] chars = buf.buffer.substring(buf.cursor).toCharArray();
if (mask != null) {
Arrays.fill(chars, mask);
}
if (getTerminal().hasWeirdWrap()) {
// need to determine if wrapping will occur:
int width = getTerminal().getWidth();
int pos = getCursorPosition();
for (int i = 0; i < chars.length; i++) {
print(chars[i]);
if ((pos + i + 1) % width == 0) {
print(32); // move cursor to next line by printing dummy space
print(13); // CR / not newline.
}
}
} else {
print(chars);
}
clearAhead(clear, chars.length);
if (getTerminal().isAnsiSupported()) {
if (chars.length > 0) {
back(chars.length);
}
} else {
back(chars.length);
}
}
if (getTerminal().hasWeirdWrap()) {
int width = getTerminal().getWidth();
// best guess on whether the cursor is in that weird location...
// Need to do this without calling ansi cursor location methods
// otherwise it breaks paste of wrapped lines in xterm.
if (getCursorPosition() > 0 && (getCursorPosition() % width == 0)
&& buf.cursor == buf.length() && clear == 0) {
// the following workaround is reverse-engineered from looking
// at what bash sent to the terminal in the same situation
print(32); // move cursor to next line by printing dummy space
print(13); // CR / not newline.
}
}
}
/**
* Redraw the rest of the buffer from the cursor onwards. This is necessary
* for inserting text into the buffer.
*/
private void drawBuffer() throws IOException {
drawBuffer(0);
}
/**
* Clear ahead the specified number of characters without moving the cursor.
*
* @param num the number of characters to clear
* @param delta the difference between the internal cursor and the screen
* cursor - if > 0, assume some stuff was printed and weird wrap has to be
* checked
*/
private void clearAhead(final int num, int delta) throws IOException {
if (num == 0) {
return;
}
if (getTerminal().isAnsiSupported()) {
int width = getTerminal().getWidth();
int screenCursorCol = getCursorPosition() + delta;
// clear current line
printAnsiSequence("K");
// if cursor+num wraps, then we need to clear the line(s) below too
int curCol = screenCursorCol % width;
int endCol = (screenCursorCol + num - 1) % width;
int lines = num / width;
if (endCol < curCol) lines++;
for (int i = 0; i < lines; i++) {
printAnsiSequence("B");
printAnsiSequence("2K");
}
for (int i = 0; i < lines; i++) {
printAnsiSequence("A");
}
return;
}
// print blank extra characters
print(' ', num);
// we need to flush here so a "clever" console doesn't just ignore the redundancy
// of a space followed by a backspace.
// flush();
// reset the visual cursor
back(num);
// flush();
}
/**
* Move the visual cursor backwards without modifying the buffer cursor.
*/
protected void back(final int num) throws IOException {
if (num == 0) return;
if (getTerminal().isAnsiSupported()) {
int width = getTerminal().getWidth();
int cursor = getCursorPosition();
int realCursor = cursor + num;
int realCol = realCursor % width;
int newCol = cursor % width;
int moveup = num / width;
int delta = realCol - newCol;
if (delta < 0) moveup++;
if (moveup > 0) {
printAnsiSequence(moveup + "A");
}
printAnsiSequence((1 + newCol) + "G");
return;
}
print(BACKSPACE, num);
// flush();
}
/**
* Flush the console output stream. This is important for printout out single characters (like a backspace or
* keyboard) that we want the console to handle immediately.
*/
public void flush() throws IOException {
out.flush();
}
private int backspaceAll() throws IOException {
return backspace(Integer.MAX_VALUE);
}
/**
* Issue <em>num</em> backspaces.
*
* @return the number of characters backed up
*/
private int backspace(final int num) throws IOException {
if (buf.cursor == 0) {
return 0;
}
int count = 0;
int termwidth = getTerminal().getWidth();
int lines = getCursorPosition() / termwidth;
count = moveCursor(-1 * num) * -1;
buf.buffer.delete(buf.cursor, buf.cursor + count);
if (getCursorPosition() / termwidth != lines) {
if (getTerminal().isAnsiSupported()) {
// debug("doing backspace redraw: " + getCursorPosition() + " on " + termwidth + ": " + lines);
printAnsiSequence("K");
// if cursor+num wraps, then we need to clear the line(s) below too
// last char printed is one pos less than cursor so we subtract
// one
/*
// TODO: fixme (does not work - test with reverse search with wrapping line and CTRL-E)
int endCol = (getCursorPosition() + num - 1) % termwidth;
int curCol = getCursorPosition() % termwidth;
if (endCol < curCol) lines++;
for (int i = 1; i < lines; i++) {
printAnsiSequence("B");
printAnsiSequence("2K");
}
for (int i = 1; i < lines; i++) {
printAnsiSequence("A");
}
return count;
*/
}
}
drawBuffer(count);
return count;
}
/**
* Issue a backspace.
*
* @return true if successful
*/
public boolean backspace() throws IOException {
return backspace(1) == 1;
}
protected boolean moveToEnd() throws IOException {
return moveCursor(buf.length() - buf.cursor) > 0;
}
/**
* Delete the character at the current position and redraw the remainder of the buffer.
*/
private boolean deleteCurrentCharacter() throws IOException {
if (buf.length() == 0 || buf.cursor == buf.length()) {
return false;
}
buf.buffer.deleteCharAt(buf.cursor);
drawBuffer(1);
return true;
}
private boolean previousWord() throws IOException {
while (isDelimiter(buf.charLeftOfCursor()) && (moveCursor(-1) != 0)) {
// nothing
}
while (!isDelimiter(buf.charLeftOfCursor()) && (moveCursor(-1) != 0)) {
// nothing
}
return true;
}
private boolean nextWord() throws IOException {
while (isDelimiter(buf.charAtCursor()) && (moveCursor(1) != 0)) {
// nothing
}
while (!isDelimiter(buf.charAtCursor()) && (moveCursor(1) != 0)) {
// nothing
}
return true;
}
private boolean deletePreviousWord() throws IOException {
while (isDelimiter(buf.charLeftOfCursor()) && backspace()) {
// nothing
}
while (!isDelimiter(buf.charLeftOfCursor()) && backspace()) {
// nothing
}
return true;
}
private boolean deleteNextWord() throws IOException {
while (isDelimiter(buf.charAtCursor()) && deleteCurrentCharacter()) {
// nothing
}
while (!isDelimiter(buf.charAtCursor()) && deleteCurrentCharacter()) {
// nothing
}
return true;
}
/**
* Move the cursor <i>where</i> characters.
*
* @param num If less than 0, move abs(<i>where</i>) to the left, otherwise move <i>where</i> to the right.
* @return The number of spaces we moved
*/
public int moveCursor(final int num) throws IOException {
int where = num;
if ((buf.cursor == 0) && (where <= 0)) {
return 0;
}
if ((buf.cursor == buf.buffer.length()) && (where >= 0)) {
return 0;
}
if ((buf.cursor + where) < 0) {
where = -buf.cursor;
}
else if ((buf.cursor + where) > buf.buffer.length()) {
where = buf.buffer.length() - buf.cursor;
}
moveInternal(where);
return where;
}
/**
* Move the cursor <i>where</i> characters, without checking the current buffer.
*
* @param where the number of characters to move to the right or left.
*/
private void moveInternal(final int where) throws IOException {
// debug ("move cursor " + where + " ("
// + buf.cursor + " => " + (buf.cursor + where) + ")");
buf.cursor += where;
if (getTerminal().isAnsiSupported()) {
if (where < 0) {
back(Math.abs(where));
} else {
int width = getTerminal().getWidth();
int cursor = getCursorPosition();
int oldLine = (cursor - where) / width;
int newLine = cursor / width;
if (newLine > oldLine) {
if (getTerminal().hasWeirdWrap()) {
// scroll up if at bottom
// note:
// on rxvt cywgin getTerminal().getHeight() is incorrect
// MacOs xterm does not seem to support scrolling
if (getCurrentAnsiRow() == getTerminal().getHeight()) {
printAnsiSequence((newLine - oldLine) + "S");
}
}
printAnsiSequence((newLine - oldLine) + "B");
}
printAnsiSequence(1 +(cursor % width) + "G");
}
// flush();
return;
}
char c;
if (where < 0) {
int len = 0;
for (int i = buf.cursor; i < buf.cursor - where; i++) {
if (buf.buffer.charAt(i) == '\t') {
len += TAB_WIDTH;
}
else {
len++;
}
}
char chars[] = new char[len];
Arrays.fill(chars, BACKSPACE);
out.write(chars);
return;
}
else if (buf.cursor == 0) {
return;
}
else if (mask != null) {
c = mask;
}
else {
print(buf.buffer.substring(buf.cursor - where, buf.cursor).toCharArray());
return;
}
// null character mask: don't output anything
if (mask == NULL_MASK) {
return;
}
print(c, Math.abs(where));
}
// FIXME: replace() is not used
public final boolean replace(final int num, final String replacement) {
buf.buffer.replace(buf.cursor - num, buf.cursor, replacement);
try {
moveCursor(-num);
drawBuffer(Math.max(0, num - replacement.length()));
moveCursor(replacement.length());
}
catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
//
// Key reading
//
/**
* Read a character from the console.
*
* @return the character, or -1 if an EOF is received.
*/
public final int readVirtualKey() throws IOException {
int c = getTerminal().readVirtualKey(in);
Log.trace("Keystroke: ", c);
// clear any echo characters
clearEcho(c);
return c;
}
/**
* Clear the echoed characters for the specified character code.
*/
private int clearEcho(final int c) throws IOException {
// if the terminal is not echoing, then ignore
if (!getTerminal().isEchoEnabled()) {
return 0;
}
// otherwise, clear
int num = countEchoCharacters((char) c);
back(num);
drawBuffer(num);
return num;
}
private int countEchoCharacters(final char c) {
// tabs as special: we need to determine the number of spaces
// to cancel based on what out current cursor position is
if (c == 9) {
int tabStop = 8; // will this ever be different?
int position = getCursorPosition();
return tabStop - (position % tabStop);
}
return getPrintableCharacters(c).length();
}
/**
* Return the number of characters that will be printed when the specified
* character is echoed to the screen
*
* Adapted from cat by Torbjorn Granlund, as repeated in stty by David MacKenzie.
*/
private StringBuilder getPrintableCharacters(final char ch) {
StringBuilder sbuff = new StringBuilder();
if (ch >= 32) {
if (ch < 127) {
sbuff.append(ch);
}
else if (ch == 127) {
sbuff.append('^');
sbuff.append('?');
}
else {
sbuff.append('M');
sbuff.append('-');
if (ch >= (128 + 32)) {
if (ch < (128 + 127)) {
sbuff.append((char) (ch - 128));
}
else {
sbuff.append('^');
sbuff.append('?');