Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2003-2007 the original author or authors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package groovy.ui.text;
 
 import java.awt.Color;
 
 
 

Author(s):
Evan "Hippy" Slatis
 
 public class GroovyFilter extends StructuredSyntaxDocumentFilter {
     
     // java tab policy action
     private static final Action AUTO_TAB_ACTION = new AutoTabAction();
     
     // Style names
     public static final String COMMENT = "comment";
     public static final String SLASH_STAR_COMMENT = "/\\*(?s:.)*?(?:\\*/|\\z)";
     public static final String SLASH_SLASH_COMMENT =  "//.*";
     public static final String QUOTES =
     	"(?ms:\"{3}(?!\\\"{1,3}).*?(?:\"{3}|\\z))|(?:\"{1}(?!\\\").*?(?:\"|\\Z))";
     public static final String SINGLE_QUOTES =
     	"(?ms:'{3}(?!'{1,3}).*?(?:'{3}|\\z))|(?:'[^'].*?(?:'|\\z))";
     public static final String SLASHY_QUOTES = "/[^/*].*?/";
     public static final String DIGIT = "\\d+?[efld]?";
     
     public static final String IDENT = "[\\w\\$&&[\\D]][\\w\\$]*";
     public static final String OPERATION = "[\\w\\$&&[\\D]][\\w\\$]* *\\(";
     public static final String LEFT_PARENS = "\\(";
     
     private static final Color COMMENT_COLOR = 
         ..darker().darker();
     
     
     public static final String RESERVED_WORD = "reserved";
     public static final String[] RESERVED_WORDS =   {"\\babstract\\b",
                                                     "\\bassert\\b",
                                                     "\\bdefault\\b",
                                                     "\\bif\\b",
                                                     "\\bprivate\\b",
                                                     "\\bthis\\b",
                                                     "\\bboolean\\b",
                                                     "\\bdo\\b",
                                                     "\\bimplements\\b",
                                                     "\\bprotected\\b",
                                                     "\\bthrow\\b",
                                                     "\\bbreak\\b",
                                                     "\\bdouble\\b",
                                                     "\\bimport\\b",
                                                     "\\bpublic\\b",
                                                     "\\bthrows\\b",
                                                     "\\bbyte\\b",
                                                     "\\belse\\b",
                                                     "\\binstanceof\\b",
                                                     "\\breturn\\b",
                                                     "\\btransient\\b",
                                                     "\\bcase\\b",
                                                     "\\bextends\\b",
                                                     "\\bint\\b",
                                                     "\\bshort\\b",
                                                     "\\btry\\b",
                                                     "\\bcatch\\b",
                                                     "\\bfinal\\b",
                                                     "\\binterface\\b",
                                                     "\\benum\\b",
                                                     "\\bstatic\\b",
                                                     "\\bvoid\\b",
                                                    "\\bchar\\b",
                                                    "\\bfinally\\b",
                                                    "\\blong\\b",
                                                    "\\bstrictfp\\b",
                                                    "\\bvolatile\\b",
                                                    "\\bclass\\b",
                                                    "\\bfloat\\b",
                                                    "\\bnative\\b",
                                                    "\\bsuper\\b",
                                                    "\\bwhile\\b",
                                                    "\\bconst\\b",
                                                    "\\bfor\\b",
                                                    "\\bnew\\b",
                                                    "\\bswitch\\b",
                                                    "\\bcontinue\\b",
                                                    "\\bgoto\\b",
                                                    "\\bpackage\\b",
                                                    "\\bdef\\b",
                                                    "\\bas\\b",
                                                    "\\bin\\b",
                                                    "\\bsynchronized\\b",
                                                    "\\bnull\\b"};
    
    
Creates a new instance of GroovyFilter
    public GroovyFilter(DefaultStyledDocument doc) {
        super(doc);
        init();
    }
    
    private void init() {
        StyleContext styleContext = StyleContext.getDefaultStyleContext();
        Style defaultStyle = styleContext.getStyle(.);
        
        Style comment = styleContext.addStyle(defaultStyle);
        StyleConstants.setForeground(comment);
        StyleConstants.setItalic(commenttrue);
        
        Style quotes = styleContext.addStyle(defaultStyle);
        StyleConstants.setForeground(quotes..darker().darker());
        
        Style charQuotes = styleContext.addStyle(defaultStyle);
        StyleConstants.setForeground(charQuotes..darker().darker());
        
        Style slashyQuotes = styleContext.addStyle(defaultStyle);
        StyleConstants.setForeground(slashyQuotes..darker());
        
        Style digit = styleContext.addStyle(defaultStyle);
        StyleConstants.setForeground(digit..darker());
        
        Style operation = styleContext.addStyle(defaultStyle);
        StyleConstants.setBold(operationtrue);
        
        Style ident = styleContext.addStyle(defaultStyle);
        
        Style reservedWords = styleContext.addStyle(defaultStyle);
        StyleConstants.setBold(reservedWordstrue);
        StyleConstants.setForeground(reservedWords..darker().darker());
        
        Style leftParens = styleContext.addStyle(defaultStyle);
        
        getRootNode().putStyle(comment);
        getRootNode().putStyle(comment);
        getRootNode().putStyle(quotes);
        getRootNode().putStyle(charQuotes);
        getRootNode().putStyle(slashyQuotes);
        getRootNode().putStyle(digit);
        
        getRootNode().putStyle(operation);
        node.putStyle(reservedWords);
        node.putStyle(leftParens);
        getRootNode().putChild(node);
        
        getRootNode().putStyle(ident);
        node = createLexerNode();
        node.putStyle(reservedWords);
        getRootNode().putChild(node);
    }
    
    public static void installAutoTabAction(JTextComponent tComp) {
        tComp.getActionMap().put("GroovyFilter-autoTab");
        KeyStroke keyStroke = KeyStroke.getKeyStroke(., 0, false);
        tComp.getInputMap().put(keyStroke"GroovyFilter-autoTab");
    }
    
    private static class AutoTabAction extends AbstractAction {
        
        private StyledDocument doc;
        private final Segment segment = new Segment();
        private final StringBuffer buffer = new StringBuffer();
        
        public void actionPerformed(ActionEvent ae) {
            JTextComponent tComp = (JTextComponent)ae.getSource();
            if (tComp.getDocument() instanceof StyledDocument) {
                 = (StyledDocument)tComp.getDocument();
                try {
                    .getText(0, .getLength(), );
                }
                catch (Exception e) {
                    // should NEVER reach here
                    e.printStackTrace();
                }
                int offset = tComp.getCaretPosition();
                int index = findTabLocation(offset);
                .delete(0, .length());
                .append('\n');
                if (index > -1) {
                    for (int i = 0; i < index + 4; i++) {
                        .append(' ');
                    }
                }
                try {
                    .insertString(offset.toString(),
                                 .getDefaultRootElement().getAttributes());
                }
                catch (BadLocationException ble) {
                    ble.printStackTrace();
                }
            }
        }
    
        public int findTabLocation(int offset) {  
            // find first {
            boolean cont = true;
            while (offset > -1 && cont) {
                Element el = .getCharacterElement(offset);
                Object color =
                    el.getAttributes().getAttribute(.);
                if (!.equals(color)) {
                    cont = .[offset] != '{' &&
                           .[offset] != '}';
                }
                offset -= cont ? 1 : 0;
            }
            if (offset > -1 && .[offset] == '{') {
                while (offset > -1 &&
                       !Character.isWhitespace(.[offset--])){
                }
            }
            int index = offset < 0 || .[offset] == '}' ? -4 : 0;
            if (offset > -1) {
                Element top = .getDefaultRootElement();
                offset = top.getElement(top.getElementIndex(offset)).getStartOffset();
                while (Character.isWhitespace(.[offset++])) {
                    index++;
                }
            }
            return index;
        }
    }
New to GrepCode? Check out our FAQ X