Search in sources :

Example 46 with InsertEdit

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

the class SurroundWithNewElementQuickAssistProposal method apply.

/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#apply(org.eclipse.jface.text.ITextViewer,
	 *      char, int, int)
	 */
public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
    try {
        int startTagOffset = offset;
        int endTagOffset = offset + viewer.getSelectedRange().y;
        // surround the node if no selection
        if (startTagOffset == endTagOffset) {
            IDOMNode cursorNode = (IDOMNode) ContentAssistUtils.getNodeAt(viewer, offset);
            // use parent node if text node is empty
            if ((cursorNode.getNodeType() == Node.TEXT_NODE) && (cursorNode.getNodeValue().trim().length() == 0)) {
                cursorNode = (IDOMNode) cursorNode.getParentNode();
            }
            startTagOffset = cursorNode.getStartOffset();
            endTagOffset = cursorNode.getEndOffset();
        }
        // insert new element
        MultiTextEdit multiTextEdit = new MultiTextEdit();
        // element tag name cannot be DBCS, do not translate "<element>"
        // and "</element>"
        // $NON-NLS-1$ //$NON-NLS-2$
        final String startElement = "<" + ELEMENT_NAME + ">";
        multiTextEdit.addChild(new InsertEdit(startTagOffset, startElement));
        // $NON-NLS-1$ //$NON-NLS-2$
        multiTextEdit.addChild(new InsertEdit(endTagOffset, "</" + ELEMENT_NAME + ">"));
        multiTextEdit.apply(viewer.getDocument());
        Position start = new Position(startTagOffset);
        Position end = new Position(endTagOffset + startElement.length());
        try {
            viewer.getDocument().addPosition(start);
            viewer.getDocument().addPosition(end);
            // get new element node
            IDOMNode newElementNode = (IDOMNode) ContentAssistUtils.getNodeAt(viewer, startTagOffset);
            IStructuredFormatProcessor formatProcessor = new FormatProcessorXML();
            formatProcessor.formatNode(newElementNode);
            // rename new element
            apply(viewer, trigger, stateMask, start, end, ELEMENT_NAME.length());
        } finally {
            viewer.getDocument().removePosition(start);
            viewer.getDocument().removePosition(end);
        }
    } catch (MalformedTreeException e) {
        // log for now, unless find reason not to
        Logger.log(Logger.INFO, e.getMessage());
    } catch (BadLocationException e) {
        // log for now, unless find reason not to
        Logger.log(Logger.INFO, e.getMessage());
    }
}
Also used : IStructuredFormatProcessor(org.eclipse.wst.sse.core.internal.format.IStructuredFormatProcessor) InsertEdit(org.eclipse.text.edits.InsertEdit) IDOMNode(org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode) LinkedPosition(org.eclipse.jface.text.link.LinkedPosition) Position(org.eclipse.jface.text.Position) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) FormatProcessorXML(org.eclipse.wst.xml.core.internal.provisional.format.FormatProcessorXML) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 47 with InsertEdit

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

the class PageImport method insertImportDeclaration.

private int insertImportDeclaration(IDocument document, int position, boolean isXML) {
    String delim = (document instanceof IStructuredDocument) ? ((IStructuredDocument) document).getLineDelimiter() : TextUtilities.getDefaultLineDelimiter(document);
    boolean isCustomTag = isCustomTagDocument(document);
    final String opening;
    final String closing;
    if (isCustomTag) {
        if (isXML) {
            // $NON-NLS-1$
            opening = "<jsp:directive.tag import=\"";
            // $NON-NLS-1$
            closing = "\"/>";
        } else {
            // $NON-NLS-1$
            opening = "<%@tag import=\"";
            // $NON-NLS-1$
            closing = "\"%>";
        }
    } else {
        if (isXML) {
            // $NON-NLS-1$
            opening = "<jsp:directive.page import=\"";
            // $NON-NLS-1$
            closing = "\"/>";
        } else {
            // $NON-NLS-1$
            opening = "<%@page import=\"";
            // $NON-NLS-1$
            closing = "\"%>";
        }
    }
    final String declaration = opening + name + closing + delim;
    final InsertEdit edit = new InsertEdit(position, declaration);
    try {
        edit.apply(document);
        return declaration.length();
    } catch (BadLocationException e) {
    } catch (MalformedTreeException e) {
    }
    return -1;
}
Also used : InsertEdit(org.eclipse.text.edits.InsertEdit) IStructuredDocument(org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 48 with InsertEdit

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

the class JSPTranslationExtension method getJspEdit.

/**
 * Returns a corresponding TextEdit for the JSP file given a TextEdit for
 * a Java file.
 *
 * @param javaEdit
 * @return the corresponding JSP edits (not applied to the document yet)
 */
public TextEdit getJspEdit(TextEdit javaEdit) {
    if (javaEdit == null)
        return null;
    List jspEdits = new ArrayList();
    int offset = javaEdit.getOffset();
    int length = javaEdit.getLength();
    if (javaEdit instanceof MultiTextEdit && javaEdit.getChildren().length > 0) {
        IRegion r = TextEdit.getCoverage(getAllEdits(javaEdit));
        offset = r.getOffset();
        length = r.getLength();
    }
    // get java ranges that will be affected by the edit
    Position[] javaPositions = getJavaRanges(offset, length);
    // record position data before the change
    Position[] jspPositions = new Position[javaPositions.length];
    PositionDelta[] deltas = new PositionDelta[javaPositions.length];
    for (int i = 0; i < javaPositions.length; i++) {
        deltas[i] = new PositionDelta(javaPositions[i].offset, javaPositions[i].length);
        // mapping from java <-> jsp (eg. an import statement)
        if (!isIndirect(javaPositions[i].offset))
            jspPositions[i] = (Position) getJava2JspMap().get(javaPositions[i]);
    }
    if (DEBUG) {
        // $NON-NLS-1$
        System.out.println("================================================");
        // $NON-NLS-1$
        System.out.println("deltas:");
        String javaText = getJavaText();
        for (int i = 0; i < deltas.length; i++) // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        System.out.println("pos[" + deltas[i].preOffset + ":" + deltas[i].preLength + "]" + javaText.substring(deltas[i].preOffset, deltas[i].preOffset + deltas[i].preLength));
        // $NON-NLS-1$
        System.out.println("===============================================");
    }
    UndoEdit undo = null;
    // apply the edit to the java document
    try {
        undo = javaEdit.apply(getJavaDocument());
    } catch (MalformedTreeException e) {
        Logger.logException(e);
    } catch (BadLocationException e) {
        Logger.logException(e);
    }
    // now at this point Java positions are unreliable since they were
    // updated after applying java edit.
    String newJavaText = getJavaDocument().get();
    if (DEBUG)
        // $NON-NLS-1$
        System.out.println("java post format text:\n" + newJavaText);
    // record post edit data
    for (int i = 0; i < javaPositions.length; i++) deltas[i].setPostEditData(javaPositions[i].offset, javaPositions[i].length, javaPositions[i].isDeleted);
    // create appropriate text edits for deltas
    Position jspPos = null;
    // $NON-NLS-1$
    String replaceText = "";
    for (int i = 0; i < deltas.length; i++) {
        jspPos = jspPositions[i];
        if (jspPos != null) {
            if (deltas[i].isDeleted) {
                jspEdits.add(new DeleteEdit(jspPos.offset, jspPos.length));
            } else {
                replaceText = newJavaText.substring(deltas[i].postOffset, deltas[i].postOffset + deltas[i].postLength);
                // get rid of pre and post white space or fine tuned
                // adjustment later.
                // fix text here...
                replaceText = fixJspReplaceText(replaceText, jspPos);
                if (// Unwanted TextEdit can lead to MalformedTreeException.See: Bug 321977
                !(replaceText.length() == 0 && jspPos.length == 0))
                    jspEdits.add(new ReplaceEdit(jspPos.offset, jspPos.length, replaceText));
            }
            if (DEBUG)
                debugReplace(deltas, jspPos, replaceText, i);
        } else {
            // possible new import?
            if (isImport(javaPositions[i].getOffset()) && replaceText.lastIndexOf("import ") != -1) {
                // $NON-NLS-1$
                replaceText = newJavaText.substring(deltas[i].postOffset, deltas[i].postOffset + deltas[i].postLength);
                // $NON-NLS-1$ //$NON-NLS-2$
                String importText = replaceText.substring(replaceText.lastIndexOf("import "), replaceText.indexOf(";"));
                // evenutally need to check if it's XML-JSP
                // $NON-NLS-1$ //$NON-NLS-2$
                importText = "<%@page import=\"" + importText + "\" %>\n";
                jspEdits.add(new InsertEdit(0, importText));
            }
        }
    }
    TextEdit allJspEdits = createMultiTextEdit((TextEdit[]) jspEdits.toArray(new TextEdit[jspEdits.size()]));
    // editor)
    if (undo != null) {
        try {
            undo.apply(getJavaDocument());
        } catch (MalformedTreeException e) {
            Logger.logException(e);
        } catch (BadLocationException e) {
            Logger.logException(e);
        }
    }
    return allJspEdits;
}
Also used : InsertEdit(org.eclipse.text.edits.InsertEdit) Position(org.eclipse.jface.text.Position) ArrayList(java.util.ArrayList) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) DeleteEdit(org.eclipse.text.edits.DeleteEdit) IRegion(org.eclipse.jface.text.IRegion) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) ArrayList(java.util.ArrayList) List(java.util.List) UndoEdit(org.eclipse.text.edits.UndoEdit) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 49 with InsertEdit

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

the class DefaultXMLPartitionFormatter method insertSpaceAndCollapse.

/**
 * Allow exactly one whitespace in currentTextRegion. If there are more,
 * collapse to one. If there are none, insert one.
 *
 * @param textEdit
 * @param currentDocumentRegion
 * @param availableLineWidth
 * @param currentTextRegion
 */
private void insertSpaceAndCollapse(TextEdit textEdit, IStructuredDocumentRegion currentDocumentRegion, int availableLineWidth, ITextRegion currentTextRegion) {
    int textLength = currentTextRegion.getTextLength();
    int regionLength = currentTextRegion.getLength();
    boolean thereAreSpaces = textLength < regionLength;
    int spacesStartOffset = currentDocumentRegion.getStartOffset(currentTextRegion) + textLength;
    if (thereAreSpaces) {
        String fullTagName = currentDocumentRegion.getFullText(currentTextRegion);
        String whitespaceRun = fullTagName.substring(textLength, regionLength);
        collapseSpaces(textEdit, spacesStartOffset, availableLineWidth, whitespaceRun);
    } else {
        // insert a space
        InsertEdit insertEdit = new InsertEdit(spacesStartOffset, SPACE);
        textEdit.addChild(insertEdit);
    }
}
Also used : InsertEdit(org.eclipse.text.edits.InsertEdit)

Example 50 with InsertEdit

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

the class DefaultXMLPartitionFormatter method compressContent.

private void compressContent(TextEdit textEdit, IStructuredDocumentRegion region, int startOffset, int indentLevel, int lineWidth, String text) {
    int length = text.length();
    int start = 0, end = 0;
    char c = 0;
    int resultLength = 0;
    boolean joinLines = fPreferences.getJoinCommentLines();
    boolean onOwnLine = false;
    String indent = getIndentString(indentLevel + 1);
    for (int i = 0; i < length; i++) {
        c = text.charAt(i);
        // Compress whitespace unless its a line delimiter and formatting does not permit joining lines
        if (Character.isWhitespace(c)) {
            if ((c != '\r' && c != '\n') || joinLines) {
                // Just came off of a word
                if (start == end) {
                    start = end = i;
                }
                end++;
                resultLength++;
            } else {
                // correct the indent of this line
                lineWidth = fPreferences.getMaxLineWidth();
                resultLength = 0;
                onOwnLine = true;
                // Compress any whitespace before the line delimiter
                if (start != end) {
                    int replaceLength = end - start;
                    textEdit.addChild(new ReplaceEdit(start + startOffset, replaceLength, EMPTY));
                    start = end = i;
                }
            }
        } else {
            // Transitioned to a new word
            if (start != end) {
                int replaceLength = end - start;
                if (onOwnLine) {
                    // If content is on its own line, replace leading whitespace with proper indent
                    textEdit.addChild(new ReplaceEdit(start + startOffset, replaceLength, indent));
                    resultLength -= (replaceLength - indent.length());
                    onOwnLine = false;
                } else if (!(replaceLength == 1 && text.charAt(start) == ' ')) {
                    textEdit.addChild(new ReplaceEdit(start + startOffset, replaceLength, SPACE));
                    resultLength -= (replaceLength - 1);
                }
                start = end = i;
                // Make sure the word starts on a new line
                if (resultLength > lineWidth) {
                    lineWidth = fPreferences.getMaxLineWidth();
                    resultLength = 0;
                    textEdit.addChild(new InsertEdit(start + startOffset, getLineDelimiter(region) + indent));
                }
            }
            // Word is immediately after line delimiters, indent appropriately
            if (onOwnLine) {
                textEdit.addChild(new InsertEdit(i + startOffset, indent));
                onOwnLine = false;
            }
            resultLength++;
        }
    }
    // Clean up any dangling whitespace
    int replaceLength = end - start;
    indent = getIndentString(indentLevel);
    if (replaceLength == 0) {
        // No trailing whitespace
        textEdit.addChild(new InsertEdit(length + startOffset, (onOwnLine) ? indent : SPACE));
    } else {
        String whitespace = text.substring(start);
        String replacement = (onOwnLine) ? indent : SPACE;
        if (!whitespace.equals(replacement)) {
            textEdit.addChild(new ReplaceEdit(start + startOffset, replaceLength, replacement));
        }
    }
}
Also used : InsertEdit(org.eclipse.text.edits.InsertEdit) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit)

Aggregations

InsertEdit (org.eclipse.text.edits.InsertEdit)65 MultiTextEdit (org.eclipse.text.edits.MultiTextEdit)33 ReplaceEdit (org.eclipse.text.edits.ReplaceEdit)24 TextEdit (org.eclipse.text.edits.TextEdit)22 DeleteEdit (org.eclipse.text.edits.DeleteEdit)20 Test (org.junit.Test)18 UndoEdit (org.eclipse.text.edits.UndoEdit)13 BadLocationException (org.eclipse.jface.text.BadLocationException)12 ArrayList (java.util.ArrayList)9 TextFileChange (org.eclipse.ltk.core.refactoring.TextFileChange)8 MalformedTreeException (org.eclipse.text.edits.MalformedTreeException)8 Location (org.eclipse.titan.designer.AST.Location)8 Module (org.eclipse.titan.designer.AST.Module)7 ProjectSourceParser (org.eclipse.titan.designer.parsers.ProjectSourceParser)7 WorkspaceJob (org.eclipse.core.resources.WorkspaceJob)5 CoreException (org.eclipse.core.runtime.CoreException)5 IFile (org.eclipse.core.resources.IFile)4 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)4 IDocument (org.eclipse.jface.text.IDocument)4 IRegion (org.eclipse.jface.text.IRegion)4