1
2
3
4
5
6
7
8
9 package com.ochafik.swing.syntaxcoloring;
10 import javax.swing.text.BadLocationException;
11 import javax.swing.text.Document;
12
13
14
15
16
17
18
19 public class TextUtilities
20 {
21
22
23
24
25
26
27
28
29
30 public static int findMatchingBracket(Document doc, int offset)
31 throws BadLocationException
32 {
33 if(doc.getLength() == 0)
34 return -1;
35 char c = doc.getText(offset,1).charAt(0);
36 char cprime;
37 boolean direction;
38
39 switch(c)
40 {
41 case '(': cprime = ')'; direction = false; break;
42 case ')': cprime = '('; direction = true; break;
43 case '[': cprime = ']'; direction = false; break;
44 case ']': cprime = '['; direction = true; break;
45 case '{': cprime = '}'; direction = false; break;
46 case '}': cprime = '{'; direction = true; break;
47 default: return -1;
48 }
49
50 int count;
51
52
53
54
55
56 if(direction)
57 {
58
59
60 count = 1;
61
62
63 String text = doc.getText(0,offset);
64
65
66 for(int i = offset - 1; i >= 0; i--)
67 {
68
69
70
71
72 char x = text.charAt(i);
73 if(x == c)
74 count++;
75
76
77
78
79 else if(x == cprime)
80 {
81 if(--count == 0)
82 return i;
83 }
84 }
85 }
86 else
87 {
88
89
90 count = 1;
91
92
93 offset++;
94
95
96 int len = doc.getLength() - offset;
97
98
99 String text = doc.getText(offset,len);
100
101
102 for(int i = 0; i < len; i++)
103 {
104
105
106
107
108 char x = text.charAt(i);
109
110 if(x == c)
111 count++;
112
113
114
115
116 else if(x == cprime)
117 {
118 if(--count == 0)
119 return i + offset;
120 }
121 }
122 }
123
124
125 return -1;
126 }
127
128
129
130
131
132
133 public static int findWordStart(String line, int pos, String noWordSep)
134 {
135 char ch = line.charAt(pos - 1);
136
137 if(noWordSep == null)
138 noWordSep = "";
139 boolean selectNoLetter = (!Character.isLetterOrDigit(ch)
140 && noWordSep.indexOf(ch) == -1);
141
142 int wordStart = 0;
143 for(int i = pos - 1; i >= 0; i--)
144 {
145 ch = line.charAt(i);
146 if(selectNoLetter ^ (!Character.isLetterOrDigit(ch) &&
147 noWordSep.indexOf(ch) == -1))
148 {
149 wordStart = i + 1;
150 break;
151 }
152 }
153
154 return wordStart;
155 }
156
157
158
159
160
161
162 public static int findWordEnd(String line, int pos, String noWordSep)
163 {
164 char ch = line.charAt(pos);
165
166 if(noWordSep == null)
167 noWordSep = "";
168 boolean selectNoLetter = (!Character.isLetterOrDigit(ch)
169 && noWordSep.indexOf(ch) == -1);
170
171 int wordEnd = line.length();
172 for(int i = pos; i < line.length(); i++)
173 {
174 ch = line.charAt(i);
175 if(selectNoLetter ^ (!Character.isLetterOrDigit(ch) &&
176 noWordSep.indexOf(ch) == -1))
177 {
178 wordEnd = i;
179 break;
180 }
181 }
182 return wordEnd;
183 }
184 }