org.eclipse.jdt.core.IBuffer Java Examples

The following examples show how to use org.eclipse.jdt.core.IBuffer. 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: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the source of the given node from the location where it was parsed.
 * @param node the node to get the source from
 * @param extendedRange if set, the extended ranges of the nodes should ne used
 * @param removeIndent if set, the indentation is removed.
 * @return return the source for the given node or null if accessing the source failed.
 */
public static String getNodeSource(ASTNode node, boolean extendedRange, boolean removeIndent) {
	ASTNode root= node.getRoot();
	if (root instanceof CompilationUnit) {
		CompilationUnit astRoot= (CompilationUnit) root;
		ITypeRoot typeRoot= astRoot.getTypeRoot();
		try {
			if (typeRoot != null && typeRoot.getBuffer() != null) {
				IBuffer buffer= typeRoot.getBuffer();
				int offset= extendedRange ? astRoot.getExtendedStartPosition(node) : node.getStartPosition();
				int length= extendedRange ? astRoot.getExtendedLength(node) : node.getLength();
				String str= buffer.getText(offset, length);
				if (removeIndent) {
					IJavaProject project= typeRoot.getJavaProject();
					int indent= StubUtility.getIndentUsed(buffer, node.getStartPosition(), project);
					str= Strings.changeIndent(str, indent, project, new String(), typeRoot.findRecommendedLineSeparator());
				}
				return str;
			}
		} catch (JavaModelException e) {
			// ignore
		}
	}
	return null;
}
 
Example #2
Source File: AddImportsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private int getNameEnd(IBuffer doc, int pos) {
	if (pos > 0) {
		if (Character.isWhitespace(doc.getChar(pos - 1))) {
			return pos;
		}
	}
	int len= doc.getLength();
	while (pos < len) {
		char ch= doc.getChar(pos);
		if (!Character.isJavaIdentifierPart(ch)) {
			return pos;
		}
		pos++;
	}
	return pos;
}
 
Example #3
Source File: JavaCodeFormatterImpl.java    From jenerate with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Examines a string and returns the first line delimiter found.
 */
private 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";
                    }
                }
                return "\r";
            } else if (ch == SWT.LF) {
                return "\n";
            }
        }
    }
    return System.getProperty("line.separator", "\n");
}
 
Example #4
Source File: ModelBasedCompletionEngine.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static void codeComplete(ICompilationUnit cu, int position, CompletionRequestor requestor, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaModelException {
	if (!(cu instanceof CompilationUnit)) {
		return;
	}

	if (requestor == null) {
		throw new IllegalArgumentException("Completion requestor cannot be null"); //$NON-NLS-1$
	}

	IBuffer buffer = cu.getBuffer();
	if (buffer == null) {
		return;
	}

	if (position < -1 || position > buffer.getLength()) {
		throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS));
	}

	JavaProject project = (JavaProject) cu.getJavaProject();
	ModelBasedSearchableEnvironment environment = new ModelBasedSearchableEnvironment(project, owner, requestor.isTestCodeExcluded());
	environment.setUnitToSkip((CompilationUnit) cu);

	// code complete
	CompletionEngine engine = new CompletionEngine(environment, requestor, project.getOptions(true), project, owner, monitor);
	engine.complete((CompilationUnit) cu, position, 0, cu);
}
 
Example #5
Source File: JavaCodeFormatterImpl.java    From jenerate with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Evaluates the indentation used by a Java element. (in tabulators)
 */
private int getUsedIndentation(IJavaElement elem) throws JavaModelException {
    if (elem instanceof ISourceReference) {
        ICompilationUnit cu = (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT);
        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), getTabWidth());
        }
    }
    return 0;
}
 
Example #6
Source File: JavadocContentAccess2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static String getHTMLContentFromSource(IMember member) throws JavaModelException {
	IBuffer buf= member.getOpenable().getBuffer();
	if (buf == null) {
		return null; // no source attachment found
	}

	ISourceRange javadocRange= member.getJavadocRange();
	if (javadocRange == null) {
		if (canInheritJavadoc(member)) {
			// Try to use the inheritDoc algorithm.
			String inheritedJavadoc= javadoc2HTML(member, "/***/"); //$NON-NLS-1$
			if (inheritedJavadoc != null && inheritedJavadoc.length() > 0) {
				return inheritedJavadoc;
			}
		}
		return getJavaFxPropertyDoc(member);
	}

	String rawJavadoc= buf.getText(javadocRange.getOffset(), javadocRange.getLength());
	return javadoc2HTML(member, rawJavadoc);
}
 
Example #7
Source File: JsonRpcHelpers.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static <T> T convert(IOpenable openable, Function<IDocument, T> consumer) throws JavaModelException {
	Assert.isNotNull(openable, "openable");
	boolean mustClose = false;
	try {
		if (!openable.isOpen()) {
			openable.open(new NullProgressMonitor());
			mustClose = openable.isOpen();
		}
		IBuffer buffer = openable.getBuffer();
		return consumer.apply(toDocument(buffer));
	} finally {
		if (mustClose) {
			try {
				openable.close();
			} catch (JavaModelException e) {
				JavaLanguageServerPlugin.logException("Error when closing openable: " + openable, e);
			}
		}
	}
}
 
Example #8
Source File: JDClassFileEditor.java    From jd-eclipse with GNU General Public License v3.0 6 votes vote down vote up
protected static void cleanupBuffer(IClassFile file) {
	IBuffer buffer = BufferManager.getDefaultBufferManager().getBuffer(file);

	if (buffer != null) {
		try {
			// Remove the buffer
			Method method = BufferManager.class.getDeclaredMethod("removeBuffer", new Class[] {IBuffer.class});
			method.setAccessible(true);
			method.invoke(BufferManager.getDefaultBufferManager(), new Object[] {buffer});				
		} catch (Exception e) {
			JavaDecompilerPlugin.getDefault().getLog().log(new Status(
				Status.ERROR, JavaDecompilerPlugin.PLUGIN_ID, 
				0, e.getMessage(), e));
		}
	}
}
 
Example #9
Source File: JavadocContentAccess.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Gets a reader for an IMember's Javadoc comment content from the source attachment.
 * The content does contain only the text from the comment without the Javadoc leading star characters.
 * Returns <code>null</code> if the member does not contain a Javadoc comment or if no source is available.
 * @param member The member to get the Javadoc of.
 * @return Returns a reader for the Javadoc comment content or <code>null</code> if the member
 * does not contain a Javadoc comment or if no source is available
 * @throws JavaModelException is thrown when the elements javadoc can not be accessed
 * @since 3.4
 */
private static Reader internalGetContentReader(IMember member) throws JavaModelException {
	IBuffer buf= member.getOpenable().getBuffer();
	if (buf == null) {
		return null; // no source attachment found
	}

	ISourceRange javadocRange= member.getJavadocRange();
	if (javadocRange != null) {
		JavaDocCommentReader reader= new JavaDocCommentReader(buf, javadocRange.getOffset(), javadocRange.getOffset() + javadocRange.getLength() - 1);
		if (!containsOnlyInheritDoc(reader, javadocRange.getLength())) {
			reader.reset();
			return reader;
		}
	}

	return null;
}
 
Example #10
Source File: JavadocContentAccess.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Gets a reader for an IMember's Javadoc comment content from the source attachment.
 * The content does contain only the text from the comment without the Javadoc leading star characters.
 * Returns <code>null</code> if the member does not contain a Javadoc comment or if no source is available.
 * @param member The member to get the Javadoc of.
 * @return Returns a reader for the Javadoc comment content or <code>null</code> if the member
 * does not contain a Javadoc comment or if no source is available
 * @throws JavaModelException is thrown when the elements javadoc can not be accessed
 * @since 3.4
 */
private static Reader internalGetContentReader(IMember member) throws JavaModelException {
	IBuffer buf= member.getOpenable().getBuffer();
	if (buf == null) {
		return null; // no source attachment found
	}

	ISourceRange javadocRange= member.getJavadocRange();
	if (javadocRange != null) {
		JavaDocCommentReader reader= new JavaDocCommentReader(buf, javadocRange.getOffset(), javadocRange.getOffset() + javadocRange.getLength() - 1);
		if (!containsOnlyInheritDoc(reader, javadocRange.getLength())) {
			reader.reset();
			return reader;
		}
	}

	return null;
}
 
Example #11
Source File: SourceContentProvider.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public String getSource(IClassFile classFile, IProgressMonitor monitor) throws CoreException {
	String source = null;
	try {
		IBuffer buffer = classFile.getBuffer();
		if (buffer == null) {
			ProjectsManager projectsManager = JavaLanguageServerPlugin.getProjectsManager();
			if (projectsManager != null) {
				Optional<IBuildSupport> bs = projectsManager.getBuildSupport(classFile.getJavaProject().getProject());
				if (bs.isPresent()) {
					bs.get().discoverSource(classFile, monitor);
				}
			}
			buffer = classFile.getBuffer();
		}
		if (buffer != null) {
			source = buffer.getContents();
			JavaLanguageServerPlugin.logInfo("ClassFile contents request completed");
		}
	} catch (JavaModelException e) {
		JavaLanguageServerPlugin.logException("Exception getting java element ", e);
	}
	return source;
}
 
Example #12
Source File: TypedSource.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static String getFieldSource(IField field, SourceTuple tuple) throws CoreException {
	if (Flags.isEnum(field.getFlags())) {
		String source= field.getSource();
		if (source != null)
			return source;
	} else {
		if (tuple.node == null) {
			ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
			parser.setSource(tuple.unit);
			tuple.node= (CompilationUnit) parser.createAST(null);
		}
		FieldDeclaration declaration= ASTNodeSearchUtil.getFieldDeclarationNode(field, tuple.node);
		if (declaration.fragments().size() == 1)
			return getSourceOfDeclararationNode(field, tuple.unit);
		VariableDeclarationFragment declarationFragment= ASTNodeSearchUtil.getFieldDeclarationFragmentNode(field, tuple.node);
		IBuffer buffer= tuple.unit.getBuffer();
		StringBuffer buff= new StringBuffer();
		buff.append(buffer.getText(declaration.getStartPosition(), ((ASTNode) declaration.fragments().get(0)).getStartPosition() - declaration.getStartPosition()));
		buff.append(buffer.getText(declarationFragment.getStartPosition(), declarationFragment.getLength()));
		buff.append(";"); //$NON-NLS-1$
		return buff.toString();
	}
	return ""; //$NON-NLS-1$
}
 
Example #13
Source File: Util.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static boolean isJustWhitespaceOrComment(int start, int end, IBuffer buffer) {
	if (start == end)
		return true;
	Assert.isTrue(start <= end);
	String trimmedText= buffer.getText(start, end - start).trim();
	if (0 == trimmedText.length()) {
		return true;
	} else {
		IScanner scanner= ToolFactory.createScanner(false, false, false, null);
		scanner.setSource(trimmedText.toCharArray());
		try {
			return scanner.getNextToken() == ITerminalSymbols.TokenNameEOF;
		} catch (InvalidInputException e) {
			return false;
		}
	}
}
 
Example #14
Source File: CallLocation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void initCallTextAndLineNumber() {
	if (fCallText != null)
		return;

    IBuffer buffer= getBufferForMember();
    if (buffer == null || buffer.getLength() < fEnd) { //binary, without source attachment || buffer contents out of sync (bug 121900)
    	fCallText= ""; //$NON-NLS-1$
    	fLineNumber= UNKNOWN_LINE_NUMBER;
    	return;
    }

    fCallText= buffer.getText(fStart, (fEnd - fStart));

    if (fLineNumber == UNKNOWN_LINE_NUMBER) {
        Document document= new Document(buffer.getContents());
        try {
            fLineNumber= document.getLineOfOffset(fStart) + 1;
        } catch (BadLocationException e) {
            JavaPlugin.log(e);
        }
    }
}
 
Example #15
Source File: Util.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static boolean isJustWhitespaceOrComment(int start, int end, IBuffer buffer) {
	if (start == end) {
		return true;
	}
	Assert.isTrue(start <= end);
	String trimmedText = buffer.getText(start, end - start).trim();
	if (0 == trimmedText.length()) {
		return true;
	} else {
		IScanner scanner = ToolFactory.createScanner(false, false, false, null);
		scanner.setSource(trimmedText.toCharArray());
		try {
			return scanner.getNextToken() == ITerminalSymbols.TokenNameEOF;
		} catch (InvalidInputException e) {
			return false;
		}
	}
}
 
Example #16
Source File: SortElementsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @see org.eclipse.jdt.internal.core.JavaModelOperation#executeOperation()
 */
protected void executeOperation() throws JavaModelException {
	try {
		beginTask(Messages.operation_sortelements, getMainAmountOfWork());
		CompilationUnit copy = (CompilationUnit) this.elementsToProcess[0];
		ICompilationUnit unit = copy.getPrimary();
		IBuffer buffer = copy.getBuffer();
		if (buffer  == null) {
			return;
		}
		char[] bufferContents = buffer.getCharacters();
		String result = processElement(unit, bufferContents);
		if (!CharOperation.equals(result.toCharArray(), bufferContents)) {
			copy.getBuffer().setContents(result);
		}
		worked(1);
	} finally {
		done();
	}
}
 
Example #17
Source File: JDTUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates a range for the given offset and length for an {@link IOpenable}
 *
 * @param openable
 * @param offset
 * @param length
 * @return
 * @throws JavaModelException
 */
public static Range toRange(IOpenable openable, int offset, int length) throws JavaModelException{
	Range range = newRange();
	if (offset > 0 || length > 0) {
		int[] loc = null;
		int[] endLoc = null;
		IBuffer buffer = openable.getBuffer();
		if (buffer != null) {
			loc = JsonRpcHelpers.toLine(buffer, offset);
			endLoc = JsonRpcHelpers.toLine(buffer, offset + length);
		}
		if (loc == null) {
			loc = new int[2];
		}
		if (endLoc == null) {
			endLoc = new int[2];
		}
		setPosition(range.getStart(), loc);
		setPosition(range.getEnd(), endLoc);
	}
	return range;
}
 
Example #18
Source File: ImportRewriteAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void removeAndInsertNew(IBuffer buffer, int contentOffset, int contentEnd, ArrayList stringsToInsert, MultiTextEdit resEdit) {
	int pos= contentOffset;
	for (int i= 0; i < stringsToInsert.size(); i++) {
		String curr= (String) stringsToInsert.get(i);
		int idx= findInBuffer(buffer, curr, pos, contentEnd);
		if (idx != -1) {
			if (idx != pos) {
				resEdit.addChild(new DeleteEdit(pos, idx - pos));
			}
			pos= idx + curr.length();
		} else {
			resEdit.addChild(new InsertEdit(pos, curr));
		}
	}
	if (pos < contentEnd) {
		resEdit.addChild(new DeleteEdit(pos, contentEnd - pos));
	}
}
 
Example #19
Source File: JdtSourceLookUpProvider.java    From java-debug with Eclipse Public License 1.0 6 votes vote down vote up
private String getContents(IClassFile cf) {
    String source = null;
    if (cf != null) {
        try {
            IBuffer buffer = cf.getBuffer();
            if (buffer != null) {
                source = buffer.getContents();
            }
        } catch (JavaModelException e) {
            logger.log(Level.SEVERE, String.format("Failed to parse the source contents of the class file: %s", e.toString()), e);
        }
        if (source == null) {
            source = "";
        }
    }
    return source;
}
 
Example #20
Source File: LapseView.java    From lapse-plus with GNU General Public License v3.0 6 votes vote down vote up
private CompilationUnit internalSetInput(IOpenable input) throws CoreException {
	IBuffer buffer = input.getBuffer();
	if (buffer == null) {
		JavaPlugin.logErrorMessage("Input has no buffer"); //$NON-NLS-1$
	}
	if (input instanceof ICompilationUnit) {
		fParser.setSource((ICompilationUnit) input);
	} else {
		fParser.setSource((IClassFile) input);
	}

	try {
		CompilationUnit root = (CompilationUnit) fParser.createAST(null);
		log("Recomputed the AST for " + buffer.getUnderlyingResource().getName());
						
		if (root == null) {
			JavaPlugin.logErrorMessage("Could not create AST"); //$NON-NLS-1$
		}

		return root;
	} catch (RuntimeException e) {
		JavaPlugin.logErrorMessage("Could not create AST:\n" + e.getMessage()); //$NON-NLS-1$
		return null;
	}
}
 
Example #21
Source File: BufferManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static IBuffer createBuffer(IOpenable owner) {
	JavaElement element = (JavaElement) owner;
	IResource resource = element.resource();
	return
		new Buffer(
			resource instanceof IFile ? (IFile)resource : null,
			owner,
			element.isReadOnly());
}
 
Example #22
Source File: BufferManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Adds a buffer to the table of open buffers.
 */
protected void addBuffer(IBuffer buffer) {
	if (VERBOSE) {
		String owner = ((Openable)buffer.getOwner()).toStringWithAncestors();
		System.out.println("Adding buffer for " + owner); //$NON-NLS-1$
	}
	synchronized (this.openBuffers) {
		this.openBuffers.put(buffer.getOwner(), buffer);
	}
	// close buffers that were removed from the cache if space was needed
	this.openBuffers.closeBuffers();
	if (VERBOSE) {
		System.out.println("-> Buffer cache filling ratio = " + NumberFormat.getInstance().format(this.openBuffers.fillingRatio()) + "%"); //$NON-NLS-1$//$NON-NLS-2$
	}
}
 
Example #23
Source File: ClassFileWorkingCopy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see Openable#openBuffer(IProgressMonitor, Object)
 */
protected IBuffer openBuffer(IProgressMonitor pm, Object info) throws JavaModelException {

	// create buffer
	IBuffer buffer = BufferManager.createBuffer(this);

	// set the buffer source
	IBuffer classFileBuffer = this.classFile.getBuffer();
	if (classFileBuffer != null) {
		buffer.setContents(classFileBuffer.getCharacters());
	} else {
		// Disassemble
		IClassFileReader reader = ToolFactory.createDefaultClassFileReader(this.classFile, IClassFileReader.ALL);
		Disassembler disassembler = new Disassembler();
		String contents = disassembler.disassemble(reader, Util.getLineSeparator("", getJavaProject()), ClassFileBytesDisassembler.WORKING_COPY); //$NON-NLS-1$
		buffer.setContents(contents);
	}

	// add buffer to buffer cache
	BufferManager bufManager = getBufferManager();
	bufManager.addBuffer(buffer);

	// listen to buffer changes
	buffer.addBufferChangedListener(this);

	return buffer;
}
 
Example #24
Source File: Util.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
static boolean rangeIncludesNonWhitespaceOutsideRange(ISourceRange selection, ISourceRange nodes, IBuffer buffer) {
	if (!covers(selection, nodes))
		return false;

	//TODO: skip leading comments. Consider that leading line comment must be followed by newline!
	if(!isJustWhitespace(selection.getOffset(), nodes.getOffset(), buffer))
		return true;
	if(!isJustWhitespaceOrComment(nodes.getOffset() + nodes.getLength(), selection.getOffset() + selection.getLength(), buffer))
		return true;
	return false;
}
 
Example #25
Source File: AddImportsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private int getSimpleNameStart(IBuffer buffer, int nameStart, String containerName) {
	int containerLen= containerName.length();
	int docLen= buffer.getLength();
	if (containerLen > 0 && nameStart + containerLen + 1 < docLen) {
		for (int k= 0; k < containerLen; k++) {
			if (buffer.getChar(nameStart + k) != containerName.charAt(k)) {
				return nameStart;
			}
		}
		if (buffer.getChar(nameStart + containerLen) == '.') {
			return nameStart + containerLen + 1;
		}
	}
	return nameStart;
}
 
Example #26
Source File: AddImportsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private int getNameStart(IBuffer buffer, int pos) {
	while (pos > 0) {
		char ch= buffer.getChar(pos - 1);
		if (!Character.isJavaIdentifierPart(ch) && ch != '.') {
			return pos;
		}
		pos--;
	}
	return pos;
}
 
Example #27
Source File: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static int getIndentUsed(IBuffer buffer, int offset, IJavaProject project) {
	int i= offset;
	// find beginning of line
	while (i > 0 && !IndentManipulation.isLineDelimiterChar(buffer.getChar(i - 1))) {
		i--;
	}
	return Strings.computeIndentUnits(buffer.getText(i, offset - i), project);
}
 
Example #28
Source File: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Evaluates the indentation used by a Java element. (in tabulators)
 * 
 * @param elem the element to get the indent of
 * @return return the indent unit
 * @throws JavaModelException thrown if the element could not be accessed
 */
public static int getIndentUsed(IJavaElement elem) throws JavaModelException {
	IOpenable openable= elem.getOpenable();
	if (openable instanceof ITypeRoot) {
		IBuffer buf= openable.getBuffer();
		if (buf != null) {
			int offset= ((ISourceReference)elem).getSourceRange().getOffset();
			return getIndentUsed(buf, offset, elem.getJavaProject());
		}
	}
	return 0;
}
 
Example #29
Source File: TokenScanner.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a TokenScanner
 * @param typeRoot The type root to scan on
 * @throws CoreException thrown if the buffer cannot be accessed
 */
public TokenScanner(ITypeRoot typeRoot) throws CoreException {
	IJavaProject project= typeRoot.getJavaProject();
	IBuffer buffer= typeRoot.getBuffer();
	if (buffer == null) {
		throw new CoreException(createError(DOCUMENT_ERROR, "Element has no source", null)); //$NON-NLS-1$
	}
	String sourceLevel= project.getOption(JavaCore.COMPILER_SOURCE, true);
	String complianceLevel= project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
	fScanner= ToolFactory.createScanner(true, false, true, sourceLevel, complianceLevel); // line info required

	fScanner.setSource(buffer.getCharacters());
	fDocument= null; // use scanner for line information
	fEndPosition= fScanner.getSource().length - 1;
}
 
Example #30
Source File: ImportRewriteAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private int findInBuffer(IBuffer buffer, String str, int start, int end) {
	int pos= start;
	int len= str.length();
	if (pos + len > end || str.length() == 0) {
		return -1;
	}
	char first= str.charAt(0);
	int step= str.indexOf(first, 1);
	if (step == -1) {
		step= len;
	}
	while (pos + len <= end) {
		if (buffer.getChar(pos) == first) {
			int k= 1;
			while (k < len && buffer.getChar(pos + k) == str.charAt(k)) {
				k++;
			}
			if (k == len) {
				return pos; // found
			}
			if (k < step) {
				pos+= k;
			} else {
				pos+= step;
			}
		} else {
			pos++;
		}
	}
	return -1;
}