-
Notifications
You must be signed in to change notification settings - Fork 250
/
RSyntaxUtilities.java
executable file
·1606 lines (1395 loc) · 49.3 KB
/
RSyntaxUtilities.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
/*
* 08/06/2004
*
* RSyntaxUtilities.java - Utility methods used by RSyntaxTextArea and its
* views.
*
* This library is distributed under a modified BSD license. See the included
* LICENSE file for details.
*/
package org.fife.ui.rsyntaxtextarea;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JViewport;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.text.BadLocationException;
import javax.swing.text.Caret;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.Position;
import javax.swing.text.Segment;
import javax.swing.text.TabExpander;
import javax.swing.text.View;
import org.fife.ui.rsyntaxtextarea.TokenUtils.TokenSubList;
import org.fife.ui.rsyntaxtextarea.folding.FoldManager;
import org.fife.ui.rtextarea.Gutter;
import org.fife.ui.rtextarea.RTextArea;
import org.fife.ui.rtextarea.RTextScrollPane;
/**
* Utility methods used by <code>RSyntaxTextArea</code> and its associated
* classes.
*
* @author Robert Futrell
* @version 0.2
*/
public final class RSyntaxUtilities implements SwingConstants {
/**
* Integer constant representing a Windows-variant OS.
*/
public static final int OS_WINDOWS = 1;
/**
* Integer constant representing Mac OS X.
*/
public static final int OS_MAC_OSX = 2;
/**
* Integer constant representing Linux.
*/
public static final int OS_LINUX = 4;
/**
* Integer constant representing an "unknown" OS. 99.99% of the
* time, this means some UNIX variant (AIX, SunOS, etc.).
*/
public static final int OS_OTHER = 8;
/**
* Used for the color of hyperlinks when a LookAndFeel uses light text
* against a dark background.
*/
private static final Color LIGHT_HYPERLINK_FG = new Color(0xd8ffff);
private static final int OS = getOSImpl();
//private static final int DIGIT_MASK = 1;
private static final int LETTER_MASK = 2;
//private static final int WHITESPACE_MASK = 4;
//private static final int UPPER_CASE_MASK = 8;
private static final int HEX_CHARACTER_MASK = 16;
private static final int LETTER_OR_DIGIT_MASK = 32;
private static final int BRACKET_MASK = 64;
private static final int JAVA_OPERATOR_MASK = 128;
/**
* A lookup table used to quickly decide if a 16-bit Java char is a
* US-ASCII letter (A-Z or a-z), a digit, a whitespace char (either space
* (0x0020) or tab (0x0009)), etc. This method should be faster
* than <code>Character.isLetter</code>, <code>Character.isDigit</code>,
* and <code>Character.isWhitespace</code> because we know we are dealing
* with ASCII chars and so don't have to worry about code planes, etc.
*/
private static final int[] DATA_TABLE = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, // 0-15
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16-31
4, 128, 0, 0, 0, 128, 128, 0, 64, 64, 128, 128, 0, 128, 0, 128, // 32-47
49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 128, 0, 128, 128, 128, 128, // 48-63
0, 58, 58, 58, 58, 58, 58, 42, 42, 42, 42, 42, 42, 42, 42, 42, // 64-79
42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 64, 0, 64, 128, 0, // 80-95
0, 50, 50, 50, 50, 50, 50, 34, 34, 34, 34, 34, 34, 34, 34, 34, // 96-111
34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 64, 128, 64, 128, 0, // 112-127
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 128-143
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 144-
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 160-
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 176-
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 192-
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 208-
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 224-
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // 240-255.
};
/**
* Used in bracket matching methods.
*/
private static Segment charSegment = new Segment();
/**
* Used in token list manipulation methods.
*/
private static final TokenImpl TEMP_TOKEN = new TokenImpl();
/**
* Used internally.
*/
private static final char[] JS_KEYWORD_RETURN = { 'r', 'e', 't', 'u', 'r', 'n' };
private static final char[] JS_AND = { '&', '&' };
private static final char[] JS_OR = { '|', '|' };
/**
* Used internally.
*/
private static final String BRACKETS = "{([})]";
/**
* An unused constructor to prevent instantiation, and keep static analysis
* tools happy.
*/
private RSyntaxUtilities() { // NOSONAR
// Private constructor to prevent instantiation.
}
/**
* Returns the best possible anti-alias hints to use when rendering text.
* If {@link #getDesktopAntiAliasHints()} returns non-{@code null}, its
* value is returned. Otherwise, default anti-aliasing values are
* returned.
*
* @return The rendering hints. This will never be {@code null}.
* @see #getDesktopAntiAliasHints()
*/
public static Map<?, ?> getBestPossibleAntiAliasHints() {
Map<?, ?> hints = RSyntaxUtilities.getDesktopAntiAliasHints();
// If the desktop query method comes up empty, use the standard
// Java2D greyscale method. Note this will likely NOT be as
// nice as what would be used if the getDesktopAntiAliasHints()
// call worked.
if (hints == null) {
Map<RenderingHints.Key, Object> temp = new HashMap<>();
temp.put(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
hints = temp;
}
return hints;
}
/**
* Returns the rendering hints for text that will most accurately reflect
* those of the native windowing system.
*
* @return The rendering hints, or <code>null</code> if they cannot be
* determined.
* @see #getBestPossibleAntiAliasHints()
*/
public static Map<?,?> getDesktopAntiAliasHints() {
return (Map<?,?>)Toolkit.getDefaultToolkit().
getDesktopProperty("awt.font.desktophints");
}
/**
* Returns the color to use for the line underneath a folded region line.
*
* @param textArea The text area.
* @return The color to use.
*/
public static Color getFoldedLineBottomColor(RSyntaxTextArea textArea) {
Color color = Color.GRAY;
Gutter gutter = RSyntaxUtilities.getGutter(textArea);
if (gutter!=null) {
color = gutter.getFoldIndicatorForeground();
}
return color;
}
/**
* Returns the gutter component of the scroll pane containing a text
* area, if any.
*
* @param textArea The text area.
* @return The gutter, or <code>null</code> if the text area is not in
* an {@link RTextScrollPane}.
* @see RTextScrollPane#getGutter()
*/
public static Gutter getGutter(RTextArea textArea) {
Gutter gutter = null;
Container parent = textArea.getParent();
if (parent instanceof JViewport) {
parent = parent.getParent();
if (parent instanceof RTextScrollPane) {
RTextScrollPane sp = (RTextScrollPane)parent;
gutter = sp.getGutter(); // Should always be non-null
}
}
return gutter;
}
/**
* Returns the color to use for hyperlink-style components. This method
* will return <code>Color.blue</code> unless it appears that the current
* LookAndFeel uses light text on a dark background, in which case a
* brighter alternative is returned.
*
* @return The color to use for hyperlinks.
* @see #isLightForeground(Color)
*/
public static Color getHyperlinkForeground() {
// This property is defined by all standard LaFs, even Nimbus (!),
// but you never know what crazy LaFs there are...
Color fg = UIManager.getColor("Label.foreground");
if (fg==null) {
fg = new JLabel().getForeground();
}
return isLightForeground(fg) ? LIGHT_HYPERLINK_FG : Color.blue;
}
/**
* Returns the leading whitespace of a string.
*
* @param text The String to check.
* @return The leading whitespace.
* @see #getLeadingWhitespace(String, int)
* @see #getLeadingWhitespace(Document, int)
*/
public static String getLeadingWhitespace(String text) {
return getLeadingWhitespace(text, Integer.MAX_VALUE);
}
/**
* Returns the leading whitespace of a string.
*
* @param text The String to check.
* @param upTo Stops checking at the specified offset.
* @return The leading whitespace.
* @see #getLeadingWhitespace(String)
*/
public static String getLeadingWhitespace(String text, int upTo) {
int count = 0;
int len = Math.min(text.length(), upTo);
while (count<len && RSyntaxUtilities.isWhitespace(text.charAt(count))) {
count++;
}
return text.substring(0, count);
}
/**
* Returns the leading whitespace of a specific line in a document.
*
* @param doc The document.
* @param offs The offset whose line to get the leading whitespace for.
* @return The leading whitespace.
* @throws BadLocationException If <code>offs</code> is not a valid offset
* in the document.
* @see #getLeadingWhitespace(String)
*/
public static String getLeadingWhitespace(Document doc, int offs)
throws BadLocationException {
Element root = doc.getDefaultRootElement();
int line = root.getElementIndex(offs);
Element elem = root.getElement(line);
int startOffs = elem.getStartOffset();
int endOffs = elem.getEndOffset() - 1;
String text = doc.getText(startOffs, endOffs-startOffs);
return getLeadingWhitespace(text);
}
private static Element getLineElem(Document doc, int offs) {
Element root = doc.getDefaultRootElement();
int line = root.getElementIndex(offs);
Element elem = root.getElement(line);
if ((offs>=elem.getStartOffset()) && (offs<elem.getEndOffset())) {
return elem;
}
return null;
}
/**
* Returns the bounding box (in the current view) of a specified position
* in the model. This method is designed for line-wrapped views to use,
* as it allows you to specify a "starting position" in the line, from
* which the x-value is assumed to be zero. The idea is that you specify
* the first character in a physical line as <code>p0</code>, as this is
* the character where the x-pixel value is 0.
*
* @param textArea The text area containing the text.
* @param s A segment in which to load the line. This is passed in so we
* don't have to reallocate a new <code>Segment</code> for each
* call.
* @param p0 The starting position in the physical line in the document.
* @param p1 The position for which to get the bounding box in the view.
* @param e How to expand tabs.
* @param rect The rectangle whose x- and width-values are changed to
* represent the bounding box of <code>p1</code>. This is reused
* to keep from needlessly reallocating Rectangles.
* @param x0 The x-coordinate (pixel) marking the left-hand border of the
* text. This is useful if the text area has a border, for example.
* @return The bounding box in the view of the character <code>p1</code>.
* @throws BadLocationException If <code>p0</code> or <code>p1</code> is
* not a valid location in the specified text area's document.
* @throws IllegalArgumentException If <code>p0</code> and <code>p1</code>
* are not on the same line.
*/
public static Rectangle getLineWidthUpTo(RSyntaxTextArea textArea,
Segment s, int p0, int p1,
TabExpander e, Rectangle rect,
int x0)
throws BadLocationException {
RSyntaxDocument doc = (RSyntaxDocument)textArea.getDocument();
// Ensure p0 and p1 are valid document positions.
if (p0<0) {
throw new BadLocationException("Invalid document position", p0);
}
else if (p1>doc.getLength()) {
throw new BadLocationException("Invalid document position", p1);
}
// Ensure p0 and p1 are in the same line, and get the start/end
// offsets for that line.
Element map = doc.getDefaultRootElement();
int lineNum = map.getElementIndex(p0);
// We do ">1" because p1 might be the first position on the next line
// or the last position on the previous one.
// if (lineNum!=map.getElementIndex(p1))
if (Math.abs(lineNum-map.getElementIndex(p1))>1) {
throw new IllegalArgumentException("p0 and p1 are not on the " +
"same line (" + p0 + ", " + p1 + ").");
}
// Get the token list.
Token t = doc.getTokenListForLine(lineNum);
// Modify the token list 't' to begin at p0 (but still have correct
// token types, etc.), and get the x-location (in pixels) of the
// beginning of this new token list.
TokenSubList subList = TokenUtils.getSubTokenList(t, p0, e, textArea,
0, TEMP_TOKEN);
t = subList.tokenList;
rect = t.listOffsetToView(textArea, e, p1, x0, rect);
return rect;
}
/**
* Returns the location of the bracket paired with the one at the current
* caret position.
*
* @param textArea The text area.
* @param input A point to use as the return value. If this is
* <code>null</code>, a new object is created and returned.
* @return A point representing the matched bracket info. The "x" field
* is the offset of the bracket at the caret position (either just
* before or just after the caret), and the "y" field is the offset
* of the matched bracket. Both "x" and "y" will be
* <code>-1</code> if there isn't a matching bracket (or the caret
* isn't on a bracket).
*/
public static Point getMatchingBracketPosition(RSyntaxTextArea textArea,
Point input) {
if (input==null) {
input = new Point();
}
input.setLocation(-1, -1);
try {
// Actually position just BEFORE caret.
int caretPosition = textArea.getCaretPosition() - 1;
RSyntaxDocument doc = (RSyntaxDocument)textArea.getDocument();
char bracket = 0;
// If the caret was at offset 0, we can't check "to its left."
if (caretPosition>=0) {
bracket = doc.charAt(caretPosition);
}
// Try to match a bracket "to the right" of the caret if one
// was not found on the left.
int index = BRACKETS.indexOf(bracket);
if (index==-1 && caretPosition<doc.getLength()-1) {
bracket = doc.charAt(++caretPosition);
}
// First, see if the char was a bracket (one of "{[()]}").
if (index==-1) {
index = BRACKETS.indexOf(bracket);
if (index==-1) {
return input;
}
}
// If it was, then make sure this bracket isn't sitting in
// the middle of a comment or string. If it isn't, then
// initialize some stuff so we can continue on.
char bracketMatch;
boolean goForward;
Element map = doc.getDefaultRootElement();
int curLine = map.getElementIndex(caretPosition);
Element line = map.getElement(curLine);
int start = line.getStartOffset();
int end = line.getEndOffset();
Token token = doc.getTokenListForLine(curLine);
token = RSyntaxUtilities.getTokenAtOffset(token, caretPosition);
// All brackets are always returned as "separators."
if (token.getType()!=Token.SEPARATOR) {
return input;
}
int languageIndex = token.getLanguageIndex();
if (index<3) { // One of "{[("
goForward = true;
bracketMatch = BRACKETS.charAt(index + 3);
}
else { // One of ")]}"
goForward = false;
bracketMatch = BRACKETS.charAt(index - 3);
}
if (goForward) {
int lastLine = map.getElementCount();
// Start just after the found bracket since we're sure
// we're not in a comment.
start = caretPosition + 1;
int numEmbedded = 0;
boolean haveTokenList = false;
while (true) {
doc.getText(start,end-start, charSegment);
int segOffset = charSegment.offset;
for (int i=segOffset; i<segOffset+charSegment.count; i++) {
char ch = charSegment.array[i];
if (ch==bracket) {
if (!haveTokenList) {
token = doc.getTokenListForLine(curLine);
haveTokenList = true;
}
int offset = start + (i-segOffset);
token = RSyntaxUtilities.getTokenAtOffset(token, offset);
if (token.getType()==Token.SEPARATOR &&
token.getLanguageIndex()==languageIndex) {
numEmbedded++;
}
}
else if (ch==bracketMatch) {
if (!haveTokenList) {
token = doc.getTokenListForLine(curLine);
haveTokenList = true;
}
int offset = start + (i-segOffset);
token = RSyntaxUtilities.getTokenAtOffset(token, offset);
if (token.getType()==Token.SEPARATOR &&
token.getLanguageIndex()==languageIndex) {
if (numEmbedded==0) {
if (textArea.isCodeFoldingEnabled() &&
textArea.getFoldManager().isLineHidden(curLine)) {
return input; // Match hidden in a fold
}
input.setLocation(caretPosition, offset);
return input;
}
numEmbedded--;
}
}
} // End of for (int i=segOffset; i<segOffset+charSegment.count; i++).
// Bail out if we've gone through all lines and
// haven't found the match.
if (++curLine==lastLine) {
return input;
}
// Otherwise, go through the next line.
haveTokenList = false;
line = map.getElement(curLine);
start = line.getStartOffset();
end = line.getEndOffset();
} // End of while (true).
} // End of if (goForward).
// Otherwise, we're going backward through the file
// (since we found '}', ')' or ']').
else { // goForward==false
// End just before the found bracket since we're sure
// we're not in a comment.
end = caretPosition;// - 1;
int numEmbedded = 0;
boolean haveTokenList = false;
Token t2;
while (true) {
doc.getText(start,end-start, charSegment);
int segOffset = charSegment.offset;
int iStart = segOffset + charSegment.count - 1;
for (int i=iStart; i>=segOffset; i--) {
char ch = charSegment.array[i];
if (ch==bracket) {
if (!haveTokenList) {
token = doc.getTokenListForLine(curLine);
haveTokenList = true;
}
int offset = start + (i-segOffset);
t2 = RSyntaxUtilities.getTokenAtOffset(token, offset);
if (t2.getType()==Token.SEPARATOR &&
token.getLanguageIndex()==languageIndex) {
numEmbedded++;
}
}
else if (ch==bracketMatch) {
if (!haveTokenList) {
token = doc.getTokenListForLine(curLine);
haveTokenList = true;
}
int offset = start + (i-segOffset);
t2 = RSyntaxUtilities.getTokenAtOffset(token, offset);
if (t2.getType()==Token.SEPARATOR &&
token.getLanguageIndex()==languageIndex) {
if (numEmbedded==0) {
input.setLocation(caretPosition, offset);
return input;
}
numEmbedded--;
}
}
}
// Bail out if we've gone through all lines and
// haven't found the match.
if (--curLine==-1) {
return input;
}
// Otherwise, get ready for going through the
// next line.
haveTokenList = false;
line = map.getElement(curLine);
start = line.getStartOffset();
end = line.getEndOffset();
} // End of while (true).
} // End of else.
} catch (BadLocationException ble) {
// Shouldn't ever happen.
ble.printStackTrace();
}
// Something went wrong...
return input;
}
/**
* Returns the next non-whitespace, non-comment token in a text area.
*
* @param t The next token in this line's token list.
* @param textArea The text area.
* @param line The current line index (the line index of <code>t</code>).
* @return The next non-whitespace, non-comment token, or <code>null</code>
* if there isn't one.
* @see #getPreviousImportantToken(RSyntaxDocument, int)
* @see #getPreviousImportantTokenFromOffs(RSyntaxDocument, int)
*/
public static Token getNextImportantToken(Token t,
RSyntaxTextArea textArea, int line) {
while (t!=null && t.isPaintable() && t.isCommentOrWhitespace()) {
t = t.getNextToken();
}
if ((t==null || !t.isPaintable()) && line<textArea.getLineCount()-1) {
t = textArea.getTokenListForLine(++line);
return getNextImportantToken(t, textArea, line);
}
return t;
}
/**
* Provides a way to determine the next visually represented model
* location at which one might place a caret.
* Some views may not be visible,
* they might not be in the same order found in the model, or they just
* might not allow access to some of the locations in the model.<p>
*
* NOTE: You should only call this method if the passed-in
* <code>javax.swing.text.View</code> is an instance of
* {@link TokenOrientedView} and <code>javax.swing.text.TabExpander</code>;
* otherwise, a <code>ClassCastException</code> could be thrown.
*
* @param pos the position to convert >= 0
* @param b The bias of the request.
* @param a the allocated region in which to render
* @param direction the direction from the current position that can
* be thought of as the arrow keys typically found on a keyboard.
* This will be one of the following values:
* <ul>
* <li>SwingConstants.WEST
* <li>SwingConstants.EAST
* <li>SwingConstants.NORTH
* <li>SwingConstants.SOUTH
* </ul>
* @param biasRet The return bias.
* @param view The parent view.
* @return The location within the model that best represents the next
* location visual position.
* @throws BadLocationException if {@code pos} is invalid.
* @throws IllegalArgumentException if <code>direction</code>
* doesn't have one of the legal values above
*/
public static int getNextVisualPositionFrom(int pos, Position.Bias b,
Shape a, int direction,
Position.Bias[] biasRet, View view)
throws BadLocationException {
RSyntaxTextArea target = (RSyntaxTextArea)view.getContainer();
biasRet[0] = Position.Bias.Forward;
// Do we want the "next position" above, below, to the left or right?
switch (direction) {
case NORTH:
case SOUTH:
if (pos == -1) {
pos = (direction == NORTH) ?
Math.max(0, view.getEndOffset() - 1) :
view.getStartOffset();
break;
}
Caret c = (target != null) ? target.getCaret() : null;
// YUCK! Ideally, the x location from the magic caret
// position would be passed in.
Point mcp;
if (c != null) {
mcp = c.getMagicCaretPosition();
}
else {
mcp = null;
}
int x;
if (mcp == null) {
Rectangle loc = target.modelToView(pos);
x = (loc == null) ? 0 : loc.x;
}
else {
x = mcp.x;
}
if (direction == NORTH) {
pos = getPositionAbove(target,pos,x,(TabExpander)view);
}
else {
pos = getPositionBelow(target,pos,x,(TabExpander)view);
}
break;
case WEST:
int endOffs = view.getEndOffset();
if(pos == -1) {
pos = Math.max(0, endOffs - 1);
}
else {
pos = Math.max(0, pos - 1);
if (target.isCodeFoldingEnabled()) {
int last = pos==endOffs-1 ? target.getLineCount()-1 :
target.getLineOfOffset(pos+1);
int current = target.getLineOfOffset(pos);
if (last!=current) { // If moving up a line...
FoldManager fm = target.getFoldManager();
if (fm.isLineHidden(current)) {
while (--current>0 && fm.isLineHidden(current));
pos = target.getLineEndOffset(current) - 1;
}
}
}
}
break;
case EAST:
if(pos == -1) {
pos = view.getStartOffset();
}
else {
pos = Math.min(pos + 1, view.getDocument().getLength());
if (target.isCodeFoldingEnabled()) {
int last = pos==0 ? 0 : target.getLineOfOffset(pos-1);
int current = target.getLineOfOffset(pos);
if (last!=current) { // If moving down a line...
FoldManager fm = target.getFoldManager();
if (fm.isLineHidden(current)) {
int lineCount = target.getLineCount();
while (++current<lineCount && fm.isLineHidden(current));
pos = current==lineCount ?
target.getLineEndOffset(last)-1 : // Was the last visible line
target.getLineStartOffset(current);
}
}
}
}
break;
default:
throw new IllegalArgumentException(
"Bad direction: " + direction);
}
return pos;
}
/**
* Returns an integer constant representing the OS. This can be handy for
* special case situations such as Mac OS-X (special application
* registration) or Windows (allow mixed case, etc.).
*
* @return An integer constant representing the OS.
* @see #isOsCaseSensitive()
*/
public static int getOS() {
return OS;
}
/**
* Returns an integer constant representing the OS. This can be handy for
* special case situations such as Mac OS-X (special application
* registration) or Windows (allow mixed case, etc.).
*
* @return An integer constant representing the OS.
*/
private static int getOSImpl() {
int os = OS_OTHER;
String osName = System.getProperty("os.name");
if (osName!=null) { // Should always be true.
osName = osName.toLowerCase();
if (osName.contains("windows")) {
os = OS_WINDOWS;
}
else if (osName.contains("mac os x")) {
os = OS_MAC_OSX;
}
else if (osName.contains("linux")) {
os = OS_LINUX;
}
else {
os = OS_OTHER;
}
}
return os;
}
/**
* Returns the flags necessary to create a {@link Pattern}.
*
* @param matchCase Whether the pattern should be case-sensitive.
* @param others Any other flags. This may be <code>0</code>.
* @return The flags.
*/
public static int getPatternFlags(boolean matchCase, int others) {
if (!matchCase) {
others |= Pattern.CASE_INSENSITIVE|Pattern.UNICODE_CASE;
}
return others;
}
/**
* Determines the position in the model that is closest to the given
* view location in the row above. The component given must have a
* size to compute the result. If the component doesn't have a size
* a value of -1 will be returned.
*
* @param c the editor
* @param offs the offset in the document >= 0
* @param x the X coordinate >= 0
* @param e How to expand tabs.
* @return the position >= 0 if the request can be computed, otherwise
* a value of -1 will be returned.
* @exception BadLocationException if the offset is out of range
*/
public static int getPositionAbove(RSyntaxTextArea c, int offs,
float x, TabExpander e) throws BadLocationException {
TokenOrientedView tov = (TokenOrientedView)e;
Token token = tov.getTokenListForPhysicalLineAbove(offs);
if (token==null) {
return -1;
}
else if (token.getType()==Token.NULL) {
int line = c.getLineOfOffset(offs); // Sure to be >0 ??
return c.getLineStartOffset(line-1);
}
else {
return token.getListOffset(c, e, c.getMargin().left, x);
}
}
/**
* Determines the position in the model that is closest to the given
* view location in the row below. The component given must have a
* size to compute the result. If the component doesn't have a size
* a value of -1 will be returned.
*
* @param c the editor
* @param offs the offset in the document >= 0
* @param x the X coordinate >= 0
* @param e How to expand tabs.
* @return the position >= 0 if the request can be computed, otherwise
* a value of -1 will be returned.
* @exception BadLocationException if the offset is out of range
*/
public static int getPositionBelow(RSyntaxTextArea c, int offs,
float x, TabExpander e) throws BadLocationException {
TokenOrientedView tov = (TokenOrientedView)e;
Token token = tov.getTokenListForPhysicalLineBelow(offs);
if (token==null) {
return -1;
}
else if (token.getType()==Token.NULL) {
int line = c.getLineOfOffset(offs); // Sure to be > c.getLineCount()-1 ??
// return c.getLineStartOffset(line+1);
FoldManager fm = c.getFoldManager();
line = fm.getVisibleLineBelow(line);
return c.getLineStartOffset(line);
}
else {
return token.getListOffset(c, e, c.getMargin().left, x);
}
}
/**
* Returns the last non-whitespace, non-comment token, starting with the
* specified line.
*
* @param doc The document.
* @param line The line at which to start looking.
* @return The last non-whitespace, non-comment token, or <code>null</code>
* if there isn't one.
* @see #getNextImportantToken(Token, RSyntaxTextArea, int)
* @see #getPreviousImportantTokenFromOffs(RSyntaxDocument, int)
*/
public static Token getPreviousImportantToken(RSyntaxDocument doc,
int line) {
if (line<0) {
return null;
}
Token t = doc.getTokenListForLine(line);
if (t!=null) {
t = t.getLastNonCommentNonWhitespaceToken();
if (t!=null) {
return t;
}
}
return getPreviousImportantToken(doc, line-1);
}
/**
* Returns the last non-whitespace, non-comment token, before the
* specified offset.
*
* @param doc The document.
* @param offs The ending offset for the search.
* @return The last non-whitespace, non-comment token, or <code>null</code>
* if there isn't one.
* @see #getPreviousImportantToken(RSyntaxDocument, int)
* @see #getNextImportantToken(Token, RSyntaxTextArea, int)
*/
public static Token getPreviousImportantTokenFromOffs(
RSyntaxDocument doc, int offs) {
Element root = doc.getDefaultRootElement();
int line = root.getElementIndex(offs);
Token t = doc.getTokenListForLine(line);
// Check line containing offs
Token target = null;
while (t!=null && t.isPaintable() && !t.containsPosition(offs)) {
if (!t.isCommentOrWhitespace()) {
target = t;
}
t = t.getNextToken();
}
// Check previous line(s)
if (target==null) {
target = RSyntaxUtilities.getPreviousImportantToken(doc, line-1);
}
return target;
}
/**
* Returns the token at the specified offset.
*
* @param textArea The text area.
* @param offset The offset of the token.
* @return The token, or <code>null</code> if the offset is not valid.
* @see #getTokenAtOffset(RSyntaxDocument, int)
* @see #getTokenAtOffset(Token, int)
* @see #getTokenAtOffsetOrLastTokenIfEndOfLine(RSyntaxTextArea, int)
*/
public static Token getTokenAtOffset(RSyntaxTextArea textArea, int offset) {
RSyntaxDocument doc = (RSyntaxDocument)textArea.getDocument();
return RSyntaxUtilities.getTokenAtOffset(doc, offset);
}
/**
* Returns the token at the specified offset. If the offset
* is at the very end of a line, the "last" token in that line is returned
* instead (which may be {@code null} if the line is empty).
*
* @param textArea The text area.
* @param offset The offset at which to get the token.
* @return The token at <code>offset</code>, or <code>null</code> if
* the offset is invalid or there is no token at that offset.
* @see #getTokenAtOffset(RSyntaxTextArea, int)
* @see #getTokenAtOffset(RSyntaxDocument, int)
* @see #getTokenAtOffset(Token, int)
*/
public static Token getTokenAtOffsetOrLastTokenIfEndOfLine(RSyntaxTextArea textArea, int offset) {
RSyntaxDocument doc = (RSyntaxDocument)textArea.getDocument();
return RSyntaxUtilities.getTokenAtOffsetOrLastTokenIfEndOfLine(doc, offset);
}
/**
* Returns the token at the specified offset.
*
* @param doc The document.
* @param offset The offset of the token.
* @return The token, or <code>null</code> if the offset is not valid.
* @see #getTokenAtOffset(RSyntaxTextArea, int)