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;
16 * Helper class for match pairs of characters.
18 public class PHPPairMatcher {
21 public static final int LEFT= 1;
22 public static final int RIGHT= 2;
25 protected char[] fPairs;
26 protected IDocument fDocument;
27 protected int fOffset;
29 protected int fStartPos;
30 protected int fEndPos;
31 protected int fAnchor;
33 protected PHPCodeReader fReader= new PHPCodeReader();
36 public PHPPairMatcher(char[] pairs) {
40 public IRegion match(IDocument document, int offset) {
49 if (matchPairsAt() && fStartPos != fEndPos)
50 return new Region(fStartPos, fEndPos - fStartPos + 1);
55 public int getAnchor() {
59 public void dispose() {
61 if (fReader != null) {
64 } catch (IOException x) {
71 protected boolean matchPairsAt() {
74 int pairIndex1= fPairs.length;
75 int pairIndex2= fPairs.length;
80 // get the chars preceding and following the start position
83 char prevChar= fDocument.getChar(Math.max(fOffset - 1, 0));
84 char nextChar= fDocument.getChar(fOffset);
86 // search for opening peer character next to the activation point
87 for (i= 0; i < fPairs.length; i= i + 2) {
88 if (nextChar == fPairs[i]) {
91 } else if (prevChar == fPairs[i]) {
92 fStartPos= fOffset - 1;
97 // search for closing peer character next to the activation point
98 for (i= 1; i < fPairs.length; i= i + 2) {
99 if (prevChar == fPairs[i]) {
100 fEndPos= fOffset - 1;
102 } else if (nextChar == fPairs[i]) {
110 fStartPos= searchForOpeningPeer(fEndPos, fPairs[pairIndex2 - 1], fPairs[pairIndex2], fDocument);
115 } else if (fStartPos > -1) {
117 fEndPos= searchForClosingPeer(fStartPos, fPairs[pairIndex1], fPairs[pairIndex1 + 1], fDocument);
124 } catch (BadLocationException x) {
125 } catch (IOException x) {
131 protected int searchForClosingPeer(int offset, int openingPeer, int closingPeer, IDocument document) throws IOException {
133 fReader.configureForwardReader(document, offset + 1, document.getLength(), true, true);
136 int c= fReader.read();
137 while (c != PHPCodeReader.EOF) {
138 if (c == openingPeer && c != closingPeer)
140 else if (c == closingPeer)
144 return fReader.getOffset();
152 protected int searchForOpeningPeer(int offset, int openingPeer, int closingPeer, IDocument document) throws IOException {
154 fReader.configureBackwardReader(document, offset, true, true);
157 int c= fReader.read();
158 while (c != PHPCodeReader.EOF) {
159 if (c == closingPeer && c != openingPeer)
161 else if (c == openingPeer)
165 return fReader.getOffset();