2 * Copyright (c) 2003-2004 Christopher Lenz and others.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Common Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/cpl-v10.html
9 * Christopher Lenz - initial API and implementation
11 * $Id: CssPairMatcher.java,v 1.1 2004-09-02 18:11:48 jsurfer Exp $
14 package net.sourceforge.phpeclipse.css.ui.internal.text;
16 import net.sourceforge.phpeclipse.css.core.internal.text.CssTextUtils;
18 import org.eclipse.jface.text.BadLocationException;
19 import org.eclipse.jface.text.IDocument;
20 import org.eclipse.jface.text.IRegion;
21 import org.eclipse.jface.text.Region;
22 import org.eclipse.jface.text.source.ICharacterPairMatcher;
23 import org.eclipse.jface.util.Assert;
28 public class CssPairMatcher implements ICharacterPairMatcher {
30 // Constants ---------------------------------------------------------------
32 private static final char PAIRS[] = {
33 '{', '}', '(', ')', '[', ']'
36 // Instance Variables ------------------------------------------------------
38 private IDocument document;
44 // ICharacterPairMatcher Implementation ------------------------------------
47 * @see ICharacterPairMatcher#clear
56 * @see ICharacterPairMatcher#dispose
58 public void dispose() {
63 * @see ICharacterPairMatcher#match
65 public IRegion match(IDocument document, int offset) {
66 Assert.isNotNull(document);
67 Assert.isLegal(offset >= 0);
68 this.document = document;
71 IRegion retVal = null;
73 retVal = matchPairsAt();
74 } catch (BadLocationException e) {
75 // ignore, there's probably no matching character to highlight
81 * @see ICharacterPairMatcher#getAnchor
83 public int getAnchor() {
87 // Private Methods ---------------------------------------------------------
89 private boolean isClosingCharacter(char ch) {
90 for (int i = 1; i < PAIRS.length; i += 2) {
98 private boolean isOpeningCharacter(char ch) {
99 for (int i = 0; i < PAIRS.length; i += 2) {
100 if (ch == PAIRS[i]) {
107 private IRegion matchPairsAt() throws BadLocationException {
108 int startPos = -1, endPos = -1;
109 char prevChar = document.getChar(Math.max(offset - 1, 0));
110 if (isOpeningCharacter(prevChar)) {
111 startPos = offset - 1;
114 endPos = CssTextUtils.findMatchingClosingPeer(
115 document, startPos + 1, prevChar);
117 return new Region(startPos, endPos - startPos + 1);
121 if (isClosingCharacter(prevChar)) {
125 startPos = CssTextUtils.findMatchingOpeningPeer(
126 document, endPos - 1, prevChar);
128 return new Region(startPos, endPos - startPos + 1);