Search in sources :

Example 96 with TextEdit

use of org.eclipse.text.edits.TextEdit in project webtools.sourceediting by eclipse.

the class FormattingStrategyJSDT method format.

/*
	 * @see org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy#format()
	 */
public void format() {
    super.format();
    final IStructuredDocument document = (IStructuredDocument) fDocuments.removeFirst();
    final TypedPosition partition = (TypedPosition) fPartitions.removeFirst();
    if (document != null) {
        // calculate the indent of the leading <script> tag because we need to add that indent level to the JS indent level
        IStructuredDocumentRegion scriptTagStartRegion = document.getRegionAtCharacterOffset(partition.offset - 1);
        // $NON-NLS-1$
        String scriptRegionIndent = "";
        if (scriptTagStartRegion != null) {
            try {
                int scriptRegionIndentLevel = getIndentOfLine(document, document.getLineOfOffset(scriptTagStartRegion.getStartOffset())).length();
                scriptRegionIndent = getIndentationString(getPreferences(), scriptRegionIndentLevel);
                this.startIndentLevel += scriptRegionIndentLevel;
            } catch (BadLocationException e) {
                // $NON-NLS-1$
                Logger.logException("Could not calculate starting indent of the script region, using 0", e);
            }
        }
        String lineDelim = TextUtilities.getDefaultLineDelimiter(document);
        try {
            // get the JS text from the document (not translated)
            String jsTextNotTranslated = document.get(partition.getOffset(), partition.getLength());
            String originalText = jsTextNotTranslated;
            // deal with getting the JS text and unwrapping it from any <!-- //--> statements
            String preText = "";
            String postText = lineDelim + scriptRegionIndent;
            // find and remove start comment tag if it's there
            // $NON-NLS-1$
            Pattern startPattern = Pattern.compile("(\\A(\\s*<!--.*(" + lineDelim + ")?))");
            Matcher matcher = startPattern.matcher(jsTextNotTranslated);
            if (matcher.find()) {
                preText = lineDelim + scriptRegionIndent + matcher.group().trim();
                // $NON-NLS-1$
                jsTextNotTranslated = matcher.replaceFirst("");
            }
            // find and remove end comment tag if it's there
            matcher = END_PATTERN.matcher(jsTextNotTranslated);
            if (matcher.find()) {
                // $NON-NLS-1$
                jsTextNotTranslated = matcher.replaceFirst("");
                postText = lineDelim + scriptRegionIndent + matcher.group().trim() + postText;
            }
            /*
				 * replace the text in the document with the non-translated JS
				 * text but without HTML leading and trailing comments
				 */
            int scriptLength = jsTextNotTranslated.length();
            TextEdit replaceEdit = null;
            if (scriptLength != originalText.length()) {
                replaceEdit = new ReplaceEdit(partition.getOffset(), partition.getLength(), jsTextNotTranslated);
                replaceEdit.apply(document);
            }
            // translate the web page without the script "wrapping"
            IJsTranslation translation = getTranslation(document);
            String jsTextTranslated = translation.getJsText();
            /*
				 * Set a default replace text that is the original contents
				 * with a new line and proper indentation in front
				 */
            String replaceText = lineDelim + getIndentationString(getPreferences(), startIndentLevel) + jsTextNotTranslated;
            int javaScriptOffset = ((JsTranslation) translation).getJavaScriptOffset(partition.getOffset());
            // known range, proceed
            if (javaScriptOffset >= 0) {
                // format the translated text
                TextEdit edit = CodeFormatterUtil.format2(CodeFormatter.K_JAVASCRIPT_UNIT, jsTextTranslated, javaScriptOffset, scriptLength, startIndentLevel, lineDelim, getPreferences());
                IDocument jsDoc = new Document(jsTextTranslated);
                if (edit != null) {
                    /*
						 * Put the original (possibly not JS) text back into the doc
						 * to which we're applying the edit
						 */
                    if (translation instanceof JsTranslation) {
                        IJsTranslator translator = ((JsTranslation) translation).getTranslator();
                        if (translator instanceof JsTranslator) {
                            Region[] regions = ((JsTranslator) translator).getGeneratedRanges();
                            Arrays.sort(regions, new Comparator() {

                                public int compare(Object o1, Object o2) {
                                    return ((IRegion) o1).getOffset() - ((IRegion) o2).getOffset();
                                }
                            });
                            /*
								 * for each web page range representing content needing replacements, replace it with the
								 * original web page's text
								 */
                            for (int r = 0; r < regions.length; ++r) {
                                int javascriptOffset = ((JsTranslation) translation).getJavaScriptOffset(regions[r].getOffset());
                                if (javascriptOffset > 0) {
                                    jsDoc.replace(javascriptOffset, regions[r].getLength(), document.get(regions[r].getOffset(), regions[r].getLength()));
                                }
                            }
                        }
                    }
                    edit.apply(jsDoc);
                    replaceText = lineDelim + getIndentationString(getPreferences(), startIndentLevel) + (jsDoc.get(edit.getOffset(), edit.getLength())).trim();
                } else {
                    /*
						 * Revert changes (it may still appear dirty, though,
						 * because of the above edits having been applied)
						 */
                    replaceEdit = new ReplaceEdit(partition.getOffset(), scriptLength, originalText);
                    replaceEdit.apply(document);
                    return;
                }
            }
            // apply edit to html doc using the formated translated text and the possible leading and trailing html comments
            replaceText = preText + replaceText + postText;
            replaceEdit = new ReplaceEdit(partition.getOffset(), scriptLength, replaceText);
            replaceEdit.apply(document);
        } catch (BadLocationException e) {
            Logger.logException(e);
        }
    }
}
Also used : IJsTranslation(org.eclipse.wst.jsdt.web.core.javascript.IJsTranslation) Pattern(java.util.regex.Pattern) IStructuredDocumentRegion(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion) Matcher(java.util.regex.Matcher) JsTranslator(org.eclipse.wst.jsdt.web.core.javascript.JsTranslator) IJsTranslator(org.eclipse.wst.jsdt.web.core.javascript.IJsTranslator) JsTranslation(org.eclipse.wst.jsdt.web.core.javascript.JsTranslation) IJsTranslation(org.eclipse.wst.jsdt.web.core.javascript.IJsTranslation) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) IDOMDocument(org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument) BasicStructuredDocument(org.eclipse.wst.sse.core.internal.text.BasicStructuredDocument) IStructuredDocument(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument) IJsTranslator(org.eclipse.wst.jsdt.web.core.javascript.IJsTranslator) IRegion(org.eclipse.jface.text.IRegion) Comparator(java.util.Comparator) TypedPosition(org.eclipse.jface.text.TypedPosition) TextEdit(org.eclipse.text.edits.TextEdit) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) Region(org.eclipse.jface.text.Region) IRegion(org.eclipse.jface.text.IRegion) IStructuredDocumentRegion(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion) IStructuredDocument(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument) BadLocationException(org.eclipse.jface.text.BadLocationException) IDocument(org.eclipse.jface.text.IDocument)

Example 97 with TextEdit

use of org.eclipse.text.edits.TextEdit in project webtools.sourceediting by eclipse.

the class FormattingStrategyJSPJava method format.

/*
	 * @see org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy#format()
	 */
public void format() {
    super.format();
    final IDocument document = (IDocument) fDocuments.removeFirst();
    final TypedPosition partition = (TypedPosition) fPartitions.removeFirst();
    if (document != null && partition != null) {
        try {
            JSPTranslationUtil translationUtil = new JSPTranslationUtil(document);
            ICompilationUnit cu = translationUtil.getCompilationUnit();
            if (cu != null) {
                String cuSource = cu.getSource();
                /*
					 * Format the entire compilation unit, but only create
					 * edits for the requested JSP partition's range in the
					 * Java source
					 */
                TextEdit textEdit = formatString(CodeFormatter.K_COMPILATION_UNIT, cuSource, translationUtil.getTranslation().getJavaOffset(partition.getOffset()), partition.getLength(), TextUtilities.getDefaultLineDelimiter(document), getPreferences());
                TextEdit jspEdit = translationUtil.getTranslation().getJspEdit(textEdit);
                if (jspEdit != null && jspEdit.hasChildren())
                    jspEdit.apply(document);
            }
        } catch (MalformedTreeException exception) {
            Logger.logException(exception);
        } catch (BadLocationException exception) {
            // Can only happen on concurrent document modification - log
            // and bail out
            Logger.logException(exception);
        } catch (JavaModelException exception) {
            Logger.logException(exception);
        }
    }
}
Also used : JSPTranslationUtil(org.eclipse.jst.jsp.core.internal.java.JSPTranslationUtil) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) JavaModelException(org.eclipse.jdt.core.JavaModelException) TypedPosition(org.eclipse.jface.text.TypedPosition) TextEdit(org.eclipse.text.edits.TextEdit) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 98 with TextEdit

use of org.eclipse.text.edits.TextEdit in project webtools.sourceediting by eclipse.

the class XMLFormatterFormatProcessor method formatModel.

public void formatModel(IStructuredModel structuredModel, int start, int length) {
    if (fProgressMonitor != null)
        fProgressMonitor.beginTask("", 2);
    IStructuredDocument structuredDocument = structuredModel.getStructuredDocument();
    DocumentRewriteSession activeRewriteSession = ((IDocumentExtension4) structuredDocument).getActiveRewriteSession();
    boolean startedRewriteSession = false;
    if (activeRewriteSession == null) {
        activeRewriteSession = ((IDocumentExtension4) structuredDocument).startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED);
        startedRewriteSession = true;
    }
    getFormatter().setProgressMonitor(new NullProgressMonitor() {

        public boolean isCanceled() {
            return fProgressMonitor != null && fProgressMonitor.isCanceled();
        }
    });
    TextEdit edit = getFormatter().format(structuredModel, start, length);
    if (fProgressMonitor != null)
        fProgressMonitor.worked(1);
    try {
        structuredModel.aboutToChangeModel();
        edit.apply(structuredDocument);
        if (fProgressMonitor != null)
            fProgressMonitor.worked(1);
    } catch (Exception e) {
        Logger.log(Logger.WARNING_DEBUG, e.getMessage(), e);
    } finally {
        if (startedRewriteSession && activeRewriteSession != null) {
            ((IDocumentExtension4) structuredDocument).stopRewriteSession(activeRewriteSession);
        }
        structuredModel.changedModel();
        if (fProgressMonitor != null)
            fProgressMonitor.done();
    }
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) DocumentRewriteSession(org.eclipse.jface.text.DocumentRewriteSession) IDocumentExtension4(org.eclipse.jface.text.IDocumentExtension4) TextEdit(org.eclipse.text.edits.TextEdit) IStructuredDocument(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument) IOException(java.io.IOException) CoreException(org.eclipse.core.runtime.CoreException)

Example 99 with TextEdit

use of org.eclipse.text.edits.TextEdit in project webtools.sourceediting by eclipse.

the class TestPartitionFormatterXML method formatAndAssertEquals.

private void formatAndAssertEquals(String beforePath, String afterPath, XMLFormattingPreferences prefs) throws UnsupportedEncodingException, IOException, CoreException {
    IStructuredModel beforeModel = null, afterModel = null;
    try {
        beforeModel = getModelForEdit(beforePath);
        assertNotNull("could not retrieve structured model for : " + beforePath, beforeModel);
        afterModel = getModelForEdit(afterPath);
        assertNotNull("could not retrieve structured model for : " + afterPath, afterModel);
        IStructuredDocument document = beforeModel.getStructuredDocument();
        String normalizedContents = document.get();
        normalizedContents = StringUtils.replace(normalizedContents, "\r\n", "\n");
        normalizedContents = StringUtils.replace(normalizedContents, "\r", "\n");
        document.set(normalizedContents);
        if (prefs == null)
            prefs = new XMLFormattingPreferences();
        TextEdit edit = partitionFormatter.format(beforeModel, 0, document.getLength(), prefs);
        try {
            edit.apply(document);
        } catch (MalformedTreeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadLocationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ByteArrayOutputStream formattedBytes = new ByteArrayOutputStream();
        // "beforeModel" should now be
        beforeModel.save(formattedBytes);
        // after the formatter
        ByteArrayOutputStream afterBytes = new ByteArrayOutputStream();
        afterModel.save(afterBytes);
        String expectedContents = new String(afterBytes.toByteArray(), UTF_8);
        String actualContents = new String(formattedBytes.toByteArray(), UTF_8);
        /* Make some adjustments to ignore cross platform line delimiter issues */
        expectedContents = StringUtils.replace(expectedContents, "\r\n", "\n");
        expectedContents = StringUtils.replace(expectedContents, "\r", "\n");
        actualContents = StringUtils.replace(actualContents, "\r\n", "\n");
        actualContents = StringUtils.replace(actualContents, "\r", "\n");
        if (!fStringCompareUtil.equalsIgnoreLineSeperator(expectedContents, actualContents)) {
            assertEquals("Formatted document differs from the expected.", expectedContents, actualContents);
        }
    } finally {
        if (beforeModel != null)
            beforeModel.releaseFromEdit();
        if (afterModel != null)
            afterModel.releaseFromEdit();
    }
}
Also used : TextEdit(org.eclipse.text.edits.TextEdit) IStructuredDocument(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) IStructuredModel(org.eclipse.wst.sse.core.internal.provisional.IStructuredModel) XMLFormattingPreferences(org.eclipse.wst.xml.core.internal.formatter.XMLFormattingPreferences) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 100 with TextEdit

use of org.eclipse.text.edits.TextEdit in project webtools.sourceediting by eclipse.

the class DefaultXMLPartitionFormatter method indentIfNotAlreadyIndented.

/**
 * Indent if whitespaceRun does not already contain an indent
 *
 * @param textEdit
 * @param indentLevel
 * @param indentStartOffset
 * @param maxAvailableLineWidth
 * @param whitespaceRun
 * @return new available line width up to where indented
 */
private int indentIfNotAlreadyIndented(TextEdit textEdit, IStructuredDocumentRegion currentRegion, int indentLevel, int indentStartOffset, String whitespaceRun) {
    int maxAvailableLineWidth = getFormattingPreferences().getMaxLineWidth();
    int availableLineWidth;
    String indentString = getIndentString(indentLevel);
    String lineDelimiter = getLineDelimiter(currentRegion);
    String newLineAndIndent = lineDelimiter + indentString;
    TextEdit indentation = null;
    // if not already correctly indented
    if (!newLineAndIndent.equals(whitespaceRun)) {
        if (getFormattingPreferences().getClearAllBlankLines()) {
            if (whitespaceRun != null) {
                // replace existing whitespace run
                indentation = new ReplaceEdit(indentStartOffset, whitespaceRun.length(), newLineAndIndent);
            } else {
                // just insert correct indent
                indentation = new InsertEdit(indentStartOffset, newLineAndIndent);
            }
        } else // Keep the empty lines
        {
            // just insert correct indent
            if (whitespaceRun == null)
                indentation = new InsertEdit(indentStartOffset, newLineAndIndent);
            else // Need to preserve the number of empty lines, but still indent on the current line properly
            {
                String existingDelimiters = extractLineDelimiters(whitespaceRun, currentRegion);
                if (existingDelimiters != null && existingDelimiters.length() > 0) {
                    String formatted = existingDelimiters + indentString;
                    // Don't perform a replace if the formatted string is the same as the existing whitespaceRun
                    if (!formatted.equals(whitespaceRun))
                        indentation = new ReplaceEdit(indentStartOffset, whitespaceRun.length(), formatted);
                } else
                    // No blank lines to preserve - correct the indent
                    indentation = new ReplaceEdit(indentStartOffset, whitespaceRun.length(), newLineAndIndent);
            }
        }
    }
    if (indentation != null)
        textEdit.addChild(indentation);
    // update line width
    availableLineWidth = maxAvailableLineWidth - indentString.length();
    return availableLineWidth;
}
Also used : InsertEdit(org.eclipse.text.edits.InsertEdit) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit)

Aggregations

TextEdit (org.eclipse.text.edits.TextEdit)190 MultiTextEdit (org.eclipse.text.edits.MultiTextEdit)113 Test (org.junit.Test)49 IDocument (org.eclipse.jface.text.IDocument)48 ReplaceEdit (org.eclipse.text.edits.ReplaceEdit)48 BadLocationException (org.eclipse.jface.text.BadLocationException)34 Document (org.eclipse.jface.text.Document)33 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)32 UndoEdit (org.eclipse.text.edits.UndoEdit)26 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)23 InsertEdit (org.eclipse.text.edits.InsertEdit)22 CoreException (org.eclipse.core.runtime.CoreException)20 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)19 MalformedTreeException (org.eclipse.text.edits.MalformedTreeException)19 DeleteEdit (org.eclipse.text.edits.DeleteEdit)17 MoveSourceEdit (org.eclipse.text.edits.MoveSourceEdit)16 ArrayList (java.util.ArrayList)15 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)15 MoveTargetEdit (org.eclipse.text.edits.MoveTargetEdit)15 TextEditGroup (org.eclipse.text.edits.TextEditGroup)15