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

The following examples show how to use org.eclipse.text.edits.TextEdit. 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
public static Change removeKeys(IPath propertyFilePath, List<String> keys) throws CoreException {

		String name= Messages.format(NLSMessages.NLSPropertyFileModifier_remove_from_property_file, BasicElementLabels.getPathLabel(propertyFilePath, false));
		TextChange textChange= new TextFileChange(name, getPropertyFile(propertyFilePath));
		textChange.setTextType("properties"); //$NON-NLS-1$

		PropertyFileDocumentModel model= new PropertyFileDocumentModel(textChange.getCurrentDocument(new NullProgressMonitor()));

		for (Iterator<String> iterator= keys.iterator(); iterator.hasNext();) {
			String key= iterator.next();
			TextEdit edit= model.remove(key);
			if (edit != null) {
				TextChangeCompatibility.addTextEdit(textChange, Messages.format(NLSMessages.NLSPropertyFileModifier_remove_entry, BasicElementLabels.getJavaElementName(key)), edit);
			}

		}
		return textChange;
	}
 
Example 2
private TextEdit getOrganizeImportsProposal(IInvocationContext context) {
	ICompilationUnit unit = context.getCompilationUnit();
	CompilationUnit astRoot = context.getASTRoot();
	OrganizeImportsOperation op = new OrganizeImportsOperation(unit, astRoot, true, false, true, null);
	try {
		TextEdit edit = op.createTextEdit(null);
		TextEdit staticEdit = OrganizeImportsHandler.wrapStaticImports(edit, astRoot, unit);
		if (staticEdit.getChildrenSize() > 0) {
			return staticEdit;
		}
		return edit;
	} catch (OperationCanceledException | CoreException e) {
		JavaLanguageServerPlugin.logException("Resolve organize imports source action", e);
	}

	return null;
}
 
Example 3
final TextEdit getCopySourceEdit(CopySourceInfo info) {
	TextEdit edit= (TextEdit) this.sourceCopyInfoToEdit.get(info);
	if (edit == null) {
		SourceRange range= getExtendedRange(info.getNode());
		int start= range.getStartPosition();
		int end= start + range.getLength();
		if (info.isMove) {
			MoveSourceEdit moveSourceEdit= new MoveSourceEdit(start, end - start);
			moveSourceEdit.setTargetEdit(new MoveTargetEdit(0));
			edit= moveSourceEdit;
		} else {
			CopySourceEdit copySourceEdit= new CopySourceEdit(start, end - start);
			copySourceEdit.setTargetEdit(new CopyTargetEdit(0));
			edit= copySourceEdit;
		}
		this.sourceCopyInfoToEdit.put(info, edit);
	}
	return edit;
}
 
Example 4
Source Project: jbt   Source File: Util.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method formats a source code file (its content is in
 * <code>sourceCode</code>) according to the Eclipse SDK defaults formatting
 * settings, and returns the formatted code.
 * <p>
 * Note that the input source code must be syntactically correct according
 * to the Java 1.7 version. Otherwise, an exception is thrown.
 * 
 * @param sourceCode
 *            the source code to format.
 * @return the formatted source code.
 */
public static String format(String sourceCode) {
	try {
		TextEdit edit = codeFormatter.format(CodeFormatter.K_COMPILATION_UNIT
				| CodeFormatter.F_INCLUDE_COMMENTS, sourceCode, 0, sourceCode.length(), 0,
				System.getProperty("line.separator"));

		IDocument document = new Document(sourceCode);

		edit.apply(document);

		return document.get();
	} catch (Exception e) {
		throw new RuntimeException("The input source code is not sintactically correct:\n\n" + sourceCode);
	}
}
 
Example 5
Source Project: aws-sdk-java-v2   Source File: JavaCodeFormatter.java    License: Apache License 2.0 6 votes vote down vote up
public String apply(String contents) {
    TextEdit edit = codeFormatter.format(
            CodeFormatter.K_COMPILATION_UNIT
            | CodeFormatter.F_INCLUDE_COMMENTS, contents, 0,
            contents.length(), 0, Constant.LF);

    if (edit == null) {
        // TODO log a fatal or warning here. Throwing an exception is causing the actual freemarker error to be lost
        return contents;
    }

    IDocument document = new Document(contents);

    try {
        edit.apply(document);
    } catch (Exception e) {
        throw new RuntimeException(
                "Failed to format the generated source code.", e);
    }

    return document.get();
}
 
Example 6
Source Project: xtext-eclipse   Source File: DocumentLockerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private ITextEditComposer createTextEditComposer() {
	return new ITextEditComposer() {
		@Override
		public void beginRecording(Resource resource) {
		}

		@Override
		public TextEdit endRecording() {
			return null;
		}

		@Override
		public TextEdit getTextEdit() {
			return null;
		}
	};
}
 
Example 7
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 8
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 9
private void addImportsToTargetUnit(final ICompilationUnit targetUnit, final IProgressMonitor monitor) throws CoreException, JavaModelException {
	monitor.beginTask("", 2); //$NON-NLS-1$
	try {
		ImportRewrite rewrite= StubUtility.createImportRewrite(targetUnit, true);
		if (fTypeImports != null) {
			ITypeBinding type= null;
			for (final Iterator<ITypeBinding> iterator= fTypeImports.iterator(); iterator.hasNext();) {
				type= iterator.next();
				rewrite.addImport(type);
			}
		}
		if (fStaticImports != null) {
			IBinding binding= null;
			for (final Iterator<IBinding> iterator= fStaticImports.iterator(); iterator.hasNext();) {
				binding= iterator.next();
				rewrite.addStaticImport(binding);
			}
		}
		fTypeImports= null;
		fStaticImports= null;
		TextEdit edits= rewrite.rewriteImports(new SubProgressMonitor(monitor, 1));
		JavaModelUtil.applyEdit(targetUnit, edits, false, new SubProgressMonitor(monitor, 1));
	} finally {
		monitor.done();
	}
}
 
Example 10
private void addAccessorOccurrences(IProgressMonitor pm, IMethod accessor, String editName, String newAccessorName, RefactoringStatus status) throws CoreException {
	Assert.isTrue(accessor.exists());

	IJavaSearchScope scope= RefactoringScopeFactory.create(accessor);
	SearchPattern pattern= SearchPattern.createPattern(accessor, IJavaSearchConstants.ALL_OCCURRENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
	SearchResultGroup[] groupedResults= RefactoringSearchEngine.search(
		pattern, scope, new MethodOccurenceCollector(accessor.getElementName()), pm, status);

	for (int i= 0; i < groupedResults.length; i++) {
		ICompilationUnit cu= groupedResults[i].getCompilationUnit();
		if (cu == null) {
			continue;
		}
		SearchMatch[] results= groupedResults[i].getSearchResults();
		for (int j= 0; j < results.length; j++){
			SearchMatch searchResult= results[j];
			TextEdit edit= new ReplaceEdit(searchResult.getOffset(), searchResult.getLength(), newAccessorName);
			addTextEdit(fChangeManager.get(cu), editName, edit);
		}
	}
}
 
Example 11
@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 12
/**
 * Creates text edits for each file affected by the refactoring. This
 * delegates to the createEdit(IIndexedJavaRef) method to actually create the
 * edit (since, for example, edits for renaming a type will be different than
 * those for renaming members). The edits are then grouped together by file
 * before being returned.
 * 
 * @param refs the Java references that need to be updated
 * @return the set of text edits to update the references, grouped by file
 */
public Map<IPath, Set<TextEdit>> createEdits(Set<IIndexedJavaRef> refs) {
  Map<IPath, Set<TextEdit>> edits = new HashMap<IPath, Set<TextEdit>>();

  for (IIndexedJavaRef ref : refs) {
    TextEdit edit = createEdit(ref);
    IPath source = ref.getSource();

    // Add the edit to the map
    if (edits.containsKey(source)) {
      edits.get(source).add(edit);
    } else {
      Set<TextEdit> sourcEdits = new HashSet<TextEdit>();
      sourcEdits.add(edit);
      edits.put(source, sourcEdits);
    }
  }

  return edits;
}
 
Example 13
Source Project: eclipse.jdt.ls   Source File: TextEditConverter.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean visit(CopySourceEdit edit) {
	try {
		if (edit.getTargetEdit() != null) {
			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());
			if (edit.getSourceModifier() != null) {
				content = applySourceModifier(content, edit.getSourceModifier());
			}
			te.setNewText(content);
			converted.add(te);
		}
		return false;
	} catch (JavaModelException | MalformedTreeException | BadLocationException e) {
		JavaLanguageServerPlugin.logException("Error converting TextEdits", e);
	}
	return super.visit(edit);
}
 
Example 14
Source Project: eclipse.jdt.ls   Source File: TextEditConverter.java    License: 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 15
/**
 * Same as format(IDocument, Map, String[]), except the formatting options
 * are taken from the given project.
 * 
 */
public static TextEdit format(IDocument document, IJavaProject project,
    String[] originalJsniMethods) {
  @SuppressWarnings("unchecked")
  // safe by IJavaScriptProject.getOptions spec
  Map<String, String> jsOptions = JavaScriptCore.create(project.getProject()).getOptions(true);
  @SuppressWarnings("unchecked")
  // safe by IJavaScriptProject.getOptions spec
  Map<String, String> jOptions = project.getOptions(true);
  return format(document, jOptions, jsOptions, originalJsniMethods);
}
 
Example 16
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 17
Source Project: jenerate   Source File: JavaCodeFormatterImpl.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public String formatCode(IType objectClass, String source) throws JavaModelException, BadLocationException {
    String lineDelim = getLineDelimiterUsed(objectClass);
    int indent = getUsedIndentation(objectClass) + 1;
    TextEdit textEdit = ToolFactory.createCodeFormatter(null).format(CodeFormatter.K_CLASS_BODY_DECLARATIONS,
            source, 0, source.length(), indent, lineDelim);
    if (textEdit == null) {
        return source;
    }
    Document document = new Document(source);
    textEdit.apply(document);
    return document.get();
}
 
Example 18
Source Project: spring-javaformat   Source File: Formatter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public TextEdit format(int kind, String source, int offset, int length, int indentationLevel,
		String lineSeparator) {
	return nlsSafe(() -> {
		return this.delegate.format(kind, source, offset, length, indentationLevel, lineSeparator);
	});
}
 
Example 19
private void addDeclarationUpdate() throws CoreException {
	ISourceRange nameRange= fField.getNameRange();
	TextEdit textEdit= new ReplaceEdit(nameRange.getOffset(), nameRange.getLength(), getNewElementName());
	ICompilationUnit cu= fField.getCompilationUnit();
	String groupName= RefactoringCoreMessages.RenameFieldRefactoring_Update_field_declaration;
	addTextEdit(fChangeManager.get(cu), groupName, textEdit);
}
 
Example 20
Source Project: spring-javaformat   Source File: FileFormatter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Format the the given source file and return a {@link FileEdit} instance.
 * @param file the file to format
 * @param encoding the source encoding
 * @return a formatted file
 */
public FileEdit formatFile(File file, Charset encoding) {
	try {
		String content = new String(Files.readAllBytes(file.toPath()), encoding);
		TextEdit edit = this.formatter.format(content);
		return new FileEdit(file, encoding, content, edit);
	}
	catch (Exception ex) {
		throw FileFormatterException.wrap(file, ex);
	}
}
 
Example 21
private void addImportsToAccessorCu(ICompilationUnit newCu, IProgressMonitor pm) throws CoreException {
	ImportRewrite is= StubUtility.createImportRewrite(newCu, true);
	if (fIsEclipseNLS) {
		is.addImport("org.eclipse.osgi.util.NLS"); //$NON-NLS-1$
	} else {
		is.addImport("java.util.MissingResourceException"); //$NON-NLS-1$
		is.addImport("java.util.ResourceBundle"); //$NON-NLS-1$
	}
	TextEdit edit= is.rewriteImports(pm);
	JavaModelUtil.applyEdit(newCu, edit, false, null);
}
 
Example 22
private void addTextEdit(TextChange change, String groupName, TextEdit textEdit) {
	if (fIsComposite) {
		TextChangeCompatibility.addTextEdit(change, groupName, textEdit, fCategorySet);
	} else {
		TextChangeCompatibility.addTextEdit(change, groupName, textEdit);
	}

}
 
Example 23
public void testBuildAddError() throws Exception {
  IProject project = getTestProject().getProject();

  // Verify that we have 1 existing GWT problem marker
  IMarker[] markers = getGWTProblemMarkers(project);
  assertEquals(1, markers.length);

  ICompilationUnit cu = testClass.getCompilationUnit();

  // Open the test class in the editor
  CompilationUnitEditor editor = (CompilationUnitEditor) JavaUI.openInEditor(cu);
  IEditorInput editorInput = editor.getEditorInput();

  // Edit the document to create a new error (add 'foobar' to the front of
  // the class name in a Java reference)
  IDocument document = editor.getDocumentProvider().getDocument(editorInput);
  TextEdit errorEdit = new InsertEdit(254, "foobar");
  errorEdit.apply(document);
  // Save the changes
  editor.doSave(null);

  // Rebuild the project
  rebuildTestProject();

  // Verify that we now have 2 GWT problem markers
  markers = getGWTProblemMarkers(project);
  assertEquals(2, markers.length);
}
 
Example 24
public static WorkspaceEdit convertToWorkspaceEdit(ICompilationUnit unit, TextEdit edit) {
    final WorkspaceEdit workspaceEdit = new WorkspaceEdit();
    final TextEditConverter converter = new TextEditConverter(unit, edit);
    final String uri = JDTUtils.toURI(unit);
    workspaceEdit.getChanges().put(uri, converter.convert());
    return workspaceEdit;
}
 
Example 25
@Test public void testRemoveRootObject() throws Exception {
	Resource res = getResource(newTestGrammar());

	composer.beginRecording(res);
	res.getContents().clear();
	TextEdit edit = composer.endRecording();

	assertEquals("", ((ReplaceEdit) edit).getText());
}
 
Example 26
private static boolean replaceTextEdit(TextEdit parentEdit, TextEdit oldEdit,
    TextEdit newEdit) {
  // The text edit API does not allow replacing an edit, so remove all and add
  // them all back (with the replaced edit)
  TextEdit[] children = parentEdit.removeChildren();
  replaceTextEdit(oldEdit, newEdit, children);
  parentEdit.addChildren(children);

  return true;
}
 
Example 27
private static IRegion getCorrespondingEditChangeRange(SearchMatch searchResult, TextChangeManager manager) {
	TextChange change= getTextChange(searchResult, manager);
	if (change == null)
		return null;

	IRegion oldMatchRange= createTextRange(searchResult);
	TextEditChangeGroup[] editChanges= change.getTextEditChangeGroups();
	for (int i= 0; i < editChanges.length; i++) {
		if (oldMatchRange.equals(editChanges[i].getRegion()))
			return TextEdit.getCoverage(change.getPreviewEdits(editChanges[i].getTextEdits()));
	}
	return null;
}
 
Example 28
public void rewriteImports(TextChangeManager changeManager, IProgressMonitor pm) throws CoreException {
	for (Iterator<Entry<ICompilationUnit, ImportChange>> iter= fImportChanges.entrySet().iterator(); iter.hasNext();) {
		Entry<ICompilationUnit, ImportChange> entry= iter.next();
		ICompilationUnit cu= entry.getKey();
		ImportChange importChange= entry.getValue();

		ImportRewrite importRewrite= StubUtility.createImportRewrite(cu, true);
		importRewrite.setFilterImplicitImports(false);
		for (Iterator<String> iterator= importChange.fStaticToRemove.iterator(); iterator.hasNext();) {
			importRewrite.removeStaticImport(iterator.next());
		}
		for (Iterator<String> iterator= importChange.fToRemove.iterator(); iterator.hasNext();) {
			importRewrite.removeImport(iterator.next());
		}
		for (Iterator<String[]> iterator= importChange.fStaticToAdd.iterator(); iterator.hasNext();) {
			String[] toAdd= iterator.next();
			importRewrite.addStaticImport(toAdd[0], toAdd[1], true);
		}
		for (Iterator<String> iterator= importChange.fToAdd.iterator(); iterator.hasNext();) {
			importRewrite.addImport(iterator.next());
		}

		if (importRewrite.hasRecordedChanges()) {
			TextEdit importEdit= importRewrite.rewriteImports(pm);
			String name= RefactoringCoreMessages.RenamePackageRefactoring_update_imports;
			try {
				TextChangeCompatibility.addTextEdit(changeManager.get(cu), name, importEdit);
			} catch (MalformedTreeException e) {
				JavaPlugin.logErrorMessage("MalformedTreeException while processing cu " + cu); //$NON-NLS-1$
				throw e;
			}
		}
	}
}
 
Example 29
@Override
protected void addEdits(IDocument doc, TextEdit rootEdit) throws CoreException {
	super.addEdits(doc, rootEdit);

	TextEdit edit= new ReplaceEdit(fOffset, fLength, fReplacementString);
	rootEdit.addChild(edit);
}
 
Example 30
public void run(IProgressMonitor monitor) throws CoreException {
  ICompilationUnit icu = clientBundle.getCompilationUnit();
  CompilationUnit cu = JavaASTUtils.parseCompilationUnit(icu);
  ImportRewrite importRewrite = StubUtility.createImportRewrite(cu, true);

  // Find the target type declaration
  TypeDeclaration typeDecl = JavaASTUtils.findTypeDeclaration(cu,
      clientBundle.getFullyQualifiedName());
  if (typeDecl == null) {
    throw new CoreException(
        StatusUtilities.newErrorStatus("Missing ClientBundle type "
            + clientBundle.getFullyQualifiedName(), GWTPlugin.PLUGIN_ID));
  }

  // We need to rewrite the AST of the ClientBundle type declaration
  ASTRewrite astRewrite = ASTRewrite.create(cu.getAST());
  ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(typeDecl);
  ListRewrite listRewriter = astRewrite.getListRewrite(typeDecl, property);

  // Add the new resource methods
  boolean addComments = StubUtility.doAddComments(icu.getJavaProject());
  for (ClientBundleResource resource : resources) {
    listRewriter.insertLast(resource.createMethodDeclaration(clientBundle,
        astRewrite, importRewrite, addComments), null);
  }

  // Create the edit to add the methods and update the imports
  TextEdit rootEdit = new MultiTextEdit();
  rootEdit.addChild(astRewrite.rewriteAST());
  rootEdit.addChild(importRewrite.rewriteImports(null));

  // Apply the change to the compilation unit
  CompilationUnitChange cuChange = new CompilationUnitChange(
      "Update ClientBundle", icu);
  cuChange.setSaveMode(TextFileChange.KEEP_SAVE_STATE);
  cuChange.setEdit(rootEdit);
  cuChange.perform(new NullProgressMonitor());
}