1 package net.sourceforge.phpdt.internal.ui.text;
4 * (c) Copyright IBM Corp. 2000, 2001.
8 import java.io.IOException;
10 import org.eclipse.jface.text.BadLocationException;
11 import org.eclipse.jface.text.IDocument;
12 import org.eclipse.jface.text.IRegion;
13 import org.eclipse.jface.text.Region;
14 import org.eclipse.jface.text.source.ICharacterPairMatcher;
17 * Helper class for match pairs of characters.
19 public class PHPPairMatcher implements ICharacterPairMatcher {
20 protected char[] fPairs;
22 protected IDocument fDocument;
24 protected int fOffset;
26 protected int fStartPos;
28 protected int fEndPos;
30 protected int fAnchor;
32 protected PHPCodeReader fReader = new PHPCodeReader();
34 public PHPPairMatcher(char[] pairs) {
39 * @see org.eclipse.jface.text.source.ICharacterPairMatcher#clear()
42 if (fReader != null) {
45 } catch (IOException x) {
51 public IRegion match(IDocument document, int offset) {
60 if (matchPairsAt() && fStartPos != fEndPos)
61 return new Region(fStartPos, fEndPos - fStartPos + 1);
66 public int getAnchor() {
70 public void dispose() {
72 if (fReader != null) {
75 } catch (IOException x) {
82 protected boolean matchPairsAt() {
85 int pairIndex1 = fPairs.length;
86 int pairIndex2 = fPairs.length;
91 // get the chars preceding and following the start position
94 char prevChar = fDocument.getChar(Math.max(fOffset - 1, 0));
95 char nextChar = fDocument.getChar(fOffset);
97 // search for opening peer character next to the activation point
98 for (i = 0; i < fPairs.length; i = i + 2) {
99 if (nextChar == fPairs[i]) {
102 } else if (prevChar == fPairs[i]) {
103 fStartPos = fOffset - 1;
108 // search for closing peer character next to the activation point
109 for (i = 1; i < fPairs.length; i = i + 2) {
110 if (prevChar == fPairs[i]) {
111 fEndPos = fOffset - 1;
113 } else if (nextChar == fPairs[i]) {
121 fStartPos = searchForOpeningPeer(fEndPos,
122 fPairs[pairIndex2 - 1], fPairs[pairIndex2], fDocument);
127 } else if (fStartPos > -1) {
129 fEndPos = searchForClosingPeer(fStartPos, fPairs[pairIndex1],
130 fPairs[pairIndex1 + 1], fDocument);
137 } catch (BadLocationException x) {
138 } catch (IOException x) {
144 protected int searchForClosingPeer(int offset, int openingPeer,
145 int closingPeer, IDocument document) throws IOException {
147 fReader.configureForwardReader(document, offset + 1, document
148 .getLength(), true, true);
151 int c = fReader.read();
152 while (c != PHPCodeReader.EOF) {
153 if (c == openingPeer && c != closingPeer)
155 else if (c == closingPeer)
159 return fReader.getOffset();
167 protected int searchForOpeningPeer(int offset, int openingPeer,
168 int closingPeer, IDocument document) throws IOException {
170 fReader.configureBackwardReader(document, offset, true, true);
173 int c = fReader.read();
174 while (c != PHPCodeReader.EOF) {
175 if (c == closingPeer && c != openingPeer)
177 else if (c == openingPeer)
181 return fReader.getOffset();