public void reformat() throws BadLocationException { final Document document = context.document(); final BaseDocument bd = (BaseDocument) document; bd.runAtomic( new Runnable() { public void run() { try { Element rootElement = document.getDefaultRootElement(); List<Context.Region> regions = context.indentRegions(); for (Context.Region region : regions) { int startOffset = region.getStartOffset(); int length = region.getEndOffset() - region.getStartOffset(); int elementIndex = rootElement.getElementIndex(startOffset); final int prevIndex = elementIndex > 0 ? elementIndex - 1 : elementIndex; int indent = getIndent(document, prevIndex); String text = document.getText(startOffset, length); if (text.startsWith(TEMPLATE_START)) { // remove template tags int st = startOffset + text.indexOf(TEMPLATE_START); document.remove(st, TEMPLATE_START.length()); int en = startOffset + text.indexOf(TEMPLATE_END) - TEMPLATE_START.length(); document.remove(en, TEMPLATE_END.length()); // modify indent int lastElement = rootElement.getElementIndex(en); for (int i = elementIndex; i <= lastElement; i++) { Element element = rootElement.getElement(i); int so = element.getStartOffset(); int currentIndent = context.lineIndent(so); // first line should not be indented if there is something already except // whitespaces boolean doIndent = true; if (i == elementIndex) { String textBefore = document.getText(so, startOffset - so); boolean isTextWSOnly = textBefore.matches("\\s+"); // NOI18N doIndent = textBefore.length() == 0 || isTextWSOnly; if (!doIndent) { indent = getIndent(document, i); } } else { doIndent = true; } if (doIndent) { context.modifyIndent(so, currentIndent + indent); } } } } } catch (BadLocationException e) { logger.log(Level.FINE, e.getLocalizedMessage()); } } }); }
public static void reformat(final BaseDocument doc, final int startOffset, final int endOffset) { final XMLLexerFormatter formatter = new XMLLexerFormatter(null); doc.runAtomic( new Runnable() { public void run() { formatter.doReformat(doc, startOffset, endOffset); } }); }
/** * Reformat with NetBeans format settings * * @param doc */ private void reformat(Document doc) { final BaseDocument baseDoc = (BaseDocument) doc; final Reformat reformat = Reformat.get(baseDoc); reformat.lock(); try { baseDoc.runAtomic( new Runnable() { @Override public void run() { try { reformat.reformat(0, baseDoc.getLength()); // Remove tab from Document Block removeIndentDocBlock(); } catch (BadLocationException ex) { LOGGER.log(Level.WARNING, null, ex); } } }); } finally { reformat.unlock(); } }