-
Notifications
You must be signed in to change notification settings - Fork 212
/
Nano.java
3813 lines (3567 loc) · 143 KB
/
Nano.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.builtins;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.jline.keymap.BindingReader;
import org.jline.keymap.KeyMap;
import org.jline.reader.Editor;
import org.jline.terminal.Attributes;
import org.jline.terminal.Attributes.ControlChar;
import org.jline.terminal.Attributes.InputFlag;
import org.jline.terminal.Attributes.LocalFlag;
import org.jline.terminal.MouseEvent;
import org.jline.terminal.Size;
import org.jline.terminal.Terminal;
import org.jline.terminal.Terminal.Signal;
import org.jline.terminal.Terminal.SignalHandler;
import org.jline.utils.*;
import org.jline.utils.InfoCmp.Capability;
import org.mozilla.universalchardet.UniversalDetector;
import static org.jline.keymap.KeyMap.KEYMAP_LENGTH;
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.key;
public class Nano implements Editor {
// Final fields
protected final Terminal terminal;
protected final Display display;
protected final BindingReader bindingReader;
protected final Size size;
protected final Path root;
protected final int vsusp;
private final List<Path> syntaxFiles = new ArrayList<>();
// Keys
protected KeyMap<Operation> keys;
// Configuration
public String title = "JLine Nano 3.0.0";
public boolean printLineNumbers = false;
public boolean wrapping = false;
public boolean smoothScrolling = true;
public boolean mouseSupport = false;
public boolean oneMoreLine = true;
public boolean constantCursor = false;
public boolean quickBlank = false;
public int tabs = 4;
public String brackets = "\"’)>]}";
public String matchBrackets = "(<[{)>]}";
public String punct = "!.?";
public String quoteStr = "^([ \\t]*[#:>\\|}])+";
private boolean restricted = false;
private String syntaxName;
private boolean writeBackup = false;
private boolean atBlanks = false;
private boolean view = false;
private boolean cut2end = false;
private boolean tempFile = false;
private String historyLog = null;
private boolean tabsToSpaces = false;
private boolean autoIndent = false;
// Input
protected final List<Buffer> buffers = new ArrayList<>();
protected int bufferIndex;
protected Buffer buffer;
protected String message;
protected String errorMessage = null;
protected int nbBindings = 0;
protected LinkedHashMap<String, String> shortcuts;
protected String editMessage;
protected final StringBuilder editBuffer = new StringBuilder();
protected boolean searchCaseSensitive;
protected boolean searchRegexp;
protected boolean searchBackwards;
protected String searchTerm;
protected int matchedLength = -1;
protected PatternHistory patternHistory = new PatternHistory(null);
protected WriteMode writeMode = WriteMode.WRITE;
protected List<String> cutbuffer = new ArrayList<>();
protected boolean mark = false;
protected boolean highlight = true;
private boolean searchToReplace = false;
protected boolean readNewBuffer = true;
private boolean nanorcIgnoreErrors;
protected enum WriteMode {
WRITE,
APPEND,
PREPEND
}
protected enum WriteFormat {
UNIX,
DOS,
MAC
}
protected enum CursorMovement {
RIGHT,
LEFT,
STILL
}
public static String[] usage() {
return new String[]{
"nano - edit files",
"Usage: nano [OPTIONS] [FILES]",
" -? --help Show help",
" -B --backup When saving a file, back up the previous version of it, using the current filename",
" suffixed with a tilde (~)." ,
" -I --ignorercfiles Don't look at the system's nanorc nor at the user's nanorc." ,
" -Q --quotestr=regex Set the regular expression for matching the quoting part of a line.",
" -T --tabsize=number Set the size (width) of a tab to number columns.",
" -U --quickblank Do quick status-bar blanking: status-bar messages will disappear after 1 keystroke.",
" -c --constantshow Constantly show the cursor position on the status bar.",
" -e --emptyline Do not use the line below the title bar, leaving it entirely blank.",
" -j --jumpyscrolling Scroll the buffer contents per half-screen instead of per line.",
" -l --linenumbers Display line numbers to the left of the text area.",
" -m --mouse Enable mouse support, if available for your system.",
" -$ --softwrap Enable 'soft wrapping'. ",
" -a --atblanks Wrap lines at whitespace instead of always at the edge of the screen.",
" -R --restricted Restricted mode: don't allow suspending; don't allow a file to be appended to,",
" prepended to, or saved under a different name if it already has one;",
" and don't use backup files.",
" -Y --syntax=name The name of the syntax highlighting to use.",
" -z --suspend Enable the ability to suspend nano using the system's suspend keystroke (usually ^Z).",
" -v --view Don't allow the contents of the file to be altered: read-only mode.",
" -k --cutfromcursor Make the 'Cut Text' command cut from the current cursor position to the end of the line",
" -t --tempfile Save a changed buffer without prompting (when exiting with ^X).",
" -H --historylog=name Log search strings to file, so they can be retrieved in later sessions",
" -E --tabstospaces Convert typed tabs to spaces.",
" -i --autoindent Indent new lines to the previous line's indentation."
};
}
protected class Buffer {
String file;
Charset charset;
WriteFormat format = WriteFormat.UNIX;
List<String> lines;
int firstLineToDisplay;
int firstColumnToDisplay = 0;
int offsetInLineToDisplay;
int line;
List<LinkedList<Integer>> offsets = new ArrayList<>();
int offsetInLine;
int column;
int wantedColumn;
boolean uncut = false;
int[] markPos = {-1, -1}; // line, offsetInLine + column
SyntaxHighlighter syntaxHighlighter;
boolean dirty;
protected Buffer(String file) {
this.file = file;
this.syntaxHighlighter = SyntaxHighlighter.build(syntaxFiles, file, syntaxName, nanorcIgnoreErrors);
}
void open() throws IOException {
if (lines != null) {
return;
}
lines = new ArrayList<>();
lines.add("");
charset = Charset.defaultCharset();
computeAllOffsets();
if (file == null) {
return;
}
Path path = root.resolve(file);
if (Files.isDirectory(path)) {
setMessage("\"" + file + "\" is a directory");
return;
}
try (InputStream fis = Files.newInputStream(path))
{
read(fis);
} catch (IOException e) {
setMessage("Error reading " + file + ": " + e.getMessage());
}
}
void open(InputStream is) throws IOException {
if (lines != null) {
return;
}
lines = new ArrayList<>();
lines.add("");
charset = Charset.defaultCharset();
computeAllOffsets();
read(is);
}
void read(InputStream fis) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int remaining;
while ((remaining = fis.read(buffer)) > 0) {
bos.write(buffer, 0, remaining);
}
byte[] bytes = bos.toByteArray();
try {
UniversalDetector detector = new UniversalDetector(null);
detector.handleData(bytes, 0, bytes.length);
detector.dataEnd();
if (detector.getDetectedCharset() != null) {
charset = Charset.forName(detector.getDetectedCharset());
}
} catch (Throwable t) {
// Ignore
}
// TODO: detect format, do not eat last newline
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(new ByteArrayInputStream(bytes), charset))) {
String line;
lines.clear();
while ((line = reader.readLine()) != null) {
lines.add(line);
}
}
if (lines.isEmpty()) {
lines.add("");
}
computeAllOffsets();
moveToChar(0);
}
private int charPosition(int displayPosition) {
return charPosition(line, displayPosition, CursorMovement.STILL);
}
private int charPosition(int displayPosition, CursorMovement move) {
return charPosition(line, displayPosition, move);
}
private int charPosition(int line, int displayPosition) {
return charPosition(line, displayPosition, CursorMovement.STILL);
}
private int charPosition(int line, int displayPosition, CursorMovement move) {
int out = lines.get(line).length();
if (!lines.get(line).contains("\t") || displayPosition == 0) {
out = displayPosition;
} else if (displayPosition < length(lines.get(line))) {
int rdiff = 0;
int ldiff = 0;
for (int i = 0; i < lines.get(line).length(); i++) {
int dp = length(lines.get(line).substring(0, i));
if (move == CursorMovement.LEFT) {
if (dp <= displayPosition) {
out = i;
} else {
break;
}
} else if (move == CursorMovement.RIGHT) {
if (dp >= displayPosition) {
out = i;
break;
}
} else if (move == CursorMovement.STILL) {
if (dp <= displayPosition) {
ldiff = displayPosition - dp;
out = i;
} else if (dp >= displayPosition) {
rdiff = dp - displayPosition;
if (rdiff < ldiff) {
out = i;
}
break;
}
}
}
}
return out;
}
String blanks(int nb) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < nb; i++) {
sb.append(' ');
}
return sb.toString();
}
void insert(String insert) {
String text = lines.get(line);
int pos = charPosition(offsetInLine + column);
insert = insert.replaceAll("\r\n", "\n");
insert = insert.replaceAll("\r", "\n");
if (tabsToSpaces && insert.length() == 1 && insert.charAt(0) == '\t') {
int len = pos == text.length() ? length(text + insert) : length(text.substring(0, pos) + insert);
insert = blanks(len - offsetInLine - column);
}
if (autoIndent && insert.length() == 1 && insert.charAt(0) == '\n') {
for (char c : lines.get(line).toCharArray()) {
if (c == ' ') {
insert += c;
} else if (c == '\t') {
insert += c;
} else {
break;
}
}
}
String mod;
String tail = "";
if (pos == text.length()) {
mod = text + insert;
} else {
mod = text.substring(0, pos) + insert;
tail = text.substring(pos);
}
List<String> ins = new ArrayList<>();
int last = 0;
int idx = mod.indexOf('\n', last);
while (idx >= 0) {
ins.add(mod.substring(last, idx));
last = idx + 1;
idx = mod.indexOf('\n', last);
}
ins.add(mod.substring(last) + tail);
int curPos = length(mod.substring(last));
lines.set(line, ins.get(0));
offsets.set(line, computeOffsets(ins.get(0)));
for (int i = 1; i < ins.size(); i++) {
++line;
lines.add(line, ins.get(i));
offsets.add(line, computeOffsets(ins.get(i)));
}
moveToChar(curPos);
ensureCursorVisible();
dirty = true;
}
void computeAllOffsets() {
offsets.clear();
for (String text : lines) {
offsets.add(computeOffsets(text));
}
}
LinkedList<Integer> computeOffsets(String line) {
String text = new AttributedStringBuilder().tabs(tabs).append(line).toString();
int width = size.getColumns() - (printLineNumbers ? 8 : 0);
LinkedList<Integer> offsets = new LinkedList<>();
offsets.add(0);
if (wrapping) {
int last = 0;
int prevword = 0;
boolean inspace = false;
for (int i = 0; i < text.length(); i++) {
if (isBreakable(text.charAt(i))) {
inspace = true;
} else if (inspace) {
prevword = i;
inspace = false;
}
if (i == last + width - 1) {
if (prevword == last) {
prevword = i;
}
offsets.add(prevword);
last = prevword;
}
}
}
return offsets;
}
boolean isBreakable(char ch) {
return !atBlanks || ch == ' ';
}
void moveToChar(int pos) {
moveToChar(pos, CursorMovement.STILL);
}
void moveToChar(int pos, CursorMovement move) {
if (!wrapping) {
if (pos > column && pos - firstColumnToDisplay + 1 > width()) {
firstColumnToDisplay = offsetInLine + column - 6;
} else if (pos < column && firstColumnToDisplay + 5 > pos) {
firstColumnToDisplay = Math.max(0, firstColumnToDisplay - width() + 5);
}
}
if (lines.get(line).contains("\t")) {
int cpos = charPosition(pos, move);
if (cpos < lines.get(line).length()) {
pos = length(lines.get(line).substring(0, cpos));
} else {
pos = length(lines.get(line));
}
}
offsetInLine = prevLineOffset(line, pos + 1).get();
column = pos - offsetInLine;
}
void delete(int count) {
while (--count >= 0 && moveRight(1) && backspace(1));
}
boolean backspace(int count) {
while (count > 0) {
String text = lines.get(line);
int pos = charPosition(offsetInLine + column);
if (pos == 0) {
if (line == 0) {
bof();
return false;
}
String prev = lines.get(--line);
lines.set(line, prev + text);
offsets.set(line, computeOffsets(prev + text));
moveToChar(length(prev));
lines.remove(line + 1);
offsets.remove(line + 1);
count--;
} else {
int nb = Math.min(pos, count);
int curPos = length(text.substring(0, pos - nb));
text = text.substring(0, pos - nb) + text.substring(pos);
lines.set(line, text);
offsets.set(line, computeOffsets(text));
moveToChar(curPos);
count -= nb;
}
dirty = true;
}
ensureCursorVisible();
return true;
}
boolean moveLeft(int chars) {
boolean ret = true;
while (--chars >= 0) {
if (offsetInLine + column > 0) {
moveToChar(offsetInLine + column - 1, CursorMovement.LEFT);
} else if (line > 0) {
line--;
moveToChar(length(getLine(line)));
} else {
bof();
ret = false;
break;
}
}
wantedColumn = column;
ensureCursorVisible();
return ret;
}
boolean moveRight(int chars) {
return moveRight(chars, false);
}
int width() {
return size.getColumns() - (printLineNumbers ? 8 : 0) - (wrapping ? 0 : 1) - (firstColumnToDisplay > 0 ? 1 : 0);
}
boolean moveRight(int chars, boolean fromBeginning) {
if (fromBeginning) {
firstColumnToDisplay = 0;
offsetInLine = 0;
column = 0;
chars = Math.min(chars, length(getLine(line)));
}
boolean ret = true;
while (--chars >= 0) {
int len = length(getLine(line));
if (offsetInLine + column + 1 <= len) {
moveToChar(offsetInLine + column + 1, CursorMovement.RIGHT);
} else if (getLine(line + 1) != null) {
line++;
firstColumnToDisplay = 0;
offsetInLine = 0;
column = 0;
} else {
eof();
ret = false;
break;
}
}
wantedColumn = column;
ensureCursorVisible();
return ret;
}
void moveDown(int lines) {
cursorDown(lines);
ensureCursorVisible();
}
void moveUp(int lines) {
cursorUp(lines);
ensureCursorVisible();
}
private Optional<Integer> prevLineOffset(int line, int offsetInLine) {
if (line >= offsets.size()) {
return Optional.empty();
}
Iterator<Integer> it = offsets.get(line).descendingIterator();
while (it.hasNext()) {
int off = it.next();
if (off < offsetInLine) {
return Optional.of(off);
}
}
return Optional.empty();
}
private Optional<Integer> nextLineOffset(int line, int offsetInLine) {
if (line >= offsets.size()) {
return Optional.empty();
}
return offsets.get(line).stream()
.filter(o -> o > offsetInLine)
.findFirst();
}
void moveDisplayDown(int lines) {
int height = size.getRows() - computeHeader().size() - computeFooter().size();
// Adjust cursor
while (--lines >= 0) {
int lastLineToDisplay = firstLineToDisplay;
if (!wrapping) {
lastLineToDisplay += height - 1;
} else {
int off = offsetInLineToDisplay;
for (int l = 0; l < height - 1; l++) {
Optional<Integer> next = nextLineOffset(lastLineToDisplay, off);
if (next.isPresent()) {
off = next.get();
} else {
off = 0;
lastLineToDisplay++;
}
}
}
if (getLine(lastLineToDisplay) == null) {
eof();
return;
}
Optional<Integer> next = nextLineOffset(firstLineToDisplay, offsetInLineToDisplay);
if (next.isPresent()) {
offsetInLineToDisplay = next.get();
} else {
offsetInLineToDisplay = 0;
firstLineToDisplay++;
}
}
}
void moveDisplayUp(int lines) {
int width = size.getColumns() - (printLineNumbers ? 8 : 0);
while (--lines >= 0) {
if (offsetInLineToDisplay > 0) {
offsetInLineToDisplay = Math.max(0, offsetInLineToDisplay - (width - 1));
} else if (firstLineToDisplay > 0) {
firstLineToDisplay--;
offsetInLineToDisplay = prevLineOffset(firstLineToDisplay, Integer.MAX_VALUE).get();
} else {
bof();
return;
}
}
}
private void cursorDown(int lines) {
// Adjust cursor
firstColumnToDisplay = 0;
while (--lines >= 0) {
if (!wrapping) {
if (getLine(line + 1) != null) {
line++;
offsetInLine = 0;
column = Math.min(length(getLine(line)), wantedColumn);
} else {
bof();
break;
}
} else {
String txt = getLine(line);
Optional<Integer> off = nextLineOffset(line, offsetInLine);
if (off.isPresent()) {
offsetInLine = off.get();
} else if (getLine(line + 1) == null) {
eof();
break;
} else {
line++;
offsetInLine = 0;
txt = getLine(line);
}
int next = nextLineOffset(line, offsetInLine).orElse(length(txt));
column = Math.min(wantedColumn, next - offsetInLine);
}
}
moveToChar(offsetInLine + column);
}
private void cursorUp(int lines) {
firstColumnToDisplay = 0;
while (--lines >= 0) {
if (!wrapping) {
if (line > 0) {
line--;
column = Math.min(length(getLine(line)) - offsetInLine, wantedColumn);
} else {
bof();
break;
}
} else {
Optional<Integer> prev = prevLineOffset(line, offsetInLine);
if (prev.isPresent()) {
offsetInLine = prev.get();
} else if (line > 0) {
line--;
offsetInLine = prevLineOffset(line, Integer.MAX_VALUE).get();
int next = nextLineOffset(line, offsetInLine).orElse(length(getLine(line)));
column = Math.min(wantedColumn, next - offsetInLine);
} else {
bof();
break;
}
}
}
moveToChar(offsetInLine + column);
}
void ensureCursorVisible() {
List<AttributedString> header = computeHeader();
int rwidth = size.getColumns();
int height = size.getRows() - header.size() - computeFooter().size();
while (line < firstLineToDisplay
|| line == firstLineToDisplay && offsetInLine < offsetInLineToDisplay) {
moveDisplayUp(smoothScrolling ? 1 : height / 2);
}
while (true) {
int cursor = computeCursorPosition(header.size() * size.getColumns() + (printLineNumbers ? 8 : 0), rwidth);
if (cursor >= (height + header.size()) * rwidth) {
moveDisplayDown(smoothScrolling ? 1 : height / 2);
} else {
break;
}
}
}
void eof() {
}
void bof() {
}
void resetDisplay() {
column = offsetInLine + column;
moveRight(column, true);
}
String getLine(int line) {
return line < lines.size() ? lines.get(line) : null;
}
String getTitle() {
return file != null ? "File: " + file : "New Buffer";
}
List<AttributedString> computeHeader() {
String left = Nano.this.getTitle();
String middle = null;
String right = dirty ? "Modified" : " ";
int width = size.getColumns();
int mstart = 2 + left.length() + 1;
int mend = width - 2 - 8;
if (file == null) {
middle = "New Buffer";
} else {
int max = mend - mstart;
String src = file;
if ("File: ".length() + src.length() > max) {
int lastSep = src.lastIndexOf('/');
if (lastSep > 0) {
String p1 = src.substring(lastSep);
String p0 = src.substring(0, lastSep);
while (p0.startsWith(".")) {
p0 = p0.substring(1);
}
int nb = max - p1.length() - "File: ...".length();
int cut;
cut = Math.max(0, Math.min(p0.length(), p0.length() - nb));
middle = "File: ..." + p0.substring(cut) + p1;
}
if (middle == null || middle.length() > max) {
left = null;
max = mend - 2;
int nb = max - "File: ...".length();
int cut = Math.max(0, Math.min(src.length(), src.length() - nb));
middle = "File: ..." + src.substring(cut);
if (middle.length() > max) {
middle = middle.substring(0, max);
}
}
} else {
middle = "File: " + src;
}
}
int pos = 0;
AttributedStringBuilder sb = new AttributedStringBuilder();
sb.style(AttributedStyle.INVERSE);
sb.append(" ");
pos += 2;
if (left != null) {
sb.append(left);
pos += left.length();
sb.append(" ");
pos += 1;
for (int i = 1; i < (size.getColumns() - middle.length()) / 2 - left.length() - 1 - 2; i++) {
sb.append(" ");
pos++;
}
}
sb.append(middle);
pos += middle.length();
while (pos < width - 8 - 2) {
sb.append(" ");
pos++;
}
sb.append(right);
sb.append(" \n");
if (oneMoreLine) {
return Collections.singletonList(sb.toAttributedString());
} else {
return Arrays.asList(sb.toAttributedString(), new AttributedString("\n"));
}
}
void highlightDisplayedLine(int curLine, int curOffset, int nextOffset, AttributedStringBuilder line) {
AttributedString disp = highlight ? syntaxHighlighter.highlight(new AttributedStringBuilder().tabs(tabs).append(getLine(curLine)))
: new AttributedStringBuilder().tabs(tabs).append(getLine(curLine)).toAttributedString();
int[] hls = highlightStart();
int[] hle = highlightEnd();
if (hls[0] == -1 || hle[0] == -1) {
line.append(disp.columnSubSequence(curOffset, nextOffset));
} else if (hls[0] == hle[0]) {
if (curLine == hls[0]) {
if (hls[1] > nextOffset) {
line.append(disp.columnSubSequence(curOffset, nextOffset));
} else if (hls[1] < curOffset) {
if (hle[1] > nextOffset) {
line.append(disp.columnSubSequence(curOffset, nextOffset), AttributedStyle.INVERSE);
} else if (hle[1] > curOffset) {
line.append(disp.columnSubSequence(curOffset, hle[1]), AttributedStyle.INVERSE);
line.append(disp.columnSubSequence(hle[1], nextOffset));
} else {
line.append(disp.columnSubSequence(curOffset, nextOffset));
}
} else {
line.append(disp.columnSubSequence(curOffset, hls[1]));
if (hle[1] > nextOffset) {
line.append(disp.columnSubSequence(hls[1], nextOffset), AttributedStyle.INVERSE);
} else {
line.append(disp.columnSubSequence(hls[1], hle[1]), AttributedStyle.INVERSE);
line.append(disp.columnSubSequence(hle[1], nextOffset));
}
}
} else {
line.append(disp.columnSubSequence(curOffset, nextOffset));
}
} else {
if (curLine > hls[0] && curLine < hle[0]) {
line.append(disp.columnSubSequence(curOffset, nextOffset), AttributedStyle.INVERSE);
} else if (curLine == hls[0]) {
if (hls[1] > nextOffset) {
line.append(disp.columnSubSequence(curOffset, nextOffset));
} else if (hls[1] < curOffset) {
line.append(disp.columnSubSequence(curOffset, nextOffset), AttributedStyle.INVERSE);
} else {
line.append(disp.columnSubSequence(curOffset, hls[1]));
line.append(disp.columnSubSequence(hls[1], nextOffset), AttributedStyle.INVERSE);
}
} else if (curLine == hle[0]) {
if (hle[1] < curOffset) {
line.append(disp.columnSubSequence(curOffset, nextOffset));
} else if (hle[1] > nextOffset) {
line.append(disp.columnSubSequence(curOffset, nextOffset), AttributedStyle.INVERSE);
} else {
line.append(disp.columnSubSequence(curOffset, hle[1]), AttributedStyle.INVERSE);
line.append(disp.columnSubSequence(hle[1], nextOffset));
}
} else {
line.append(disp.columnSubSequence(curOffset, nextOffset));
}
}
}
List<AttributedString> getDisplayedLines(int nbLines) {
AttributedStyle s = AttributedStyle.DEFAULT.foreground(AttributedStyle.BLACK + AttributedStyle.BRIGHT);
AttributedString cut = new AttributedString("…", s);
AttributedString ret = new AttributedString("↩", s);
List<AttributedString> newLines = new ArrayList<>();
int rwidth = size.getColumns();
int width = rwidth - (printLineNumbers ? 8 : 0);
int curLine = firstLineToDisplay;
int curOffset = offsetInLineToDisplay;
int prevLine = -1;
syntaxHighlighter.reset();
for (int terminalLine = 0; terminalLine < nbLines; terminalLine++) {
AttributedStringBuilder line = new AttributedStringBuilder().tabs(tabs);
if (printLineNumbers && curLine < lines.size()) {
line.style(s);
if (curLine != prevLine) {
line.append(String.format("%7d ", curLine + 1));
} else {
line.append(" ‧ ");
}
line.style(AttributedStyle.DEFAULT);
prevLine = curLine;
}
if (curLine >= lines.size()) {
// Nothing to do
} else if (!wrapping) {
AttributedString disp = new AttributedStringBuilder().tabs(tabs).append(getLine(curLine)).toAttributedString();
if (this.line == curLine) {
int cutCount = 1;
if (firstColumnToDisplay > 0) {
line.append(cut);
cutCount = 2;
}
if (disp.columnLength() - firstColumnToDisplay >= width - (cutCount - 1)*cut.columnLength()) {
highlightDisplayedLine(curLine, firstColumnToDisplay
, firstColumnToDisplay + width - cutCount*cut.columnLength(), line);
line.append(cut);
} else {
highlightDisplayedLine(curLine, firstColumnToDisplay, disp.columnLength(), line);
}
} else {
if (disp.columnLength() >= width) {
highlightDisplayedLine(curLine, 0, width - cut.columnLength(), line);
line.append(cut);
} else {
highlightDisplayedLine(curLine, 0, disp.columnLength(), line);
}
}
curLine++;
} else {
Optional<Integer> nextOffset = nextLineOffset(curLine, curOffset);
if (nextOffset.isPresent()) {
highlightDisplayedLine(curLine, curOffset, nextOffset.get(), line);
line.append(ret);
curOffset = nextOffset.get();
} else {
highlightDisplayedLine(curLine, curOffset, Integer.MAX_VALUE, line);
curLine++;
curOffset = 0;
}
}
line.append('\n');
newLines.add(line.toAttributedString());
}
return newLines;
}
public void moveTo(int x, int y) {
if (printLineNumbers) {
x = Math.max(x - 8, 0);
}
line = firstLineToDisplay;
offsetInLine = offsetInLineToDisplay;
wantedColumn = x;
cursorDown(y);
}
public void gotoLine(int x, int y) {
line = y < lines.size() ? y : lines.size() - 1;
x = Math.min(x, length(lines.get(line)));
firstLineToDisplay = line > 0 ? line - 1 : line;
offsetInLine = 0;
offsetInLineToDisplay = 0;
column = 0;
moveRight(x);
}
public int getDisplayedCursor() {
return computeCursorPosition(printLineNumbers ? 8 : 0, size.getColumns() + 1);
}
private int computeCursorPosition(int cursor, int rwidth) {
int cur = firstLineToDisplay;
int off = offsetInLineToDisplay;
while (true) {
if (cur < line || off < offsetInLine) {
if (!wrapping) {
cursor += rwidth;
cur++;
} else {
cursor += rwidth;
Optional<Integer> next = nextLineOffset(cur, off);
if (next.isPresent()) {
off = next.get();
} else {
cur++;
off = 0;
}
}
} else if (cur == line) {
if (!wrapping && column > firstColumnToDisplay + width()) {
while (column > firstColumnToDisplay + width()) {
firstColumnToDisplay += width();
}
}
cursor += column - firstColumnToDisplay + (firstColumnToDisplay > 0 ? 1 : 0);
break;
} else {
throw new IllegalStateException();
}
}
return cursor;
}
char getCurrentChar() {
String str = lines.get(line);
if (column + offsetInLine < str.length()) {
return str.charAt(column + offsetInLine);
} else if (line < lines.size() - 1) {
return '\n';
} else {
return 0;
}
}
@SuppressWarnings("StatementWithEmptyBody")
public void prevWord() {
while (Character.isAlphabetic(getCurrentChar())
&& moveLeft(1));
while (!Character.isAlphabetic(getCurrentChar())
&& moveLeft(1));
while (Character.isAlphabetic(getCurrentChar())
&& moveLeft(1));
moveRight(1);
}