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 {
22 public static final int LEFT= 1;
23 public static final int RIGHT= 2;
26 protected char[] fPairs;
27 protected IDocument fDocument;
28 protected int fOffset;
30 protected int fStartPos;
31 protected int fEndPos;
32 protected int fAnchor;
34 protected PHPCodeReader fReader= new PHPCodeReader();
37 public PHPPairMatcher(char[] pairs) {
42 * @see org.eclipse.jface.text.source.ICharacterPairMatcher#clear()
45 if (fReader != null) {
48 } catch (IOException x) {
54 public IRegion match(IDocument document, int offset) {
63 if (matchPairsAt() && fStartPos != fEndPos)
64 return new Region(fStartPos, fEndPos - fStartPos + 1);
69 public int getAnchor() {
73 public void dispose() {
75 if (fReader != null) {
78 } catch (IOException x) {
85 protected boolean matchPairsAt() {
88 int pairIndex1= fPairs.length;
89 int pairIndex2= fPairs.length;
94 // get the chars preceding and following the start position
97 char prevChar= fDocument.getChar(Math.max(fOffset - 1, 0));
98 char nextChar= fDocument.getChar(fOffset);
100 // search for opening peer character next to the activation point
101 for (i= 0; i < fPairs.length; i= i + 2) {
102 if (nextChar == fPairs[i]) {
105 } else if (prevChar == fPairs[i]) {
106 fStartPos= fOffset - 1;
111 // search for closing peer character next to the activation point
112 for (i= 1; i < fPairs.length; i= i + 2) {
113 if (prevChar == fPairs[i]) {
114 fEndPos= fOffset - 1;
116 } else if (nextChar == fPairs[i]) {
124 fStartPos= searchForOpeningPeer(fEndPos, fPairs[pairIndex2 - 1], fPairs[pairIndex2], fDocument);
129 } else if (fStartPos > -1) {
131 fEndPos= searchForClosingPeer(fStartPos, fPairs[pairIndex1], fPairs[pairIndex1 + 1], fDocument);
138 } catch (BadLocationException x) {
139 } catch (IOException x) {
145 protected int searchForClosingPeer(int offset, int openingPeer, int closingPeer, IDocument document) throws IOException {
147 fReader.configureForwardReader(document, offset + 1, document.getLength(), true, true);
150 int c= fReader.read();
151 while (c != PHPCodeReader.EOF) {
152 if (c == openingPeer && c != closingPeer)
154 else if (c == closingPeer)
158 return fReader.getOffset();
166 protected int searchForOpeningPeer(int offset, int openingPeer, int closingPeer, IDocument document) throws IOException {
168 fReader.configureBackwardReader(document, offset, true, true);
171 int c= fReader.read();
172 while (c != PHPCodeReader.EOF) {
173 if (c == closingPeer && c != openingPeer)
175 else if (c == openingPeer)
179 return fReader.getOffset();