Java Code Examples for org.eclipse.jdt.core.ICompilationUnit#getBuffer()

The following examples show how to use org.eclipse.jdt.core.ICompilationUnit#getBuffer() . 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: 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 2
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 3
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 4
Source File: MoveCuUpdateCreator.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void acceptSearchMatch(SearchMatch match) throws CoreException {
	if (filterMatch(match)) {
		return;
	}

	/*
	 * Processing is done in collector to reuse the buffer which was
	 * already required by the search engine to locate the matches.
	 */
	// [start, end[ include qualification.
	IJavaElement element = SearchUtils.getEnclosingJavaElement(match);
	int accuracy = match.getAccuracy();
	int start = match.getOffset();
	int length = match.getLength();
	boolean insideDocComment = match.isInsideDocComment();
	IResource res = match.getResource();
	if (element.getAncestor(IJavaElement.IMPORT_DECLARATION) != null) {
		collectMatch(TypeReference.createImportReference(element, accuracy, start, length, insideDocComment, res));
	} else {
		ICompilationUnit unit = (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
		if (unit != null) {
			IBuffer buffer = unit.getBuffer();
			String matchText = buffer.getText(start, length);
			if (fSource.isDefaultPackage()) {
				collectMatch(TypeReference.createSimpleReference(element, accuracy, start, length, insideDocComment, res, matchText));
			} else {
				// assert: matchText doesn't start nor end with comment
				int simpleNameStart = getLastSimpleNameStart(matchText);
				if (simpleNameStart != 0) {
					collectMatch(TypeReference.createQualifiedReference(element, accuracy, start, length, insideDocComment, res, start + simpleNameStart));
				} else {
					collectMatch(TypeReference.createSimpleReference(element, accuracy, start, length, insideDocComment, res, matchText));
				}
			}
		}
	}
}
 
Example 5
Source File: NLSUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static int findLineEnd(ICompilationUnit cu, int position) throws JavaModelException {
	IBuffer buffer= cu.getBuffer();
	int length= buffer.getLength();
	for (int i= position; i < length; i++) {
		if (IndentManipulation.isLineDelimiterChar(buffer.getChar(i))) {
			return i;
		}
	}
	return length;
}
 
Example 6
Source File: QuickFixProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static int moveBack(int offset, int start, String ignoreCharacters, ICompilationUnit cu) {
	try {
		IBuffer buf = cu.getBuffer();
		while (offset >= start) {
			if (ignoreCharacters.indexOf(buf.getChar(offset - 1)) == -1) {
				return offset;
			}
			offset--;
		}
	} catch (JavaModelException e) {
		// use start
	}
	return start;
}
 
Example 7
Source File: MoveCuUpdateCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void acceptSearchMatch(SearchMatch match) throws CoreException {
	if (filterMatch(match))
		return;

	/*
	 * Processing is done in collector to reuse the buffer which was
	 * already required by the search engine to locate the matches.
	 */
	// [start, end[ include qualification.
	IJavaElement element= SearchUtils.getEnclosingJavaElement(match);
	int accuracy= match.getAccuracy();
	int start= match.getOffset();
	int length= match.getLength();
	boolean insideDocComment= match.isInsideDocComment();
	IResource res= match.getResource();
	if (element.getAncestor(IJavaElement.IMPORT_DECLARATION) != null) {
		collectMatch(TypeReference.createImportReference(element, accuracy, start, length, insideDocComment, res));
	} else {
		ICompilationUnit unit= (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
		if (unit != null) {
			IBuffer buffer= unit.getBuffer();
			String matchText= buffer.getText(start, length);
			if (fSource.isDefaultPackage()) {
				collectMatch(TypeReference.createSimpleReference(element, accuracy, start, length, insideDocComment, res, matchText));
			} else {
				// assert: matchText doesn't start nor end with comment
				int simpleNameStart= getLastSimpleNameStart(matchText);
				if (simpleNameStart != 0) {
					collectMatch(TypeReference.createQualifiedReference(element, accuracy, start, length, insideDocComment, res, start + simpleNameStart));
				} else {
					collectMatch(TypeReference.createSimpleReference(element, accuracy, start, length, insideDocComment, res, matchText));
				}
			}
		}
	}
}
 
Example 8
Source File: NLSUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static int findLineEnd(ICompilationUnit cu, int position) throws JavaModelException {
	IBuffer buffer= cu.getBuffer();
	int length= buffer.getLength();
	for (int i= position; i < length; i++) {
		if (IndentManipulation.isLineDelimiterChar(buffer.getChar(i))) {
			return i;
		}
	}
	return length;
}
 
Example 9
Source File: QuickFixProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static int moveBack(int offset, int start, String ignoreCharacters, ICompilationUnit cu) {
	try {
		IBuffer buf= cu.getBuffer();
		while (offset >= start) {
			if (ignoreCharacters.indexOf(buf.getChar(offset - 1)) == -1) {
				return offset;
			}
			offset--;
		}
	} catch(JavaModelException e) {
		// use start
	}
	return start;
}
 
Example 10
Source File: UpdateCopyrightFix.java    From saneclipse with Eclipse Public License 1.0 5 votes vote down vote up
public static ICleanUpFix createCleanUp(ICompilationUnit compilationUnit, boolean updateIbmCopyright) throws CoreException {
	if (!updateIbmCopyright)
		return null;
	
	IBuffer buffer= compilationUnit.getBuffer();
	String contents= buffer.getContents();
	
	for (SearchReplacePattern pattern : SEARCH_REPLACE_PATTERNS) {
		Matcher matcher= pattern.getSearchPattern().matcher(contents);
		if (matcher.find(0)) {
			int start= matcher.start();
			int end= matcher.end();
			String substring= contents.substring(start, end);
			
			matcher= pattern.getSearchPattern().matcher(substring);
			String replacement= matcher.replaceFirst(pattern.getReplaceString());
			if (substring.equals(replacement))
				return null;
			
			ReplaceEdit edit= new ReplaceEdit(start, substring.length(), replacement);
			
			CompilationUnitChange change= new CompilationUnitChange("Update Copyright", compilationUnit); //$NON-NLS-1$
			change.setEdit(edit);
			
			return new UpdateCopyrightFix(change);
		}
	}
	
	return null;
}
 
Example 11
Source File: CompletionHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private CompletionList computeContentAssist(ICompilationUnit unit, int line, int column, IProgressMonitor monitor) throws JavaModelException {
	CompletionResponses.clear();
	if (unit == null) {
		return null;
	}
	List<CompletionItem> proposals = new ArrayList<>();

	final int offset = JsonRpcHelpers.toOffset(unit.getBuffer(), line, column);
	CompletionProposalRequestor collector = new CompletionProposalRequestor(unit, offset, manager);
	// Allow completions for unresolved types - since 3.3
	collector.setAllowsRequiredProposals(CompletionProposal.FIELD_REF, CompletionProposal.TYPE_REF, true);
	collector.setAllowsRequiredProposals(CompletionProposal.FIELD_REF, CompletionProposal.TYPE_IMPORT, true);
	collector.setAllowsRequiredProposals(CompletionProposal.FIELD_REF, CompletionProposal.FIELD_IMPORT, true);

	collector.setAllowsRequiredProposals(CompletionProposal.METHOD_REF, CompletionProposal.TYPE_REF, true);
	collector.setAllowsRequiredProposals(CompletionProposal.METHOD_REF, CompletionProposal.TYPE_IMPORT, true);
	collector.setAllowsRequiredProposals(CompletionProposal.METHOD_REF, CompletionProposal.METHOD_IMPORT, true);

	collector.setAllowsRequiredProposals(CompletionProposal.CONSTRUCTOR_INVOCATION, CompletionProposal.TYPE_REF, true);

	collector.setAllowsRequiredProposals(CompletionProposal.ANONYMOUS_CLASS_CONSTRUCTOR_INVOCATION, CompletionProposal.TYPE_REF, true);
	collector.setAllowsRequiredProposals(CompletionProposal.ANONYMOUS_CLASS_DECLARATION, CompletionProposal.TYPE_REF, true);

	collector.setAllowsRequiredProposals(CompletionProposal.TYPE_REF, CompletionProposal.TYPE_REF, true);
	collector.setFavoriteReferences(getFavoriteStaticMembers());

	if (offset >-1 && !monitor.isCanceled()) {
		IBuffer buffer = unit.getBuffer();
		if (buffer != null && buffer.getLength() >= offset) {
			IProgressMonitor subMonitor = new ProgressMonitorWrapper(monitor) {
				private long timeLimit;
				private final long TIMEOUT = Long.getLong("completion.timeout", 5000);

				@Override
				public void beginTask(String name, int totalWork) {
					timeLimit = System.currentTimeMillis() + TIMEOUT;
				}

				@Override
				public boolean isCanceled() {
					return super.isCanceled() || timeLimit <= System.currentTimeMillis();
				}

			};
			try {
				if (isIndexEngineEnabled()) {
					unit.codeComplete(offset, collector, subMonitor);
				} else {
					ModelBasedCompletionEngine.codeComplete(unit, offset, collector, DefaultWorkingCopyOwner.PRIMARY, subMonitor);
				}
				proposals.addAll(collector.getCompletionItems());
				if (isSnippetStringSupported() && !UNSUPPORTED_RESOURCES.contains(unit.getResource().getName())) {
					proposals.addAll(SnippetCompletionProposal.getSnippets(unit, collector.getContext(), subMonitor));
				}
				proposals.addAll(new JavadocCompletionProposal().getProposals(unit, offset, collector, subMonitor));
			} catch (OperationCanceledException e) {
				monitor.setCanceled(true);
			}
		}
	}
	proposals.sort(PROPOSAL_COMPARATOR);
	CompletionList list = new CompletionList(proposals);
	list.setIsIncomplete(!collector.isComplete());
	return list;
}
 
Example 12
Source File: TypeCreator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates the new type.
 *
 * NOTE: If this method throws a {@link JavaModelException}, its {@link JavaModelException#getJavaModelStatus()}
 * method can provide more detailed information about the problem.
 */
public IType createType() throws CoreException {
  IProgressMonitor monitor = new NullProgressMonitor();

  ICompilationUnit cu = null;
  try {
    String cuName = simpleTypeName + ".java";

    // Create empty compilation unit
    cu = pckg.createCompilationUnit(cuName, "", false, monitor);
    cu.becomeWorkingCopy(monitor);
    IBuffer buffer = cu.getBuffer();

    // Need to create a minimal type stub here so we can create an import
    // rewriter a few lines down. The rewriter has to be in place when we
    // create the real type stub, so we can use it to transform the names of
    // any interfaces this type extends/implements.
    String dummyTypeStub = createDummyTypeStub();

    // Generate the content (file comment, package declaration, type stub)
    String cuContent = createCuContent(cu, dummyTypeStub);
    buffer.setContents(cuContent);

    ImportRewrite imports = StubUtility.createImportRewrite(cu, true);

    // Create the real type stub and replace the dummy one
    int typeDeclOffset = cuContent.lastIndexOf(dummyTypeStub);
    if (typeDeclOffset != -1) {
      String typeStub = createTypeStub(cu, imports);
      buffer.replace(typeDeclOffset, dummyTypeStub.length(), typeStub);
    }

    // Let our subclasses add members
    IType type = cu.getType(simpleTypeName);
    createTypeMembers(type, imports);

    // Rewrite the imports and apply the edit
    TextEdit edit = imports.rewriteImports(monitor);
    applyEdit(cu, edit, false, null);

    // Format the Java code
    String formattedSource = formatJava(type);
    buffer.setContents(formattedSource);

    // Save the new type
    JavaModelUtil.reconcile(cu);
    cu.commitWorkingCopy(true, monitor);

    return type;
  } finally {
    if (cu != null) {
      cu.discardWorkingCopy();
    }
  }
}
 
Example 13
Source File: NewPackageWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
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();
	}
}
 
Example 14
Source File: CreateCompilationUnitOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates a compilation unit.
 *
 * @exception JavaModelException if unable to create the compilation unit.
 */
protected void executeOperation() throws JavaModelException {
	try {
		beginTask(Messages.operation_createUnitProgress, 2);
		JavaElementDelta delta = newJavaElementDelta();
		ICompilationUnit unit = getCompilationUnit();
		IPackageFragment pkg = (IPackageFragment) getParentElement();
		IContainer folder = (IContainer) pkg.getResource();
		worked(1);
		IFile compilationUnitFile = folder.getFile(new Path(this.name));
		if (compilationUnitFile.exists()) {
			// update the contents of the existing unit if fForce is true
			if (this.force) {
				IBuffer buffer = unit.getBuffer();
				if (buffer == null) return;
				buffer.setContents(this.source);
				unit.save(new NullProgressMonitor(), false);
				this.resultElements = new IJavaElement[] {unit};
				if (!Util.isExcluded(unit)
						&& unit.getParent().exists()) {
					for (int i = 0; i < this.resultElements.length; i++) {
						delta.changed(this.resultElements[i], IJavaElementDelta.F_CONTENT);
					}
					addDelta(delta);
				}
			} else {
				throw new JavaModelException(new JavaModelStatus(
					IJavaModelStatusConstants.NAME_COLLISION,
					Messages.bind(Messages.status_nameCollision, compilationUnitFile.getFullPath().toString())));
			}
		} else {
			try {
				String encoding = null;
				try {
					encoding = folder.getDefaultCharset(); // get folder encoding as file is not accessible
				}
				catch (CoreException ce) {
					// use no encoding
				}
				InputStream stream = new ByteArrayInputStream(encoding == null ? this.source.getBytes() : this.source.getBytes(encoding));
				createFile(folder, unit.getElementName(), stream, this.force);
				this.resultElements = new IJavaElement[] {unit};
				if (!Util.isExcluded(unit)
						&& unit.getParent().exists()) {
					for (int i = 0; i < this.resultElements.length; i++) {
						delta.added(this.resultElements[i]);
					}
					addDelta(delta);
				}
			} catch (IOException e) {
				throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
			}
		}
		worked(1);
	} finally {
		done();
	}
}