org.eclipse.text.edits.TextEdit Java Examples

The following examples show how to use org.eclipse.text.edits.TextEdit. 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: 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 #2
Source File: TextEditConverter.java    From eclipse.jdt.ls with 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 #3
Source File: DefaultTextEditComposer.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected List<TextEdit> getObjectEdits() {
	final Collection<EObject> modifiedObjects = getModifiedObjects();
	Collection<EObject> topLevelObjects = EcoreUtil.filterDescendants(modifiedObjects);
	Iterable<EObject> containedModifiedObjects = Collections.emptyList();
	if (!resource.getContents().isEmpty()) {
		final EObject root = resource.getContents().get(0);
		containedModifiedObjects = Iterables.filter(topLevelObjects, new Predicate<EObject>() {
			@Override
			public boolean apply(EObject input) {
				return EcoreUtil.isAncestor(root, input);
			}
		});
	}
	List<TextEdit> edits = Lists.newArrayListWithExpectedSize(Iterables.size(containedModifiedObjects));
	for (EObject modifiedObject : containedModifiedObjects) {
		ReplaceRegion replaceRegion = serializer.serializeReplacement(modifiedObject, getSaveOptions());
		TextEdit edit = new ReplaceEdit(replaceRegion.getOffset(), replaceRegion.getLength(), replaceRegion.getText());
		edits.add(edit);
	}
	return edits;
}
 
Example #4
Source File: JavaCodeFormatter.java    From aws-sdk-java-v2 with 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 #5
Source File: Util.java    From jbt with 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 #6
Source File: ASTRewriteAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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 #7
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 #8
Source File: GWTRefactoringSupport.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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 #9
Source File: SourceAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
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 #10
Source File: RenameNodeCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void addEdits(IDocument doc, TextEdit root) throws CoreException {
	super.addEdits(doc, root);

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

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

		SimpleName[] names= LinkedNodeFinder.findByProblems(unit, (SimpleName) name);
		if (names != null) {
			for (int i= 0; i < names.length; i++) {
				SimpleName curr= names[i];
				root.addChild(new ReplaceEdit(curr.getStartPosition(), curr.getLength(), fNewName));
			}
			return;
		}
	}
	root.addChild(new ReplaceEdit(fOffset, fLength, fNewName));
}
 
Example #11
Source File: DocumentLockerTest.java    From xtext-eclipse with 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 #12
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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 #13
Source File: RenameFieldProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
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 #14
Source File: NLSPropertyFileModifier.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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 #15
Source File: AddResourcesToClientBundleAction.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
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());
}
 
Example #16
Source File: DefaultRefactoringDocumentProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Change createChange(String name, TextEdit textEdit) {
	EditorDocumentChange documentChange = new EditorDocumentChange(getName(), editor, doSave);
	documentChange.setEdit(textEdit);
	documentChange.setTextType(getURI().fileExtension());
	return documentChange;
}
 
Example #17
Source File: OrganizeImportsCommand.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void addWorkspaceEdit(ICompilationUnit cu, CUCorrectionProposal proposal, WorkspaceEdit rootEdit) throws CoreException {
	TextChange textChange = proposal.getTextChange();
	TextEdit edit = textChange.getEdit();
	TextEditConverter converter = new TextEditConverter(cu, edit);
	List<org.eclipse.lsp4j.TextEdit> edits = converter.convert();
	if (ChangeUtil.hasChanges(edits)) {
		rootEdit.getChanges().put(JDTUtils.toURI(cu), edits);
	}
}
 
Example #18
Source File: TextEditUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean replaceTextEdit(TextEdit oldEdit, TextEdit newEdit,
    TextEdit[] children) {
  int index = 0;
  for (; index < children.length; index++) {
    if (children[index] == oldEdit) {
      children[index] = newEdit;
      break;
    }
  }

  return index != children.length;
}
 
Example #19
Source File: ASTRewriteAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
final void doTextRemoveAndVisit(int offset, int len, ASTNode node, TextEditGroup editGroup) {
	TextEdit edit= doTextRemove(offset, len, editGroup);
	if (edit != null) {
		this.currentEdit= edit;
		voidVisit(node);
		this.currentEdit= edit.getParent();
	} else {
		voidVisit(node);
	}
}
 
Example #20
Source File: AccessorClassCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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 #21
Source File: RenameAnalyzeUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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 #22
Source File: CompilationUnitSourceSetter.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
public void commitCodeChange(ICompilationUnit iCompilationUnit, ASTRewrite rewriter) {
    try {
        Document document = new Document(iCompilationUnit.getSource());
        TextEdit edits = rewriter.rewriteAST(document, null);
        edits.apply(document);
        iCompilationUnit.getBuffer().setContents(document.get());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #23
Source File: SourceAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static WorkspaceEdit convertToWorkspaceEdit(ICompilationUnit cu, TextEdit edit) {
	if (cu == null || edit == null) {
		return null;
	}

	WorkspaceEdit workspaceEdit = new WorkspaceEdit();
	TextEditConverter converter = new TextEditConverter(cu, edit);
	String uri = JDTUtils.toURI(cu);
	workspaceEdit.getChanges().put(uri, converter.convert());
	return workspaceEdit;
}
 
Example #24
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static String asFormattedString(ASTNode node, int indent, String lineDelim, Map<String, String> options) {
	String unformatted= asString(node);
	TextEdit edit= CodeFormatterUtil.format2(node, unformatted, indent, lineDelim, options);
	if (edit != null) {
		Document document= new Document(unformatted);
		try {
			edit.apply(document, TextEdit.NONE);
		} catch (BadLocationException e) {
			JavaPlugin.log(e);
		}
		return document.get();
	}
	return unformatted; // unknown node
}
 
Example #25
Source File: JsniFormattingUtil.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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 #26
Source File: HashCodeEqualsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static WorkspaceEdit generateHashCodeEquals(GenerateHashCodeEqualsParams params) {
	IType type = SourceAssistProcessor.getSelectionType(params.context);
	Preferences preferences = JavaLanguageServerPlugin.getPreferencesManager().getPreferences();
	boolean useJava7Objects = preferences.isHashCodeEqualsTemplateUseJava7Objects();
	boolean useInstanceof = preferences.isHashCodeEqualsTemplateUseInstanceof();
	boolean useBlocks = preferences.isCodeGenerationTemplateUseBlocks();
	boolean generateComments = preferences.isCodeGenerationTemplateGenerateComments();
	TextEdit edit = generateHashCodeEqualsTextEdit(type, params.fields, params.regenerate, useJava7Objects, useInstanceof, useBlocks, generateComments);
	return (edit == null) ? null : SourceAssistProcessor.convertToWorkspaceEdit(type.getCompilationUnit(), edit);
}
 
Example #27
Source File: MultiImportOrganizer.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @param files
 *            ordered by corresponding {@link IProject}
 * @param mon
 * @return Creates {@link Change}s for each {@link IFile} using {@link ImportOrganizer}
 * @throws InterruptedException
 */
public List<Change> organizeImports(Multimap<IProject, IFile> files, IProgressMonitor mon)
		throws InterruptedException {
	List<Change> result = Lists.newArrayList();
	for (IProject project : files.keySet()) {
		ResourceSet resSet = resSetProvider.get(project);
		for (IFile file : files.get(project)) {
			mon.subTask("Calculating imports in - " + file.getName());
			URI uri = storageMapper.getUri(file);
			if (uri != null) {
				XtextResource resource = (XtextResource) resSet.getResource(uri, true);
				List<ReplaceRegion> replace = importOrganizer.getOrganizedImportChanges(resource);
				//TODO - find out why \n\n changes are produced, even if there are any unused imports
				if (replace == null || replace.isEmpty()) {
					continue;
				}
				TextEdit textEdit = replaceConverter.convertToTextEdit(replace);
				IRefactoringDocument iRefactoringDocument = provider.get(uri, status);
				if (iRefactoringDocument != null) {
					Change change = iRefactoringDocument.createChange(Messages.OrganizeImports, textEdit);
					if (change instanceof EditorDocumentChange) {
						if (((EditorDocument) iRefactoringDocument).getEditor().isDirty()) {
							((EditorDocumentChange) change).setDoSave(false);
						}
					}
					result.add(change);
				}
			}
			mon.worked(1);
			if (mon.isCanceled()) {
				throw new InterruptedException();
			}
		}
	}
	return result;
}
 
Example #28
Source File: CodeUtils.java    From minnal with Apache License 2.0 5 votes vote down vote up
public static String format(String code, Map<String, String> options) {
    DefaultCodeFormatterOptions cfOptions = DefaultCodeFormatterOptions.getJavaConventionsSettings();
    cfOptions.tab_char = DefaultCodeFormatterOptions.TAB;
    CodeFormatter cf = new DefaultCodeFormatter(cfOptions, options);
    TextEdit te = cf.format(CodeFormatter.K_UNKNOWN, code, 0, code.length(), 0, null);
    IDocument dc = new Document(code);

    try {
        te.apply(dc);
    } catch (Exception e) {
        throw new MinnalGeneratorException("Failed while formatting the code", e);
    }
    return dc.get();
}
 
Example #29
Source File: FormatterHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static org.eclipse.lsp4j.TextEdit convertEdit(TextEdit edit, IDocument document) {
	org.eclipse.lsp4j.TextEdit textEdit = new org.eclipse.lsp4j.TextEdit();
	if (edit instanceof ReplaceEdit) {
		ReplaceEdit replaceEdit = (ReplaceEdit) edit;
		textEdit.setNewText(replaceEdit.getText());
		int offset = edit.getOffset();
		textEdit.setRange(new Range(createPosition(document, offset), createPosition(document, offset + edit.getLength())));
	}
	return textEdit;
}
 
Example #30
Source File: DefaultCodeFormatter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private TextEdit formatClassBodyDeclarations(String source, int indentationLevel, String lineSeparator, IRegion[] regions, boolean includeComments) {
	ASTNode[] bodyDeclarations = this.codeSnippetParsingUtil.parseClassBodyDeclarations(source.toCharArray(), getDefaultCompilerOptions(), true);

	if (bodyDeclarations == null) {
		// a problem occurred while parsing the source
		return null;
	}
	return internalFormatClassBodyDeclarations(source, indentationLevel, lineSeparator, bodyDeclarations, regions, includeComments);
}