Java Code Examples for org.eclipse.text.edits.MultiTextEdit#addChildren()

The following examples show how to use org.eclipse.text.edits.MultiTextEdit#addChildren() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ChangeConverter.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void _handleReplacements(ITextDocumentChange change) {
	if (!change.getReplacements().isEmpty()) {
		IFile file = resourceUriConverter.toFile(change.getOldURI());
		if (!canWrite(file)) {
			issues.add(RefactoringIssueAcceptor.Severity.FATAL, "Affected file '" + file.getFullPath() + "' is read-only");
		}
		checkDerived(file);
		List<ReplaceEdit> textEdits = change.getReplacements().stream().map(replacement -> {
			return new ReplaceEdit(replacement.getOffset(), replacement.getLength(), replacement.getReplacementText());
		}).collect(Collectors.toList());

		MultiTextEdit textEdit = new MultiTextEdit();
		textEdit.addChildren(textEdits.toArray(new TextEdit[textEdits.size()]));
		ITextEditor openEditor = findOpenEditor(file);
		final TextChange ltkChange;
		if (openEditor == null) {
			TextFileChange textFileChange = new TextFileChange(change.getOldURI().lastSegment(), file);
			textFileChange.setSaveMode(TextFileChange.FORCE_SAVE);
			ltkChange = textFileChange;
		} else {
			ltkChange = new EditorDocumentChange(currentChange.getName(), openEditor, false);
		}
		ltkChange.setEdit(textEdit);
		ltkChange.setTextType(change.getOldURI().fileExtension());
		addChange(ltkChange);
	}
}
 
Example 2
Source File: TextEditCreation.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Puts the edits found in a doc change, tak
 * @param fChange
 * @param editsAlreadyCreatedLst
 * @param docChange
 * @param rootEdit
 * @param renameEdits
 */
private void fillEditsInDocChange(TextChange docChange, MultiTextEdit rootEdit,
        List<Tuple<List<TextEdit>, String>> renameEdits) {
    Assert.isTrue(renameEdits.size() > 0);
    try {
        for (Tuple<List<TextEdit>, String> t : renameEdits) {
            TextEdit[] arr = t.o1.toArray(new TextEdit[t.o1.size()]);
            rootEdit.addChildren(arr);
            docChange.addTextEditGroup(new TextEditGroup(t.o2, arr));
        }
    } catch (RuntimeException e) {
        //StringBuffer buf = new StringBuffer("Found occurrences:");
        //for (Tuple<TextEdit, String> t : renameEdits) {
        //  buf.append("Offset: ");
        //  buf.append(t.o1.getOffset());
        //  buf.append("Len: ");
        //  buf.append(t.o1.getLength());
        //  buf.append("Str: ");
        //  buf.append(t.o2);
        //  buf.append("\n");
        //}
        //
        //don't bother reporting this to the user (usually happens if we have it the file changes during the analysis).
        //PydevPlugin.log(buf.toString(), e);
        throw e;
    }
}
 
Example 3
Source File: AddBlockCommentHandler.java    From xds-ide with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    try {
        ITextSelection selection = WorkbenchUtils.getActiveTextSelection();
        IDocument      doc       = WorkbenchUtils.getActiveDocument();
        IEditorInput   input     = WorkbenchUtils.getActiveInput();
        IEditorPart    editor    = WorkbenchUtils.getActiveEditor(false);

        boolean isTextOperationAllowed = (selection != null) && (doc != null) 
                                      && (input != null)     && (editor != null) 
                                      && (editor instanceof ModulaEditor);

        if (isTextOperationAllowed) {
            ITextEditor iTextEditor = (ITextEditor)editor;
            final ITextOperationTarget operationTarget = (ITextOperationTarget) editor.getAdapter(ITextOperationTarget.class);
            String commentPrefix = ((SourceCodeTextEditor)editor).getEOLCommentPrefix();
            isTextOperationAllowed = (operationTarget != null)
                                  && (operationTarget instanceof TextViewer)
                                  && (validateEditorInputState(iTextEditor))
                                  && (commentPrefix != null);
            
            if ((isTextOperationAllowed)) {
                int startLine = selection.getStartLine();
                int endLine = selection.getEndLine(); 
                int selOffset = selection.getOffset();
                int selLen = selection.getLength();
                int realEndLine = doc.getLineOfOffset(selOffset + selLen); // for selection end at pos=0 (endLine is line before here) 
                
                // Are cursor and anchor at 0 positions?
                boolean is0pos = false;
                if (doc.getLineOffset(startLine) == selOffset) {
                    if ((doc.getLineOffset(endLine) + doc.getLineLength(endLine) == selOffset + selLen)) {
                        is0pos = true;
                    }
                }
                
                
                ArrayList<ReplaceEdit> edits = null;
                int offsAfter[] = {0};
                if (is0pos || selLen == 0) {
                    edits = commentWholeLines(startLine, (selLen == 0) ? startLine : endLine, realEndLine, doc, offsAfter);
                } else {
                    edits = commentRange(selOffset, selLen, "(*", "*)", offsAfter); //$NON-NLS-1$ //$NON-NLS-2$
                }
                
                if (edits != null && !edits.isEmpty()) {
                    DocumentRewriteSession drws = null;
                    try {
                        if (doc instanceof IDocumentExtension4) {
                            drws = ((IDocumentExtension4)doc).startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED);
                        }
                        MultiTextEdit edit= new MultiTextEdit(0, doc.getLength());
                        edit.addChildren((TextEdit[]) edits.toArray(new TextEdit[edits.size()]));
                        edit.apply(doc, TextEdit.CREATE_UNDO);
                        iTextEditor.getSelectionProvider().setSelection(new TextSelection(offsAfter[0], 0));
                    }
                    finally {
                        if (doc instanceof IDocumentExtension4 && drws != null) {
                            ((IDocumentExtension4)doc).stopRewriteSession(drws);
                        }
                    }
                    
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 4
Source File: ModulaTextFormatter.java    From xds-ide with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * 
 * @param document
 * @param ast
 * @param begPos begin offset of the formatted area (0 to format all)
 * @param endPos end offset of the formatted area (doc.getLength() to format all)
 */
public void doFormat(IDocument doc, ModulaAst ast, int begPos, int endPos, boolean indentOnly) throws Exception {
    buildChunksModel(doc, ast, doc.getLength());
    if (chunks.size() == 0) {
        return; // Nothing to do
    }
    
    int firstChunkIdx = chunkIdxAtPos(begPos);
    int lastChunkIdx  = chunkIdxAtPos(endPos-1);

    { // Fix selection margins to include whole chunks:
        begPos = chunks.get(firstChunkIdx).getOffsetInDoc();
        Chunk c = chunks.get(lastChunkIdx);
        endPos = c.getOffsetInDoc() + c.getLengthInDoc();
    }


    if (lastChunkIdx == chunks.size()-1) {
        // chunks[lastChunkIdx+1] should always be some chunk with offset,
        // it will be required to build format edits from chunk model
        chunks.add(Chunk.createNoPlnChunkFromDoc(doc, doc.getLength(), 0));
    }
    
    // lastChunkIdx may be changed with model so use terminalChunk:
    Chunk terminalChunk = chunks.get(lastChunkIdx+1);  
   
    if (!indentOnly) {
        processNewLines(doc, firstChunkIdx, terminalChunk);
    }

    processWhitespaces(doc, firstChunkIdx, terminalChunk, indentOnly);

    if (!indentOnly) {
        processWrapLines(doc, firstChunkIdx, terminalChunk);
    }

    ArrayList<ReplaceEdit> edits = buildEditsFromModel(doc, firstChunkIdx, terminalChunk);
    
    DocumentRewriteSession drws = null;
    try {
        if (doc instanceof IDocumentExtension4) {
            drws = ((IDocumentExtension4)doc).startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED);
        }
        MultiTextEdit edit= new MultiTextEdit(0, doc.getLength());
        edit.addChildren((TextEdit[]) edits.toArray(new TextEdit[edits.size()]));
        edit.apply(doc, TextEdit.CREATE_UNDO);
    }
    finally {
        if (doc instanceof IDocumentExtension4 && drws != null) {
            ((IDocumentExtension4)doc).stopRewriteSession(drws);
        }
    }
}