Community
Participate
Working Groups
The class org.eclipse.jdt.core.dom.CompilationUnit gets a copy of the table of line-ending positions from the scanner and allows one to convert from a character position to a line number. For non-GUI tools, however, this is not sufficient. One also needs to be able to get the start and end character positions of a given line (as is available for instance in PublicScanner). I suggest adding the following methods to org.eclipse.jdt.core.dom.CompilationUnit (sorry I don't have a means of either compiling or testing the following code). [Adapted from org.eclipse.jdt.internal.core.util.PublicScanner ] /* * * Line numbers are 1-based. * Character positions are 0-based. * * In case the given line number is inconsistent, answers -1. * @param lineNumber a 1-based line number * @return the character position of the end of that line */ public final int getLineEnd(int lineNumber) { if (lineEndTable == null) return -1; if (lineNumber > lineEndTable.length) return -1; if (lineNumber <= 0) return -1; return lineEndTable[lineNumber-1]; // next line start one character behind the lineEnd of the previous line } public final int[] getLineEnds() { //return a live copy of the lineEndTable return lineEndTable; } /** * * Line numbers are 1-based. * Character positions are 0-based. * * e.g. getLineStart(1) --> 0 indicates that the first line starts at character 0. * * In case the given line number is inconsistent, answers -1. * * @param lineNumber a 1-based line number * @return the character position of the beginning of that line */ public final int getLineStart(int lineNumber) { if (lineEndTable == null) return -1; if (lineNumber > lineEndTable.length) return -1; if (lineNumber <= 0) return -1; if (lineNumber == 1) return 0; return lineEndTable[lineNumber-2]+1; // next line starts one character beyond the lineEnd of the previous line }