1 19 20 package org.netbeans.modules.web.core.palette; 21 22 import javax.swing.text.BadLocationException ; 23 import javax.swing.text.Caret ; 24 import javax.swing.text.Document ; 25 import javax.swing.text.JTextComponent ; 26 import org.netbeans.api.html.lexer.HTMLTokenId; 27 import org.netbeans.api.jsp.lexer.JspTokenId; 28 import org.netbeans.api.lexer.Token; 29 import org.netbeans.api.lexer.TokenHierarchy; 30 import org.netbeans.api.lexer.TokenSequence; 31 import org.netbeans.editor.BaseDocument; 32 import org.netbeans.editor.Formatter; 33 34 38 public final class JSPPaletteUtilities { 39 40 public static int wrapTags(int start, int end, BaseDocument doc) { 42 try { 43 TokenHierarchy th = TokenHierarchy.get(doc); 44 TokenSequence jspTs = th.tokenSequence(); 45 if(jspTs.move(start) == Integer.MAX_VALUE) { 46 return end; } 48 Token token = jspTs.token(); 49 while (token.offset(th) < end && jspTs.moveNext()) { token = jspTs.token(); 52 if (token.text().toString().startsWith("<") && token.id() == JspTokenId.SYMBOL) { 53 int offset = token.offset(th); 55 doc.insertString(offset, "\n", null); end++; } 58 } 59 TokenSequence htmlTs = th.tokenSequence(HTMLTokenId.language()); 61 if(htmlTs == null || htmlTs.move(start) == Integer.MAX_VALUE) { 62 return end; } 64 while (token.offset(th) < end && htmlTs.moveNext()) { token = htmlTs.token(); 66 if (token.text().toString().startsWith("<") && token.id() == HTMLTokenId.TAG_OPEN_SYMBOL) { 67 int offset = token.offset(th); 69 doc.insertString(offset, "\n", null); end++; } 72 } 73 } catch (IllegalStateException ise) { 74 } catch (BadLocationException ble) { 76 } 78 79 return end; 80 } 81 82 public static void insert(String s, JTextComponent target) 83 throws BadLocationException 84 { 85 insert(s, target, true); 86 } 87 88 public static void insert(String s, JTextComponent target, boolean reformat) 89 throws BadLocationException 90 { 91 Document doc = target.getDocument(); 92 if (doc == null) 93 return; 94 95 102 if (s == null) 103 s = ""; 104 105 if (doc instanceof BaseDocument) 106 ((BaseDocument)doc).atomicLock(); 107 108 int start = insert(s, target, doc); 109 110 if (reformat && start >= 0 && doc instanceof BaseDocument) { int end = start + s.length(); 112 Formatter f = ((BaseDocument)doc).getFormatter(); 113 f.reformat((BaseDocument)doc, start, end); 114 } 115 116 124 if (doc instanceof BaseDocument) 125 ((BaseDocument)doc).atomicUnlock(); 126 127 } 128 129 private static int insert(String s, JTextComponent target, Document doc) 130 throws BadLocationException 131 { 132 133 int start = -1; 134 try { 135 Caret caret = target.getCaret(); 137 int p0 = Math.min(caret.getDot(), caret.getMark()); 138 int p1 = Math.max(caret.getDot(), caret.getMark()); 139 doc.remove(p0, p1 - p0); 140 141 start = caret.getDot(); 143 doc.insertString(start, s, null); 144 } 145 catch (BadLocationException ble) {} 146 147 return start; 148 } 149 150 } 151 | Popular Tags |