org.eclipse.text.edits.ReplaceEdit Java Examples

The following examples show how to use org.eclipse.text.edits.ReplaceEdit. 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: GWTTypeRefactoringSupportTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
public void testCreateEditPreserveSlashPackageSeparator() {
  GWTTypeRefactoringSupport support = new GWTTypeRefactoringSupport();

  // Change the name of the R class to RRR
  IType oldType = rClass.getCompilationUnit().getType("R");
  support.setOldElement(oldType);
  IType newType = rClass.getCompilationUnit().getType("RRR");
  support.setNewElement(newType);

  String rawRef = "Lcom/hello/client/R;";
  IIndexedJavaRef ref = JsniJavaRefParamType.parse(null, 0, rawRef);

  ReplaceEdit edit = (ReplaceEdit) support.createEdit(ref);
  assertEquals(1, edit.getOffset());
  assertEquals(18, edit.getLength());
  assertEquals("com/hello/client/RRR", edit.getText());
}
 
Example #2
Source File: RenameNodeCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void addEdits(IDocument doc, TextEdit root) throws CoreException {
	super.addEdits(doc, root);

	// build a full AST
	CompilationUnit unit = CoreASTProvider.getInstance().getAST(getCompilationUnit(), CoreASTProvider.WAIT_YES, null);

	ASTNode name= NodeFinder.perform(unit, fOffset, fLength);
	if (name instanceof SimpleName) {

		SimpleName[] names= LinkedNodeFinder.findByProblems(unit, (SimpleName) name);
		if (names != null) {
			for (int i= 0; i < names.length; i++) {
				SimpleName curr= names[i];
				root.addChild(new ReplaceEdit(curr.getStartPosition(), curr.getLength(), fNewName));
			}
			return;
		}
	}
	root.addChild(new ReplaceEdit(fOffset, fLength, fNewName));
}
 
Example #3
Source File: CorrectPackageDeclarationProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void addEdits(IDocument doc, TextEdit root) throws CoreException {
	super.addEdits(doc, root);

	ICompilationUnit cu= getCompilationUnit();

	IPackageFragment parentPack= (IPackageFragment) cu.getParent();
	IPackageDeclaration[] decls= cu.getPackageDeclarations();

	if (parentPack.isDefaultPackage() && decls.length > 0) {
		for (int i= 0; i < decls.length; i++) {
			ISourceRange range= decls[i].getSourceRange();
			root.addChild(new DeleteEdit(range.getOffset(), range.getLength()));
		}
		return;
	}
	if (!parentPack.isDefaultPackage() && decls.length == 0) {
		String lineDelim = "\n";
		String str= "package " + parentPack.getElementName() + ';' + lineDelim + lineDelim; //$NON-NLS-1$
		root.addChild(new InsertEdit(0, str));
		return;
	}

	root.addChild(new ReplaceEdit(fLocation.getOffset(), fLocation.getLength(), parentPack.getElementName()));
}
 
Example #4
Source File: RenameTypeProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private void addReferenceUpdates(TextChangeManager manager, IProgressMonitor pm) {
	pm.beginTask("", fReferences.length); //$NON-NLS-1$
	for (int i = 0; i < fReferences.length; i++) {
		ICompilationUnit cu = fReferences[i].getCompilationUnit();
		if (cu == null) {
			continue;
		}

		String name = RefactoringCoreMessages.RenameTypeRefactoring_update_reference;
		SearchMatch[] results = fReferences[i].getSearchResults();

		for (int j = 0; j < results.length; j++) {
			SearchMatch match = results[j];
			ReplaceEdit replaceEdit = new ReplaceEdit(match.getOffset(), match.getLength(), getNewElementName());
			TextChangeCompatibility.addTextEdit(manager.get(cu), name, replaceEdit, CATEGORY_TYPE_RENAME);
		}
		pm.worked(1);
	}
}
 
Example #5
Source File: AbstractScriptFormatter.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Perform an indentation-only formatting, which does not involve any parsing.<br>
 * This method can be called when a parsing error prevents us from applying an accurate formatting. To avoid any
 * de-dented code appearing in the source, we just indent the source into the desired location.
 * 
 * @param completeSource
 *            full source module content
 * @param toFormat
 *            the source to format
 * @param offset
 *            the offset of the region to format
 * @param length
 *            the length of the region to format
 * @param indentationLevel
 *            the indent level
 * @return A {@link TextEdit} for the indented code.
 */
protected TextEdit indent(String completeSource, String toFormat, int offset, int length, int indentationLevel)
{
	// Only indent when the source to format is located at the beginning of a line, or when there are only
	// white-space characters to its left.
	if (!canIndent(completeSource, offset - 1))
	{
		return null;
	}
	// push the first line of the code
	IFormatterIndentGenerator indentGenerator = createIndentGenerator();
	StringBuilder builder = new StringBuilder();
	indentGenerator.generateIndent(indentationLevel, builder);
	int leftWhitespaceChars = countLeftWhitespaceChars(toFormat);
	// replace the left chars with the indent
	builder.append(toFormat.substring(leftWhitespaceChars));
	return new ReplaceEdit(offset, length, builder.toString());
}
 
Example #6
Source File: DotRenameStrategy.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void createDeclarationUpdates(String newName,
		ResourceSet resourceSet,
		IRefactoringUpdateAcceptor updateAcceptor) {
	super.createDeclarationUpdates(newName, resourceSet, updateAcceptor);

	// perform renaming of the dependent element
	if (targetElement instanceof NodeId) {
		URI resourceURI = getTargetElementOriginalURI().trimFragment();

		NodeId targetNodeId = (NodeId) targetElement;
		List<NodeId> dependentNodeIds = DotAstHelper
				.getAllNodeIds(targetNodeId);

		for (NodeId dependentNodeId : dependentNodeIds) {
			ITextRegion dependentNodeIdTextRegion = locationInFileProvider
					.getFullTextRegion(dependentNodeId);
			TextEdit referenceEdit = new ReplaceEdit(
					dependentNodeIdTextRegion.getOffset(),
					dependentNodeIdTextRegion.getLength(), newName);
			updateAcceptor.accept(resourceURI, referenceEdit);
		}
	}
}
 
Example #7
Source File: RenameTypeProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private void addConstructorRenames(TextChangeManager manager) throws CoreException {
	ICompilationUnit cu = fType.getCompilationUnit();
	IMethod[] methods = fType.getMethods();
	int typeNameLength = fType.getElementName().length();
	for (int i = 0; i < methods.length; i++) {
		if (methods[i].isConstructor()) {
			/*
			 * constructor declarations cannot be fully qualified so we can use simple replace here
			 *
			 * if (methods[i].getNameRange() == null), then it's a binary file so it's wrong anyway
			 * (checked as a precondition)
			 */
			String name = RefactoringCoreMessages.RenameTypeRefactoring_rename_constructor;
			TextChangeCompatibility.addTextEdit(manager.get(cu), name, new ReplaceEdit(methods[i].getNameRange().getOffset(), typeNameLength, getNewElementName()));
		}
	}
}
 
Example #8
Source File: DefaultTextEditComposer.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected List<TextEdit> getObjectEdits() {
	final Collection<EObject> modifiedObjects = getModifiedObjects();
	Collection<EObject> topLevelObjects = EcoreUtil.filterDescendants(modifiedObjects);
	Iterable<EObject> containedModifiedObjects = Collections.emptyList();
	if (!resource.getContents().isEmpty()) {
		final EObject root = resource.getContents().get(0);
		containedModifiedObjects = Iterables.filter(topLevelObjects, new Predicate<EObject>() {
			@Override
			public boolean apply(EObject input) {
				return EcoreUtil.isAncestor(root, input);
			}
		});
	}
	List<TextEdit> edits = Lists.newArrayListWithExpectedSize(Iterables.size(containedModifiedObjects));
	for (EObject modifiedObject : containedModifiedObjects) {
		ReplaceRegion replaceRegion = serializer.serializeReplacement(modifiedObject, getSaveOptions());
		TextEdit edit = new ReplaceEdit(replaceRegion.getOffset(), replaceRegion.getLength(), replaceRegion.getText());
		edits.add(edit);
	}
	return edits;
}
 
Example #9
Source File: JsniReferenceChangeTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
public void testPerform() throws CoreException {
  // Create a dummy change for updating references in RefactorTest.java
  // to the class R to its new name 'RRR'
  ICompilationUnit cu = refactorTestClass.getCompilationUnit();
  GWTRefactoringSupport support = new DummyRefactoringSupport();
  JsniReferenceChangeFactory factory = new JsniReferenceChangeFactory(support);
  IJsniReferenceChange jsniChange = factory.createChange(cu);

  // Add one dummy edit to the change
  TextEdit oldRootEdit = new MultiTextEdit();
  oldRootEdit.addChild(new ReplaceEdit(252, 0, ""));
  ((TextFileChange)jsniChange).setEdit(oldRootEdit);

  // Perform the change (this should replace the original edits with new ones
  // with the correct offsets).
  ((TextFileChange)jsniChange).perform(new NullProgressMonitor());

  // Verify that the change still has one edit
  TextEdit newRootEdit = ((TextFileChange)jsniChange).getEdit();
  assertEquals(1, newRootEdit.getChildrenSize());
}
 
Example #10
Source File: GWTTypeRefactoringSupportTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
public void testCreateEdit() {
  GWTTypeRefactoringSupport support = new GWTTypeRefactoringSupport();

  // Change the name of the R class to RRR
  IType oldType = rClass.getCompilationUnit().getType("R");
  support.setOldElement(oldType);
  IType newType = rClass.getCompilationUnit().getType("RRR");
  support.setNewElement(newType);

  String rawRef = "@com.hello.client.R.B::getNumber()";
  IIndexedJavaRef ref = new IndexedJsniJavaRef(JsniJavaRef.parse(rawRef));

  ReplaceEdit edit = (ReplaceEdit) support.createEdit(ref);
  assertEquals(1, edit.getOffset());
  assertEquals(18, edit.getLength());
  assertEquals("com.hello.client.RRR", edit.getText());
}
 
Example #11
Source File: GWTTypeRefactoringSupportTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
public void testCreateEditForInnerClass() {
  GWTTypeRefactoringSupport support = new GWTTypeRefactoringSupport();

  // Change the name of the inner class B to BBB
  IType r = rClass.getCompilationUnit().getType("R");
  IType oldType = r.getType("B");
  support.setOldElement(oldType);
  IType newType = r.getType("BBB");
  support.setNewElement(newType);

  String rawRef = "@com.hello.client.R.B::getNumber()";
  IIndexedJavaRef ref = new IndexedJsniJavaRef(JsniJavaRef.parse(rawRef));

  ReplaceEdit edit = (ReplaceEdit) support.createEdit(ref);
  assertEquals(1, edit.getOffset());
  assertEquals(20, edit.getLength());
  assertEquals("com.hello.client.R.BBB", edit.getText());
}
 
Example #12
Source File: BslQuickFix.java    From ru.capralow.dt.bslls.validator with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Fix("bsl-language-server")
public void processBslLanguageServerDiagnostic(final Issue issue, final IssueResolutionAcceptor acceptor)
{
    String[] issueData = issue.getData();
    for (String issueLine : issueData)
    {
        if (issueLine.isEmpty())
            continue;

        String[] issueList = issueLine.split("[|]"); //$NON-NLS-1$

        String issueCommand = issueList[0];
        String issueMessage = issueList[1];
        Integer issueOffset = Integer.decode(issueList[2]);
        Integer issueLength = Integer.decode(issueList[3]);
        String issueNewText = issueList.length == 5 ? issueList[4] : ""; //$NON-NLS-1$

        acceptor.accept(issue, issueCommand, issueMessage, (String)null,
            new AbstractExternalQuickfixProvider.ExternalQuickfixModification<>(issue, EObject.class,
                module -> new ReplaceEdit(issueOffset, issueLength, issueNewText)));
    }
}
 
Example #13
Source File: DefaultRenameElementStrategyTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testRenameElementStrategy() throws Exception {
	final XtextResource resource = getResourceFromString("A { B { C } }");
	EObject targetElement = resource.getContents().get(0).eContents().get(0);
	assertNotNull(targetElement);
	assertTrue(targetElement instanceof Element);
	assertEquals("A", ((Element) targetElement).getName());
	IRenameStrategy renameElementStrategy = strategyProvider.get(targetElement, null);
	assertNotNull(renameElementStrategy);
	assertEquals("A", renameElementStrategy.getOriginalName());
	RefactoringStatus validateNewNameStatus = renameElementStrategy.validateNewName("A");
	assertTrue(validateNewNameStatus.isOK());
	validateNewNameStatus = renameElementStrategy.validateNewName("}");
	assertTrue(validateNewNameStatus.hasFatalError());
	validateNewNameStatus = renameElementStrategy.validateNewName("ref");
	assertTrue(validateNewNameStatus.hasError());
	renameElementStrategy.applyDeclarationChange("D", resource.getResourceSet());
	assertEquals("D", ((Element) targetElement).getName());
	renameElementStrategy.createDeclarationUpdates("D", resource.getResourceSet(), this);
	assertEquals(0, changes.size());
	assertEquals(1, textEdits.size());
	assertTrue(textEdits.get(0) instanceof ReplaceEdit);
	ReplaceEdit renameEdit = (ReplaceEdit) textEdits.get(0);
	assertEquals(0, renameEdit.getOffset());
	assertEquals(1, renameEdit.getLength());
	assertEquals("D", renameEdit.getText());
}
 
Example #14
Source File: RenameTypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void addReferenceUpdates(TextChangeManager manager, IProgressMonitor pm) {
	pm.beginTask("", fReferences.length); //$NON-NLS-1$
	for (int i= 0; i < fReferences.length; i++){
		ICompilationUnit cu= fReferences[i].getCompilationUnit();
		if (cu == null)
			continue;

		String name= RefactoringCoreMessages.RenameTypeRefactoring_update_reference;
		SearchMatch[] results= fReferences[i].getSearchResults();

		for (int j= 0; j < results.length; j++){
			SearchMatch match= results[j];
			ReplaceEdit replaceEdit= new ReplaceEdit(match.getOffset(), match.getLength(), getNewElementName());
			TextChangeCompatibility.addTextEdit(manager.get(cu), name, replaceEdit, CATEGORY_TYPE_RENAME);
		}
		pm.worked(1);
	}
}
 
Example #15
Source File: NLSSourceModifier.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void addAccessor(NLSSubstitution sub, TextChange change, String accessorName) {
	if (sub.getState() == NLSSubstitution.EXTERNALIZED) {
		NLSElement element= sub.getNLSElement();
		Region position= element.getPosition();
		String[] args= {sub.getValueNonEmpty(), BasicElementLabels.getJavaElementName(sub.getKey())};
		String text= Messages.format(NLSMessages.NLSSourceModifier_externalize, args);

		String resourceGetter= createResourceGetter(sub.getKey(), accessorName);

		TextEdit edit= new ReplaceEdit(position.getOffset(), position.getLength(), resourceGetter);
		if (fIsEclipseNLS && element.getTagPosition() != null) {
			MultiTextEdit multiEdit= new MultiTextEdit();
			multiEdit.addChild(edit);
			Region tagPosition= element.getTagPosition();
			multiEdit.addChild(new DeleteEdit(tagPosition.getOffset(), tagPosition.getLength()));
			edit= multiEdit;
		}
		TextChangeCompatibility.addTextEdit(change, text, edit);
	}
}
 
Example #16
Source File: RenameNonVirtualMethodProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private void addReferenceUpdates(TextChangeManager manager, IProgressMonitor pm) {
	SearchResultGroup[] grouped= getOccurrences();
	for (int i= 0; i < grouped.length; i++) {
		SearchResultGroup group= grouped[i];
		SearchMatch[] results= group.getSearchResults();
		ICompilationUnit cu= group.getCompilationUnit();
		TextChange change= manager.get(cu);
		for (int j= 0; j < results.length; j++){
			SearchMatch match= results[j];
			if (!(match instanceof MethodDeclarationMatch)) {
				ReplaceEdit replaceEdit= createReplaceEdit(match, cu);
				String editName= RefactoringCoreMessages.RenamePrivateMethodRefactoring_update;
				addTextEdit(change, editName, replaceEdit);
			}
		}
	}
	pm.done();
}
 
Example #17
Source File: ProcessVariableRenamer.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void visitVariableExpression(final VariableExpression expression) {
    final Variable accessedVar = expression.getAccessedVariable();
    // look for dynamic variables since the parameters already have the
    // new names, the actual references to the parameters are using the
    // old names
    if (accessedVar instanceof DynamicVariable) {
        final String newName = findReplacement(accessedVar.getName());
        if (newName != null) {
            ReplaceEdit replaceEdit = new ReplaceEdit(expression.getStart(), expression.getLength(), newName);
            try {
                edits.addChild(replaceEdit);
            }catch (MalformedTreeException e) {
                BonitaStudioLog.error(e);
            }
        }
    }
}
 
Example #18
Source File: RenameNonVirtualMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void addReferenceUpdates(TextChangeManager manager, IProgressMonitor pm) {
	SearchResultGroup[] grouped= getOccurrences();
	for (int i= 0; i < grouped.length; i++) {
		SearchResultGroup group= grouped[i];
		SearchMatch[] results= group.getSearchResults();
		ICompilationUnit cu= group.getCompilationUnit();
		TextChange change= manager.get(cu);
		for (int j= 0; j < results.length; j++){
			SearchMatch match= results[j];
			if (!(match instanceof MethodDeclarationMatch)) {
				ReplaceEdit replaceEdit= createReplaceEdit(match, cu);
				String editName= RefactoringCoreMessages.RenamePrivateMethodRefactoring_update;
				addTextEdit(change, editName, replaceEdit);
			}
		}
	}
	pm.done();
}
 
Example #19
Source File: N4JSRenameStrategy.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Custom logics for creating text edits for definitions of composed members
 */
@Override
public void createDeclarationUpdates(String newName, ResourceSet resourceSet,
		IRefactoringUpdateAcceptor updateAcceptor) {

	EObject targetElement = resourceSet.getEObject(getTargetElementOriginalURI(), true);
	if (TypeModelUtils.isComposedTElement(targetElement)) {
		// If target element is a composed element, create updates for its constituent members
		List<TMember> constituentMembers = ((TMember) targetElement).getConstituentMembers();
		for (TMember constituentMember : constituentMembers) {
			String text = newName;
			EAttribute att = getNameAttribute(constituentMember);
			ITextRegion nameRegion = getOriginalNameRegion(constituentMember, att);
			ReplaceEdit replaceEdit = new ReplaceEdit(nameRegion.getOffset(), nameRegion.getLength(), text);
			updateAcceptor.accept(EcoreUtil.getURI(constituentMember).trimFragment(),
					replaceEdit);
		}
	} else {
		updateAcceptor.accept(getTargetElementOriginalURI().trimFragment(), getDeclarationTextEdit(newName));
	}
}
 
Example #20
Source File: ImportRewriter.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings({ "unused", "deprecation" })
private AliasLocation enhanceExistingImportDeclaration(ImportDeclaration importDeclaration,
		QualifiedName qualifiedName,
		String optionalAlias, MultiTextEdit result) {

	addImportSpecifier(importDeclaration, qualifiedName, optionalAlias);
	ICompositeNode replaceMe = NodeModelUtils.getNode(importDeclaration);
	int offset = replaceMe.getOffset();
	AliasLocationAwareBuffer observableBuffer = new AliasLocationAwareBuffer(
			optionalAlias,
			offset,
			grammarAccess);

	try {
		serializer.serialize(
				importDeclaration,
				observableBuffer,
				SaveOptions.newBuilder().noValidation().getOptions());
	} catch (IOException e) {
		throw new RuntimeException("Should never happen since we write into memory", e);
	}
	result.addChild(new ReplaceEdit(offset, replaceMe.getLength(), observableBuffer.toString()));
	return observableBuffer.getAliasLocation();
}
 
Example #21
Source File: RenameNodeCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void addEdits(IDocument doc, TextEdit root) throws CoreException {
	super.addEdits(doc, root);

	// build a full AST
	CompilationUnit unit= SharedASTProvider.getAST(getCompilationUnit(), SharedASTProvider.WAIT_YES, null);

	ASTNode name= NodeFinder.perform(unit, fOffset, fLength);
	if (name instanceof SimpleName) {

		SimpleName[] names= LinkedNodeFinder.findByProblems(unit, (SimpleName) name);
		if (names != null) {
			for (int i= 0; i < names.length; i++) {
				SimpleName curr= names[i];
				root.addChild(new ReplaceEdit(curr.getStartPosition(), curr.getLength(), fNewName));
			}
			return;
		}
	}
	root.addChild(new ReplaceEdit(fOffset, fLength, fNewName));
}
 
Example #22
Source File: FixedContentFormatter.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * This method makes sure that no changes are applied (no dirty state), if there are no changes. This fixes bug
 * GHOLD-272
 */
@Override
public void format(IDocument document, IRegion region) {
	IXtextDocument doc = (IXtextDocument) document;
	TextEdit e = doc.priorityReadOnly(new FormattingUnitOfWork(doc, region));

	if (e == null)
		return;
	if (e instanceof ReplaceEdit) {
		ReplaceEdit r = (ReplaceEdit) e;
		if ((r.getOffset() == 0) && (r.getLength() == 0) && (r.getText().isEmpty())) {
			return;
		}
	}
	try {
		e.apply(document);
	} catch (BadLocationException ex) {
		throw new RuntimeException(ex);
	}

}
 
Example #23
Source File: PyRenameImportProcess.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public List<TextEdit> createRenameEdit(IDocument doc, String initialName, String inputName,
        RefactoringStatus status, IPath file, IPythonNature nature) {
    initialName = fixedInitialString;
    if (!initialName.contains(".") && !this.forceFull) {
        inputName = FullRepIterable.getLastPart(inputName);
    }

    int offset = AbstractRenameRefactorProcess.getOffset(doc, this);
    TextEditCreation.checkExpectedInput(doc, node.beginLine, offset, initialName, status, file);
    TextEdit replaceEdit = new ReplaceEdit(offset, initialName.length(), inputName);
    List<TextEdit> edits = Arrays.asList(replaceEdit);
    return edits;
}
 
Example #24
Source File: PropertyFileDocumentModel.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public ReplaceEdit replace(KeyValuePair toReplace, KeyValuePair replaceWith) {
    for (Iterator<KeyValuePairModell> iter = fKeyValuePairs.iterator(); iter.hasNext();) {
        KeyValuePairModell keyValuePair = iter.next();
        if (keyValuePair.fKey.equals(toReplace.getKey())) {
            String newText= new KeyValuePairModell(replaceWith).getKeyValueText();
            return new ReplaceEdit(keyValuePair.fOffset, keyValuePair.getLength(), newText);
        }
    }
    return null;
}
 
Example #25
Source File: RenameMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected void addTextEdit(TextChange change, String editName, ReplaceEdit replaceEdit) {
	if (fIsComposite)
		TextChangeCompatibility.addTextEdit(change, editName, replaceEdit, fCategorySet);
	else
		TextChangeCompatibility.addTextEdit(change, editName, replaceEdit);

}
 
Example #26
Source File: TextMatchUpdater.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void addTextUpdates(ICompilationUnit cu, Set<TextMatch> matches) {
	for (Iterator<TextMatch> resultIter= matches.iterator(); resultIter.hasNext();){
		TextMatch match= resultIter.next();
		if (!match.isQualified() && fOnlyQualified)
			continue;
		int matchStart= match.getStartPosition();
		ReplaceEdit edit= new ReplaceEdit(matchStart, fCurrentNameLength, fNewName);
		try {
			TextChangeCompatibility.addTextEdit(fManager.get(cu), TEXT_EDIT_LABEL, edit, TEXTUAL_MATCHES);
		} catch (MalformedTreeException e) {
			// conflicting update -> omit text match
		}
	}
}
 
Example #27
Source File: MoveCuUpdateCreator.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void addReferenceUpdates(TextChangeManager changeManager, ICompilationUnit movedUnit, IProgressMonitor pm, RefactoringStatus status) throws JavaModelException, CoreException {
	List<ICompilationUnit> cuList = Arrays.asList(fCus);
	SearchResultGroup[] references = getReferences(movedUnit, pm, status);
	for (int i = 0; i < references.length; i++) {
		SearchResultGroup searchResultGroup = references[i];
		ICompilationUnit referencingCu = searchResultGroup.getCompilationUnit();
		if (referencingCu == null) {
			continue;
		}

		boolean simpleReferencesNeedNewImport = simpleReferencesNeedNewImport(movedUnit, referencingCu, cuList);
		SearchMatch[] results = searchResultGroup.getSearchResults();
		for (int j = 0; j < results.length; j++) {
			// TODO: should update type references with results from addImport
			TypeReference reference = (TypeReference) results[j];
			if (reference.isImportDeclaration()) {
				ImportRewrite rewrite = getImportRewrite(referencingCu);
				IImportDeclaration importDecl = (IImportDeclaration) SearchUtils.getEnclosingJavaElement(results[j]);
				if (Flags.isStatic(importDecl.getFlags())) {
					rewrite.removeStaticImport(importDecl.getElementName());
					addStaticImport(movedUnit, importDecl, rewrite);
				} else {
					rewrite.removeImport(importDecl.getElementName());
					rewrite.addImport(createStringForNewImport(movedUnit, importDecl));
				}
			} else if (reference.isQualified()) {
				TextChange textChange = changeManager.get(referencingCu);
				String changeName = RefactoringCoreMessages.MoveCuUpdateCreator_update_references;
				TextEdit replaceEdit = new ReplaceEdit(reference.getOffset(), reference.getSimpleNameStart() - reference.getOffset(), fNewPackage);
				TextChangeCompatibility.addTextEdit(textChange, changeName, replaceEdit);
			} else if (simpleReferencesNeedNewImport) {
				ImportRewrite importEdit = getImportRewrite(referencingCu);
				String typeName = reference.getSimpleName();
				importEdit.addImport(getQualifiedType(fDestination.getElementName(), typeName));
			}
		}
	}
}
 
Example #28
Source File: QualifiedNameFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean acceptPatternMatch(TextSearchMatchAccess matchAccess) throws CoreException {
	int start= matchAccess.getMatchOffset();
	int length= matchAccess.getMatchLength();

	// skip embedded FQNs (bug 130764):
	if (start > 0) {
		char before= matchAccess.getFileContentChar(start - 1);
		if (before == '.' || Character.isJavaIdentifierPart(before))
			return true;
	}
	int fileContentLength= matchAccess.getFileContentLength();
	int end= start + length;
	if (end < fileContentLength) {
		char after= matchAccess.getFileContentChar(end);
		if (Character.isJavaIdentifierPart(after))
			return true;
	}

	IFile file= matchAccess.getFile();
	TextChange change= fResult.getChange(file);
	TextChangeCompatibility.addTextEdit(
		change,
		RefactoringCoreMessages.QualifiedNameFinder_update_name,
		new ReplaceEdit(start, length, fNewValue), QUALIFIED_NAMES);

	return true;
}
 
Example #29
Source File: RenameMethodProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
protected void addTextEdit(TextChange change, String editName, ReplaceEdit replaceEdit) {
	if (fIsComposite) {
		TextChangeCompatibility.addTextEdit(change, editName, replaceEdit, fCategorySet);
	} else {
		TextChangeCompatibility.addTextEdit(change, editName, replaceEdit);
	}

}
 
Example #30
Source File: RenameMethodProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
protected final ReplaceEdit createReplaceEdit(SearchMatch searchResult, ICompilationUnit cu) {
	if (searchResult.isImplicit()) { // handle Annotation Element references, see bug 94062
		StringBuffer sb= new StringBuffer(getNewElementName());
		if (JavaCore.INSERT.equals(cu.getJavaProject().getOption(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR, true))) {
			sb.append(' ');
		}
		sb.append('=');
		if (JavaCore.INSERT.equals(cu.getJavaProject().getOption(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_ASSIGNMENT_OPERATOR, true))) {
			sb.append(' ');
		}
		return new ReplaceEdit(searchResult.getOffset(), 0, sb.toString());
	} else {
		return new ReplaceEdit(searchResult.getOffset(), searchResult.getLength(), getNewElementName());
	}
}