org.eclipse.jdt.internal.corext.util.CodeFormatterUtil Java Examples
The following examples show how to use
org.eclipse.jdt.internal.corext.util.CodeFormatterUtil.
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: GetterSetterCompletionProposal.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
/** * @param document * @param offset * @param importRewrite * @param completionSnippetsSupported * @param addComments * @return * @throws CoreException * @throws BadLocationException */ public String updateReplacementString(IDocument document, int offset, ImportRewrite importRewrite, boolean completionSnippetsSupported, boolean addComments) throws CoreException, BadLocationException { int flags= Flags.AccPublic | (fField.getFlags() & Flags.AccStatic); String stub; if (fIsGetter) { String getterName= GetterSetterUtil.getGetterName(fField, null); stub = GetterSetterUtil.getGetterStub(fField, getterName, addComments, flags); } else { String setterName= GetterSetterUtil.getSetterName(fField, null); stub = GetterSetterUtil.getSetterStub(fField, setterName, addComments, flags); } // use the code formatter String lineDelim= TextUtilities.getDefaultLineDelimiter(document); String replacement = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, stub, 0, lineDelim, fField.getJavaProject()); if (replacement.endsWith(lineDelim)) { replacement = replacement.substring(0, replacement.length() - lineDelim.length()); } return replacement; }
Example #2
Source File: ProjectResources.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 6 votes |
/** * Given a String containing the text of a Java source file, return the same * Java source, but reformatted by the Eclipse auto-format code, with the * user's current Java preferences. */ public static String reformatJavaSourceAsString(String source) { TextEdit reformatTextEdit = CodeFormatterUtil.format2( CodeFormatter.K_COMPILATION_UNIT, source, 0, (String) null, JavaCore.getOptions()); if (reformatTextEdit != null) { Document document = new Document(source); try { reformatTextEdit.apply(document, TextEdit.NONE); source = document.get(); } catch (BadLocationException ble) { CorePluginLog.logError(ble); } } return source; }
Example #3
Source File: JsniMethodBodyCompletionProposalComputer.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 6 votes |
/** * Creates the standard JSNI delimiter blocks. This method is default access * to facilitate testing. */ static String createJsniBlock(IJavaProject project, String body, int indentationUnits) { StringBuilder sb = new StringBuilder(); sb.append("/*-{\n"); sb.append(CodeFormatterUtil.createIndentString(indentationUnits + 1, project)); if (body != null) { sb.append(body); } sb.append("\n"); sb.append(CodeFormatterUtil.createIndentString(indentationUnits, project)); sb.append("}-*/;\n"); return sb.toString(); }
Example #4
Source File: JavaMethodCompletionProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
/** * Appends everything up to the method name including * the opening parenthesis. * <p> * In case of {@link CompletionProposal#METHOD_REF_WITH_CASTED_RECEIVER} * it add cast. * </p> * * @param buffer the string buffer * @since 3.4 */ protected void appendMethodNameReplacement(StringBuffer buffer) { if (fProposal.getKind() == CompletionProposal.METHOD_REF_WITH_CASTED_RECEIVER) { String coreCompletion= String.valueOf(fProposal.getCompletion()); String lineDelimiter= TextUtilities.getDefaultLineDelimiter(getTextViewer().getDocument()); String replacement= CodeFormatterUtil.format(CodeFormatter.K_EXPRESSION, coreCompletion, 0, lineDelimiter, fInvocationContext.getProject()); buffer.append(replacement.substring(0, replacement.lastIndexOf('.') + 1)); } if (fProposal.getKind() != CompletionProposal.CONSTRUCTOR_INVOCATION) buffer.append(fProposal.getName()); FormatterPrefs prefs= getFormatterPrefs(); if (prefs.beforeOpeningParen) buffer.append(SPACE); buffer.append(LPAREN); }
Example #5
Source File: JavaStringAutoIndentStrategy.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
/** * Returns extra indentation string for strings that are broken by a newline * based on the value of the formatter preferences for tabs vs. spaces. * * @return two tabs or equivalent number of spaces */ private String getExtraIndentAfterNewLine() { // read settings int formatterContinuationIndentationSize= getContinuationIndentationSize(); int binaryAlignmentValue= getBinaryOperatorAlignmentStyle(); // work out indent int indentSize= formatterContinuationIndentationSize; if (binaryAlignmentValue == DefaultCodeFormatterConstants.INDENT_BY_ONE) { indentSize= 1; } else if (binaryAlignmentValue == DefaultCodeFormatterConstants.INDENT_ON_COLUMN) { // there is no obvious way to work out the current column indent } // generate indentation string with correct size return CodeFormatterUtil.createIndentString(indentSize, fProject); }
Example #6
Source File: JavaFormatter.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
private void format(IDocument doc, CompilationUnitContext context) throws BadLocationException { Map<String, String> options; IJavaProject project= context.getJavaProject(); if (project != null) options= project.getOptions(true); else options= JavaCore.getOptions(); String contents= doc.get(); int[] kinds= { CodeFormatter.K_EXPRESSION, CodeFormatter.K_STATEMENTS, CodeFormatter.K_UNKNOWN}; TextEdit edit= null; for (int i= 0; i < kinds.length && edit == null; i++) { edit= CodeFormatterUtil.format2(kinds[i], contents, fInitialIndentLevel, fLineDelimiter, options); } if (edit == null) throw new BadLocationException(); // fall back to indenting edit.apply(doc, TextEdit.UPDATE_REGIONS); }
Example #7
Source File: IndentUtil.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
/** * Indents the line range specified by <code>lines</code> in * <code>document</code>. The passed Java project may be * <code>null</code>, it is used solely to obtain formatter preferences. * * @param document the document to be changed * @param lines the line range to be indented * @param project the Java project to get the formatter preferences from, or * <code>null</code> if global preferences should be used * @param result the result from a previous call to <code>indentLines</code>, * in order to maintain comment line properties, or <code>null</code>. * Note that the passed result may be changed by the call. * @return an indent result that may be queried for changes and can be * reused in subsequent indentation operations * @throws BadLocationException if <code>lines</code> is not a valid line * range on <code>document</code> */ public static IndentResult indentLines(IDocument document, ILineRange lines, IJavaProject project, IndentResult result) throws BadLocationException { int numberOfLines= lines.getNumberOfLines(); if (numberOfLines < 1) return new IndentResult(null); result= reuseOrCreateToken(result, numberOfLines); JavaHeuristicScanner scanner= new JavaHeuristicScanner(document); JavaIndenter indenter= new JavaIndenter(document, scanner, project); boolean changed= false; int tabSize= CodeFormatterUtil.getTabWidth(project); for (int line= lines.getStartLine(), last= line + numberOfLines, i= 0; line < last; line++) { changed |= indentLine(document, line, indenter, scanner, result.commentLinesAtColumnZero, i++, tabSize); } result.hasChanged= changed; return result; }
Example #8
Source File: JavaSourceViewerConfiguration.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
@Override public String[] getIndentPrefixes(ISourceViewer sourceViewer, String contentType) { IJavaProject project= getProject(); final int tabWidth= CodeFormatterUtil.getTabWidth(project); final int indentWidth= CodeFormatterUtil.getIndentWidth(project); boolean allowTabs= tabWidth <= indentWidth; String indentMode; if (project == null) indentMode= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR); else indentMode= project.getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, true); boolean useSpaces= JavaCore.SPACE.equals(indentMode) || DefaultCodeFormatterConstants.MIXED.equals(indentMode); Assert.isLegal(allowTabs || useSpaces); if (!allowTabs) { char[] spaces= new char[indentWidth]; Arrays.fill(spaces, ' '); return new String[] { new String(spaces), "" }; //$NON-NLS-1$ } else if (!useSpaces) return getIndentPrefixesForTab(tabWidth); else return getIndentPrefixesForSpaces(tabWidth); }
Example #9
Source File: CompletionProposalCollector.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 6 votes |
/** * Creates the Java completion proposal for the JDT Core * {@link CompletionProposal#FIELD_REF_WITH_CASTED_RECEIVER} proposal. * * @param proposal the JDT Core proposal * @return the Java completion proposal * @since 3.4 */ private IJavaCompletionProposal createFieldWithCastedReceiverProposal(CompletionProposal proposal) { String completion= String.valueOf(proposal.getCompletion()); completion= CodeFormatterUtil.format(CodeFormatter.K_EXPRESSION, completion, 0, "\n", fJavaProject); //$NON-NLS-1$ int start= proposal.getReplaceStart(); int length= getLength(proposal); StyledString label= fLabelProvider.createStyledLabel(proposal); Image image= getImage(fLabelProvider.createFieldImageDescriptor(proposal)); int relevance= computeRelevance(proposal); JavaCompletionProposal javaProposal= new JavaFieldWithCastedReceiverCompletionProposal(completion, start, length, image, label, relevance, getContext().isInJavadoc(), getInvocationContext(), proposal); if (fJavaProject != null) javaProposal.setProposalInfo(new FieldProposalInfo(fJavaProject, proposal)); javaProposal.setTriggerCharacters(VAR_TRIGGER); return javaProposal; }
Example #10
Source File: AnonymousTypeCompletionProposal.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
public String updateReplacementString(IDocument document, int offset, ImportRewrite impRewrite) throws CoreException, BadLocationException { // Construct empty body for performance concern // See https://github.com/microsoft/language-server-protocol/issues/1032#issuecomment-648748013 String newBody = fSnippetSupport ? "{\n\t${0}\n}" : "{\n\n}"; StringBuilder buf = new StringBuilder("new A()"); //$NON-NLS-1$ buf.append(newBody); // use the code formatter String lineDelim = TextUtilities.getDefaultLineDelimiter(document); final IJavaProject project = fCompilationUnit.getJavaProject(); IRegion lineInfo = document.getLineInformationOfOffset(fReplacementOffset); Map<String, String> options = project != null ? project.getOptions(true) : JavaCore.getOptions(); String replacementString = CodeFormatterUtil.format(CodeFormatter.K_EXPRESSION, buf.toString(), 0, lineDelim, options); int lineEndOffset = lineInfo.getOffset() + lineInfo.getLength(); int p = offset; if (p < document.getLength()) { char ch = document.getChar(p); while (p < lineEndOffset) { if (ch == '(' || ch == ')' || ch == ';' || ch == ',') { break; } ch = document.getChar(++p); } if (ch != ';' && ch != ',' && ch != ')') { replacementString = replacementString + ';'; } } int beginIndex = replacementString.indexOf('('); replacementString = replacementString.substring(beginIndex); return replacementString; }
Example #11
Source File: JavaPreferencesSettings.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
public static CodeGenerationSettings getCodeGenerationSettings(IJavaProject project) { CodeGenerationSettings res= new CodeGenerationSettings(); res.createComments= Boolean.valueOf(PreferenceConstants.getPreference(PreferenceConstants.CODEGEN_ADD_COMMENTS, project)).booleanValue(); res.useKeywordThis= Boolean.valueOf(PreferenceConstants.getPreference(PreferenceConstants.CODEGEN_KEYWORD_THIS, project)).booleanValue(); res.overrideAnnotation= Boolean.valueOf(PreferenceConstants.getPreference(PreferenceConstants.CODEGEN_USE_OVERRIDE_ANNOTATION, project)).booleanValue(); res.importIgnoreLowercase= Boolean.valueOf(PreferenceConstants.getPreference(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE, project)).booleanValue(); res.tabWidth= CodeFormatterUtil.getTabWidth(project); res.indentWidth= CodeFormatterUtil.getIndentWidth(project); return res; }
Example #12
Source File: SnippetPreview.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
@Override protected void doFormatPreview() { if (fSnippets.isEmpty()) { fPreviewDocument.set(""); //$NON-NLS-1$ return; } //This delimiter looks best for invisible characters final String delimiter= "\n"; //$NON-NLS-1$ final StringBuffer buffer= new StringBuffer(); for (final Iterator<PreviewSnippet> iter= fSnippets.iterator(); iter.hasNext();) { final PreviewSnippet snippet= iter.next(); String formattedSource; try { formattedSource= CodeFormatterUtil.format(snippet.kind, snippet.source, 0, delimiter, fWorkingValues); } catch (Exception e) { final IStatus status= new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, FormatterMessages.JavaPreview_formatter_exception, e); JavaPlugin.log(status); continue; } buffer.append(delimiter); buffer.append(formattedSource); buffer.append(delimiter); buffer.append(delimiter); } fPreviewDocument.set(buffer.toString()); }
Example #13
Source File: GetterSetterCompletionProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
@Override protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportRewrite impRewrite) throws CoreException, BadLocationException { CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(fField.getJavaProject()); boolean addComments= settings.createComments; int flags= Flags.AccPublic | (fField.getFlags() & Flags.AccStatic); String stub; if (fIsGetter) { String getterName= GetterSetterUtil.getGetterName(fField, null); stub= GetterSetterUtil.getGetterStub(fField, getterName, addComments, flags); } else { String setterName= GetterSetterUtil.getSetterName(fField, null); stub= GetterSetterUtil.getSetterStub(fField, setterName, addComments, flags); } // use the code formatter String lineDelim= TextUtilities.getDefaultLineDelimiter(document); IRegion region= document.getLineInformationOfOffset(getReplacementOffset()); int lineStart= region.getOffset(); int indent= Strings.computeIndentUnits(document.get(lineStart, getReplacementOffset() - lineStart), settings.tabWidth, settings.indentWidth); String replacement= CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, stub, indent, lineDelim, fField.getJavaProject()); if (replacement.endsWith(lineDelim)) { replacement= replacement.substring(0, replacement.length() - lineDelim.length()); } setReplacementString(Strings.trimLeadingTabsAndSpaces(replacement)); return true; }
Example #14
Source File: JavaAutoIndentStrategy.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
/** * Indents line <code>line</code> in <code>document</code> with <code>indent</code>. * Leaves leading comment signs alone. * * @param document the document * @param line the line * @param indent the indentation to insert * @param tabLength the length of a tab * @throws BadLocationException on concurrent document modification */ private void addIndent(Document document, int line, CharSequence indent, int tabLength) throws BadLocationException { IRegion region= document.getLineInformation(line); int insert= region.getOffset(); int endOffset= region.getOffset() + region.getLength(); // Compute insert after all leading line comment markers int newInsert= insert; while (newInsert < endOffset - 2 && document.get(newInsert, 2).equals(LINE_COMMENT)) newInsert += 2; // Heuristic to check whether it is commented code or just a comment if (newInsert > insert) { int whitespaceCount= 0; int i= newInsert; while (i < endOffset - 1) { char ch= document.get(i, 1).charAt(0); if (!Character.isWhitespace(ch)) break; whitespaceCount= whitespaceCount + computeVisualLength(ch, tabLength); i++; } if (whitespaceCount != 0 && whitespaceCount >= CodeFormatterUtil.getIndentWidth(fProject)) insert= newInsert; } // Insert indent document.replace(insert, 0, indent.toString()); }
Example #15
Source File: DelegateCreator.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
/** * Performs the actual rewriting and adds an edit to the ASTRewrite set with * {@link #setSourceRewrite(CompilationUnitRewrite)}. * * @throws JavaModelException */ public void createEdit() throws JavaModelException { try { IDocument document= new Document(fDelegateRewrite.getCu().getBuffer().getContents()); TextEdit edit= fDelegateRewrite.getASTRewrite().rewriteAST(document, fDelegateRewrite.getCu().getJavaProject().getOptions(true)); edit.apply(document, TextEdit.UPDATE_REGIONS); int tabWidth = CodeFormatterUtil.getTabWidth(fOriginalRewrite.getCu().getJavaProject()); int identWidth = CodeFormatterUtil.getIndentWidth(fOriginalRewrite.getCu().getJavaProject()); String newSource= Strings.trimIndentation(document.get(fTrackedPosition.getStartPosition(), fTrackedPosition.getLength()), tabWidth, identWidth, false); ASTNode placeholder= fOriginalRewrite.getASTRewrite().createStringPlaceholder(newSource, fDeclaration.getNodeType()); CategorizedTextEditGroup groupDescription= fOriginalRewrite.createCategorizedGroupDescription(getTextEditGroupLabel(), CATEGORY_DELEGATE); ListRewrite bodyDeclarationsListRewrite= fOriginalRewrite.getASTRewrite().getListRewrite(fDeclaration.getParent(), getTypeBodyDeclarationsProperty()); if (fCopy) { if (fInsertBefore) { bodyDeclarationsListRewrite.insertBefore(placeholder, fDeclaration, groupDescription); } else { bodyDeclarationsListRewrite.insertAfter(placeholder, fDeclaration, groupDescription); } } else { bodyDeclarationsListRewrite.replace(fDeclaration, placeholder, groupDescription); } } catch (BadLocationException e) { //JavaPlugin.log(e); } }
Example #16
Source File: PreferenceManager.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
public static CodeGenerationSettings getCodeGenerationSettings(IResource resource) { IJavaProject project = JavaCore.create(resource.getProject()); CodeGenerationSettings res = new CodeGenerationSettings(); res.overrideAnnotation = true; res.createComments = false; // TODO indentation settings should be retrieved from client/external // settings? res.tabWidth = CodeFormatterUtil.getTabWidth(project); res.indentWidth = CodeFormatterUtil.getIndentWidth(project); return res; }
Example #17
Source File: JavaFormatter.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private void indent(IDocument document) throws BadLocationException, MalformedTreeException { // first line int offset= document.getLineOffset(0); document.replace(offset, 0, CodeFormatterUtil.createIndentString(fInitialIndentLevel, fProject)); // following lines int lineCount= document.getNumberOfLines(); IndentUtil.indentLines(document, new LineRange(1, lineCount - 1), fProject, null); }
Example #18
Source File: ASTNodes.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
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 #19
Source File: SourceProvider.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
private String[] getBlocks(RangeMarker[] markers) throws BadLocationException { String[] result= new String[markers.length]; for (int i= 0; i < markers.length; i++) { RangeMarker marker= markers[i]; String content= fDocument.get(marker.getOffset(), marker.getLength()); String lines[]= Strings.convertIntoLines(content); Strings.trimIndentation(lines, fTypeRoot.getJavaProject(), false); if (fMarkerMode == STATEMENT_MODE && lines.length == 2 && isSingleControlStatementWithoutBlock()) { lines[1]= CodeFormatterUtil.createIndentString(1, fTypeRoot.getJavaProject()) + lines[1]; } result[i]= Strings.concatenate(lines, TextUtilities.getDefaultLineDelimiter(fDocument)); } return result; }
Example #20
Source File: JsniMethodBodyCompletionProposalComputer.java From gwt-eclipse-plugin with Eclipse Public License 1.0 | 5 votes |
/** * Proposes an JSNI method where the cursor is inside of the JSNI block and * set to the proper indentation for the file. */ private void proposeEmptyJsniBlock(IJavaProject project, IMethod method, int invocationOffset, int indentationUnits, List<ICompletionProposal> proposals, int numCharsFilled, int numCharsToOverwrite) throws JavaModelException { String code = createJsniBlock(project, "", indentationUnits); int cursorPosition = (CodeFormatterUtil.createIndentString( indentationUnits + 1, project)).length() + (5 - numCharsFilled); JavaCompletionProposal javaCompletionProposal = createProposal( method.getFlags(), code, invocationOffset, numCharsFilled, numCharsToOverwrite, ""); javaCompletionProposal.setCursorPosition(cursorPosition); proposals.add(javaCompletionProposal); }
Example #21
Source File: JavaSourceViewerConfiguration.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
@Override public int getTabWidth(ISourceViewer sourceViewer) { return CodeFormatterUtil.getTabWidth(getProject()); }
Example #22
Source File: SmartTypingConfigurationBlock.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
private int getTabDisplaySize() { return CodeFormatterUtil.getTabWidth(null); }
Example #23
Source File: SmartTypingConfigurationBlock.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
private int getIndentSize() { return CodeFormatterUtil.getIndentWidth(null); }
Example #24
Source File: JavaIndenter.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
private int prefIndentationSize() { return CodeFormatterUtil.getIndentWidth(fProject); }
Example #25
Source File: JavaIndenter.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
private int prefTabSize() { return CodeFormatterUtil.getTabWidth(fProject); }
Example #26
Source File: AnonymousTypeCompletionProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
@Override protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportRewrite impRewrite) throws CoreException, BadLocationException { fImportRewrite= impRewrite; String newBody= createNewBody(impRewrite); if (newBody == null) return false; CompletionProposal coreProposal= ((MemberProposalInfo)getProposalInfo()).fProposal; boolean isAnonymousConstructorInvoc= coreProposal.getKind() == CompletionProposal.ANONYMOUS_CLASS_CONSTRUCTOR_INVOCATION; boolean replacementStringEndsWithParentheses= isAnonymousConstructorInvoc || getReplacementString().endsWith(")"); //$NON-NLS-1$ // construct replacement text: an expression to be formatted StringBuffer buf= new StringBuffer("new A("); //$NON-NLS-1$ if (!replacementStringEndsWithParentheses || isAnonymousConstructorInvoc) buf.append(')'); buf.append(newBody); // use the code formatter String lineDelim= TextUtilities.getDefaultLineDelimiter(document); final IJavaProject project= fCompilationUnit.getJavaProject(); IRegion lineInfo= document.getLineInformationOfOffset(getReplacementOffset()); int indent= Strings.computeIndentUnits(document.get(lineInfo.getOffset(), lineInfo.getLength()), project); Map<String, String> options= project != null ? project.getOptions(true) : JavaCore.getOptions(); options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_EMPTY_LINES, DefaultCodeFormatterConstants.TRUE); String replacementString= CodeFormatterUtil.format(CodeFormatter.K_EXPRESSION, buf.toString(), 0, lineDelim, options); int lineEndOffset= lineInfo.getOffset() + lineInfo.getLength(); int p= offset; char ch= document.getChar(p); while (p < lineEndOffset) { if (ch == '(' || ch == ')' || ch == ';' || ch == ',') break; ch= document.getChar(++p); } if (ch != ';' && ch != ',' && ch != ')') replacementString= replacementString + ';'; replacementString= Strings.changeIndent(replacementString, 0, project, CodeFormatterUtil.createIndentString(indent, project), lineDelim); int beginIndex= replacementString.indexOf('('); if (!isAnonymousConstructorInvoc) beginIndex++; replacementString= replacementString.substring(beginIndex); int pos= offset; if (isAnonymousConstructorInvoc && (insertCompletion() ^ isInsertModeToggled())) { // Keep existing code int endPos= pos; ch= document.getChar(endPos); while (endPos < lineEndOffset && ch != '(' && ch != ')' && ch != ';' && ch != ',' && !Character.isWhitespace(ch)) ch= document.getChar(++endPos); int keepLength= endPos - pos; if (keepLength > 0) { String keepStr= document.get(pos, keepLength); replacementString= replacementString + keepStr; setCursorPosition(replacementString.length() - keepLength); } } else setCursorPosition(replacementString.length()); setReplacementString(replacementString); if (pos < document.getLength() && document.getChar(pos) == ')') { int currentLength= getReplacementLength(); if (replacementStringEndsWithParentheses) setReplacementLength(currentLength + pos - offset); else setReplacementLength(currentLength + pos - offset + 1); } return false; }
Example #27
Source File: MethodDeclarationCompletionProposal.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
@Override protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportRewrite impRewrite) throws CoreException, BadLocationException { CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(fType.getJavaProject()); boolean addComments= settings.createComments; String[] empty= new String[0]; String lineDelim= TextUtilities.getDefaultLineDelimiter(document); String declTypeName= fType.getTypeQualifiedName('.'); boolean isInterface= fType.isInterface(); StringBuffer buf= new StringBuffer(); if (addComments) { String comment= CodeGeneration.getMethodComment(fType.getCompilationUnit(), declTypeName, fMethodName, empty, empty, fReturnTypeSig, empty, null, lineDelim); if (comment != null) { buf.append(comment); buf.append(lineDelim); } } if (fReturnTypeSig != null) { if (!isInterface) { buf.append("private "); //$NON-NLS-1$ } } else { if (fType.isEnum()) buf.append("private "); //$NON-NLS-1$ else buf.append("public "); //$NON-NLS-1$ } if (fReturnTypeSig != null) { buf.append(Signature.toString(fReturnTypeSig)); } buf.append(' '); buf.append(fMethodName); if (isInterface) { buf.append("();"); //$NON-NLS-1$ buf.append(lineDelim); } else { buf.append("() {"); //$NON-NLS-1$ buf.append(lineDelim); String body= CodeGeneration.getMethodBodyContent(fType.getCompilationUnit(), declTypeName, fMethodName, fReturnTypeSig == null, "", lineDelim); //$NON-NLS-1$ if (body != null) { buf.append(body); buf.append(lineDelim); } buf.append("}"); //$NON-NLS-1$ buf.append(lineDelim); } String stub= buf.toString(); // use the code formatter IRegion region= document.getLineInformationOfOffset(getReplacementOffset()); int lineStart= region.getOffset(); int indent= Strings.computeIndentUnits(document.get(lineStart, getReplacementOffset() - lineStart), settings.tabWidth, settings.indentWidth); String replacement= CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, stub, indent, lineDelim, fType.getJavaProject()); if (replacement.endsWith(lineDelim)) { replacement= replacement.substring(0, replacement.length() - lineDelim.length()); } setReplacementString(Strings.trimLeadingTabsAndSpaces(replacement)); return true; }
Example #28
Source File: AccessorClassCreator.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
private String createAccessorCUSource(IProgressMonitor pm) throws CoreException { IProject project= getFileHandle(fAccessorPath).getProject(); String lineDelimiter= StubUtility.getLineDelimiterPreference(project); return CodeFormatterUtil.format(CodeFormatter.K_COMPILATION_UNIT, getUnformattedSource(pm), 0, lineDelimiter, fCu.getJavaProject()); }
Example #29
Source File: IndentUtil.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
/** * Shifts the line range specified by <code>lines</code> in * <code>document</code>. The amount that the lines get shifted * are determined by the first line in the range, all subsequent * lines are adjusted accordingly. The passed Java project may be * <code>null</code>, it is used solely to obtain formatter * preferences. * * @param document the document to be changed * @param lines the line range to be shifted * @param project the Java project to get the formatter preferences * from, or <code>null</code> if global preferences should * be used * @param result the result from a previous call to * <code>shiftLines</code>, in order to maintain comment * line properties, or <code>null</code>. Note that the * passed result may be changed by the call. * @return an indent result that may be queried for changes and can * be reused in subsequent indentation operations * @throws BadLocationException if <code>lines</code> is not a * valid line range on <code>document</code> */ public static IndentResult shiftLines(IDocument document, ILineRange lines, IJavaProject project, IndentResult result) throws BadLocationException { int numberOfLines= lines.getNumberOfLines(); if (numberOfLines < 1) return new IndentResult(null); result= reuseOrCreateToken(result, numberOfLines); result.hasChanged= false; JavaHeuristicScanner scanner= new JavaHeuristicScanner(document); JavaIndenter indenter= new JavaIndenter(document, scanner, project); String current= getCurrentIndent(document, lines.getStartLine()); StringBuffer correct= indenter.computeIndentation(document.getLineOffset(lines.getStartLine())); if (correct == null) return result; // bail out int tabSize= CodeFormatterUtil.getTabWidth(project); StringBuffer addition= new StringBuffer(); int difference= subtractIndent(correct, current, addition, tabSize); if (difference == 0) return result; if (result.leftmostLine == -1) result.leftmostLine= getLeftMostLine(document, lines, tabSize); int maxReduction= computeVisualLength(getCurrentIndent(document, result.leftmostLine + lines.getStartLine()), tabSize); if (difference > 0) { for (int line= lines.getStartLine(), last= line + numberOfLines, i= 0; line < last; line++) addIndent(document, line, addition, result.commentLinesAtColumnZero, i++); } else { int reduction= Math.min(-difference, maxReduction); for (int line= lines.getStartLine(), last= line + numberOfLines, i= 0; line < last; line++) cutIndent(document, line, reduction, tabSize, result.commentLinesAtColumnZero, i++); } result.hasChanged= true; return result; }
Example #30
Source File: NewPackageWizardPage.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
private void createPackageInfoJava(IProgressMonitor monitor) throws CoreException { String lineDelimiter= StubUtility.getLineDelimiterUsed(fCreatedPackageFragment.getJavaProject()); StringBuilder content = new StringBuilder(); String fileComment= getFileComment(lineDelimiter); String typeComment= getTypeComment(lineDelimiter); if (fileComment != null) { content.append(fileComment); content.append(lineDelimiter); } if (typeComment != null) { content.append(typeComment); content.append(lineDelimiter); } else if (fileComment != null) { // insert an empty file comment to avoid that the file comment becomes the type comment content.append("/**"); //$NON-NLS-1$ content.append(lineDelimiter); content.append(" *"); //$NON-NLS-1$ content.append(lineDelimiter); content.append(" */"); //$NON-NLS-1$ content.append(lineDelimiter); } content.append("package "); //$NON-NLS-1$ content.append(fCreatedPackageFragment.getElementName()); content.append(";"); //$NON-NLS-1$ ICompilationUnit compilationUnit= fCreatedPackageFragment.createCompilationUnit(PACKAGE_INFO_JAVA_FILENAME, content.toString(), true, monitor); JavaModelUtil.reconcile(compilationUnit); compilationUnit.becomeWorkingCopy(monitor); try { IBuffer buffer= compilationUnit.getBuffer(); ISourceRange sourceRange= compilationUnit.getSourceRange(); String originalContent= buffer.getText(sourceRange.getOffset(), sourceRange.getLength()); String formattedContent= CodeFormatterUtil.format(CodeFormatter.K_COMPILATION_UNIT, originalContent, 0, lineDelimiter, fCreatedPackageFragment.getJavaProject()); formattedContent= Strings.trimLeadingTabsAndSpaces(formattedContent); buffer.replace(sourceRange.getOffset(), sourceRange.getLength(), formattedContent); compilationUnit.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1)); } finally { compilationUnit.discardWorkingCopy(); } }