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, fPairs[pairIndex2 - 1], fPairs[pairIndex2], fDocument);
126 } else if (fStartPos > -1) {
128 fEndPos = searchForClosingPeer(fStartPos, fPairs[pairIndex1], fPairs[pairIndex1 + 1], fDocument);
135 } catch (BadLocationException x) {
136 } catch (IOException x) {
142 protected int searchForClosingPeer(int offset, int openingPeer, int closingPeer, IDocument document) throws IOException {
144 fReader.configureForwardReader(document, offset + 1, document.getLength(), true, true);
147 int c = fReader.read();
148 while (c != PHPCodeReader.EOF) {
149 if (c == openingPeer && c != closingPeer)
151 else if (c == closingPeer)
155 return fReader.getOffset();
163 protected int searchForOpeningPeer(int offset, int openingPeer, int closingPeer, IDocument document) throws IOException {
165 fReader.configureBackwardReader(document, offset, true, true);
168 int c = fReader.read();
169 while (c != PHPCodeReader.EOF) {
170 if (c == closingPeer && c != openingPeer)
172 else if (c == openingPeer)
176 return fReader.getOffset();