1 package bluej.editor.moe; 2 3 11 12 import javax.swing.text.*; 13 14 19 public class TextUtilities 20 { 21 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; boolean direction; 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 55 if(direction) 57 { 58 count = 1; 61 62 String text = doc.getText(0,offset); 64 65 for(int i = offset - 1; i >= 0; i--) 67 { 68 char x = text.charAt(i); 73 if(x == c) 74 count++; 75 76 else if(x == cprime) 80 { 81 if(--count == 0) 82 return i; 83 } 84 } 85 } 86 else 87 { 88 count = 1; 91 92 offset++; 94 95 int len = doc.getLength() - offset; 97 98 String text = doc.getText(offset,len); 100 101 for(int i = 0; i < len; i++) 103 { 104 char x = text.charAt(i); 109 110 if(x == c) 111 count++; 112 113 else if(x == cprime) 117 { 118 if(--count == 0) 119 return i + offset; 120 } 121 } 122 } 123 124 return -1; 126 } 127 128 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 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 } 185 | Popular Tags |