01: /*
02: * MobilityPaletteUtilities.java
03: *
04: * Created on August 21, 2006, 3:59 PM
05: *
06: * To change this template, choose Tools | Template Manager
07: * and open the template in the editor.
08: */
09:
10: package org.netbeans.modules.mobility.snippets;
11:
12: import javax.swing.text.BadLocationException;
13: import javax.swing.text.Caret;
14: import javax.swing.text.Document;
15: import javax.swing.text.JTextComponent;
16: import org.netbeans.editor.BaseDocument;
17: import org.netbeans.editor.Formatter;
18:
19: /**
20: *
21: * @author bohemius
22: */
23: public class SnippetsPaletteUtilities {
24:
25: /** Creates a new instance of MobilityPaletteUtilities */
26: public SnippetsPaletteUtilities() {
27: }
28:
29: public static void insert(String s, JTextComponent target)
30: throws BadLocationException {
31: insert(s, target, true);
32: }
33:
34: public static void insert(String s, JTextComponent target,
35: boolean reformat) throws BadLocationException {
36: if (s == null)
37: s = "";
38: Document doc = target.getDocument();
39: if (doc == null)
40: return;
41: Formatter f = null;
42: if (reformat && doc instanceof BaseDocument) {
43: f = ((BaseDocument) doc).getFormatter();
44: f.reformatLock();
45: }
46: try {
47: if (doc instanceof BaseDocument)
48: ((BaseDocument) doc).atomicLock();
49: try {
50: int start = insert(s, target, doc);
51: if (f != null && start >= 0) { // format the inserted text
52: int end = start + s.length();
53: f.reformat((BaseDocument) doc, start, end);
54: }
55: } finally {
56: if (doc instanceof BaseDocument)
57: ((BaseDocument) doc).atomicUnlock();
58: }
59: } finally {
60: if (f != null)
61: f.reformatUnlock();
62: }
63: }
64:
65: private static int insert(String s, JTextComponent target,
66: Document doc) throws BadLocationException {
67:
68: int start = -1;
69: try {
70: //at first, find selected text range
71: Caret caret = target.getCaret();
72: int p0 = Math.min(caret.getDot(), caret.getMark());
73: int p1 = Math.max(caret.getDot(), caret.getMark());
74: doc.remove(p0, p1 - p0);
75:
76: //replace selected text by the inserted one
77: start = caret.getDot();
78: doc.insertString(start, s, null);
79: } catch (BadLocationException ble) {
80: }
81:
82: return start;
83: }
84: }
|