org.eclipse.text.edits.MultiTextEdit Java Examples

The following examples show how to use org.eclipse.text.edits.MultiTextEdit. 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: DocumentUtils.java    From typescript.java with MIT License 6 votes vote down vote up
private static void toTextEdit(CodeEdit codeEdit, IDocument document, MultiTextEdit textEdit)
		throws TypeScriptException {
	String newText = codeEdit.getNewText();
	int startLine = codeEdit.getStart().getLine();
	int startOffset = codeEdit.getStart().getOffset();
	int endLine = codeEdit.getEnd().getLine();
	int endOffset = codeEdit.getEnd().getOffset();
	int start = DocumentUtils.getPosition(document, startLine, startOffset);
	int end = DocumentUtils.getPosition(document, endLine, endOffset);
	int length = end - start;
	if (newText.isEmpty()) {
		if (length > 0) {
			textEdit.addChild(new DeleteEdit(start, length));
		}
	} else {
		if (length > 0) {
			textEdit.addChild(new ReplaceEdit(start, length, newText));
		} else if (length == 0) {
			textEdit.addChild(new InsertEdit(start, newText));
		}
	}
}
 
Example #2
Source File: TextEditConverter.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private String applySourceModifier(String content, ISourceModifier modifier) {
	if (StringUtils.isBlank(content) || modifier == null) {
		return content;
	}

	SimpleDocument subDocument = new SimpleDocument(content);
	TextEdit newEdit = new MultiTextEdit(0, subDocument.getLength());
	ReplaceEdit[] replaces = modifier.getModifications(content);
	for (ReplaceEdit replace : replaces) {
		newEdit.addChild(replace);
	}
	try {
		newEdit.apply(subDocument, TextEdit.NONE);
	} catch (BadLocationException e) {
		JavaLanguageServerPlugin.logException("Error applying edit to document", e);
	}
	return subDocument.get();
}
 
Example #3
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 #4
Source File: AccessorClassModifier.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static Change removeFields(ICompilationUnit cu, List<String> fields) throws CoreException {
	AccessorClassModifier sourceModification= new AccessorClassModifier(cu);
	String message= Messages.format(NLSMessages.AccessorClassModifier_remove_fields_from_accessor, BasicElementLabels.getFileName(cu));

	TextChange change= new CompilationUnitChange(message, cu);
	MultiTextEdit multiTextEdit= new MultiTextEdit();
	change.setEdit(multiTextEdit);

	for (int i= 0; i < fields.size(); i++) {
		String field= fields.get(i);
		NLSSubstitution substitution= new NLSSubstitution(NLSSubstitution.EXTERNALIZED, field, null, null, null);
		sourceModification.removeKey(substitution, change);
	}

	if (change.getChangeGroups().length == 0)
		return null;

	change.addEdit(sourceModification.getTextEdit());

	return change;
}
 
Example #5
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 #6
Source File: TextChangeCombiner.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public Change combineChanges(Change masterChange) {
	if (!(masterChange instanceof CompositeChange))
		return masterChange;
	Map<Object, TextChange> resource2textChange = newLinkedHashMap();
	List<Change> otherChanges = newArrayList();
	Set<IEditorPart> editorsToSave = newHashSet();
	visitCompositeChange((CompositeChange) masterChange, resource2textChange, otherChanges, editorsToSave);
	CompositeChange compositeChange = new FilteringCompositeChange(masterChange.getName());
	for (TextChange combinedTextChange : resource2textChange.values()) {
		if(((MultiTextEdit) combinedTextChange.getEdit()).getChildrenSize() >0) {
			if(combinedTextChange instanceof EditorDocumentChange) {
				((EditorDocumentChange) combinedTextChange).setDoSave(editorsToSave.contains(((EditorDocumentChange) combinedTextChange).getEditor()));
				compositeChange.add(combinedTextChange);
			}
			else
				compositeChange.add(DisplayChangeWrapper.wrap(combinedTextChange));
		}
	}
	for(Change otherChange: otherChanges) 
		compositeChange.add(DisplayChangeWrapper.wrap(otherChange));
	if(compositeChange.getChildren().length == 0)
		return null;
	return compositeChange;
}
 
Example #7
Source File: AccessorClassModifier.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static Change addFields(ICompilationUnit cu, List<String> fields) throws CoreException {
	AccessorClassModifier sourceModification= new AccessorClassModifier(cu);
	String message= Messages.format(NLSMessages.AccessorClassModifier_add_fields_to_accessor, BasicElementLabels.getFileName(cu));

	TextChange change= new CompilationUnitChange(message, cu);
	MultiTextEdit multiTextEdit= new MultiTextEdit();
	change.setEdit(multiTextEdit);

	for (int i= 0; i < fields.size(); i++) {
		String field= fields.get(i);
		NLSSubstitution substitution= new NLSSubstitution(NLSSubstitution.EXTERNALIZED, field, null, null, null);
		sourceModification.addKey(substitution, change);
	}

	if (change.getChangeGroups().length == 0)
		return null;

	change.addEdit(sourceModification.getTextEdit());

	return change;
}
 
Example #8
Source File: ContentFormatter.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected TextEdit exec(IXtextDocument document, IRegion region, XtextResource resource) throws Exception {
	try {
		IParseResult parseResult = resource.getParseResult();
		if (parseResult != null && parseResult.getRootASTElement() != null) {
			FormatterRequest request = requestProvider.get();
			initRequest(document, region, resource, request);
			IFormatter2 formatter = formatterProvider.get();
			List<ITextReplacement> replacements = formatter.format(request);
			final TextEdit mte = createTextEdit(replacements);
			return mte;
		}
	} catch (Exception e) {
		LOG.error("Error formatting " + resource.getURI() + ": " + e.getMessage(), e);
	}
	return new MultiTextEdit();
}
 
Example #9
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 #10
Source File: ChangeSerializerTextEditComposer.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected TextEdit endRecordingAndCompose() {
	List<TextEdit> edits = Lists.newArrayList();
	super.endRecordChanges(change -> {
		collectChanges(change, edits);
	});
	if (edits.isEmpty()) {
		return null;
	}
	if (edits.size() == 1) {
		return edits.get(0);
	}
	MultiTextEdit multi = new MultiTextEdit();
	for (TextEdit e : edits) {
		multi.addChild(e);
	}
	return multi;
}
 
Example #11
Source File: TextEditUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns true if the given <code>edit</code> is minimal.
 * <p>
 * That is if:
 * <ul>
 * <li><b>true</b> if <code>edit</code> is a leaf</li>
 * <li>if <code>edit</code> is a inner node then <b>true</b> if
 *   <ul>
 *   <li><code>edit</code> has same size as all its children</li>
 *   <li><code>isPacked</code> is <b>true</b> for all children</li>
 *   </ul>
 * </li>
 * </ul>
 * </p>
 *
 * @param edit the edit to verify
 * @return true if edit is minimal
 * @since 3.4
 */
public static boolean isPacked(TextEdit edit) {
	if (!(edit instanceof MultiTextEdit))
		return true;

	if (!edit.hasChildren())
		return true;

	TextEdit[] children= edit.getChildren();
	if (edit.getOffset() != children[0].getOffset())
		return false;

	if (edit.getExclusiveEnd() != children[children.length - 1].getExclusiveEnd())
		return false;

	for (int i= 0; i < children.length; i++) {
		if (!isPacked(children[i]))
			return false;
	}

	return true;
}
 
Example #12
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 #13
Source File: TextEditCreation.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Create the change for the current module
 *
 * @param status the status for the change.
 * @param fChange tho 'root' change.
 * @param editsAlreadyCreated
 */
private void createCurrModuleChange(RefactoringRequest request) {
    if (docOccurrences.size() == 0 && !(request.isModuleRenameRefactoringRequest())) {
        status.addFatalError("No occurrences found.");
        return;
    }

    Tuple<TextChange, MultiTextEdit> textFileChange = getTextFileChange(this.currentFile, this.currentDoc);
    TextChange docChange = textFileChange.o1;
    MultiTextEdit rootEdit = textFileChange.o2;

    List<Tuple<List<TextEdit>, String>> renameEdits = getAllRenameEdits(currentDoc, docOccurrences,
            this.currentFile != null ? this.currentFile.getFullPath() : null, request.nature);
    if (status.hasFatalError()) {
        return;
    }
    if (renameEdits.size() > 0) {
        fillEditsInDocChange(docChange, rootEdit, renameEdits);
    }
}
 
Example #14
Source File: UpdateAcceptorTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testAddTextEdit() throws Exception {

		updateAcceptor.accept(resourceURI0, new ReplaceEdit(0, 1, "foo"));
		updateAcceptor.accept(resourceURI1, new ReplaceEdit(1, 2, "bar"));
		updateAcceptor.accept(resourceURI0, new ReplaceEdit(3, 4, "baz"));

		Change change = updateAcceptor.createCompositeChange(CHANGE_NAME, new NullProgressMonitor());
		assertTrue(change instanceof CompositeChange);
		Change[] children = ((CompositeChange) change).getChildren();
		assertEquals(2, children.length);
		assertTrue(children[0] instanceof MockChange);
		MockChange change0 = (MockChange) children[0];
		assertEquals(CHANGE_NAME, change0.getName());
		assertTrue(children[1] instanceof MockChange);
		MockChange change1 = (MockChange) children[1];
		assertEquals(CHANGE_NAME, change1.getName());
		assertTrue(change0.getTextEdit() instanceof MultiTextEdit);
		assertTrue(change1.getTextEdit() instanceof MultiTextEdit);
		assertEquals(
				3,
				((MultiTextEdit) change0.getTextEdit()).getChildrenSize()
						+ ((MultiTextEdit) change1.getTextEdit()).getChildrenSize());
	}
 
Example #15
Source File: AbstractTextEditComposerTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testMultiEdit() throws Exception {
	Resource res = getResource(newTestGrammar());

	composer.beginRecording(res);
	Grammar grammar = (Grammar) res.getContents().get(0);
	ParserRule fooRule = (ParserRule) grammar.getRules().get(0);
	ParserRule barRule = (ParserRule) grammar.getRules().get(1);
	Alternatives fooAlternatives = (Alternatives) fooRule.getAlternatives();
	barRule.setAlternatives(fooAlternatives.getElements().remove(0));
	TextEdit edit = composer.endRecording();

	assertTrue(edit instanceof MultiTextEdit);
	TextEdit[] children = ((MultiTextEdit) edit).getChildren();
	assertEquals(2, children.length);
	assertMatches("'bar' | 'baz'", children[0]);
	assertMatches("Bar: 'foo' ;", children[1]);
}
 
Example #16
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 #17
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates the method content of the moved method.
 *
 * @param document
 *            the document representing the source compilation unit
 * @param declaration
 *            the source method declaration
 * @param rewrite
 *            the ast rewrite to use
 * @return the string representing the moved method body
 * @throws BadLocationException
 *             if an offset into the document is invalid
 */
protected String createMethodContent(final IDocument document, final MethodDeclaration declaration, final ASTRewrite rewrite) throws BadLocationException {
	Assert.isNotNull(document);
	Assert.isNotNull(declaration);
	Assert.isNotNull(rewrite);
	final IRegion range= new Region(declaration.getStartPosition(), declaration.getLength());
	final RangeMarker marker= new RangeMarker(range.getOffset(), range.getLength());
	final IJavaProject project= fMethod.getJavaProject();
	final TextEdit[] edits= rewrite.rewriteAST(document, project.getOptions(true)).removeChildren();
	for (int index= 0; index < edits.length; index++)
		marker.addChild(edits[index]);
	final MultiTextEdit result= new MultiTextEdit();
	result.addChild(marker);
	final TextEditProcessor processor= new TextEditProcessor(document, new MultiTextEdit(0, document.getLength()), TextEdit.UPDATE_REGIONS);
	processor.getRoot().addChild(result);
	processor.performEdits();
	final IRegion region= document.getLineInformation(document.getLineOfOffset(marker.getOffset()));
	return Strings.changeIndent(document.get(marker.getOffset(), marker.getLength()), Strings.computeIndentUnits(document.get(region.getOffset(), region.getLength()), project), project, "", TextUtilities.getDefaultLineDelimiter(document)); //$NON-NLS-1$
}
 
Example #18
Source File: ImportRewriter.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
	 * Add the necessary text edits to the accumulating result. Optionally return the offset of the alias.
	 */
	private AliasLocation toTextEdit(QualifiedName qualifiedName, String optionalAlias, int insertionOffset,
			MultiTextEdit result) {
		QualifiedName moduleName = qualifiedName.skipLast(1);
		// the following code for enhancing existing ImportDeclarations makes use of the Xtext serializer, which is not
		// yet compatible with fragments in Xtext grammars (as of Xtext 2.9.1) -> deactivated for now
// @formatter:off
//		String moduleNameAsString = unquoted(syntacticModuleName(moduleName));
//		for (ImportDeclaration existing : existingImports) {
//			String importedModuleName = existing.getModule().getQualifiedName();
//			if (moduleNameAsString.equals(importedModuleName)) {
//				return enhanceExistingImportDeclaration(existing, qualifiedName, optionalAlias, result);
//			}
//		}
// @formatter:on
		return addNewImportDeclaration(moduleName, qualifiedName, optionalAlias, insertionOffset, result);
	}
 
Example #19
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 #20
Source File: ImportRewriteAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void removeAndInsertNew(IBuffer buffer, int contentOffset, int contentEnd, ArrayList stringsToInsert, MultiTextEdit resEdit) {
	int pos= contentOffset;
	for (int i= 0; i < stringsToInsert.size(); i++) {
		String curr= (String) stringsToInsert.get(i);
		int idx= findInBuffer(buffer, curr, pos, contentEnd);
		if (idx != -1) {
			if (idx != pos) {
				resEdit.addChild(new DeleteEdit(pos, idx - pos));
			}
			pos= idx + curr.length();
		} else {
			resEdit.addChild(new InsertEdit(pos, curr));
		}
	}
	if (pos < contentEnd) {
		resEdit.addChild(new DeleteEdit(pos, contentEnd - pos));
	}
}
 
Example #21
Source File: TextEditUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static void flatten(TextEdit edit, MultiTextEdit result) {
	if (!edit.hasChildren()) {
		result.addChild(edit);
	} else {
		TextEdit[] children= edit.getChildren();
		for (int i= 0; i < children.length; i++) {
			TextEdit child= children[i];
			child.getParent().removeChild(0);
			flatten(child, result);
		}
	}
}
 
Example #22
Source File: LinkedProposalPositionGroup.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public TextEdit computeEdits(int offset, LinkedPosition position, char trigger, int stateMask, LinkedModeModel model) throws CoreException {
	ImportRewrite impRewrite= StubUtility.createImportRewrite(fCompilationUnit, true);
	String replaceString= impRewrite.addImport(fTypeProposal);

	MultiTextEdit composedEdit= new MultiTextEdit();
	composedEdit.addChild(new ReplaceEdit(position.getOffset(), position.getLength(), replaceString));
	composedEdit.addChild(impRewrite.rewriteImports(null));
	return composedEdit;
}
 
Example #23
Source File: TextEditUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Create an edit which contains <code>edit1</code> and <code>edit2</code>
 * <p>If <code>edit1</code> overlaps <code>edit2</code> this method fails with a {@link MalformedTreeException}</p>
 * <p><strong>The given edits are modified and they can no longer be used.</strong></p>
 *
 * @param edit1 the edit to merge with edit2
 * @param edit2 the edit to merge with edit1
 * @return the merged tree
 * @throws MalformedTreeException if {@link #overlaps(TextEdit, TextEdit)} returns <b>true</b>
 * @see #overlaps(TextEdit, TextEdit)
 * @since 3.4
 */
public static TextEdit merge(TextEdit edit1, TextEdit edit2) {
	if (edit1 instanceof MultiTextEdit && !edit1.hasChildren()) {
		return edit2;
	}

	if (edit2 instanceof MultiTextEdit && !edit2.hasChildren()) {
		return edit1;
	}

	MultiTextEdit result= new MultiTextEdit();
	merge(edit1, edit2, result);
	return result;
}
 
Example #24
Source File: InternalASTRewrite.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Performs the rewrite: The rewrite events are translated to the corresponding in text changes.
 * The given options can be null in which case the global options {@link JavaCore#getOptions() JavaCore.getOptions()}
 * will be used.
 *
 * @param document Document which describes the code of the AST that is passed in in the
 * constructor. This document is accessed read-only.
 * @param options the given options
 * @throws IllegalArgumentException if the rewrite fails
 * @return Returns the edit describing the text changes.
 */
public TextEdit rewriteAST(IDocument document, Map options) {
	TextEdit result = new MultiTextEdit();

	final CompilationUnit rootNode = getRootNode();
	if (rootNode != null) {
		TargetSourceRangeComputer xsrComputer = new TargetSourceRangeComputer() {
			/**
			 * This implementation of
			 * {@link TargetSourceRangeComputer#computeSourceRange(ASTNode)}
			 * is specialized to work in the case of internal AST rewriting, where the
			 * original AST has been modified from its original form. This means that
			 * one cannot trust that the root of the given node is the compilation unit.
			 */
			public SourceRange computeSourceRange(ASTNode node) {
				int extendedStartPosition = rootNode.getExtendedStartPosition(node);
				int extendedLength = rootNode.getExtendedLength(node);
				return new SourceRange(extendedStartPosition, extendedLength);
			}
		};
		char[] content= document.get().toCharArray();
		LineInformation lineInfo= LineInformation.create(document);
		String lineDelim= TextUtilities.getDefaultLineDelimiter(document);
		List comments= rootNode.getCommentList();

		Map currentOptions = options == null ? JavaCore.getOptions() : options;
		ASTRewriteAnalyzer visitor = new ASTRewriteAnalyzer(content, lineInfo, lineDelim, result, this.eventStore, this.nodeStore, comments, currentOptions, xsrComputer, (RecoveryScannerData)rootNode.getStatementsRecoveryData());
		rootNode.accept(visitor);
	}
	return result;
}
 
Example #25
Source File: AbstractFileChangeProcessor.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Change createChange() throws MisconfigurationException {
    if (info.getSourceFile() != null) {
        change = new SynchronizedTextFileChange(name, info.getSourceFile());
        change.setTextType("py");
    } else {
        // Not insisting on a source file makes testing easier.
        change = PyDocumentChange.create(name, info.getDocument());

    }
    multiEdit = new MultiTextEdit();
    change.setEdit(this.multiEdit);
    processEdit();
    return change;
}
 
Example #26
Source File: ASTRewrite.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private TextEdit internalRewriteAST(char[] content, LineInformation lineInfo, String lineDelim, List commentNodes, Map options, ASTNode rootNode, RecoveryScannerData recoveryScannerData) {
	TextEdit result= new MultiTextEdit();
	//validateASTNotModified(rootNode);

	TargetSourceRangeComputer sourceRangeComputer= getExtendedSourceRangeComputer();
	this.eventStore.prepareMovedNodes(sourceRangeComputer);

	ASTRewriteAnalyzer visitor= new ASTRewriteAnalyzer(content, lineInfo, lineDelim, result, this.eventStore, this.nodeStore, commentNodes, options, sourceRangeComputer, recoveryScannerData);
	rootNode.accept(visitor); // throws IllegalArgumentException

	this.eventStore.revertMovedNodes();
	return result;
}
 
Example #27
Source File: RenameLocalVariableProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void createEdits() {
	TextEdit declarationEdit= createRenameEdit(fTempDeclarationNode.getName().getStartPosition());
	TextEdit[] allRenameEdits= getAllRenameEdits(declarationEdit);

	TextEdit[] allUnparentedRenameEdits= new TextEdit[allRenameEdits.length];
	TextEdit unparentedDeclarationEdit= null;

	fChange= new CompilationUnitChange(RefactoringCoreMessages.RenameTempRefactoring_rename, fCu);
	MultiTextEdit rootEdit= new MultiTextEdit();
	fChange.setEdit(rootEdit);
	fChange.setKeepPreviewEdits(true);

	for (int i= 0; i < allRenameEdits.length; i++) {
		if (fIsComposite) {
			// Add a copy of the text edit (text edit may only have one
			// parent) to keep problem reporting code clean
			TextChangeCompatibility.addTextEdit(fChangeManager.get(fCu), RefactoringCoreMessages.RenameTempRefactoring_changeName, allRenameEdits[i].copy(), fCategorySet);

			// Add a separate copy for problem reporting
			allUnparentedRenameEdits[i]= allRenameEdits[i].copy();
			if (allRenameEdits[i].equals(declarationEdit))
				unparentedDeclarationEdit= allUnparentedRenameEdits[i];
		}
		rootEdit.addChild(allRenameEdits[i]);
		fChange.addTextEditGroup(new TextEditGroup(RefactoringCoreMessages.RenameTempRefactoring_changeName, allRenameEdits[i]));
	}

	// store information for analysis
	if (fIsComposite) {
		fLocalAnalyzePackage= new RenameAnalyzeUtil.LocalAnalyzePackage(unparentedDeclarationEdit, allUnparentedRenameEdits);
	} else
		fLocalAnalyzePackage= new RenameAnalyzeUtil.LocalAnalyzePackage(declarationEdit, allRenameEdits);
}
 
Example #28
Source File: ChangeTypeRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * update a CompilationUnit's imports after changing the type of declarations
 * @param astRoot the AST
 * @param rootEdit the resulting edit
 * @return the type name to use
 * @throws CoreException
 */
private String updateImports(CompilationUnit astRoot, MultiTextEdit rootEdit) throws CoreException{
	ImportRewrite rewrite= StubUtility.createImportRewrite(astRoot, true);
	ContextSensitiveImportRewriteContext context= new ContextSensitiveImportRewriteContext(astRoot, fSelectionStart, rewrite);
	String typeName= rewrite.addImport(fSelectedType.getQualifiedName(), context);
	rootEdit.addChild(rewrite.rewriteImports(null));
	return typeName;
}
 
Example #29
Source File: ChangeTypeRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Apply all changes related to a single ICompilationUnit
 * @param icu the compilation unit
 * @param vars
 * @param unitChange
 * @throws CoreException
 */
private void addAllChangesFor(ICompilationUnit icu, Set<ConstraintVariable> vars, CompilationUnitChange unitChange) throws CoreException {
	CompilationUnit	unit= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(icu, true);
	ASTRewrite unitRewriter= ASTRewrite.create(unit.getAST());
	MultiTextEdit root= new MultiTextEdit();
	unitChange.setEdit(root); // Adam sez don't need this, but then unitChange.addGroupDescription() fails an assertion!

	String typeName= updateImports(unit, root);
	updateCu(unit, vars, unitChange, unitRewriter, typeName);
	root.addChild(unitRewriter.rewriteAST());
}
 
Example #30
Source File: ImportsFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static ICleanUpFix createCleanUp(final CompilationUnit cu, CodeGenerationSettings settings, boolean organizeImports, RefactoringStatus status) throws CoreException {
if (!organizeImports)
	return null;

final boolean hasAmbiguity[]= new boolean[] { false };
IChooseImportQuery query= new IChooseImportQuery() {
	public TypeNameMatch[] chooseImports(TypeNameMatch[][] openChoices, ISourceRange[] ranges) {
		hasAmbiguity[0]= true;
		return new TypeNameMatch[0];
	}
};

final ICompilationUnit unit= (ICompilationUnit)cu.getJavaElement();
OrganizeImportsOperation op= new OrganizeImportsOperation(unit, cu, settings.importIgnoreLowercase, false, false, query);
final TextEdit edit= op.createTextEdit(null);
if (hasAmbiguity[0]) {
	status.addInfo(Messages.format(ActionMessages.OrganizeImportsAction_multi_error_unresolvable, getLocationString(cu)));
}

if (op.getParseError() != null) {
	status.addInfo(Messages.format(ActionMessages.OrganizeImportsAction_multi_error_parse, getLocationString(cu)));
	return null;
}

if (edit == null || (edit instanceof MultiTextEdit && edit.getChildrenSize() == 0))
	return null;

return new ImportsFix(edit, unit, FixMessages.ImportsFix_OrganizeImports_Description);
  }