01: package org.drools.eclipse.editors;
02:
03: import java.util.Stack;
04:
05: import org.drools.eclipse.DroolsEclipsePlugin;
06: import org.eclipse.jface.text.BadLocationException;
07: import org.eclipse.jface.text.IDocument;
08: import org.eclipse.jface.text.IRegion;
09: import org.eclipse.jface.text.Region;
10: import org.eclipse.jface.text.source.ICharacterPairMatcher;
11:
12: public final class DroolsPairMatcher implements ICharacterPairMatcher {
13:
14: private int anchor;
15: private static final char[] leftChars = new char[] { '(', '{', '[' };
16: private static final char[] rightChars = new char[] { ')', '}', ']' };
17:
18: public IRegion match(IDocument document, int offset) {
19: if (offset <= 0) {
20: return null;
21: }
22: try {
23: char c = document.getChar(offset - 1);
24: for (int i = 0; i < rightChars.length; i++) {
25: if (c == rightChars[i]) {
26: return searchLeft(document, offset, rightChars[i],
27: leftChars[i]);
28: }
29: if (c == leftChars[i]) {
30: return searchRight(document, offset, rightChars[i],
31: leftChars[i]);
32: }
33: }
34: } catch (BadLocationException e) {
35: DroolsEclipsePlugin.log(e);
36: }
37: return null;
38: }
39:
40: private IRegion searchRight(IDocument document, int offset,
41: char rightChar, char leftChar) throws BadLocationException {
42: Stack stack = new Stack();
43: anchor = ICharacterPairMatcher.LEFT;
44: char[] chars = document.get(offset,
45: document.getLength() - offset).toCharArray();
46: for (int i = 0; i < chars.length; i++) {
47: if (chars[i] == leftChar) {
48: stack.push(new Character(chars[i]));
49: continue;
50: }
51: if (chars[i] == rightChar) {
52: if (stack.isEmpty()) {
53: return new Region(offset - 1, i + 2);
54: } else {
55: stack.pop();
56: }
57: }
58: }
59: return null;
60: }
61:
62: private IRegion searchLeft(IDocument document, int offset,
63: char rightChar, char leftChar) throws BadLocationException {
64: Stack stack = new Stack();
65: anchor = ICharacterPairMatcher.RIGHT;
66: char[] chars = document.get(0, offset - 1).toCharArray();
67: for (int i = chars.length - 1; i >= 0; i--) {
68: if (chars[i] == rightChar) {
69: stack.push(new Character(chars[i]));
70: continue;
71: }
72: if (chars[i] == leftChar) {
73: if (stack.isEmpty()) {
74: return new Region(i, offset - i);
75: } else {
76: stack.pop();
77: }
78: }
79: }
80: return null;
81: }
82:
83: public int getAnchor() {
84: return anchor;
85: }
86:
87: public void dispose() {
88: }
89:
90: public void clear() {
91: }
92:
93: }
|