1
2
3
4
5
6
7
8
9 package com.ochafik.swing.syntaxcoloring;
10
11 import javax.swing.event.DocumentEvent;
12 import javax.swing.text.BadLocationException;
13 import javax.swing.text.Element;
14 import javax.swing.text.PlainDocument;
15 import javax.swing.text.Segment;
16 import javax.swing.undo.UndoableEdit;
17
18
19
20
21
22
23
24
25 public class SyntaxDocument extends PlainDocument
26 {
27
28
29
30
31
32 public TokenMarker getTokenMarker()
33 {
34 return tokenMarker;
35 }
36
37
38
39
40
41
42
43 public void setTokenMarker(TokenMarker tm)
44 {
45 tokenMarker = tm;
46 if(tm == null)
47 return;
48 tokenMarker.insertLines(0,getDefaultRootElement()
49 .getElementCount());
50 tokenizeLines();
51 }
52
53
54
55
56
57
58 public void tokenizeLines()
59 {
60 tokenizeLines(0,getDefaultRootElement().getElementCount());
61 }
62
63
64
65
66
67
68
69
70 public void tokenizeLines(int start, int len)
71 {
72 if(tokenMarker == null || !tokenMarker.supportsMultilineTokens())
73 return;
74
75 Segment lineSegment = new Segment();
76 Element map = getDefaultRootElement();
77
78 len += start;
79
80 try
81 {
82 for(int i = start; i < len; i++)
83 {
84 Element lineElement = map.getElement(i);
85 int lineStart = lineElement.getStartOffset();
86 getText(lineStart,lineElement.getEndOffset()
87 - lineStart - 1,lineSegment);
88 tokenMarker.markTokens(lineSegment,i);
89 }
90 }
91 catch(BadLocationException bl)
92 {
93 bl.printStackTrace();
94 }
95 }
96
97
98
99
100
101
102
103 public void beginCompoundEdit() {}
104
105
106
107
108
109
110
111 public void endCompoundEdit() {}
112
113
114
115
116
117
118
119
120 public void addUndoableEdit(UndoableEdit edit) {}
121
122
123 protected TokenMarker tokenMarker;
124
125
126
127
128
129
130 protected void fireInsertUpdate(DocumentEvent evt)
131 {
132 if(tokenMarker != null)
133 {
134 DocumentEvent.ElementChange ch = evt.getChange(
135 getDefaultRootElement());
136 if(ch != null)
137 {
138 tokenMarker.insertLines(ch.getIndex() + 1,
139 ch.getChildrenAdded().length -
140 ch.getChildrenRemoved().length);
141 }
142 }
143
144 super.fireInsertUpdate(evt);
145 }
146
147
148
149
150
151
152 protected void fireRemoveUpdate(DocumentEvent evt)
153 {
154 if(tokenMarker != null)
155 {
156 DocumentEvent.ElementChange ch = evt.getChange(
157 getDefaultRootElement());
158 if(ch != null)
159 {
160 tokenMarker.deleteLines(ch.getIndex() + 1,
161 ch.getChildrenRemoved().length -
162 ch.getChildrenAdded().length);
163 }
164 }
165
166 super.fireRemoveUpdate(evt);
167 }
168 }