JDT API allows other plugins to perform codeassist or codeselect on some Java elements. Elements that allow this manipulation implement ICodeAssist. In the Java model there are two elements that implement this interface: IClassFile and ICompilationUnit.
There are two kinds of manipulation:
Note: completion and selection answer results for a classfile only if it has attached source.
The only way to programmatically perform code completion is to use ICodeAssist.codeComplete. You specify the location of the completion in the unit and provide an instance of ICompletionRequestor to accept the possible completions.
Each kind of proposal is accepted by a method of the requestor. The parameters of these methods describe the element (name, parameters, declaring type, ...) and its position, as well as the relevance of the proposal in the current context.
When you are not interested by all the result kinds, a simple way to perform code completion is to use CompletionRequestorAdapter.
// Get the compilation unit
ICompilationUnit unit = ...;
// Get the offset
int offset = ...;
// Create the requestor
ICompletionRequestor requestor = new CompletionRequestorAdapter() {
public void acceptClass(
char[] packageName,
char[] className,
char[] completionName,
int modifiers,
int completionStart,
int completionEnd,
int relevance) {
System.out.println("propose a class named " + new String(className));
}
};
// Compute proposals
unit.codeComplete(offset, requestor);
The options of code completion can be changed by other plugins. You can modify JDT Core options to change the completion behavior.
There are two options:
To know how to modify JDT Core options see: What are the JDT Core options?
If you want to programmatically perform code selection, the method to use is ICodeAssist.codeSelect. This method needs to know the start location of the selection and the length.
The result is an array of Java elements. Most of the time there is only one element in the array, but if the selection is ambiguous then all the possible elements are returned.
// Get the compilation unit
ICompilationUnit unit = ...;
// Get the offset and length
int offset = ...;
int length = ...;
// perform selection
IJavaElement[] elements = unit.codeSelect(offset, length);
System.out.println("the selected element is " + element[0].getElementName());
If the length of the selection equals 0 then the selection is computed with the complete enclosing token.
public void fooMethod(Object) { }When the offset is after the first character of fooMethod and the length is 0 then the selection is fooMethod. But if the length is 5 then the selection is ooMet.