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

The following examples show how to use org.eclipse.text.edits.MultiTextEdit#addChild() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
Source File: NLSSourceModifier.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private String createImportForAccessor(MultiTextEdit parent, String accessorClassName, IPackageFragment accessorPackage, ICompilationUnit cu) throws CoreException {
	IType type= accessorPackage.getCompilationUnit(accessorClassName + JavaModelUtil.DEFAULT_CU_SUFFIX).getType(accessorClassName);
	String fullyQualifiedName= type.getFullyQualifiedName();

	ImportRewrite importRewrite= StubUtility.createImportRewrite(cu, true);
	String nameToUse= importRewrite.addImport(fullyQualifiedName);
	TextEdit edit= importRewrite.rewriteImports(null);
	parent.addChild(edit);

	return nameToUse;
}
 
Example 12
Source File: SelfEncapsulateFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void createEdits(ICompilationUnit unit, ASTRewrite rewriter, List<TextEditGroup> groups, ImportRewrite importRewrite) throws CoreException {
	TextChange change= fChangeManager.get(unit);
	MultiTextEdit root= new MultiTextEdit();
	change.setEdit(root);
	root.addChild(importRewrite.rewriteImports(null));
	root.addChild(rewriter.rewriteAST());
	for (Iterator<TextEditGroup> iter= groups.iterator(); iter.hasNext();) {
		change.addTextEditGroup(iter.next());
	}
}
 
Example 13
Source File: SelfEncapsulateFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void createEdits(ICompilationUnit unit, ASTRewrite rewriter, List<TextEditGroup> groups, ImportRewrite importRewrite) throws CoreException {
	TextChange change = fChangeManager.get(unit);
	MultiTextEdit root = new MultiTextEdit();
	change.setEdit(root);
	root.addChild(importRewrite.rewriteImports(null));
	root.addChild(rewriter.rewriteAST());
	for (Iterator<TextEditGroup> iter = groups.iterator(); iter.hasNext();) {
		change.addTextEditGroup(iter.next());
	}
}
 
Example 14
Source File: TextChangeCombiner.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void addIfNotDuplicate(MultiTextEdit multiTextEdit, final TextEdit editToBeAdded) {
	final boolean[] overlaps = new boolean[] { false };
	TextEditVisitor textEditVisitor = new TextEditVisitor() {
		@Override
		public boolean visitNode(TextEdit edit) {
			overlaps[0] |= !(edit instanceof MultiTextEdit) && edit.covers(editToBeAdded);
			return super.visitNode(edit);
		}
	};
	multiTextEdit.accept(textEditVisitor);
	if (!overlaps[0])
		multiTextEdit.addChild(editToBeAdded.copy());
}
 
Example 15
Source File: ImportRewriter.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private AliasLocation addNewImportDeclaration(QualifiedName moduleName, QualifiedName qualifiedName,
		String optionalAlias,
		int insertionOffset, MultiTextEdit result) {

	final String spacer = lazySpacer.get();
	String syntacticModuleName = syntacticModuleName(moduleName);

	AliasLocation aliasLocation = null;
	String importSpec = (insertionOffset != 0 ? lineDelimiter : "") + "import ";

	if (!N4JSLanguageUtils.isDefaultExport(qualifiedName)) { // not an 'default' export
		importSpec = importSpec + "{" + spacer + qualifiedName.getLastSegment();
		if (optionalAlias != null) {
			importSpec = importSpec + " as ";
			aliasLocation = new AliasLocation(insertionOffset, importSpec.length(), optionalAlias);
			importSpec = importSpec + optionalAlias;
		}
		importSpec = importSpec + spacer + "}";
	} else { // import default exported element
		if (optionalAlias == null) {
			importSpec = importSpec + N4JSLanguageUtils.lastSegmentOrDefaultHost(qualifiedName);
		} else {
			aliasLocation = new AliasLocation(insertionOffset, importSpec.length(), optionalAlias);
			importSpec = importSpec + optionalAlias;
		}
	}

	result.addChild(new InsertEdit(insertionOffset, importSpec + " from "
			+ syntacticModuleName + ";"
			+ (insertionOffset != 0 ? "" : lineDelimiter)));

	return aliasLocation;
}
 
Example 16
Source File: RenameRefactoringProcessor.java    From xds-ide with Eclipse Public License 1.0 4 votes vote down vote up
private void processIFile(RenameCompositeChange resultChange,
		RefactoringChangeContext refactoringChangeContext,
		IFile ifileWithOccurrence,
		Set<ModulaSymbolMatch> fileMatches,
		IProgressMonitor monitor) {
	File fileWithOccurrence = ResourceUtils.getAbsoluteFile(ifileWithOccurrence);
	Change renameFileChange = null;
	
	resultChange.moduleFileDamaged(ifileWithOccurrence);
	resultChange.setProject(ifileWithOccurrence.getProject());
	
	boolean isRefactoringEnabled = isRefactoringEnabledByDefaultOn(ifileWithOccurrence);
	TextFileChange textFileChange = new TextFileChange( ifileWithOccurrence.getName(), ifileWithOccurrence );
	// a file change contains a tree of edits, first add the root of them
	MultiTextEdit fileChangeRootEdit = new MultiTextEdit();
	textFileChange.setEdit( fileChangeRootEdit );
	String ext = FilenameUtils.getExtension(ifileWithOccurrence.getName());
	textFileChange.setTextType(ext);
	
	for (ModulaSymbolMatch symbolMatch : fileMatches) {
		IModulaSymbol symbol = symbolMatch.getSymbol();
		boolean isTopLevelModuleSymbol = symbol == ModulaSymbolUtils.getHostModule(symbol);
		// this automatically implies that TRUE(symbol instanceof IModuleSymbol) 
		if (isTopLevelModuleSymbol) {
			File sourceFile = ModulaSymbolUtils.getSourceFile(symbol);
			if (sourceFile != null && !refactoringChangeContext.isRenameFileChangeRegistered(sourceFile)) {
				boolean areFileSame = ResourceUtils.equalsPathesAsInFS(sourceFile, fileWithOccurrence);
				if (areFileSame) {
					String newModuleName = createNewModuleName(ifileWithOccurrence, renameRefactoringInfo.getNewName());
					renameFileChange = createRenameModuleFileChange(ifileWithOccurrence, newModuleName, refactoringChangeContext);
					if (renameFileChange != null) {
						renameFileChange.setEnabled(isRefactoringEnabled);
						refactoringChangeContext.registerRenameFileChange(fileWithOccurrence, resultChange, renameFileChange);
					}
				}
			}
		}
		ReplaceEdit edit = new ReplaceEdit( symbolMatch.getOffset(), 
				symbolMatch.getLength(), 
	            renameRefactoringInfo.getNewName() );
		fileChangeRootEdit.addChild(edit);
		
		monitor.worked(1);
	}
	
	if (refactoringChangeContext.registerTextFileChange(fileWithOccurrence, resultChange, textFileChange)) {
		textFileChange.setEnabled(isRefactoringEnabled);
		resultChange.add(textFileChange);
	}
	
	if (renameFileChange != null) {
		resultChange.add(renameFileChange);
	}
}
 
Example 17
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 18
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;
}
 
Example 19
Source File: ReplaceInvocationsRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
	pm.beginTask("", 20); //$NON-NLS-1$
	fChangeManager= new TextChangeManager();
	RefactoringStatus result= new RefactoringStatus();

	fSourceProvider= resolveSourceProvider(fMethodBinding, result);
	if (result.hasFatalError())
		return result;

	result.merge(fSourceProvider.checkActivation());
	if (result.hasFatalError())
		return result;

	fSourceProvider.initialize();
	fTargetProvider.initialize();

	pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_searching);
	RefactoringStatus searchStatus= new RefactoringStatus();
	String binaryRefsDescription= Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description , BasicElementLabels.getJavaElementName(fSourceProvider.getMethodName()));
	ReferencesInBinaryContext binaryRefs= new ReferencesInBinaryContext(binaryRefsDescription);
	ICompilationUnit[] units= fTargetProvider.getAffectedCompilationUnits(searchStatus, binaryRefs, new SubProgressMonitor(pm, 1));
	binaryRefs.addErrorIfNecessary(searchStatus);

	if (searchStatus.hasFatalError()) {
		result.merge(searchStatus);
		return result;
	}
	IFile[] filesToBeModified= getFilesToBeModified(units);
	result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext()));
	if (result.hasFatalError())
		return result;
	result.merge(ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1)));
	checkOverridden(result, new SubProgressMonitor(pm, 4));
	IProgressMonitor sub= new SubProgressMonitor(pm, 15);
	sub.beginTask("", units.length * 3); //$NON-NLS-1$
	for (int c= 0; c < units.length; c++) {
		ICompilationUnit unit= units[c];
		sub.subTask(Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_processing,  BasicElementLabels.getFileName(unit)));
		CallInliner inliner= null;
		try {
			boolean added= false;
			MultiTextEdit root= new MultiTextEdit();
			CompilationUnitChange change= (CompilationUnitChange)fChangeManager.get(unit);
			change.setEdit(root);
			BodyDeclaration[] bodies= fTargetProvider.getAffectedBodyDeclarations(unit, new SubProgressMonitor(pm, 1));
			if (bodies.length == 0)
				continue;
			inliner= new CallInliner(unit, (CompilationUnit) bodies[0].getRoot(), fSourceProvider);
			for (int b= 0; b < bodies.length; b++) {
				BodyDeclaration body= bodies[b];
				inliner.initialize(body);
				RefactoringStatus nestedInvocations= new RefactoringStatus();
				ASTNode[] invocations= removeNestedCalls(nestedInvocations, unit,
					fTargetProvider.getInvocations(body, new SubProgressMonitor(sub, 2)));
				for (int i= 0; i < invocations.length; i++) {
					ASTNode invocation= invocations[i];
					result.merge(inliner.initialize(invocation, fTargetProvider.getStatusSeverity()));
					if (result.hasFatalError())
						break;
					if (result.getSeverity() < fTargetProvider.getStatusSeverity()) {
						added= true;
						TextEditGroup group= new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_inline);
						change.addTextEditGroup(group);
						result.merge(inliner.perform(group));
					}
				}
				// do this after we have inlined the method calls. We still want
				// to generate the modifications.
				result.merge(nestedInvocations);
			}
			if (!added) {
				fChangeManager.remove(unit);
			} else {
				root.addChild(inliner.getModifications());
				ImportRewrite rewrite= inliner.getImportEdit();
				if (rewrite.hasRecordedChanges()) {
					TextEdit edit= rewrite.rewriteImports(null);
					if (edit instanceof MultiTextEdit ? ((MultiTextEdit)edit).getChildrenSize() > 0 : true) {
						root.addChild(edit);
						change.addTextEditGroup(
							new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_import, new TextEdit[] {edit}));
					}
				}
			}
		} finally {
			if (inliner != null)
				inliner.dispose();
		}
		sub.worked(1);
		if (sub.isCanceled())
			throw new OperationCanceledException();
	}
	result.merge(searchStatus);
	sub.done();
	pm.done();
	return result;
}
 
Example 20
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;
}