001 package nl.cwi.sen1.gui.plugin.editor;
002
003 /*
004 * TextUtilities.java - Utility functions used by the text area classes
005 * Copyright (C) 1999 Slava Pestov
006 *
007 * You may use and modify this package for any purpose. Redistribution is
008 * permitted, in both source and binary form, provided that this notice
009 * remains intact in all source distributions of this package.
010 */
011
012 import javax.swing.text.Document;
013 import javax.swing.text.BadLocationException;
014
015 public class TextUtilities {
016 public static int findMatchingBracket(Document doc, int offset)
017 throws BadLocationException {
018 if (doc.getLength() == 0) {
019 return -1;
020 }
021
022 char c = doc.getText(offset, 1).charAt(0);
023 char cprime; // c' - corresponding character
024 boolean direction; // true = back, false = forward
025
026 switch (c) {
027 case '(':
028 cprime = ')';
029 direction = false;
030 break;
031 case ')':
032 cprime = '(';
033 direction = true;
034 break;
035 case '[':
036 cprime = ']';
037 direction = false;
038 break;
039 case ']':
040 cprime = '[';
041 direction = true;
042 break;
043 case '{':
044 cprime = '}';
045 direction = false;
046 break;
047 case '}':
048 cprime = '{';
049 direction = true;
050 break;
051 default:
052 return -1;
053 }
054
055 int count = 0;
056
057 if (direction) {
058 String text = doc.getText(0, offset);
059
060 for (int i = offset - 1; i >= 0; i--) {
061 char x = text.charAt(i);
062
063 if (x == c) {
064 count++;
065 } else if (x == cprime) {
066 if (count == 0) {
067 return i;
068 }
069 count--;
070 }
071 }
072 } else {
073 offset++;
074
075 int len = doc.getLength() - offset;
076 String text = doc.getText(offset, len);
077
078 for (int i = 0; i < len; i++) {
079 char x = text.charAt(i);
080
081 if (x == c) {
082 count++;
083 } else if (x == cprime) {
084 if (count == 0) {
085 return i + offset;
086 }
087 count--;
088 }
089 }
090 }
091
092 return -1;
093 }
094 }