1 19 20 package org.netbeans.modules.editor.java; 21 22 import com.sun.source.tree.Tree; 23 import com.sun.source.util.TreePath; 24 import java.io.IOException ; 25 import java.util.EnumSet ; 26 import javax.swing.text.JTextComponent ; 27 import org.netbeans.api.java.source.CancellableTask; 28 import org.netbeans.api.java.source.CompilationController; 29 import org.netbeans.api.java.source.JavaSource; 30 import org.netbeans.api.java.source.JavaSource.Phase; 31 import org.netbeans.lib.editor.codetemplates.api.CodeTemplate; 32 import org.netbeans.lib.editor.codetemplates.spi.CodeTemplateFilter; 33 import org.openide.util.Exceptions; 34 35 39 public class JavaCodeTemplateFilter implements CodeTemplateFilter, CancellableTask<CompilationController> { 40 41 private int startOffset; 42 private int endOffset; 43 private Tree.Kind ctx = null; 44 45 private JavaCodeTemplateFilter(JTextComponent component, int offset) { 46 this.startOffset = offset; 47 this.endOffset = component.getSelectionStart() == offset ? component.getSelectionEnd() : -1; 48 JavaSource js = JavaSource.forDocument(component.getDocument()); 49 if (js != null) { 50 try { 51 js.runUserActionTask(this, true); 52 } catch (IOException ex) { 53 Exceptions.printStackTrace(ex); 54 } 55 } 56 } 57 58 public synchronized boolean accept(CodeTemplate template) { 59 return ctx != null && getTemplateContexts(template).contains(ctx); 60 } 61 62 public void cancel() { 63 } 64 65 public synchronized void run(CompilationController controller) throws IOException { 66 controller.toPhase(Phase.PARSED); 67 TreePath startPath = controller.getTreeUtilities().pathFor(startOffset); 68 ctx = startPath.getLeaf().getKind(); 69 if (endOffset >= 0 && startOffset != endOffset) { 70 TreePath endPath = controller.getTreeUtilities().pathFor(endOffset); 71 if (endPath.getLeaf().getKind() != ctx) 72 ctx = null; 73 } 74 } 75 76 private EnumSet <Tree.Kind> getTemplateContexts(CodeTemplate template) { 77 String abbrev = template.getAbbreviation().toLowerCase(); 79 if (abbrev.equals("runn") || abbrev.startsWith("for") || abbrev.startsWith("while") || abbrev.equals("inst") || abbrev.startsWith("if") || abbrev.startsWith("do") || abbrev.startsWith("try")) 80 return EnumSet.of(Tree.Kind.BLOCK); 81 return EnumSet.noneOf(Tree.Kind.class); 82 } 83 84 public static final class Factory implements CodeTemplateFilter.Factory { 85 86 public CodeTemplateFilter createFilter(JTextComponent component, int offset) { 87 return new JavaCodeTemplateFilter(component, offset); 88 } 89 } 90 } 91 | Popular Tags |