01: package org.columba.core.gui.base;
02:
03: import java.awt.Color;
04: import java.util.regex.Matcher;
05: import java.util.regex.Pattern;
06:
07: import javax.swing.text.AttributeSet;
08: import javax.swing.text.BadLocationException;
09: import javax.swing.text.SimpleAttributeSet;
10: import javax.swing.text.StyleConstants;
11:
12: public class HighlighterDocument extends UndoDocument {
13:
14: /* CEDRIC: not used right now. */
15: public void highlightInitialText(int length) {
16: SimpleAttributeSet gray = new SimpleAttributeSet();
17: StyleConstants.setForeground(gray, Color.GRAY);
18: setCharacterAttributes(0, length, gray, true);
19: }
20:
21: public void insertString(int offs, String str, AttributeSet a)
22: throws BadLocationException {
23:
24: super .insertString(offs, str, a);
25:
26: String s = getText(0, getLength());
27: highlightText(s);
28: }
29:
30: public void remove(int offs, int len) throws BadLocationException {
31:
32: super .remove(offs, len);
33:
34: String s = getText(0, getLength());
35: highlightText(s);
36: }
37:
38: public void highlightText(String str) {
39:
40: String EMailRegex = "([a-zA-Z0-9]+([_+\\.-][a-zA-Z0-9]+)*@([a-zA-Z0-9]+([\\.-][a-zA-Z0-9]+)*)+\\.[a-zA-Z]{2,4})";
41: String URLRegex = "(\\b((\\w*(:\\S*)?@)?(http|https|ftp)://[\\S]+)(?=\\s|$))";
42: String regex = EMailRegex + "|" + URLRegex;
43: Pattern EMailPat = Pattern.compile(regex);
44: Matcher EMailMatcher = EMailPat.matcher(str);
45:
46: SimpleAttributeSet standard = new SimpleAttributeSet();
47:
48: SimpleAttributeSet highlighted = new SimpleAttributeSet();
49: StyleConstants.setForeground(highlighted, Color.BLUE);
50: StyleConstants.setUnderline(highlighted, true);
51:
52: int begin = 0;
53: int end;
54: while (EMailMatcher.find()) {
55: end = EMailMatcher.start();
56: if (end > 1)
57: setCharacterAttributes(begin, end - begin, standard,
58: true);
59:
60: begin = end;
61: end = EMailMatcher.end();
62: setCharacterAttributes(begin, end - begin, highlighted,
63: true);
64: begin = end;
65: }
66: setCharacterAttributes(begin, str.length(), standard, true);
67: }
68: }
|