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

The following examples show how to use org.eclipse.text.edits.MultiTextEdit#apply() . 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: TextEditConverter.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean visit(MultiTextEdit edit) {
	try {
		org.eclipse.lsp4j.TextEdit te = new org.eclipse.lsp4j.TextEdit();
		te.setRange(JDTUtils.toRange(compilationUnit, edit.getOffset(), edit.getLength()));
		Document doc = new Document(compilationUnit.getSource());
		edit.apply(doc, TextEdit.UPDATE_REGIONS);
		String content = doc.get(edit.getOffset(), edit.getLength());
		te.setNewText(content);
		converted.add(te);
		return false;
	} catch (JavaModelException | MalformedTreeException | BadLocationException e) {
		JavaLanguageServerPlugin.logException("Error converting TextEdits", e);
	}
	return false;
}
 
Example 2
Source File: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static String fixEmptyVariables(TemplateBuffer buffer, String[] variables) throws MalformedTreeException, BadLocationException {
	IDocument doc= new Document(buffer.getString());
	int nLines= doc.getNumberOfLines();
	MultiTextEdit edit= new MultiTextEdit();
	HashSet<Integer> removedLines= new HashSet<Integer>();
	for (int i= 0; i < variables.length; i++) {
		TemplateVariable position= findVariable(buffer, variables[i]); // look if Javadoc tags have to be added
		if (position == null || position.getLength() > 0) {
			continue;
		}
		int[] offsets= position.getOffsets();
		for (int k= 0; k < offsets.length; k++) {
			int line= doc.getLineOfOffset(offsets[k]);
			IRegion lineInfo= doc.getLineInformation(line);
			int offset= lineInfo.getOffset();
			String str= doc.get(offset, lineInfo.getLength());
			if (Strings.containsOnlyWhitespaces(str) && nLines > line + 1 && removedLines.add(new Integer(line))) {
				int nextStart= doc.getLineOffset(line + 1);
				edit.addChild(new DeleteEdit(offset, nextStart - offset));
			}
		}
	}
	edit.apply(doc, 0);
	return doc.get();
}
 
Example 3
Source File: GeneratePropertiesTestCase.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
private IDocument applyGenerateProperties(MockupGeneratePropertiesRequestProcessor requestProcessor)
        throws BadLocationException, MalformedTreeException, MisconfigurationException {
    IDocument refactoringDoc = new Document(data.source);
    MultiTextEdit multi = new MultiTextEdit();
    for (GeneratePropertiesRequest req : requestProcessor.getRefactoringRequests()) {
        SelectionState state = req.getSelectionState();

        if (state.isGetter()) {
            multi.addChild(new GetterMethodEdit(req).getEdit());
        }
        if (state.isSetter()) {
            multi.addChild(new SetterMethodEdit(req).getEdit());
        }
        if (state.isDelete()) {
            multi.addChild(new DeleteMethodEdit(req).getEdit());
        }
        multi.addChild(new PropertyEdit(req).getEdit());
    }
    multi.apply(refactoringDoc);
    return refactoringDoc;
}
 
Example 4
Source File: ExtractMethodTestCase.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
private IDocument applyExtractMethod(RefactoringInfo info, MockupExtractMethodRequestProcessor requestProcessor)
        throws BadLocationException, MalformedTreeException, MisconfigurationException {
    ExtractMethodRequest req = requestProcessor.getRefactoringRequests().get(0);

    ExtractMethodEdit extractedMethodEdit = new ExtractMethodEdit(req);
    ExtractCallEdit callExtractedMethodEdit = new ExtractCallEdit(req);

    MultiTextEdit edit = new MultiTextEdit();
    edit.addChild(extractedMethodEdit.getEdit());
    edit.addChild(callExtractedMethodEdit.getEdit());

    IDocument refactoringDoc = new Document(data.source);
    edit.apply(refactoringDoc);
    return refactoringDoc;
}
 
Example 5
Source File: N4JSReplacementTextApplier.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Really do apply the proposal. Assumed to be run within the prevent flickering mode.
 */
private int doApply(QualifiedName qualifiedName, String alias, IDocument document,
		ConfigurableCompletionProposal proposal) throws BadLocationException {
	String shortSemanticReplacementString = alias != null ? alias : lastSegmentOrDefaultHost(qualifiedName);
	String shortSyntacticReplacementString = valueConverter.toString(shortSemanticReplacementString);
	String longReplacementString = shortSyntacticReplacementString
			+ ConfigurableCompletionProposalExtensions.getReplacementSuffix(proposal);

	ImportRewriter importRewriter = importRewriterFactory.create(document, context);

	ReplaceEdit replaceEdit = new ReplaceEdit(
			proposal.getReplacementOffset(),
			proposal.getReplacementLength(),
			longReplacementString);
	MultiTextEdit compound = new MultiTextEdit();
	AliasLocation aliasLocation = null;
	if (alias != null) {
		aliasLocation = importRewriter.addSingleImport(qualifiedName, alias, compound);
	} else {
		importRewriter.addSingleImport(qualifiedName, compound);
	}
	compound.addChild(replaceEdit);

	Position caret = new Position(proposal.getReplacementOffset(), 0);
	document.addPosition(caret);
	compound.apply(document);
	document.removePosition(caret);

	int cursorPosition = caret.getOffset();
	proposal.setReplacementOffset(cursorPosition - longReplacementString.length());
	proposal.setReplacementLength(shortSyntacticReplacementString.length()); // do not include suffix!
	proposal.setCursorPosition(
			cursorPosition - proposal.getReplacementOffset()); // cursorPosition is relative to replacementOffset!

	if (aliasLocation != null) {
		final int aliasOffset = aliasLocation.getBaseOffset() + aliasLocation.getRelativeOffset();
		final int aliasLength = shortSyntacticReplacementString.length();
		N4JSCompletionProposal castedProposal = (N4JSCompletionProposal) proposal;
		castedProposal.setLinkedModeBuilder((appliedProposal, currentDocument) -> {
			if (viewer.getTextWidget() == null || viewer.getTextWidget().isDisposed()) {
				return; // do not attempt to set up linked mode in a disposed UI
			}
			try {
				LinkedPositionGroup group = new LinkedPositionGroup();
				group.addPosition(new LinkedPosition(
						currentDocument,
						aliasOffset,
						aliasLength,
						LinkedPositionGroup.NO_STOP));
				group.addPosition(new LinkedPosition(
						currentDocument,
						proposal.getReplacementOffset(),
						proposal.getReplacementLength(),
						LinkedPositionGroup.NO_STOP));
				proposal.setSelectionStart(proposal.getReplacementOffset());
				proposal.setSelectionLength(proposal.getReplacementLength());
				LinkedModeModel model = new LinkedModeModel();
				model.addGroup(group);
				model.forceInstall();

				LinkedModeUI ui = new LinkedModeUI(model, viewer);
				ui.setExitPolicy(new IdentifierExitPolicy('\n'));
				ui.setExitPosition(
						viewer,
						proposal.getReplacementOffset()
								+ proposal.getCursorPosition()
								+ ConfigurableCompletionProposalExtensions.getCursorOffset(proposal),
						0,
						Integer.MAX_VALUE);
				ui.setCyclingMode(LinkedModeUI.CYCLE_NEVER);
				ui.enter();
			} catch (BadLocationException e) {
				logger.error(e.getMessage(), e);
			}
		});
	} else {
		adjustCursorPositionIfRequested(proposal);
	}
	return cursorPosition;
}
 
Example 6
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 7
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);
        }
    }
}
 
Example 8
Source File: JavaFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private List<TypedPosition> createRangeMarkers(TemplateVariable[] variables, IDocument document) throws MalformedTreeException, BadLocationException {
	Map<ReplaceEdit, String> markerToOriginal= new HashMap<ReplaceEdit, String>();

	MultiTextEdit root= new MultiTextEdit(0, document.getLength());
	List<TextEdit> edits= new ArrayList<TextEdit>();
	boolean hasModifications= false;
	for (int i= 0; i != variables.length; i++) {
		final TemplateVariable variable= variables[i];
		int[] offsets= variable.getOffsets();

		String value= variable.getDefaultValue();
		if (isWhitespaceVariable(value)) {
			// replace whitespace positions with unformattable comments
			String placeholder= COMMENT_START + value + COMMENT_END;
			for (int j= 0; j != offsets.length; j++) {
				ReplaceEdit replace= new ReplaceEdit(offsets[j], value.length(), placeholder);
				root.addChild(replace);
				hasModifications= true;
				markerToOriginal.put(replace, value);
				edits.add(replace);
			}
		} else {
			for (int j= 0; j != offsets.length; j++) {
				RangeMarker marker= new RangeMarker(offsets[j], value.length());
				root.addChild(marker);
				edits.add(marker);
			}
		}
	}

	if (hasModifications) {
		// update the document and convert the replaces to markers
		root.apply(document, TextEdit.UPDATE_REGIONS);
	}

	List<TypedPosition> positions= new ArrayList<TypedPosition>();
	for (Iterator<TextEdit> it= edits.iterator(); it.hasNext();) {
		TextEdit edit= it.next();
		try {
			// abuse TypedPosition to piggy back the original contents of the position
			final TypedPosition pos= new TypedPosition(edit.getOffset(), edit.getLength(), markerToOriginal.get(edit));
			document.addPosition(CATEGORY, pos);
			positions.add(pos);
		} catch (BadPositionCategoryException x) {
			Assert.isTrue(false);
		}
	}

	return positions;
}
 
Example 9
Source File: AddJavaDocStubOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void addJavadocComments(IProgressMonitor monitor) throws CoreException {
	ICompilationUnit cu= fMembers[0].getCompilationUnit();

	ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
	IPath path= cu.getPath();

	manager.connect(path, LocationKind.IFILE, new SubProgressMonitor(monitor, 1));
	try {
		IDocument document= manager.getTextFileBuffer(path, LocationKind.IFILE).getDocument();

		String lineDelim= TextUtilities.getDefaultLineDelimiter(document);
		MultiTextEdit edit= new MultiTextEdit();

		for (int i= 0; i < fMembers.length; i++) {
			IMember curr= fMembers[i];
			int memberStartOffset= getMemberStartOffset(curr, document);

			String comment= null;
			switch (curr.getElementType()) {
				case IJavaElement.TYPE:
					comment= createTypeComment((IType) curr, lineDelim);
					break;
				case IJavaElement.FIELD:
					comment= createFieldComment((IField) curr, lineDelim);
					break;
				case IJavaElement.METHOD:
					comment= createMethodComment((IMethod) curr, lineDelim);
					break;
			}
			if (comment == null) {
				StringBuffer buf= new StringBuffer();
				buf.append("/**").append(lineDelim); //$NON-NLS-1$
				buf.append(" *").append(lineDelim); //$NON-NLS-1$
				buf.append(" */").append(lineDelim); //$NON-NLS-1$
				comment= buf.toString();
			} else {
				if (!comment.endsWith(lineDelim)) {
					comment= comment + lineDelim;
				}
			}

			final IJavaProject project= cu.getJavaProject();
			IRegion region= document.getLineInformationOfOffset(memberStartOffset);

			String line= document.get(region.getOffset(), region.getLength());
			String indentString= Strings.getIndentString(line, project);

			String indentedComment= Strings.changeIndent(comment, 0, project, indentString, lineDelim);

			edit.addChild(new InsertEdit(memberStartOffset, indentedComment));

			monitor.worked(1);
		}
		edit.apply(document); // apply all edits
	} catch (BadLocationException e) {
		throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
	} finally {
		manager.disconnect(path, LocationKind.IFILE,new SubProgressMonitor(monitor, 1));
	}
}
 
Example 10
Source File: JavaFormatter.java    From goclipse with Eclipse Public License 1.0 4 votes vote down vote up
private List<TypedPosition> createRangeMarkers(TemplateVariable[] variables, IDocument document) throws MalformedTreeException, BadLocationException {
	Map<ReplaceEdit, String> markerToOriginal= new HashMap<ReplaceEdit, String>();

	MultiTextEdit root= new MultiTextEdit(0, document.getLength());
	List<TextEdit> edits= new ArrayList<TextEdit>();
	boolean hasModifications= false;
	for (int i= 0; i != variables.length; i++) {
		final TemplateVariable variable= variables[i];
		int[] offsets= variable.getOffsets();

		String value= variable.getDefaultValue();
		if (isWhitespaceVariable(value)) {
			// replace whitespace positions with unformattable comments
			String placeholder= COMMENT_START + value + COMMENT_END;
			for (int j= 0; j != offsets.length; j++) {
				ReplaceEdit replace= new ReplaceEdit(offsets[j], value.length(), placeholder);
				root.addChild(replace);
				hasModifications= true;
				markerToOriginal.put(replace, value);
				edits.add(replace);
			}
		} else {
			for (int j= 0; j != offsets.length; j++) {
				RangeMarker marker= new RangeMarker(offsets[j], value.length());
				root.addChild(marker);
				edits.add(marker);
			}
		}
	}

	if (hasModifications) {
		// update the document and convert the replaces to markers
		root.apply(document, TextEdit.UPDATE_REGIONS);
	}

	List<TypedPosition> positions= new ArrayList<TypedPosition>();
	for (Iterator<TextEdit> it= edits.iterator(); it.hasNext();) {
		TextEdit edit= it.next();
		try {
			// abuse TypedPosition to piggy back the original contents of the position
			final TypedPosition pos= new TypedPosition(edit.getOffset(), edit.getLength(), markerToOriginal.get(edit));
			document.addPosition(CATEGORY, pos);
			positions.add(pos);
		} catch (BadPositionCategoryException x) {
			Assert.isTrue(false);
		}
	}

	return positions;
}