List of usage examples for org.eclipse.jdt.core.formatter CodeFormatter F_INCLUDE_COMMENTS
int F_INCLUDE_COMMENTS
To view the source code for org.eclipse.jdt.core.formatter CodeFormatter F_INCLUDE_COMMENTS.
Click Source Link
From source file:com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.java
License:Open Source License
private static String format(IProject project, String contents, IPath to) { String name = to.lastSegment(); if (name.endsWith(DOT_XML)) { XmlFormatStyle formatStyle = EclipseXmlPrettyPrinter.getForFile(to); EclipseXmlFormatPreferences prefs = EclipseXmlFormatPreferences.create(); return EclipseXmlPrettyPrinter.prettyPrint(contents, prefs, formatStyle, null); } else if (name.endsWith(DOT_JAVA)) { Map<?, ?> options = null; if (project != null && project.isAccessible()) { try { IJavaProject javaProject = BaseProjectHelper.getJavaProject(project); if (javaProject != null) { options = javaProject.getOptions(true); }// ww w . j a v a2 s . c o m } catch (CoreException e) { AdtPlugin.log(e, null); } } if (options == null) { options = JavaCore.getOptions(); } CodeFormatter formatter = ToolFactory.createCodeFormatter(options); try { IDocument doc = new org.eclipse.jface.text.Document(); // format the file (the meat and potatoes) doc.set(contents); TextEdit edit = formatter.format( CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, contents, 0, contents.length(), 0, null); if (edit != null) { edit.apply(doc); } return doc.get(); } catch (Exception e) { AdtPlugin.log(e, null); } } return contents; }
From source file:com.diffplug.gradle.spotless.java.eclipse.EclipseFormatterStepImpl.java
License:Apache License
public String format(String raw) throws Exception { TextEdit edit = codeFormatter.format(CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, raw, 0, raw.length(), 0, UNIX); if (edit == null) { throw new IllegalArgumentException("Invalid java syntax for formatting."); } else {//from w w w.java2 s. c o m IDocument doc = new Document(raw); edit.apply(doc); return doc.get(); } }
From source file:com.diffplug.spotless.extra.eclipse.java.EclipseJdtFormatterStepImpl.java
License:Apache License
public String format(String raw) throws Exception { TextEdit edit = codeFormatter.format(CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, raw, 0, raw.length(), 0, SpotlessEclipseFramework.LINE_DELIMITER); if (edit == null) { throw new IllegalArgumentException("Invalid java syntax for formatting."); } else {/*from w w w. ja v a 2s. c o m*/ IDocument doc = new Document(raw); edit.apply(doc); return doc.get(); } }
From source file:com.google.gdt.eclipse.platform.jdt.formatter.CodeFormatterFlags.java
License:Open Source License
public static int getFlagsForCompilationUnitFormat() { return CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS; }
From source file:com.google.googlejavaformat.java.GoogleJavaFormatter.java
License:Apache License
/** Runs the Google Java formatter on the given source, with only the given ranges specified. */ private TextEdit formatInternal(int kind, String source, IRegion[] regions, int initialIndent) { try {//from ww w . ja va 2 s . com boolean includeComments = (kind & CodeFormatter.F_INCLUDE_COMMENTS) == CodeFormatter.F_INCLUDE_COMMENTS; kind &= ~CodeFormatter.F_INCLUDE_COMMENTS; SnippetKind snippetKind; switch (kind) { case ASTParser.K_EXPRESSION: snippetKind = SnippetKind.EXPRESSION; break; case ASTParser.K_STATEMENTS: snippetKind = SnippetKind.STATEMENTS; break; case ASTParser.K_CLASS_BODY_DECLARATIONS: snippetKind = SnippetKind.CLASS_BODY_DECLARATIONS; break; case ASTParser.K_COMPILATION_UNIT: snippetKind = SnippetKind.COMPILATION_UNIT; break; default: throw new IllegalArgumentException(String.format("Unknown snippet kind: %d", kind)); } List<Replacement> replacements = new SnippetFormatter().format(snippetKind, source, rangesFromRegions(regions), initialIndent, includeComments); if (idempotent(source, regions, replacements)) { // Do not create edits if there's no diff. return null; } // Convert replacements to text edits. return editFromReplacements(replacements); } catch (IllegalArgumentException | FormatterException exception) { // Do not format on errors. return null; } }
From source file:com.marvinformatics.formatter.java.JavaFormatter.java
License:Apache License
public String format(String code) { final TextEdit te = formatter.format(CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, code, 0, code.length(), 0, lineEnding.getChars()); if (te == null) throw new IllegalArgumentException( "Code cannot be formatted. Possible cause " + "is unmatched source/target/compliance version."); final IDocument doc = new Document(code); try {// w w w. jav a 2s . c o m te.apply(doc); } catch (MalformedTreeException | BadLocationException e) { throw new IllegalStateException("Code cannot be formatted. original code:\n" + code); } return doc.get(); }
From source file:com.motorola.studio.android.codeutils.db.utils.DatabaseUtils.java
License:Apache License
/** * Formats the code using the Eclipse Java settings if possible, * otherwise returns original document not indented. * @param destinationFile Destination file. * @param databaseHelperText Text to generate. * @param monitor A progress monitor to be used to show operation status. * @return Created document.//from w w w . java2 s.c o m */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static IDocument formatCode(IFile destinationFile, String databaseHelperText, IProgressMonitor monitor) { IDocument document = new Document(); File file = new File(destinationFile.getLocation().toOSString()); try { document.set(databaseHelperText); try { IJavaProject p = JavaCore.create(destinationFile.getProject()); Map mapOptions = p.getOptions(true); TextEdit textEdit = CodeFormatterUtil.format2( CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, document.get(), 0, System.getProperty("line.separator"), mapOptions); if (textEdit != null) { textEdit.apply(document); } } catch (Exception ex) { //do nothing } BufferedWriter out = new BufferedWriter(new FileWriter(file)); try { out.write(document.get()); out.flush(); } finally { try { out.close(); } catch (IOException e) { /* ignore */ } } // the refresh is needed in order to avoid the user to have to press F5 destinationFile.getParent().refreshLocal(IResource.DEPTH_INFINITE, monitor); } catch (Exception e) { String errMsg = NLS.bind(CodeUtilsNLS.EXC_JavaClass_ErrorFormattingSourceCode, destinationFile.getName()); StudioLogger.error(DatabaseUtils.class, errMsg, e); } return document; }
From source file:com.motorola.studio.android.model.ActivityBasedOnTemplate.java
License:Apache License
/** * Creates the Java Class file based on text template file * //w ww . java 2 s .co m * @param sourcePath The path to the file * @param monitor The progress monitor * @throws JavaModelException * @throws AndroidException */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected void createJavaClassFileFromTemplate(String[] sourcePath, IProgressMonitor monitor) throws JavaModelException, AndroidException { //only one class supported for (int i = 0; i < sourcePath.length; i++) { String loadedTemplate = EclipseUtils.readEmbeddedResource(CodeUtilsActivator.getDefault().getBundle(), sourcePath[i]); String packageName = getPackageFragment().getElementName(); loadedTemplate = loadedTemplate.replaceAll(CLASS_REPLACE_TAG, getName()); loadedTemplate = loadedTemplate.replaceAll(PACKAGE_REPLACE_TAG, packageName); loadedTemplate = loadedTemplate.replaceAll("#FILL_PARENT_LPARAM#", getApiVersion() > 7 ? "MATCH_PARENT" : "FILL_PARENT"); try { loadedTemplate = loadedTemplate.replaceAll("#ManifestPackageName#", //$NON-NLS-1$ getManifestPackageName(getProject())); } catch (CoreException e) { throw new AndroidException("Failed to get manifest file to add import from R", e); //$NON-NLS-1$ } if ((sample != null) && sample.equals(ActivityBasedOnTemplate.DATABASE_LIST_SAMPLE_LOCALIZED)) { collector = getDatabaseSampleActivityParametersWizardCollector(); if (collector != null) { collector.setDatabaseName(this.collectorDatabaseName); collector.setTable(this.collectorTable); collector.setSelectedColumns(collectorColumnList); collector.setSqlOpenHelperClassName(getSqlOpenHelperClassName()); collector.setSqlOpenHelperPackageName(getSqlOpenHelperPackageName()); collector.setCreateOpenHelper(isCreateOpenHelper()); //using Database list sample - it is an special case because it get data from an specific .db table loadedTemplate = loadedTemplate.replaceAll("#dbName#", collector.getDatabaseName()); //$NON-NLS-1$ loadedTemplate = loadedTemplate.replaceAll("#tableName#", collector.getTableName()); //$NON-NLS-1$ loadedTemplate = loadedTemplate.replaceAll("#tableNameUpperCase#", collector.getTableName() //$NON-NLS-1$ .toUpperCase()); loadedTemplate = loadedTemplate.replaceAll("#tableNameLowerCase#", collector.getTableName() //$NON-NLS-1$ .toLowerCase()); loadedTemplate = loadedTemplate.replaceAll("#columsNames#", collector.getColumnsNames()); //$NON-NLS-1$ loadedTemplate = loadedTemplate.replaceAll("#constColumnsNames#", //$NON-NLS-1$ collector.getConstColumnsNames()); loadedTemplate = loadedTemplate.replaceAll("#columnGetValues#", collector.getCursorValues()); //$NON-NLS-1$ loadedTemplate = loadedTemplate.replaceAll("#columnAddRows#", collector.getAddColumnsToRow()); //$NON-NLS-1$ loadedTemplate = loadedTemplate.replaceAll("#sqlOpenHelperName#", //$NON-NLS-1$ getSqlOpenHelperClassName()); loadedTemplate = loadedTemplate.replaceAll("#imports#", collector.getImports()); //$NON-NLS-1$ loadedTemplate = loadedTemplate.replaceAll("#getReadableDatabase#", //$NON-NLS-1$ collector.getReadableDatabase()); if (isCreateOpenHelper()) { collector.createSqlOpenHelper(getProject(), monitor); } } } //replace the main activity of the project, first used by action_bar template try { //assume mainActivity be the activity we are creating (if the project has no main activity). Try to find the real main activity if the isMainActivity flag is false. String mainActivityName = getName(); if (!isMainActivity) { ActivityNode mainActivityNode = AndroidProjectManifestFile.getFromProject(getProject()) .getMainActivity(); if (mainActivityNode != null) { mainActivityName = mainActivityNode.getNodeProperties().get("android:name"); //remove a possible '.' that activities may contain before the name if ((mainActivityName.length() > 0) && (mainActivityName.charAt(0) == '.')) { mainActivityName = mainActivityName.substring(1, mainActivityName.length()); } } } loadedTemplate = loadedTemplate.replaceAll(MAIN_ACTIVITY_REPLACE_TAG, mainActivityName); } catch (CoreException e) { StudioLogger.error("Could not get Android Manifest File from project."); } loadedTemplate = replaceResourceNames(loadedTemplate); IPackageFragment targetPackage = getPackageFragmentRoot() .getPackageFragment(getPackageFragment().getElementName()); if (!targetPackage.exists()) { getPackageFragmentRoot().createPackageFragment(targetPackage.getElementName(), true, monitor); } /* * Create activity class. Only the first src resource will become the Activity subclass. * The other classes will be copied AS IS */ String resourceName = i == 0 ? getName() + JAVA_EXTENSION : Path.fromPortableString(sourcePath[i]).lastSegment(); ICompilationUnit cu = targetPackage.createCompilationUnit(resourceName, loadedTemplate, true, monitor); //indent activity class try { ICompilationUnit workingCopy = cu.getWorkingCopy(monitor); IDocument document = new DocumentAdapter(workingCopy.getBuffer()); //get project indentation configuration Map mapOptions = JavaCore.create(getProject()).getOptions(true); //changes to be applyed to the document TextEdit textEdit = CodeFormatterUtil.format2( CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, document.get(), 0, System.getProperty("line.separator"), mapOptions); //$NON-NLS-1$ workingCopy.applyTextEdit(textEdit, monitor); workingCopy.reconcile(ICompilationUnit.NO_AST, false, null, null); workingCopy.commitWorkingCopy(true, monitor); workingCopy.discardWorkingCopy(); } catch (Exception ex) { //do nothing - indentation fails } } }
From source file:com.motorola.studio.android.model.java.JavaClass.java
License:Apache License
/** * Gets the class content//from w w w .j a v a 2s . co m * * @return an IDocument object containing the class content */ public IDocument getClassContent() throws AndroidException { String content = compUnit.toString(); document = new Document(content); // Formats the code using the Eclipse settings CodeFormatter codeFormatter = ToolFactory .createCodeFormatter(DefaultCodeFormatterConstants.getEclipseDefaultSettings()); TextEdit textEdit = codeFormatter.format( CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS, content, 0, content.length(), 0, null); try { textEdit.apply(document); } catch (MalformedTreeException e) { String errMsg = NLS.bind(CodeUtilsNLS.EXC_JavaClass_ErrorFormattingSourceCode, className); StudioLogger.error(JavaClass.class, errMsg, e); throw new AndroidException(errMsg); } catch (BadLocationException e) { String errMsg = NLS.bind(CodeUtilsNLS.EXC_JavaClass_ErrorFormattingSourceCode, className); StudioLogger.error(JavaClass.class, errMsg, e); throw new AndroidException(errMsg); } addComments(); return document; }
From source file:com.payex.utils.formatter.FormatExecutor.java
License:Apache License
/** * Format individual file.//from w w w . java2s .co m * * @param file * @param rc * @param hashCache * @param basedirPath * @throws IOException * @throws BadLocationException */ private void doFormatFile(File file, ResultCollector rc, Properties hashCache, String basedirPath) throws IOException, BadLocationException { log.debug("Processing file: " + file); String code = new String(Files.readAllBytes(file.toPath()));// readFileAsString(file); String lineSeparator = getLineEnding(code); TextEdit te = formatter.format(CodeFormatter.K_COMPILATION_UNIT + CodeFormatter.F_INCLUDE_COMMENTS, code, 0, code.length(), 0, lineSeparator); if (te == null) { rc.skippedCount++; log.debug( "Code cannot be formatted. Possible cause " + "is unmatched source/target/compliance version."); return; } IDocument doc = new Document(code); te.apply(doc); String formattedCode = doc.get(); writeStringToFile(formattedCode, file); rc.successCount++; }