Java Code Examples for org.eclipse.text.edits.ReplaceEdit

The following examples show how to use org.eclipse.text.edits.ReplaceEdit. These examples are extracted from open source projects. 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
@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 2
Source Project: n4js   Source File: FixedContentFormatter.java    License: 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 3
@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 4
Source Project: n4js   Source File: ImportRewriter.java    License: 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 5
Source Project: n4js   Source File: N4JSRenameStrategy.java    License: 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 6
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 7
@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 8
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
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 10
@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 11
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 12
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 13
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 14
@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 15
@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 16
/**
 * 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 17
Source Project: gef   Source File: DotRenameStrategy.java    License: 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 18
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 19
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 20
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 21
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 22
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 23
@Test public void testDirtyEditorRename() throws Exception {
	XtextEditor editor0 = openEditor(testFile0);
	XtextEditor editor1 = openEditor(testFile1);
	new ReplaceEdit(0, 0, " ").apply(editor0.getDocument());
	new ReplaceEdit(0, 0, " ").apply(editor1.getDocument());
	waitForReconciler(editor0);
	waitForReconciler(editor1);
	doRename();
	assertEquals(" " + initialModel0.replaceAll("B", "C"), editor0.getDocument().get());
	assertEquals(" " + initialModel1.replaceAll("B", "C"), editor1.getDocument().get());
	undoRename();
	assertEquals(" " + initialModel0, editor0.getDocument().get());
	assertEquals(" " + initialModel1, editor1.getDocument().get());
}
 
Example 24
@Override
public void setUp() throws Exception {
	super.setUp();
	IJavaProject project = JavaProjectSetupUtil.createJavaProject(TEST_PROJECT);
	addNature(project.getProject(), XtextProjectHelper.NATURE_ID);
	project.getProject().setDefaultCharset(StandardCharsets.ISO_8859_1.name(), new NullProgressMonitor());
	Injector injector = TestsActivator.getInstance().getInjector(getEditorId());
	injector.injectMembers(this);
	testFile = IResourcesSetupUtil.createFile(TEST_FILE_PATH, TEST_FILE_CONTENT);
	textEdit = new ReplaceEdit(0, 1, "C");
}
 
Example 25
protected Change createTextFileChange(IFile file, int offset, int length, String replacement) {
	ReplaceEdit edit = new ReplaceEdit(offset, length, replacement);
	TextFileChange textFileChange = new TextFileChange("text change", file);
	textFileChange.setEdit(edit);
	textFileChange.setTextType(TEXT_TYPE);
	return textFileChange;
}
 
Example 26
/**
 * Returns the text edits retrieved after changing the indentation of a, possible multi-line, code string.
 *
 * <p>The given number of indent units is removed, and a new indent string is added.</p>
 * <p>The first line of the code will not be changed (It is considered to have no indent as it might start in
 * the middle of a line).</p>
 *
 * @param source The code to change the indent of
 * @param indentUnitsToRemove the number of indent units to remove from each line (except the first) of the given code
 * @param tabWidth the size of one tab in space equivalents
 * @param indentWidth the width of one indentation unit in space equivalents
 * @param newIndentString the new indent string to be added to all lines (except the first)
 * @return returns the resulting text edits
 * @exception IllegalArgumentException if:
 * <ul>
 * <li>the given <code>indentWidth</code> is lower than zero</li>
 * <li>the given <code>tabWidth</code> is lower than zero</li>
 * <li>the given <code>source</code> is null</li>
 * <li>the given <code>indentUnitsToRemove</code> is lower than zero</li>
 * <li>the given <code>newIndentString</code> is null</li>
 * </ul>
 */
public static ReplaceEdit[] getChangeIndentEdits(String source, int indentUnitsToRemove, int tabWidth, int indentWidth, String newIndentString) {
	if (tabWidth < 0 || indentWidth < 0 || source == null || indentUnitsToRemove < 0 || newIndentString == null) {
		throw new IllegalArgumentException();
	}

	ArrayList result= new ArrayList();
	try {
		ILineTracker tracker= new DefaultLineTracker();
		tracker.set(source);
		int nLines= tracker.getNumberOfLines();
		if (nLines == 1)
			return (ReplaceEdit[])result.toArray(new ReplaceEdit[result.size()]);
		for (int i= 1; i < nLines; i++) {
			IRegion region= tracker.getLineInformation(i);
			int offset= region.getOffset();
			String line= source.substring(offset, offset + region.getLength());
			int length= indexOfIndent(line, indentUnitsToRemove, tabWidth, indentWidth);
			if (length >= 0) {
				result.add(new ReplaceEdit(offset, length, newIndentString));
			} else {
				length= measureIndentUnits(line, tabWidth, indentWidth);
				result.add(new ReplaceEdit(offset, length, "")); //$NON-NLS-1$
			}
		}
	} catch (BadLocationException cannotHappen) {
		// can not happen
	}
	return (ReplaceEdit[])result.toArray(new ReplaceEdit[result.size()]);
}
 
Example 27
protected LinkedPositionGroup createLinkedGroupFromReplaceEdits(List<ReplaceEdit> edits, XtextEditor xtextEditor, String originalName,
		SubMonitor progress) {
	if (edits == null) {
		return null;
	}

	IXtextDocument document = xtextEditor.getDocument();
	LinkedPositionGroup group = new LinkedPositionGroup();
	List<LinkedPosition> linkedPositions = new ArrayList<>();
	edits.forEach(replaceEdit -> {
		try {
			String textToReplace = document.get(replaceEdit.getOffset(), replaceEdit.getLength());
			int indexOf = textToReplace.indexOf(originalName);
			if (indexOf != -1) {
				int calculatedOffset = replaceEdit.getOffset() + indexOf;
				linkedPositions.add(new LinkedPosition(document, calculatedOffset, originalName.length()));
			}
		} catch (BadLocationException exc) {
			LOG.error("Skipping invalid text edit " + replaceEdit, exc);
		}
	});

	progress.worked(10);

	int invocationOffset = xtextEditor.getInternalSourceViewer().getSelectedRange().x;
	int i = 0;
	for (LinkedPosition position : sortPositions(linkedPositions, invocationOffset)) {
		try {
			position.setSequenceNumber(i);
			i++;
			group.addPosition(position);
		} catch (BadLocationException e) {
			LOG.error(e.getMessage(), e);
			return null;
		}
	}
	return group;
}
 
Example 28
protected void collectChanges(IEmfResourceChange e, List<TextEdit> edits) {
	if (e instanceof ITextDocumentChange && e.getResource() == recording) {
		ITextDocumentChange change = (ITextDocumentChange) e;
		for (ITextReplacement c : change.getReplacements()) {
			ReplaceEdit edit = new ReplaceEdit(c.getOffset(), c.getLength(), c.getReplacementText());
			edits.add(edit);
		}
	}
}
 
Example 29
@Override
protected void addEdits(IDocument document, TextEdit rootEdit) throws CoreException {
	super.addEdits(document, rootEdit);

	try {
		Position pos= getUpdatedPosition(document);
		if (pos != null) {
			rootEdit.addChild(new ReplaceEdit(pos.getOffset(), pos.getLength(), "")); //$NON-NLS-1$
		} else {
			rootEdit.addChild(new ReplaceEdit(fLocation.getOffset(), fLocation.getLength(), "")); //$NON-NLS-1$
		}
	} catch (BadLocationException e) {
		throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
	}
}
 
Example 30
protected LinkedPositionGroup createLinkedGroupFromReplaceEdits(List<ReplaceEdit> edits, XtextEditor xtextEditor,
		final String originalName, SubMonitor progress) {
	if (edits == null)
		return null;
	final IXtextDocument document = xtextEditor.getDocument();
	LinkedPositionGroup group = new LinkedPositionGroup();
	Iterable<LinkedPosition> linkedPositions = filter(
			Iterables.transform(edits, new Function<ReplaceEdit, LinkedPosition>() {
				@Override
				public LinkedPosition apply(ReplaceEdit edit) {
					try {
						String textToReplace = document.get(edit.getOffset(), edit.getLength());
						int indexOf = textToReplace.indexOf(originalName);
						if (indexOf != -1) {
							int calculatedOffset = edit.getOffset() + indexOf;
							return new LinkedPosition(document, calculatedOffset, originalName.length());
						}
					} catch (BadLocationException exc) {
						LOG.error("Skipping invalid text edit " + notNull(edit), exc);
					}
					return null;
				}
			}), Predicates.notNull());
	progress.worked(10);
	final int invocationOffset = xtextEditor.getInternalSourceViewer().getSelectedRange().x;
	int i = 0;
	for (LinkedPosition position : sortPositions(linkedPositions, invocationOffset)) {
		try {
			position.setSequenceNumber(i);
			i++;
			group.addPosition(position);
		} catch (BadLocationException e) {
			LOG.error(e.getMessage(), e);
			return null;
		}
	}
	return group;
}