-
Notifications
You must be signed in to change notification settings - Fork 250
/
RSyntaxTextAreaEditorKit.java
executable file
·2322 lines (1914 loc) · 65.1 KB
/
RSyntaxTextAreaEditorKit.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/29/2004
*
* RSyntaxTextAreaEditorKit.java - The editor kit used by RSyntaxTextArea.
*
* This library is distributed under a modified BSD license. See the included
* LICENSE file for details.
*/
package org.fife.ui.rsyntaxtextarea;
import java.awt.Component;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.text.CharacterIterator;
import java.util.ResourceBundle;
import java.util.Stack;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
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.Segment;
import javax.swing.text.TextAction;
import org.fife.ui.rsyntaxtextarea.folding.Fold;
import org.fife.ui.rsyntaxtextarea.folding.FoldCollapser;
import org.fife.ui.rsyntaxtextarea.folding.FoldManager;
import org.fife.ui.rsyntaxtextarea.templates.CodeTemplate;
import org.fife.ui.rtextarea.IconRowHeader;
import org.fife.ui.rtextarea.RTextArea;
import org.fife.ui.rtextarea.RTextAreaEditorKit;
import org.fife.ui.rtextarea.RecordableTextAction;
/**
* An extension of <code>RTextAreaEditorKit</code> that adds functionality for
* programming-specific stuff. There are currently subclasses to handle:
*
* <ul>
* <li>Toggling code folds.</li>
* <li>Aligning "closing" curly braces with their matches, if the current
* programming language uses curly braces to identify code blocks.</li>
* <li>Copying the current selection as RTF.</li>
* <li>Block indentation (increasing the indent of one or multiple lines)</li>
* <li>Block un-indentation (decreasing the indent of one or multiple lines)
* </li>
* <li>Inserting a "code template" when a configurable key (e.g. a space) is
* pressed</li>
* <li>Decreasing the point size of all fonts in the text area</li>
* <li>Increasing the point size of all fonts in the text area</li>
* <li>Moving the caret to the "matching bracket" of the one at the current
* caret position</li>
* <li>Toggling whether the currently selected lines are commented out.</li>
* <li>Better selection of "words" on mouse double-clicks for programming
* languages.</li>
* <li>Better keyboard navigation via Ctrl+arrow keys for programming
* languages.</li>
* </ul>
*
* @author Robert Futrell
* @version 0.5
*/
@SuppressWarnings("checkstyle:constantname")
public class RSyntaxTextAreaEditorKit extends RTextAreaEditorKit {
private static final long serialVersionUID = 1L;
public static final String rstaBacktickAction = "RSTA.BacktickAction";
public static final String rstaCloseCurlyBraceAction = "RSTA.CloseCurlyBraceAction";
public static final String rstaCloseMarkupTagAction = "RSTA.CloseMarkupTagAction";
public static final String rstaCollapseAllFoldsAction = "RSTA.CollapseAllFoldsAction";
public static final String rstaCollapseAllCommentFoldsAction = "RSTA.CollapseAllCommentFoldsAction";
public static final String rstaCollapseFoldAction = "RSTA.CollapseFoldAction";
public static final String rstaCopyAsStyledTextAction = "RSTA.CopyAsStyledTextAction";
public static final String rstaCutAsStyledTextAction = "RSTA.CutAsStyledTextAction";
public static final String rstaDecreaseIndentAction = "RSTA.DecreaseIndentAction";
public static final String rstaDoubleQuoteAction = "RSTA.DoubleQuoteAction";
public static final String rstaExpandAllFoldsAction = "RSTA.ExpandAllFoldsAction";
public static final String rstaExpandFoldAction = "RSTA.ExpandFoldAction";
public static final String rstaGoToMatchingBracketAction = "RSTA.GoToMatchingBracketAction";
public static final String rstaOpenParenAction = "RSTA.OpenParenAction";
public static final String rstaOpenSquareBracketAction = "RSTA.OpenSquareBracketAction";
public static final String rstaOpenCurlyAction = "RSTA.OpenCurlyAction";
public static final String rstaPossiblyInsertTemplateAction = "RSTA.TemplateAction";
public static final String rstaSingleQuoteAction = "RSTA.SingleQuoteAction";
public static final String rstaToggleCommentAction = "RSTA.ToggleCommentAction";
public static final String rstaToggleCurrentFoldAction = "RSTA.ToggleCurrentFoldAction";
private static final String MSG = "org.fife.ui.rsyntaxtextarea.RSyntaxTextArea";
private static final ResourceBundle msg = ResourceBundle.getBundle(MSG);
/**
* The actions that <code>RSyntaxTextAreaEditorKit</code> adds to those of
* <code>RTextAreaEditorKit</code>.
*/
private static final Action[] defaultActions = {
new CloseCurlyBraceAction(),
new CloseMarkupTagAction(),
new BeginWordAction(beginWordAction, false),
new BeginWordAction(selectionBeginWordAction, true),
new ChangeFoldStateAction(rstaCollapseFoldAction, true),
new ChangeFoldStateAction(rstaExpandFoldAction, false),
new CollapseAllFoldsAction(),
new CopyCutAsStyledTextAction(false),
new CopyCutAsStyledTextAction(true),
//new DecreaseFontSizeAction(),
new DecreaseIndentAction(),
new DeletePrevWordAction(),
new DumbCompleteWordAction(),
new EndAction(endAction, false),
new EndAction(selectionEndAction, true),
new EndWordAction(endWordAction, false),
new EndWordAction(endWordAction, true),
new ExpandAllFoldsAction(),
new GoToMatchingBracketAction(),
//new IncreaseFontSizeAction(),
new InsertBreakAction(),
new InsertPairedCharacterAction(rstaOpenParenAction, '(', ')'),
new InsertPairedCharacterAction(rstaOpenSquareBracketAction, '[', ']'),
new InsertPairedCharacterAction(rstaOpenCurlyAction, '{', '}'),
new InsertQuoteAction(rstaDoubleQuoteAction, InsertQuoteAction.QuoteType.DOUBLE_QUOTE),
new InsertQuoteAction(rstaSingleQuoteAction, InsertQuoteAction.QuoteType.SINGLE_QUOTE),
new InsertQuoteAction(rstaBacktickAction, InsertQuoteAction.QuoteType.BACKTICK),
new InsertTabAction(),
new NextWordAction(nextWordAction, false),
new NextWordAction(selectionNextWordAction, true),
new PossiblyInsertTemplateAction(),
new PreviousWordAction(previousWordAction, false),
new PreviousWordAction(selectionPreviousWordAction, true),
new SelectWordAction(),
new ToggleCommentAction(),
};
/**
* Constructor.
*/
public RSyntaxTextAreaEditorKit() {
}
/**
* Returns the default document used by <code>RSyntaxTextArea</code>s.
*
* @return The document.
*/
@Override
public Document createDefaultDocument() {
return new RSyntaxDocument(SyntaxConstants.SYNTAX_STYLE_NONE);
}
/**
* Overridden to return a row header that is aware of folding.
*
* @param textArea The text area.
* @return The icon row header.
*/
@Override
public IconRowHeader createIconRowHeader(RTextArea textArea) {
return new FoldingAwareIconRowHeader((RSyntaxTextArea)textArea);
}
/**
* Fetches the set of commands that can be used
* on a text component that is using a model and
* view produced by this kit.
*
* @return the command list
*/
@Override
public Action[] getActions() {
return TextAction.augmentList(super.getActions(),
RSyntaxTextAreaEditorKit.defaultActions);
}
/**
* Returns localized text for an action. There's definitely a better place
* for this functionality.
*
* @param key The key into the action resource bundle.
* @return The localized text.
*/
public static String getString(String key) {
return msg.getString(key);
}
/**
* Positions the caret at the beginning of the word. This class is here
* to better handle finding the "beginning of the word" for programming
* languages.
*/
protected static class BeginWordAction
extends RTextAreaEditorKit.BeginWordAction {
private Segment seg;
protected BeginWordAction(String name, boolean select) {
super(name, select);
seg = new Segment();
}
@Override
protected int getWordStart(RTextArea textArea, int offs)
throws BadLocationException {
if (offs==0) {
return offs;
}
RSyntaxDocument doc = (RSyntaxDocument)textArea.getDocument();
int line = textArea.getLineOfOffset(offs);
int start = textArea.getLineStartOffset(line);
if (offs==start) {
return start;
}
int end = textArea.getLineEndOffset(line);
if (line!=textArea.getLineCount()-1) {
end--;
}
doc.getText(start, end-start, seg);
// Determine the "type" of char at offs - lower case, upper case,
// whitespace or other. We take special care here as we're starting
// in the middle of the Segment to check whether we're already at
// the "beginning" of a word.
int firstIndex = seg.getBeginIndex() + (offs-start) - 1;
seg.setIndex(firstIndex);
char ch = seg.current();
char nextCh = offs==end ? 0 : seg.array[seg.getIndex() + 1];
// The "word" is a group of letters and/or digits
int languageIndex = 0; // TODO
if (doc.isIdentifierChar(languageIndex, ch)) {
if (offs!=end && !doc.isIdentifierChar(languageIndex, nextCh)) {
return offs;
}
do {
ch = seg.previous();
} while (doc.isIdentifierChar(languageIndex, ch) && ch != CharacterIterator.DONE);
}
// The "word" is whitespace
else if (Character.isWhitespace(ch)) {
if (offs!=end && !Character.isWhitespace(nextCh)) {
return offs;
}
do {
ch = seg.previous();
} while (Character.isWhitespace(ch));
}
// Otherwise, the "word" a single "something else" char (operator,
// etc.).
offs -= firstIndex - seg.getIndex() + 1;//seg.getEndIndex() - seg.getIndex();
if (ch!=Segment.DONE && nextCh!='\n') {
offs++;
}
return offs;
}
}
/**
* Expands or collapses the nearest fold.
*/
public static class ChangeFoldStateAction extends FoldRelatedAction {
private boolean collapse;
public ChangeFoldStateAction(String name, boolean collapse) {
super(name);
this.collapse = collapse;
}
public ChangeFoldStateAction(String name, Icon icon,
String desc, Integer mnemonic, KeyStroke accelerator) {
super(name, icon, desc, mnemonic, accelerator);
}
@Override
public void actionPerformedImpl(ActionEvent e, RTextArea textArea) {
RSyntaxTextArea rsta = (RSyntaxTextArea)textArea;
if (rsta.isCodeFoldingEnabled()) {
Fold fold = getClosestFold(rsta);
if (fold!=null) {
fold.setCollapsed(collapse);
}
RSyntaxUtilities.possiblyRepaintGutter(textArea);
}
else {
UIManager.getLookAndFeel().provideErrorFeedback(rsta);
}
}
@Override
public final String getMacroID() {
return getName();
}
}
/**
* Action that (optionally) aligns a closing curly brace with the line
* containing its matching opening curly brace.
*/
public static class CloseCurlyBraceAction extends RecordableTextAction {
private static final long serialVersionUID = 1L;
private Point bracketInfo;
private Segment seg;
public CloseCurlyBraceAction() {
super(rstaCloseCurlyBraceAction);
seg = new Segment();
}
@Override
public void actionPerformedImpl(ActionEvent e, RTextArea textArea) {
if (!textArea.isEditable() || !textArea.isEnabled()) {
UIManager.getLookAndFeel().provideErrorFeedback(textArea);
return;
}
RSyntaxTextArea rsta = (RSyntaxTextArea)textArea;
RSyntaxDocument doc = (RSyntaxDocument)rsta.getDocument();
int languageIndex = 0;
int dot = textArea.getCaretPosition();
if (dot>0) {
Token t = RSyntaxUtilities.getTokenAtOffset(rsta, dot-1);
languageIndex = t==null ? 0 : t.getLanguageIndex();
}
boolean alignCurlyBraces = rsta.isAutoIndentEnabled() &&
doc.getCurlyBracesDenoteCodeBlocks(languageIndex);
if (alignCurlyBraces) {
textArea.beginAtomicEdit();
}
try {
textArea.replaceSelection("}");
// If the user wants to align curly braces...
if (alignCurlyBraces) {
Element root = doc.getDefaultRootElement();
dot = rsta.getCaretPosition() - 1; // Start before '}'
int line = root.getElementIndex(dot);
Element elem = root.getElement(line);
int start = elem.getStartOffset();
// Get the current line's text up to the '}' entered.
try {
doc.getText(start, dot-start, seg);
} catch (BadLocationException ble) { // Never happens
ble.printStackTrace();
return;
}
// Only attempt to align if there's only whitespace up to
// the '}' entered.
for (int i=0; i<seg.count; i++) {
char ch = seg.array[seg.offset+i];
if (!Character.isWhitespace(ch)) {
return;
}
}
// Locate the matching '{' bracket, and replace the leading
// whitespace for the '}' to match that of the '{' char's line.
bracketInfo = RSyntaxUtilities.getMatchingBracketPosition(
rsta, bracketInfo);
if (bracketInfo.y>-1) {
try {
String ws = RSyntaxUtilities.getLeadingWhitespace(
doc, bracketInfo.y);
rsta.replaceRange(ws, start, dot);
} catch (BadLocationException ble) {
ble.printStackTrace();
return;
}
}
}
} finally {
if (alignCurlyBraces) {
textArea.endAtomicEdit();
}
}
}
@Override
public final String getMacroID() {
return rstaCloseCurlyBraceAction;
}
}
/**
* (Optionally) completes a closing markup tag.
*/
public static class CloseMarkupTagAction extends RecordableTextAction {
private static final long serialVersionUID = 1L;
public CloseMarkupTagAction() {
super(rstaCloseMarkupTagAction);
}
@Override
public void actionPerformedImpl(ActionEvent e, RTextArea textArea) {
if (!textArea.isEditable() || !textArea.isEnabled()) {
UIManager.getLookAndFeel().provideErrorFeedback(textArea);
return;
}
RSyntaxTextArea rsta = (RSyntaxTextArea)textArea;
RSyntaxDocument doc = (RSyntaxDocument)rsta.getDocument();
Caret c = rsta.getCaret();
boolean selection = c.getDot()!=c.getMark();
rsta.replaceSelection("/");
// Don't automatically complete a tag if there was a selection
int dot = c.getDot();
if (doc.getLanguageIsMarkup() &&
doc.getCompleteMarkupCloseTags() &&
!selection && rsta.getCloseMarkupTags() && dot>1) {
try {
// Check actual char before token type, since it's quicker
char ch = doc.charAt(dot-2);
if (ch=='<' || ch=='[') {
Token t = doc.getTokenListForLine(
rsta.getCaretLineNumber());
t = RSyntaxUtilities.getTokenAtOffset(t, dot-1);
if (t!=null && t.getType()==Token.MARKUP_TAG_DELIMITER) { // Closing tag
String tagName = discoverTagName(doc, dot);
if (tagName!=null) {
rsta.replaceSelection(tagName + (char)(ch+2));
}
}
}
} catch (BadLocationException ble) { // Never happens
UIManager.getLookAndFeel().provideErrorFeedback(rsta);
ble.printStackTrace();
}
}
}
/**
* Discovers the name of the tag being closed. Assumes standard
* SGML-style markup tags.
*
* @param doc The document to parse.
* @param dot The location of the caret. This should be right after
* the start of a closing tag token (e.g. "<code></</code>"
* or "<code>[</code>" in the case of BBCode).
* @return The name of the tag to close, or <code>null</code> if it
* could not be determined.
*/
private String discoverTagName(RSyntaxDocument doc, int dot) {
Stack<String> stack = new Stack<>();
Element root = doc.getDefaultRootElement();
int curLine = root.getElementIndex(dot);
for (int i=0; i<=curLine; i++) {
Token t = doc.getTokenListForLine(i);
while (t!=null && t.isPaintable()) {
if (t.getType()==Token.MARKUP_TAG_DELIMITER) {
if (t.isSingleChar('<') || t.isSingleChar('[')) {
t = t.getNextToken();
while (t!=null && t.isPaintable()) {
if (t.getType()==Token.MARKUP_TAG_NAME ||
// Being lenient here and also checking
// for attributes, in case they
// (incorrectly) have whitespace between
// the '<' char and the element name.
t.getType()==Token.MARKUP_TAG_ATTRIBUTE) {
stack.push(t.getLexeme());
break;
}
t = t.getNextToken();
}
}
else if (t.length()==2 && t.charAt(0)=='/' &&
(t.charAt(1)=='>' ||
t.charAt(1)==']')) {
if (!stack.isEmpty()) { // Always true for valid XML
stack.pop();
}
}
else if (t.length()==2 &&
(t.charAt(0)=='<' || t.charAt(0)=='[') &&
t.charAt(1)=='/') {
String tagName = null;
if (!stack.isEmpty()) { // Always true for valid XML
tagName = stack.pop();
}
if (t.getEndOffset()>=dot) {
return tagName;
}
}
}
t = t==null ? null : t.getNextToken();
}
}
return null; // Should never happen
}
@Override
public String getMacroID() {
return getName();
}
}
/**
* Collapses all comment folds.
*/
public static class CollapseAllCommentFoldsAction extends FoldRelatedAction{
private static final long serialVersionUID = 1L;
public CollapseAllCommentFoldsAction() {
super(rstaCollapseAllCommentFoldsAction);
setProperties(msg, "Action.CollapseCommentFolds");
}
public CollapseAllCommentFoldsAction(String name, Icon icon,
String desc, Integer mnemonic, KeyStroke accelerator) {
super(name, icon, desc, mnemonic, accelerator);
}
@Override
public void actionPerformedImpl(ActionEvent e, RTextArea textArea) {
RSyntaxTextArea rsta = (RSyntaxTextArea)textArea;
if (rsta.isCodeFoldingEnabled()) {
FoldCollapser collapser = new FoldCollapser();
collapser.collapseFolds(rsta.getFoldManager());
RSyntaxUtilities.possiblyRepaintGutter(textArea);
}
else {
UIManager.getLookAndFeel().provideErrorFeedback(rsta);
}
}
@Override
public final String getMacroID() {
return rstaCollapseAllCommentFoldsAction;
}
}
/**
* Collapses all folds.
*/
public static class CollapseAllFoldsAction extends FoldRelatedAction {
private static final long serialVersionUID = 1L;
public CollapseAllFoldsAction() {
this(false);
}
public CollapseAllFoldsAction(boolean localizedName) {
super(rstaCollapseAllFoldsAction);
if (localizedName) {
setProperties(msg, "Action.CollapseAllFolds");
}
}
public CollapseAllFoldsAction(String name, Icon icon,
String desc, Integer mnemonic, KeyStroke accelerator) {
super(name, icon, desc, mnemonic, accelerator);
}
@Override
public void actionPerformedImpl(ActionEvent e, RTextArea textArea) {
RSyntaxTextArea rsta = (RSyntaxTextArea)textArea;
if (rsta.isCodeFoldingEnabled()) {
FoldCollapser collapser = new FoldCollapser() {
@Override
public boolean getShouldCollapse(Fold fold) {
return true;
}
};
collapser.collapseFolds(rsta.getFoldManager());
RSyntaxUtilities.possiblyRepaintGutter(textArea);
}
else {
UIManager.getLookAndFeel().provideErrorFeedback(rsta);
}
}
@Override
public final String getMacroID() {
return rstaCollapseAllFoldsAction;
}
}
/**
* Action for copying text as styled text.
*/
public static class CopyCutAsStyledTextAction extends RecordableTextAction {
private Theme theme;
private boolean cutAction;
private static final long serialVersionUID = 2L;
private static String getActionName(boolean cutAction) {
return cutAction ? rstaCutAsStyledTextAction : rstaCopyAsStyledTextAction;
}
public CopyCutAsStyledTextAction(boolean cutAction) {
super(getActionName(cutAction));
this.cutAction = cutAction;
}
public CopyCutAsStyledTextAction(String themeName, Theme theme, boolean cutAction) {
super(getActionName(cutAction) + "_" + themeName);
this.theme = theme;
this.cutAction = cutAction;
}
public CopyCutAsStyledTextAction(String name, Icon icon, String desc,
Integer mnemonic, KeyStroke accelerator) {
super(name, icon, desc, mnemonic, accelerator);
}
@Override
public void actionPerformedImpl(ActionEvent e, RTextArea textArea) {
if (cutAction && (!textArea.isEditable() || !textArea.isEnabled())) {
UIManager.getLookAndFeel().provideErrorFeedback(textArea);
return;
}
((RSyntaxTextArea)textArea).copyAsStyledText(theme);
if (cutAction) {
int selStart = textArea.getSelectionStart();
int selEnd = textArea.getSelectionEnd();
try {
textArea.getDocument().remove(selStart, selEnd - selStart);
} catch (BadLocationException ble) {
ble.printStackTrace();
UIManager.getLookAndFeel().provideErrorFeedback(textArea);
}
}
textArea.requestFocusInWindow();
}
@Override
public final String getMacroID() {
return getName();
}
}
/**
* Action for decreasing the font size of all fonts in the text area.
*/
public static class DecreaseFontSizeAction
extends RTextAreaEditorKit.DecreaseFontSizeAction {
private static final long serialVersionUID = 1L;
public DecreaseFontSizeAction() {
super();
}
public DecreaseFontSizeAction(String name, Icon icon, String desc,
Integer mnemonic, KeyStroke accelerator) {
super(name, icon, desc, mnemonic, accelerator);
}
@Override
public void actionPerformedImpl(ActionEvent e, RTextArea textArea) {
RSyntaxTextArea rsta = (RSyntaxTextArea)textArea;
SyntaxScheme scheme = rsta.getSyntaxScheme();
// All we need to do is update all the fonts in syntax
// schemes, then call setSyntaxHighlightingColorScheme with the
// same scheme already being used. This relies on the fact that
// that method does not check whether the new scheme is different
// from the old scheme before updating.
boolean changed = false;
int count = scheme.getStyleCount();
for (int i=0; i<count; i++) {
Style ss = scheme.getStyle(i);
if (ss!=null) {
Font font = ss.font;
if (font!=null) {
float oldSize = font.getSize2D();
float newSize = oldSize - decreaseAmount;
if (newSize>=MINIMUM_SIZE) {
// Shrink by decreaseAmount.
ss.font = font.deriveFont(newSize);
changed = true;
}
else if (oldSize>MINIMUM_SIZE) {
// Can't shrink by full decreaseAmount, but
// can shrink a little bit.
ss.font = font.deriveFont(MINIMUM_SIZE);
changed = true;
}
}
}
}
// Do the text area's font also.
Font font = rsta.getFont();
float oldSize = font.getSize2D();
float newSize = oldSize - decreaseAmount;
if (newSize>=MINIMUM_SIZE) {
// Shrink by decreaseAmount.
rsta.setFont(font.deriveFont(newSize));
changed = true;
}
else if (oldSize>MINIMUM_SIZE) {
// Can't shrink by full decreaseAmount, but
// can shrink a little bit.
rsta.setFont(font.deriveFont(MINIMUM_SIZE));
changed = true;
}
// If we updated at least one font, update the screen. If
// all the fonts were already the minimum size, beep.
if (changed) {
rsta.setSyntaxScheme(scheme);
// NOTE: This is a hack to get an encompassing
// RTextScrollPane to repaint its line numbers to account
// for a change in line height due to a font change. I'm
// not sure why we need to do this here but not when we
// change the syntax highlighting color scheme via the
// Options dialog... setSyntaxHighlightingColorScheme()
// calls revalidate() which won't repaint the scroll pane
// if scrollbars don't change, which is why we need this.
Component parent = rsta.getParent();
if (parent instanceof javax.swing.JViewport) {
parent = parent.getParent();
if (parent instanceof JScrollPane) {
parent.repaint();
}
}
}
else {
UIManager.getLookAndFeel().provideErrorFeedback(rsta);
}
}
}
/**
* Action for when un-indenting lines (either the current line if there is
* selection, or all selected lines if there is one).
*/
public static class DecreaseIndentAction extends RecordableTextAction {
private static final long serialVersionUID = 1L;
private Segment s;
public DecreaseIndentAction() {
this(rstaDecreaseIndentAction);
}
public DecreaseIndentAction(String name) {
super(name);
s = new Segment();
}
@Override
public void actionPerformedImpl(ActionEvent e, RTextArea textArea) {
if (!textArea.isEditable() || !textArea.isEnabled()) {
UIManager.getLookAndFeel().provideErrorFeedback(textArea);
return;
}
Document document = textArea.getDocument();
Element map = document.getDefaultRootElement();
Caret c = textArea.getCaret();
int dot = c.getDot();
int mark = c.getMark();
int line1 = map.getElementIndex(dot);
int tabSize = textArea.getTabSize();
// If there is a selection, indent all lines in the selection.
// Otherwise, indent the line the caret is on.
if (dot!=mark) {
// Note that we cheaply reuse variables here, so don't
// take their names to mean what they are.
int line2 = map.getElementIndex(mark);
dot = Math.min(line1, line2);
mark = Math.max(line1, line2);
Element elem;
textArea.beginAtomicEdit();
try {
for (line1=dot; line1<mark; line1++) {
elem = map.getElement(line1);
handleDecreaseIndent(elem, document, tabSize);
}
// Don't do the last line if the caret is at its
// beginning. We must call getDot() again and not just
// use 'dot' as the caret's position may have changed
// due to the insertion of the tabs above.
elem = map.getElement(mark);
int start = elem.getStartOffset();
if (Math.max(c.getDot(),c.getMark())!=start) {
handleDecreaseIndent(elem, document, tabSize);
}
} catch (BadLocationException ble) {
ble.printStackTrace();
UIManager.getLookAndFeel().
provideErrorFeedback(textArea);
} finally {
textArea.endAtomicEdit();
}
}
else {
Element elem = map.getElement(line1);
try {
handleDecreaseIndent(elem, document, tabSize);
} catch (BadLocationException ble) {
ble.printStackTrace();
UIManager.getLookAndFeel().
provideErrorFeedback(textArea);
}
}
}
@Override
public final String getMacroID() {
return rstaDecreaseIndentAction;
}
/**
* Actually does the "de-indentation." This method finds where the
* given element's leading whitespace ends, then, if there is indeed
* leading whitespace, removes either the last char in it (if it is a
* tab), or removes up to the number of spaces equal to a tab in the
* specified document (i.e., if the tab size was 5 and there were 3
* spaces at the end of the leading whitespace, the three will be
* removed; if there were 8 spaces, only the first 5 would be
* removed).
*
* @param elem The element to "de-indent."
* @param doc The document containing the specified element.
* @param tabSize The size of a tab, in spaces.
*/
private void handleDecreaseIndent(Element elem, Document doc,
int tabSize)
throws BadLocationException {
int start = elem.getStartOffset();
int end = elem.getEndOffset() - 1; // Why always true??
doc.getText(start,end-start, s);
int i = s.offset;
end = i+s.count;
if (end>i) {
// If the first character is a tab, remove it.
if (s.array[i]=='\t') {
doc.remove(start, 1);
}
// Otherwise, see if the first character is a space. If it
// is, remove all contiguous whitespaces at the beginning of
// this line, up to the tab size.
else if (s.array[i]==' ') {
i++;
int toRemove = 1;
while (i<end && s.array[i]==' ' && toRemove<tabSize) {
i++;
toRemove++;
}
doc.remove(start, toRemove);
}
}
}
}
/**
* Deletes the previous word, but differentiates symbols from "words" to
* match the behavior of code editors.
*/
public static class DeletePrevWordAction
extends RTextAreaEditorKit.DeletePrevWordAction {
private Segment seg = new Segment();
@Override
protected int getPreviousWordStart(RTextArea textArea, int offs)
throws BadLocationException {
if (offs==0) {
return offs;
}
RSyntaxDocument doc = (RSyntaxDocument)textArea.getDocument();
int line = textArea.getLineOfOffset(offs);
int start = textArea.getLineStartOffset(line);
if (offs==start) {
return start-1; // Just delete the newline
}
int end = textArea.getLineEndOffset(line);
if (line!=textArea.getLineCount()-1) {
end--;
}
doc.getText(start, end-start, seg);
// Determine the "type" of char at offs - lower case, upper case,
// whitespace or other. We take special care here as we're starting
// in the middle of the Segment to check whether we're already at
// the "beginning" of a word.
int firstIndex = seg.getBeginIndex() + (offs-start) - 1;
seg.setIndex(firstIndex);
char ch = seg.current();
// Always strip off whitespace first
if (Character.isWhitespace(ch)) {
do {
ch = seg.previous();
} while (Character.isWhitespace(ch));
}
// The "word" is a group of letters and/or digits
int languageIndex = 0; // TODO
if (doc.isIdentifierChar(languageIndex, ch)) {
do {
ch = seg.previous();
} while (doc.isIdentifierChar(languageIndex, ch));
}
// The "word" is a series of symbols.
else {
while (!Character.isWhitespace(ch) &&
!doc.isIdentifierChar(languageIndex, ch) &&
ch!=Segment.DONE) {
ch = seg.previous();
}
}
if (ch==Segment.DONE) {
return start; // Removed last "token" of the line
}
offs -= firstIndex - seg.getIndex();
return offs;