Java 类javax.swing.text.BadLocationException 实例源码

项目:incubator-netbeans    文件:IndentFactory.java   
private static boolean isEmpty (
    int                     ln,
    StyledDocument          document,
    Set<Integer>            whitespaces
) throws BadLocationException {
    int start = NbDocument.findLineOffset (document, ln);
    int end = document.getLength ();
    try {
        end = NbDocument.findLineOffset (document, ln + 1) - 1;
    } catch (IndexOutOfBoundsException ex) {
    }
    TokenSequence ts = Utils.getTokenSequence (document, start);
    if (ts.token () == null) return true;
    while (whitespaces.contains (ts.token ().id ().ordinal ())) {
        if (!ts.moveNext ()) return true;
        if (ts.offset () > end) return true;
    }
    return false;
}
项目:incubator-netbeans    文件:JavaElementRefFinder.java   
private String createClassDisplayText(AttributeValueFinder finder, String classAttrValue, int matchIndex, int matchLength) throws BadLocationException {
    StringBuilder builder = new StringBuilder();
    builder.append("&lt;bean"); // NOI18N
    String attrWithValue = getAttributeWithValue(finder, "id"); // NOI18N
    if (attrWithValue == null) {
        attrWithValue = getAttributeWithValue(finder, "name"); // NOI18N
    }
    if (attrWithValue != null) {
        builder.append(' '); // NOI18N
        builder.append(attrWithValue);
    }
    String beforeMatch = escapeAttrValue(classAttrValue.substring(0, matchIndex));
    String match = escapeAttrValue(classAttrValue.substring(matchIndex, matchIndex + matchLength));
    String afterMatch = escapeAttrValue(classAttrValue.substring(matchIndex + matchLength, classAttrValue.length()));
    if (beforeMatch != null && match != null && afterMatch != null) {
        builder.append(" class="); // NOI18N
        builder.append(beforeMatch).append("<b>").append(match).append("</b>").append(afterMatch); // NOI18N
    }
    return builder.toString();
}
项目:powertext    文件:RSyntaxTextAreaEditorKit.java   
private int getPreviousWordStartInLine(RSyntaxDocument doc,
        Element elem, int offs) throws BadLocationException {

    int start = elem.getStartOffset();
    int cur = offs;

    // Skip any whitespace or non-word chars
    while (cur >= start) {
        char ch = doc.charAt(cur);
        if (isIdentifierChar(ch)) {
            break;
        }
        cur--;
    }
    if (cur < start) {
        // Empty line or nothing but whitespace/non-word chars
        return -1;
    }

    return getWordStartImpl(doc, elem, cur);

}
项目:incubator-netbeans    文件:PositionBounds.java   
public String toString() {
    StringBuilder buf = new StringBuilder("Position bounds["); // NOI18N

    try {
        String content = getText();
        buf.append(begin);
        buf.append(","); // NOI18N
        buf.append(end);
        buf.append(",\""); // NOI18N
        buf.append(content);
        buf.append("\""); // NOI18N
    } catch (BadLocationException e) {
        buf.append("Invalid: "); // NOI18N
        buf.append(e.getMessage());
    }

    buf.append("]"); // NOI18N

    return buf.toString();
}
项目:incubator-netbeans    文件:FindLocalUsagesQuery.java   
@Override
public DocTree visitReference(ReferenceTree node, Element p) {
    DocTrees trees = info.getDocTrees();
    Element el = trees.getElement(getCurrentPath());
    if (el != null && el.equals(toFind)) {
        int[] span = treeUtils.findNameSpan(getCurrentPath().getDocComment(), node);
        if(span != null) {
            try {
                MutablePositionRegion region = createRegion(doc, span[0], span[1]);
                usages.add(region);
            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    }
    return super.visitReference(node, p);
}
项目:incubator-netbeans    文件:DefaultIndentEngine.java   
@Override
public int indentLine(Document doc, int offset) {
    Indent indent = Indent.get(doc);
    indent.lock();
    try {
        if (doc instanceof BaseDocument) {
            ((BaseDocument) doc).atomicLock();
        }
        try {
            Position pos = doc.createPosition(offset);
            indent.reindent(offset);
            return pos.getOffset();
        } catch (BadLocationException ble) {
            return offset;
        } finally {
            if (doc instanceof BaseDocument) {
                ((BaseDocument) doc).atomicUnlock();
            }
        }
    } finally {
        indent.unlock();
    }
}
项目:Tarski    文件:OurHighlighter.java   
/** This method is called by Swing to draw highlights. */
public void paint(Graphics gr, int start, int end, Shape shape, JTextComponent text) {
   Color old = gr.getColor();
   gr.setColor(color);
   try {
      Rectangle box = shape.getBounds(), a = text.getUI().modelToView(text, start), b = text.getUI().modelToView(text, end);
      if (a.y == b.y) {
         // same line (Note: furthermore, if start==end, then we draw all the way to the right edge)
         Rectangle r = a.union(b);
         gr.fillRect(r.x, r.y, (r.width<=1 ? (box.x + box.width - r.x) : r.width), r.height);
      } else {
         // Multiple lines; (Note: on first line we'll draw from "start" and extend to rightmost)
         gr.fillRect(a.x, a.y, box.x + box.width - a.x, a.height);
         if (a.y + a.height < b.y) gr.fillRect(box.x, a.y + a.height, box.width, b.y - (a.y + a.height));
         gr.fillRect(box.x, b.y, b.x - box.x, b.height);
      }
   } catch (BadLocationException e) { } // Failure to highlight is not fatal
   gr.setColor(old);
}
项目:incubator-netbeans    文件:XmlMultiViewEditorSupport.java   
private boolean checkCharsetConversion(final String encoding) {
    boolean value = true;
    try {
        CharsetEncoder coder = Charset.forName(encoding).newEncoder();
        if (!coder.canEncode(getDocument().getText(0, getDocument().getLength()))){
            NotifyDescriptor nd = new NotifyDescriptor.Confirmation(
                    NbBundle.getMessage(XmlMultiViewEditorSupport.class, "MSG_BadCharConversion",
                    new Object [] { getDataObject().getPrimaryFile().getNameExt(),
                    encoding}),
                    NotifyDescriptor.YES_NO_OPTION,
                    NotifyDescriptor.WARNING_MESSAGE);
            nd.setValue(NotifyDescriptor.NO_OPTION);
            DialogDisplayer.getDefault().notify(nd);
            if(nd.getValue() != NotifyDescriptor.YES_OPTION) {
                value = false;
            }
        }
    } catch (BadLocationException e){
        ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
    }
    return value;
}
项目:incubator-netbeans    文件:IndentTest.java   
public void run() {
    Indent indent = Indent.get(doc);
    indent.lock();
    try {
        //doc.atomicLock();
        try {
            lockAcquired = true;
            indent.reindent(0);
        } catch (BadLocationException ex) {
            fail();
        } finally {
            //doc.atomicUnlock();
        }
    } finally {
        indent.unlock();
    }
    indentFinished = true;
}
项目:incubator-netbeans    文件:CssBracketCompleterTest.java   
public void testQuoteAutocompletion() throws BadLocationException, IOException {
    //test pair autocomplete
    clear(doc);

    //test skipping closing curly bracket
    String text = "h1 { color:  } ";
    //             0123456789012345678        
    doc.insertString(0, text , null);

    pane.setCaretPosition(12);
    type('"');

    assertEquals("h1 { color: \"\" } ", getText()); //no change in the text
    //             0123456789012345678        
    assertEquals(13, pane.getCaretPosition()); //+1

}
项目:incubator-netbeans    文件:XMLSyntaxSupport.java   
/**
 * Get token at given offet or previous one if at token boundary.
 * It does not lock the document. Returns {@code null} for invalid offsets.
 * 
 * @param offset valid position in document
 * @return Token instance
 */
public Token<XMLTokenId> getNextToken( int offset) throws BadLocationException {
    if (offset == 0) {
        offset = 1;
    }
    if (offset < 0) throw new BadLocationException("Offset " +
            offset + " cannot be less than 0.", offset);  //NOI18N
    ((AbstractDocument)document).readLock();
    try {
        TokenSequence ts = getSequence();
        synchronized (ts) {
            return getToken(ts, offset, true, null);
        }
    } finally {
        ((AbstractDocument)document).readUnlock();
    }
}
项目:incubator-netbeans    文件:CustomCodeView.java   
private void retreiveGuardedBlock(CodeCategory category, int index) {
    GuardedBlock gBlock = codeData.getGuardedBlock(category, index);
    if (!gBlock.isCustomizable())
        return;

    if (getGuardInfos(category)[index].customized) {
        Document doc = getDocument(category);
        int[] blockBounds = getGuardBlockBounds(category, index);
        try {
            int startPos = blockBounds[0] + gBlock.getHeaderLength();
            String code = doc.getText(startPos,
                                      blockBounds[1] - gBlock.getFooterLength() - startPos);
            gBlock.setCustomizedCode(code);
        }
        catch (BadLocationException ex) { // should not happen
            ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
        }
    }
    else { // reset to default code
        gBlock.setCustomizedCode(null);
    }
}
项目:incubator-netbeans    文件:DocumentContent.java   
public void getChars(int offset, int length, Segment chars)
throws BadLocationException {

    checkBounds(offset, length, length());

    if ((offset + length) <= gapStart) { // completely below gap
        chars.array = charArray;
        chars.offset = offset;

    } else if (offset >= gapStart) { // completely above gap
        chars.array = charArray;
        chars.offset = offset + gapLength;

    } else { // spans the gap, must copy
        chars.array = copySpanChars(offset, length);
        chars.offset = 0;
    }

    chars.count = length;
}
项目:BEAST    文件:AutocompletionController.java   
@Override
public void keyReleased(KeyEvent ke) {
    if(ke.getSource() == frame.getjList1()) {
        if(ke.getKeyCode() == KeyEvent.VK_UP ||
            ke.getKeyCode() == KeyEvent.VK_DOWN ||
            ke.getKeyCode() == KeyEvent.VK_ENTER || 
            ke.getKeyCode() == KeyEvent.VK_CONTROL || 
            ke.getKeyCode() == KeyEvent.VK_SPACE) {                
            return;
        } 
    }
    if(ke.isControlDown() && ke.getKeyChar()== KeyEvent.VK_SPACE) {            
        try {
            giveMenuOptions();
            Point loc = new Point(
                    pane.modelToView(pane.getCaretPosition()).x,
                    pane.modelToView(pane.getCaretPosition()).y);                  
            frame.setLocation(pane.getLocationOnScreen().x + loc.x, pane.getLocationOnScreen().y + loc.y + 20);
            frame.setVisible(true);
            frame.getjList1().setSelectedIndex(0);
        } catch (BadLocationException ex) {
            Logger.getLogger(AutocompletionController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
项目:incubator-netbeans    文件:ActionFactory.java   
public void actionPerformed(ActionEvent evt, final JTextComponent target) {
    Document doc = target.getDocument();
    doc.render(new Runnable() {
        @Override
        public void run() {
            FoldHierarchy hierarchy = FoldHierarchy.get(target);
            int dot = target.getCaret().getDot();
            hierarchy.lock();
            try {
                try {
                    int rowStart = javax.swing.text.Utilities.getRowStart(target, dot);
                    int rowEnd = javax.swing.text.Utilities.getRowEnd(target, dot);
                    Fold fold = getLineFold(hierarchy, dot, rowStart, rowEnd);
                    if (fold != null) {
                        hierarchy.expand(fold);
                    }
                } catch (BadLocationException ble) {
                    Exceptions.printStackTrace(ble);
                }
            } finally {
                hierarchy.unlock();
            }
        }
    });
}
项目:BEAST    文件:NewlineInserterTest.java   
@Test 
public void standardInserterTest() throws BadLocationException {
    StandardNewlineInserter ins = new StandardNewlineInserter();
    String insert = "{}";
    pane.getStyledDocument().insertString(0, insert, null);
    ins.insertNewlineAtCurrentPosition(pane, tabsInserter, lineBeg, 1);
    String code = pane.getStyledDocument().getText(0, pane.getStyledDocument().getLength());
    String codeafter = "{\n" +
                        "}";
    assertEquals(codeafter, code);

    ins.insertNewlineAtCurrentPosition(pane, tabsInserter, lineBeg, 1);
    code = pane.getText();
    codeafter = "{\r\n" +
                "        \r\n" +
                "}";        
    //assertEquals(codeafter, code);
}
项目:incubator-netbeans    文件:JavaElementRefFinder.java   
public void addOccurrences(Matcher matcher, List<Occurrence> result) throws BadLocationException {
    List<SpringBean> beans = docAccess.getSpringBeans().getFileBeans(docAccess.getFileObject()).getBeans();
    for (SpringBean bean : beans) {
        String className = bean.getClassName();
        if (className != null) {
            String matched = matcher.accept(className);
            if (matched == null) {
                continue;
            }
            Occurrence occurrence = createClassOccurrence(matched, bean);
            if (occurrence != null) {
                result.add(occurrence);
            }
        }
    }
}
项目:incubator-netbeans    文件:GuardedSectionManagerTest.java   
public void testRemoveInteriorSection() throws BadLocationException {
    System.out.println("-- testRemoveInteriorSection -------------");

    editor.doc.insertString(0, "aaa", null);
    InteriorSection is = guards.createInteriorSection(editor.doc.createPosition(1), "is1");

    assertEquals("is1.content", "a\n \n \n \naa", editor.doc.getText(0, editor.doc.getLength()));
    assertTrue("'\\n'", !GuardUtils.isGuarded(editor.doc, 1));
    assertTrue("header.' '", GuardUtils.isGuarded(editor.doc, 2));
    assertTrue("header.'\\n'", GuardUtils.isGuarded(editor.doc, 3));
    assertTrue("body.' '", !GuardUtils.isGuarded(editor.doc, 4));
    assertTrue("body.'\\n'", !GuardUtils.isGuarded(editor.doc, 5));
    assertTrue("footer.' '", GuardUtils.isGuarded(editor.doc, 6));
    assertTrue("footer.'\\n'", GuardUtils.isGuarded(editor.doc, 7));
    assertTrue("'a'", !GuardUtils.isGuarded(editor.doc, 8));
    is.removeSection();
    assertEquals("is1.content2", "a\n \n \n \naa", editor.doc.getText(0, editor.doc.getLength()));
    assertTrue("'\\n'", !GuardUtils.isGuarded(editor.doc, 1));
    assertTrue("header.' '", !GuardUtils.isGuarded(editor.doc, 2));
    assertTrue("header.'\\n'", !GuardUtils.isGuarded(editor.doc, 3));
    assertTrue("body.' '", !GuardUtils.isGuarded(editor.doc, 4));
    assertTrue("body.'\\n'", !GuardUtils.isGuarded(editor.doc, 5));
    assertTrue("footer.' '", !GuardUtils.isGuarded(editor.doc, 6));
    assertTrue("footer.'\\n'", !GuardUtils.isGuarded(editor.doc, 7));
    assertTrue("'a'", !GuardUtils.isGuarded(editor.doc, 8));
}
项目:incubator-netbeans    文件:EncodedReaderFactory.java   
/**
 * Write a portion of an array of characters.
 *
 * @param  cbuf  Array of characters
 * @param  off   Offset from which to start writing characters
 * @param  len   Number of characters to write
 *
 * @exception  IOException  If an I/O error occurs
 */
public void write(char cbuf[], int off, int len) throws IOException {
    if ((off < 0) || (off > cbuf.length) || (len < 0) ||
        ((off + len) > cbuf.length) || ((off + len) < 0)) {
        throw new IndexOutOfBoundsException();
    } else if (len == 0) {
        return;
    }
    try {
        doc.insertString(doc.getLength(), new String(cbuf, off, len), null);
    } catch (BadLocationException blex) {
        IOException ioex = new IOException(blex.getLocalizedMessage());
        ioex.initCause(blex);
        throw ioex;
    }
}
项目:incubator-netbeans    文件:LexerUtils.java   
/**
 * Note: The input text must contain only \n as line terminators. This is
 * compatible with the netbeans document which never contains \r\n line
 * separators.
 *
 * @param text
 * @param line line number
 * @return offset of the beginning of the line
 */
public static int getLineBeginningOffset(CharSequence text, int line) throws BadLocationException {
    if (text == null) {
        throw new NullPointerException();
    }

    if (line < 0) {
        throw new IllegalArgumentException("Line number must be >= 0!");
    }
    int linecount = 0;
    for (int i = 0; i < text.length(); i++) {
        char c = text.charAt(i);
        if (c == '\r') {
            throw new IllegalArgumentException("The input text cannot contain carriage return char \\r"); //NOI18N
        }
        if (linecount == line) {
            return i;
        }
        if (c == '\n') {
            linecount++;
        }
    }

    //for position just at the length of the text
    return text.length();
}
项目:incubator-netbeans    文件:HighlighterSupport.java   
private static void refresh (final Document doc, final int offset) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            Iterator it = TopComponent.getRegistry ().getOpened ().iterator ();
            while (it.hasNext ()) {
                TopComponent tc = (TopComponent) it.next ();
                EditorCookie ec = tc.getLookup ().lookup (EditorCookie.class);
                if (ec == null) continue;
                JEditorPane[] eps = ec.getOpenedPanes ();
                if (eps == null) continue;
                int i, k = eps.length;
                for (i = 0; i < k; i++) {
                    if (eps [i].getDocument () == doc) {
                        final JEditorPane ep = eps [i];
                        if (ep != null)
                            try {
                                ep.scrollRectToVisible (ep.modelToView (offset));
                            } catch (BadLocationException ex) {
                                ErrorManager.getDefault ().notify (ex);
                            }
                    }
                }
            }
        }
    });
}
项目:openjdk-jdk10    文件:Test6968363.java   
@Override
public void insertString(int offset, String string, AttributeSet set) throws BadLocationException {
    for (int i = 0; i < string.length(); i++) {
        System.out.println("i: " + i + "; ch: " + Integer.toHexString(string.charAt(i)));
    }
    this.document.insertString(offset, string, set);
}
项目:incubator-netbeans    文件:ShowGoldenFiles.java   
private static StyledDocument loadDocument(File file) throws IOException, BadLocationException {
    StringBuffer sb = new StringBuffer();
    Reader r = new FileReader(file);
    int c;

    while ((c = r.read()) != (-1)) {
        sb.append((char) c);
    }

    StyledDocument result = new HTMLDocument();//new DefaultStyledDocument();

    result.insertString(0, sb.toString(), null);

    return result;
}
项目:ripme    文件:MainWindow.java   
private void appendLog(final String text, final Color color) {
    SimpleAttributeSet sas = new SimpleAttributeSet();
    StyleConstants.setForeground(sas, color);
    StyledDocument sd = logText.getStyledDocument();
    try {
        synchronized (this) {
            sd.insertString(sd.getLength(), text + "\n", sas);
        }
    } catch (BadLocationException e) { }

    logText.setCaretPosition(sd.getLength());
}
项目:incubator-netbeans    文件:CatalogFileWrapperDOMImpl.java   
public InputStream getCatalogAsStream() throws IOException{
    try {
        String docContent = backendCatalogSwingDocument.getText(0, backendCatalogSwingDocument.getLength());
        InputStream bis = new ByteArrayInputStream(docContent.getBytes());
        logger.finer("In getCatalogAsStream gona return:"+docContent);
        return bis;
    } catch (BadLocationException ex) {
        throw new IOException(ex.getMessage());
    }
}
项目:incubator-netbeans    文件:HibernateCompletionItem.java   
protected void substituteText(JTextComponent c, int offset, int len, String toAdd) {
    BaseDocument doc = (BaseDocument) c.getDocument();
    CharSequence prefix = getInsertPrefix();
    String text = prefix.toString();
    if (toAdd != null) {
        text += toAdd;
    }

    doc.atomicLock();
    try {
        Position position = doc.createPosition(offset);
        doc.remove(offset, len);
        doc.insertString(position.getOffset(), text.toString(), null);
    } catch (BadLocationException ble) {
    // nothing can be done to update
    } finally {
        doc.atomicUnlock();
    }
}
项目:incubator-netbeans    文件:HtmlPaletteCompletionProvider.java   
@Override
protected boolean canFilter(final JTextComponent component) {
    final Collection<PaletteCompletionItem> currentItems = items;
    if(currentItems == null) {
        return false;
    }
    final Document doc = component.getDocument();
    final AtomicBoolean retval = new AtomicBoolean();
    doc.render(new Runnable() {

        @Override
        public void run() {
            try {
                int offset = component.getCaretPosition();
                if (completionExpressionStartOffset < 0  || offset < completionExpressionStartOffset) {
                    retval.set(false);
                    return;
                }
                String prefix = doc.getText(completionExpressionStartOffset, offset - completionExpressionStartOffset);
                //check the items
                for (PaletteCompletionItem item : currentItems) {
                    if (startsWithIgnoreCase(item.getItemName(), prefix)) {
                        retval.set(true); //at least one item will remain
                        return;
                    }
                }
            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    });


    return retval.get();

}
项目:incubator-netbeans    文件:CompletionContext.java   
public List<String> getExistingAttributes() {
    if (existingAttributes == null) {
        try {
            existingAttributes = (List<String>)support.runWithSequence(
                    documentContext.getCurrentTokenOffset(),
                    this::getExistingAttributesLocked
            );
        } catch (BadLocationException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    return existingAttributes;
}
项目:incubator-netbeans    文件:SimpleTestStepLocation.java   
@Override
public void insertString(
                    DocumentFilter.FilterBypass bypass,
                    int offset,
                    String string,
                    AttributeSet attr) throws BadLocationException {
    if (!programmaticChange && srcGroupNameDisplayed) {
        removeSrcGroupName(bypass);
    }
    super.insertString(bypass, offset, string, attr);
}
项目:incubator-netbeans    文件:BIGuardedBlockHandlerFactory.java   
private boolean checkChange(CompilationController javac, PositionBounds span) throws IOException, BadLocationException {
    final int begin = span.getBegin().getOffset();
    final Trees trees = javac.getTrees();
    TreePath path = javac.getTreeUtilities().pathFor(begin + 1);
    if (path == null) {
        return false;
    }

    Element element = trees.getElement(path);
    if (element == null) {
        return false;
    }

    TreePath decl = trees.getPath(element);
    if (decl != null) {
        SourcePositions sourcePositions = trees.getSourcePositions();
        long declBegin = sourcePositions.getStartPosition(decl.getCompilationUnit(), decl.getLeaf());
        FileObject fo = SourceUtils.getFile(element, javac.getClasspathInfo());
        Document doc = javac.getDocument();
        GuardedSectionManager guards = GuardedSectionManager.getInstance((StyledDocument) doc);

        if (fo != javac.getFileObject() || guards != null && !isGuarded(guards, doc.createPosition((int) declBegin))) {
            // tree being refactored is declared outside of this file
            // or out of guarded sections. It should be safe to make change
            return true;
        }
    } else {
        // e.g. package; change is OK
            return true;
    }
    return false;
}
项目:powertext    文件:CompletionProviderBase.java   
/**
 * {@inheritDoc}
 */
@Override
public boolean isAutoActivateOkay(JTextComponent tc) {
    Document doc = tc.getDocument();
    char ch = 0;
    try {
        doc.getText(tc.getCaretPosition(), 1, s);
        ch = s.first();
    } catch (BadLocationException ble) { // Never happens
        ble.printStackTrace();
    }
    return (autoActivateAfterLetters && Character.isLetter(ch)) ||
            (autoActivateChars!=null && autoActivateChars.indexOf(ch)>-1);
}
项目:incubator-netbeans    文件:CslTestBase.java   
protected void checkNoOverlaps(Set<OffsetRange> ranges, Document doc) throws BadLocationException {
    // Make sure there are no overlapping ranges
    List<OffsetRange> sortedRanges = new ArrayList<OffsetRange>(ranges);
    Collections.sort(sortedRanges);
    OffsetRange prevRange = OffsetRange.NONE;
    for (OffsetRange range : sortedRanges) {
        if (range.getStart() < prevRange.getEnd() && range.getEnd() > prevRange.getEnd()) {
            fail("OffsetRanges should be non-overlapping! " + prevRange +
                    "(" + doc.getText(prevRange.getStart(), prevRange.getLength()) + ") and " + range +
                    "(" + doc.getText(range.getStart(), range.getLength()) + ")");
        }
        prevRange = range;
    }
}
项目:incubator-netbeans    文件:IndentationPanel.java   
public @Override void refreshPreview() {
    JEditorPane pane = (JEditorPane) getPreviewComponent();
    pane.getDocument().putProperty(SimpleValueNames.TEXT_LINE_WRAP, ""); //NOI18N
    pane.getDocument().putProperty(SimpleValueNames.TAB_SIZE, ""); //NOI18N
    pane.getDocument().putProperty(SimpleValueNames.INDENT_SHIFT_WIDTH, prefs.getInt(SimpleValueNames.INDENT_SHIFT_WIDTH, 4));
    pane.getDocument().putProperty(SimpleValueNames.SPACES_PER_TAB, prefs.getInt(SimpleValueNames.SPACES_PER_TAB, 4));
    pane.getDocument().putProperty(SimpleValueNames.TEXT_LIMIT_WIDTH, ""); //NOI18N
    pane.setText(previewText);

    final Document doc = pane.getDocument();
    if (doc instanceof BaseDocument) {
        final Reformat reformat = Reformat.get(doc);
        reformat.lock();
        try {
            ((BaseDocument) doc).runAtomic(new Runnable() {
                public @Override void run() {
                    if (LOG.isLoggable(Level.FINE)) {
                        LOG.fine("Refreshing preview: expandTabs=" + IndentUtils.isExpandTabs(doc) //NOI18N
                                + ", indentLevelSize=" + IndentUtils.indentLevelSize(doc) //NOI18N
                                + ", tabSize=" + IndentUtils.tabSize(doc) //NOI18N
                                + ", mimeType='" + doc.getProperty("mimeType") + "'" //NOI18N
                                + ", doc=" + s2s(doc)); //NOI18N
                    }

                    try {
                        reformat.reformat(0, doc.getLength());
                    } catch (BadLocationException ble) {
                        LOG.log(Level.WARNING, null, ble);
                    }
                }
            });
        } finally {
            reformat.unlock();
        }
    } else {
        LOG.warning("Can't format " + doc + "; it's not BaseDocument."); //NOI18N
    }
}
项目:incubator-netbeans    文件:DocUtils.java   
public static int getRowEnd(Document doc, int offset)
throws BadLocationException {
    checkOffsetValid(doc, offset);

    return doc.getDefaultRootElement().getElement(
           doc.getDefaultRootElement().getElementIndex(offset)).getEndOffset() - 1;
}
项目:incubator-netbeans    文件:SourceTest.java   
private Document createDocument(String mimeType, String contents) {
    Document doc = new DefaultStyledDocument();
    doc.putProperty("mimeType", mimeType);
    try {
        doc.insertString(0, contents, null);
        return doc;
    } catch (BadLocationException ble) {
        throw new IllegalStateException(ble);
    }
}
项目:incubator-netbeans    文件:SQLCloneableEditor.java   
private String getText(JEditorPane editorPane) {
    // issue 75529: must not use the simpler JEditorPane.getText() 
    // since we want to obtain the text from the document, which has
    // line ends normalized to '\n'
    Document doc = editorPane.getDocument();
    try {
        return doc.getText(0, doc.getLength());
    } catch (BadLocationException e) {
        // should not happen
        Logger.getLogger("global").log(Level.INFO, null, e);
        return ""; // NOI18N
    }
}
项目:powertext    文件:StaticCodeTemplate.java   
/**
 * Invokes this code template.  The changes are made to the given text
 * area.
 *
 * @param textArea The text area to operate on.
 * @throws BadLocationException If something bad happens.
 */
@Override
public void invoke(RSyntaxTextArea textArea) throws BadLocationException {

    Caret c = textArea.getCaret();
    int dot = c.getDot();
    int mark = c.getMark();
    int p0 = Math.min(dot, mark);
    int p1 = Math.max(dot, mark);
    RSyntaxDocument doc = (RSyntaxDocument)textArea.getDocument();
    Element map = doc.getDefaultRootElement();

    int lineNum = map.getElementIndex(dot);
    Element line = map.getElement(lineNum);
    int start = line.getStartOffset();
    int end = line.getEndOffset()-1; // Why always "-1"?
    String s = textArea.getText(start,end-start);
    int len = s.length();

    // endWS is the end of the leading whitespace
    // of the current line.
    int endWS = 0;
    while (endWS<len && RSyntaxUtilities.isWhitespace(s.charAt(endWS))) {
        endWS++;
    }
    s = s.substring(0, endWS);
    p0 -= getID().length();
    String beforeText = getBeforeTextIndented(s);
    String afterText = getAfterTextIndented(s);
    doc.replace(p0,p1-p0, beforeText+afterText, null);
    textArea.setCaretPosition(p0+beforeText.length());

}
项目:incubator-netbeans    文件:DocumentFinder.java   
/**
 * Finds in document 
 *
 * @param doc document where to find
 * @param startOffset offset in the document where the search will start
 * @param endOffset offset where the search will end with reporting
 *   that nothing was found.
 * @param props find properties
 */
public static int[] find(Document doc, int startOffset, int endOffset, Map<String, Object>  props,
                         boolean oppositeDir) throws BadLocationException{
    FindReplaceResult result = findReplaceImpl(null, doc, startOffset, endOffset, props, oppositeDir);
    if (result == null){
        return null;
    }

    return result.getFoundPositions();
}
项目:incubator-netbeans    文件:LineDocumentUtils.java   
public static int getPreviousWordEnd(@NonNull LineDocument doc, int offset)
throws BadLocationException
{
    checkOffsetValid(doc, offset);
    CharClassifier classifier = getValidClassifier(doc);
    CharSequence docText = DocumentUtilities.getText(doc);
    return TextSearchUtils.getPreviousWordEnd(docText, classifier, offset);
}
项目:BEAST    文件:CAntlrHandler.java   
/**
 * updates the parser
 */
public void updateParser() {
    try {
        String code = pane.getStyledDocument().getText(0, pane.getStyledDocument().getLength());
        lexer.setInputStream(new ANTLRInputStream(code));
        CommonTokenStream commonTokenStream = new CommonTokenStream(lexer);
        cParser.setTokenStream(commonTokenStream);
    } catch (BadLocationException ex) {
        Logger.getLogger(CAntlrHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
}