List of usage examples for org.eclipse.jdt.core IBuffer getChar
public char getChar(int position);
From source file:com.android.ide.eclipse.adt.internal.build.ConvertSwitchQuickFixProcessor.java
License:Open Source License
@Override public IJavaCompletionProposal[] getCorrections(IInvocationContext context, IProblemLocation[] location) throws CoreException { if (location == null || location.length == 0) { return null; }//from ww w .ja v a 2 s.c om ASTNode coveringNode = context.getCoveringNode(); if (coveringNode == null) { return null; } // Look up the fully qualified name of the non-constant expression, if any, and // make sure it's R-something. if (coveringNode.getNodeType() == ASTNode.SIMPLE_NAME) { coveringNode = coveringNode.getParent(); if (coveringNode == null) { return null; } } if (coveringNode.getNodeType() != ASTNode.QUALIFIED_NAME) { return null; } QualifiedName name = (QualifiedName) coveringNode; if (!name.getFullyQualifiedName().startsWith("R.")) { //$NON-NLS-1$ return null; } IProblemLocation error = location[0]; int errorStart = error.getOffset(); int errorLength = error.getLength(); int caret = context.getSelectionOffset(); // Even though the hasCorrections() method above will return false for everything // other than non-constant expression errors, it turns out this getCorrections() // method will ALSO be called on lines where there is no such error. In particular, // if you have an invalid cast expression like this: // Button button = findViewById(R.id.textView); // then this method will be called, and the expression will pass all of the above // checks. However, we -don't- want to show a migrate code suggestion in that case! // Therefore, we'll need to check if we're *actually* on a line with the given // problem. // // Unfortunately, we don't get passed the problemId again, and there's no access // to it. So instead we'll need to look up the markers on the line, and see // if we actually have a constant expression warning. This is not pretty!! boolean foundError = false; ICompilationUnit compilationUnit = context.getCompilationUnit(); IResource file = compilationUnit.getResource(); if (file != null) { IDocumentProvider provider = new TextFileDocumentProvider(); try { provider.connect(file); IDocument document = provider.getDocument(file); if (document != null) { List<IMarker> markers = AdtUtils.findMarkersOnLine(IMarker.PROBLEM, file, document, errorStart); for (IMarker marker : markers) { String message = marker.getAttribute(IMarker.MESSAGE, ""); // There are no other attributes in the marker we can use to identify // the exact error, so we'll need to resort to the actual message // text even though that would not work if the messages had been // localized... This can also break if the error messages change. Yuck. if (message.contains("constant expressions")) { //$NON-NLS-1$ foundError = true; } } } } catch (Exception e) { AdtPlugin.log(e, "Can't validate error message in %1$s", file.getName()); } finally { provider.disconnect(file); } } if (!foundError) { // Not a constant-expression warning, so do nothing return null; } IBuffer buffer = compilationUnit.getBuffer(); boolean sameLine = false; // See if the caret is on the same line as the error if (caret <= errorStart) { // Search backwards to beginning of line for (int i = errorStart; i >= 0; i--) { if (i <= caret) { sameLine = true; break; } char c = buffer.getChar(i); if (c == '\n') { break; } } } else { // Search forwards to the end of the line for (int i = errorStart + errorLength, n = buffer.getLength(); i < n; i++) { if (i >= caret) { sameLine = true; break; } char c = buffer.getChar(i); if (c == '\n') { break; } } } if (sameLine) { String expression = buffer.getText(errorStart, errorLength); return new IJavaCompletionProposal[] { new MigrateProposal(expression) }; } return null; }
From source file:com.android.ide.eclipse.adt.internal.refactorings.extractstring.ExtractStringProposal.java
License:Open Source License
@Override public String getAdditionalProposalInfo() { try {//from ww w . ja v a 2 s .co m ASTNode coveringNode = mContext.getCoveringNode(); int start = coveringNode.getStartPosition(); int length = coveringNode.getLength(); IBuffer buffer = mContext.getCompilationUnit().getBuffer(); StringBuilder sb = new StringBuilder(); String string = buffer.getText(start, length); string = ExtractStringRefactoring.unquoteAttrValue(string); String token = ExtractStringInputPage.guessId(string); // Look up the beginning and the end of the line (outside of the extracted string) // such that we can show a preview of the diff, e.g. if you have // foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello); // so we need to extract "foo.setTitle(" and ");". // Look backwards to the beginning of the line (and strip whitespace) int i = start - 1; while (i > 0) { char c = buffer.getChar(i); if (c == '\r' || (c == '\n')) { break; } i--; } String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim(); // Look forwards to the end of the line (and strip whitespace) i = start + length; while (i < buffer.getLength()) { char c = buffer.getChar(i); if (c == '\r' || (c == '\n')) { break; } i++; } String lineSuffix = buffer.getText(start + length, i - (start + length)); // Should we show the replacement as just R.string.foo or // context.getString(R.string.foo) ? boolean useContext = false; ASTNode parent = coveringNode.getParent(); if (parent != null) { int type = parent.getNodeType(); if (type == ASTNode.ASSIGNMENT || type == ASTNode.VARIABLE_DECLARATION_STATEMENT || type == ASTNode.VARIABLE_DECLARATION_FRAGMENT || type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) { useContext = true; } } // Display .java change: sb.append("...<br>"); //$NON-NLS-1$ sb.append(linePrefix); sb.append("<b>"); //$NON-NLS-1$ if (useContext) { sb.append("context.getString("); //$NON-NLS-1$ } sb.append("R.string."); //$NON-NLS-1$ sb.append(token); if (useContext) { sb.append(")"); //$NON-NLS-1$ } sb.append("</b>"); //$NON-NLS-1$ sb.append(lineSuffix); sb.append("<br>...<br>"); //$NON-NLS-1$ // Display strings.xml change: sb.append("<br>"); //$NON-NLS-1$ sb.append("<resources><br>"); //$NON-NLS-1$ sb.append(" <b><string name=\""); //$NON-NLS-1$ sb.append(token); sb.append("\">"); //$NON-NLS-1$ sb.append(string); sb.append("</string></b><br>"); //$NON-NLS-1$ sb.append("</resources>"); //$NON-NLS-1$ return sb.toString(); } catch (JavaModelException e) { AdtPlugin.log(e, null); } return "Initiates the Extract String refactoring operation"; }
From source file:com.codenvy.ide.ext.java.server.internal.core.Member.java
License:Open Source License
public ISourceRange getJavadocRange() throws JavaModelException { ISourceRange range = getSourceRange(); if (range == null) return null; IBuffer buf = null; if (isBinary()) { buf = getClassFile().getBuffer(); } else {//ww w.ja va 2 s .c o m ICompilationUnit compilationUnit = getCompilationUnit(); if (!compilationUnit.isConsistent()) { return null; } buf = compilationUnit.getBuffer(); } final int start = range.getOffset(); final int length = range.getLength(); if (length > 0 && buf.getChar(start) == '/') { IScanner scanner = ToolFactory.createScanner(true, false, false, false); try { scanner.setSource(buf.getText(start, length).toCharArray()); int docOffset = -1; int docEnd = -1; int terminal = scanner.getNextToken(); loop: while (true) { switch (terminal) { case ITerminalSymbols.TokenNameCOMMENT_JAVADOC: docOffset = scanner.getCurrentTokenStartPosition(); docEnd = scanner.getCurrentTokenEndPosition() + 1; terminal = scanner.getNextToken(); break; case ITerminalSymbols.TokenNameCOMMENT_LINE: case ITerminalSymbols.TokenNameCOMMENT_BLOCK: terminal = scanner.getNextToken(); continue loop; default: break loop; } } if (docOffset != -1) { return new SourceRange(docOffset + start, docEnd - docOffset); } } catch (InvalidInputException ex) { // try if there is inherited Javadoc } catch (IndexOutOfBoundsException e) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=305001 } } return null; }
From source file:com.iw.plugins.spindle.ui.wizards.factories.ClassFactory.java
License:Mozilla Public License
/** * Examines a string and returns the first line delimiter found. */// w w w .j a v a 2 s . c om public static String getLineDelimiterUsed(IJavaElement elem) throws JavaModelException { ICompilationUnit cu = (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null && cu.exists()) { IBuffer buf = cu.getBuffer(); int length = buf.getLength(); for (int i = 0; i < length; i++) { char ch = buf.getChar(i); if (ch == SWT.CR) { if (i + 1 < length) { if (buf.getChar(i + 1) == SWT.LF) { return "\r\n"; //$NON-NLS-1$ } } return "\r"; //$NON-NLS-1$ } else if (ch == SWT.LF) { return "\n"; //$NON-NLS-1$ } } } return System.getProperty("line.separator", "\n"); }
From source file:net.sf.commonclipse.Generator.java
License:Apache License
/** * Evaluates the indention used by a Java element. * @param elem Java element/*from w w w . j a va 2 s . c om*/ * @param cu compilation unit * @return indentation level * @throws JavaModelException model exception when trying to access source */ public int getIndentUsed(IJavaElement elem, ICompilationUnit cu) throws JavaModelException { if (elem instanceof ISourceReference) { if (cu != null) { IBuffer buf = cu.getBuffer(); int offset = ((ISourceReference) elem).getSourceRange().getOffset(); int i = offset; // find beginning of line while (i > 0 && !isLineDelimiterChar(buf.getChar(i - 1))) { i--; } return computeIndent(buf.getText(i, offset - i)); } } return 0; }
From source file:org.eclim.plugin.jdt.util.JavaUtils.java
License:Open Source License
/** * Format a region in the supplied source file. * * @param src The ICompilationUnit./*from ww w . j a va 2 s . c om*/ * @param kind The kind of code snippet to format. * @param offset The starting offset of the region to format. * @param length The length of the region to format. */ public static void format(ICompilationUnit src, int kind, int offset, int length) throws Exception { IBuffer buffer = src.getBuffer(); String contents = buffer.getContents(); String delimiter = StubUtility.getLineDelimiterUsed(src); DefaultCodeFormatter formatter = new DefaultCodeFormatter(src.getJavaProject().getOptions(true)); // when the eclipse indent settings differ from vim (tabs vs spaces) then // the inserted method's indent may be a bit off. this is a workaround to // force reformatting of the code from the start of the line to the start of // the next set of code following the new method. Doesn't quite fix indent // formatting of methods in nested classes. while (offset > 0 && !IndentManipulation.isLineDelimiterChar(buffer.getChar(offset - 1))) { offset--; length++; } while ((offset + length) < contents.length() && IndentManipulation.isLineDelimiterChar(buffer.getChar(offset + length))) { length++; } TextEdit edits = formatter.format(kind, contents, offset, length, 0, delimiter); if (edits != null) { int oldLength = contents.length(); Document document = new Document(contents); edits.apply(document); String formatted = document.get(); // jdt formatter can introduce trailing whitespace (javadoc comments), so // we'll remove all trailing whitespace from the formatted section (unless // the user has configured eclim not to do so). length += formatted.length() - oldLength; if (offset < (offset + length)) { String stripTrailingWhitespace = Preferences.getInstance().getValue( src.getJavaProject().getProject(), "org.eclim.java.format.strip_trialing_whitespace"); if ("true".equals(stripTrailingWhitespace)) { String pre = formatted.substring(0, offset); StringBuffer section = new StringBuffer(formatted.substring(offset, offset + length)); StringBuffer post = new StringBuffer(formatted.substring(offset + length)); // account for section not ending at a line delimiter while (!section.toString().endsWith(delimiter) && post.length() > 0) { section.append(post.charAt(0)); post.deleteCharAt(0); } Matcher matcher = TRAILING_WHITESPACE.matcher(section); String stripped = matcher.replaceAll(StringUtils.EMPTY); src.getBuffer().setContents(pre + stripped + post); } else { src.getBuffer().setContents(formatted); } } else { src.getBuffer().setContents(formatted); } if (src.isWorkingCopy()) { src.commitWorkingCopy(true, null); } src.save(null, false); } }
From source file:org.eclipse.ajdt.core.model.AJProjectModelFacade.java
License:Open Source License
/** * Open up the buffer to to convert from line number to offset * this is slow//from www.j a va 2 s. c o m * We are always working in an AJCU with an aspect element * * cache the results since it is likely that we will be * calling this often for the same sloc */ private int offsetFromLine(ITypeRoot unit, ISourceLocation sloc) throws JavaModelException { if (sloc.getOffset() > 0) { return sloc.getOffset(); } if (slocCache != null && slocCache.containsKey(sloc)) { return slocCache.get(sloc).intValue(); } if (unit instanceof AJCompilationUnit) { AJCompilationUnit ajUnit = (AJCompilationUnit) unit; ajUnit.requestOriginalContentMode(); } IBuffer buf = unit.getBuffer(); if (unit instanceof AJCompilationUnit) { AJCompilationUnit ajUnit = (AJCompilationUnit) unit; ajUnit.discardOriginalContentMode(); } if (buf != null) { int requestedLine = sloc.getLine(); int currentLine = 1; int offset = 0; while (offset < buf.getLength() && currentLine < requestedLine) { if (buf.getChar(offset++) == '\n') { currentLine++; } } while (offset < buf.getLength() && Character.isWhitespace(buf.getChar(offset))) { offset++; } // cache if (slocCache == null) { slocCache = new HashMap<ISourceLocation, Integer>(); } slocCache.put(sloc, new Integer(offset)); return offset; } // no source code return 0; }
From source file:org.eclipse.ajdt.internal.ui.editor.quickfix.QuickFixProcessor.java
License:Open Source License
private static int moveBack(int offset, int start, String ignoreCharacters, ICompilationUnit cu) { try {//from ww w . j av a2s. com IBuffer buf = cu.getBuffer(); while (offset >= start) { if (ignoreCharacters.indexOf(buf.getChar(offset - 1)) == -1) { return offset; } offset--; } } catch (JavaModelException e) { } return start; }
From source file:org.eclipse.ajdt.internal.ui.refactoring.pullout.PullOutRefactoring.java
License:Open Source License
/** * For cosmetic reasons (nicer indentation of resulting text after deletion of membernode * we force the nodes sourcerange to include any spaces in front of the node, upto the * beginning of the line.//from w w w. j a va 2 s . c om * @param cu * @return */ private ISourceRange grabSpaceBefore(ICompilationUnit cu, ISourceRange range) { try { IBuffer sourceText = cu.getBuffer(); int start = range.getOffset(); int len = range.getLength(); while (start > 0 && isSpace(sourceText.getChar(start - 1))) { start--; len++; } return new SourceRange(start, len); } catch (JavaModelException e) { //This operation is not essential, so it is fine if it silently fails. return range; } }
From source file:org.eclipse.andmore.internal.build.ConvertSwitchQuickFixProcessor.java
License:Open Source License
@Override public IJavaCompletionProposal[] getCorrections(IInvocationContext context, IProblemLocation[] location) throws CoreException { if (location == null || location.length == 0) { return null; }/* ww w . ja va 2 s. c o m*/ ASTNode coveringNode = context.getCoveringNode(); if (coveringNode == null) { return null; } // Look up the fully qualified name of the non-constant expression, if any, and // make sure it's R-something. if (coveringNode.getNodeType() == ASTNode.SIMPLE_NAME) { coveringNode = coveringNode.getParent(); if (coveringNode == null) { return null; } } if (coveringNode.getNodeType() != ASTNode.QUALIFIED_NAME) { return null; } QualifiedName name = (QualifiedName) coveringNode; if (!name.getFullyQualifiedName().startsWith("R.")) { //$NON-NLS-1$ return null; } IProblemLocation error = location[0]; int errorStart = error.getOffset(); int errorLength = error.getLength(); int caret = context.getSelectionOffset(); // Even though the hasCorrections() method above will return false for everything // other than non-constant expression errors, it turns out this getCorrections() // method will ALSO be called on lines where there is no such error. In particular, // if you have an invalid cast expression like this: // Button button = findViewById(R.id.textView); // then this method will be called, and the expression will pass all of the above // checks. However, we -don't- want to show a migrate code suggestion in that case! // Therefore, we'll need to check if we're *actually* on a line with the given // problem. // // Unfortunately, we don't get passed the problemId again, and there's no access // to it. So instead we'll need to look up the markers on the line, and see // if we actually have a constant expression warning. This is not pretty!! boolean foundError = false; ICompilationUnit compilationUnit = context.getCompilationUnit(); IResource file = compilationUnit.getResource(); if (file != null) { IDocumentProvider provider = new TextFileDocumentProvider(); try { provider.connect(file); IDocument document = provider.getDocument(file); if (document != null) { List<IMarker> markers = AdtUtils.findMarkersOnLine(IMarker.PROBLEM, file, document, errorStart); for (IMarker marker : markers) { String message = marker.getAttribute(IMarker.MESSAGE, ""); // There are no other attributes in the marker we can use to identify // the exact error, so we'll need to resort to the actual message // text even though that would not work if the messages had been // localized... This can also break if the error messages change. Yuck. if (message.contains("constant expressions")) { //$NON-NLS-1$ foundError = true; } } } } catch (Exception e) { AndmoreAndroidPlugin.log(e, "Can't validate error message in %1$s", file.getName()); } finally { provider.disconnect(file); } } if (!foundError) { // Not a constant-expression warning, so do nothing return null; } IBuffer buffer = compilationUnit.getBuffer(); boolean sameLine = false; // See if the caret is on the same line as the error if (caret <= errorStart) { // Search backwards to beginning of line for (int i = errorStart; i >= 0; i--) { if (i <= caret) { sameLine = true; break; } char c = buffer.getChar(i); if (c == '\n') { break; } } } else { // Search forwards to the end of the line for (int i = errorStart + errorLength, n = buffer.getLength(); i < n; i++) { if (i >= caret) { sameLine = true; break; } char c = buffer.getChar(i); if (c == '\n') { break; } } } if (sameLine) { String expression = buffer.getText(errorStart, errorLength); return new IJavaCompletionProposal[] { new MigrateProposal(expression) }; } return null; }