下面列出了怎么用org.eclipse.jface.text.contentassist.ICompletionProposal的API类实例代码及写法,或者点击链接到github查看源代码。
private void createStringProposal(ContentAssistContext context, ICompletionProposalAcceptor acceptor,
String feature, RuleCall ruleCall) {
String proposalText = feature != null ? feature : Strings.toFirstUpper(ruleCall.getRule().getName().toLowerCase());
proposalText = getValueConverter().toString(proposalText, ruleCall.getRule().getName());
String displayText = proposalText;
if (feature != null)
displayText = displayText + " - " + ruleCall.getRule().getName();
ICompletionProposal proposal = createCompletionProposal(proposalText, displayText, null, context);
if (proposal instanceof ConfigurableCompletionProposal) {
ConfigurableCompletionProposal configurable = (ConfigurableCompletionProposal) proposal;
configurable.setSelectionStart(configurable.getReplacementOffset() + 1);
configurable.setSelectionLength(proposalText.length() - 2);
configurable.setAutoInsertable(false);
configurable.setSimpleLinkedMode(context.getViewer(), proposalText.charAt(0), '\t');
}
acceptor.accept(proposal);
}
private ICompletionProposal[] computeStyleProposals(String selectedText,
Point selectedRange) {
if (styleManager == null) {
styleManager = TexStyleCompletionManager.getInstance();
}
return styleManager.getStyleCompletions(selectedText, selectedRange);
/*
* ICompletionProposal[] result = new
* ICompletionProposal[STYLETAGS.length];
*
* // Loop through all styles for (int i = 0; i < STYLETAGS.length; i++)
* { String tag = STYLETAGS[i];
*
* // Compute replacement text String replacement = "{" + tag + " " +
* selectedText + "}";
*
* // Derive cursor position int cursor = tag.length() + 2;
*
* // Compute a suitable context information IContextInformation
* contextInfo = new ContextInformation(null, STYLELABELS[i]+" Style");
*
* // Construct proposal result[i] = new CompletionProposal(replacement,
* selectedRange.x, selectedRange.y, cursor, null, STYLELABELS[i],
* contextInfo, replacement); } return result;
*/
}
@Override
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
ModeAware proposalProvider = getModeAwareProposalProvider();
if (proposalProvider == null)
return new ICompletionProposal[0];
int i = 0;
CompletionProposalComputer proposalComputer = createCompletionProposalComputer(viewer, offset);
while(i++ < 1000) { // just to prevent endless loop in case #isLastMode has an error
proposalProvider.nextMode();
if (currentAssistant != null)
currentAssistant.setStatusMessage(getStatusMessage());
ICompletionProposal[] result = computeCompletionProposals(xtextDocumentUtil.getXtextDocument(viewer), proposalComputer);
if (result != null && result.length > 0)
return result;
if (proposalProvider.isLastMode()) {
return new ICompletionProposal[0];
}
}
throw new IllegalStateException("#isLastMode did not return true for 1000 times");
}
private List<IContextInformation> addContextInformations(JavaContentAssistInvocationContext context, int offset) {
List<ICompletionProposal> proposals= internalComputeCompletionProposals(offset, context);
List<IContextInformation> result= new ArrayList<IContextInformation>(proposals.size());
List<IContextInformation> anonymousResult= new ArrayList<IContextInformation>(proposals.size());
for (Iterator<ICompletionProposal> it= proposals.iterator(); it.hasNext();) {
ICompletionProposal proposal= it.next();
IContextInformation contextInformation= proposal.getContextInformation();
if (contextInformation != null) {
ContextInformationWrapper wrapper= new ContextInformationWrapper(contextInformation);
wrapper.setContextInformationPosition(offset);
if (proposal instanceof AnonymousTypeCompletionProposal)
anonymousResult.add(wrapper);
else
result.add(wrapper);
}
}
if (result.size() == 0)
return anonymousResult;
return result;
}
@Override
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
int offset) {
CompletionContext context = computeContext(viewer, offset);
List<ICompletionProposal> completionProposals = new ArrayList<ICompletionProposal>();
doComputeCompletionProposals(context, completionProposals);
if (completionProposals.isEmpty() /*&& !isAstUpToDate()*/) {
IModuleSymbol moduleSymbol = context.getModuleSymbol();
if (moduleSymbol == null) {
EmptyCompletionProposal emptyCompletionProposal = new EmptyCompletionProposal(Messages.XdsOutlinePage_Loading,
LOADING_IMAGE, viewer.getSelectedRange().x);
return new ICompletionProposal[]{emptyCompletionProposal, emptyCompletionProposal};
}
else {
return null;
}
}
return completionProposals.toArray(new ICompletionProposal[0]);
}
/**
* Try to execute the correction command.
*
* @return <code>true</code> iff the correction could be started
* @since 3.6
*/
public boolean doExecute() {
ISelection selection= fEditor.getSelectionProvider().getSelection();
ICompilationUnit cu= JavaUI.getWorkingCopyManager().getWorkingCopy(fEditor.getEditorInput());
IAnnotationModel model= JavaUI.getDocumentProvider().getAnnotationModel(fEditor.getEditorInput());
if (selection instanceof ITextSelection && cu != null && model != null) {
if (! ActionUtil.isEditable(fEditor)) {
return false;
}
ICompletionProposal proposal= findCorrection(fId, fIsAssist, (ITextSelection) selection, cu, model);
if (proposal != null) {
invokeProposal(proposal, ((ITextSelection) selection).getOffset());
return true;
}
}
return false;
}
private void setItem(TableItem[] items, int i)
{
TableItem item = items[i];
ICompletionProposal proposal = fFilteredProposals[i];
item.setData("isAlt", "false");
item.setImage(0, proposal.getImage());
item.setText(1, proposal.getDisplayString());
boolean isItalics = false;
if (!(isItalics))
{
setDefaultStyle(item);
}
item.setData(proposal);
}
public ICompletionProposal[] computeCompletionProposals(IContentAssistSubjectControl contentAssistSubject, int documentOffset) {
if (fTempNameProposals.length == 0)
return null;
String input= contentAssistSubject.getDocument().get();
ArrayList<JavaCompletionProposal> proposals= new ArrayList<JavaCompletionProposal>();
String prefix= input.substring(0, documentOffset);
Image image= fImageRegistry.get(fProposalImageDescriptor);
for (int i= 0; i < fTempNameProposals.length; i++) {
String tempName= fTempNameProposals[i];
if (tempName.length() == 0 || ! tempName.startsWith(prefix))
continue;
JavaCompletionProposal proposal= new JavaCompletionProposal(tempName, 0, input.length(), image, tempName, 0);
proposals.add(proposal);
}
fErrorMessage= proposals.size() > 0 ? null : JavaUIMessages.JavaEditor_codeassist_noCompletions;
return proposals.toArray(new ICompletionProposal[proposals.size()]);
}
@Override
public final ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
resetComputeState();
// The code below has been commented, it causes a bug with templates with "${word_selection} " usage,
// and it's not clear this functionality made sense in the first place.
// if(viewer instanceof LangSourceViewer) {
// LangSourceViewer sourceViewer = (LangSourceViewer) viewer;
// if(sourceViewer.getSelectedRange().y > 0) {
// // Correct the invocation offset for content assist.
// // The issue is that if text is selected, the cursor can either be on the left, or the right
// // but the offset used will always be the left side of the selection, unless we correct it.
//
// int caretOffset = sourceViewer.getTextWidget().getCaretOffset();
// offset = sourceViewer.widgetOffset2ModelOffset(caretOffset);
// }
// }
return doComputeCompletionProposals(viewer, offset);
}
private void addModulaSymbolToCompletionProposals(List<ICompletionProposal> completionProposals, Set<ICompletionProposal> proposalsSet,
IModulaSymbol s, Predicate<IModulaSymbol> symbolFilter)
{
if (s == null || s.getName() == null) {
return; // parser sometimes may produce it
}
if (symbolFilter != null && !symbolFilter.test(s)) {
return;
}
String proposalText = s.getName();
String filterPrefix = context.getBeforeCursorWordPart();
if (filterPrefix != null && !StringUtils.startsWithIgnoreCase(proposalText, filterPrefix)) {
return;
}
addProposal(completionProposals, proposalsSet, s);
}
private void createStringProposal(ContentAssistContext context, ICompletionProposalAcceptor acceptor,
String feature, RuleCall ruleCall) {
String proposalText = feature != null ? feature : Strings.toFirstUpper(ruleCall.getRule().getName().toLowerCase());
proposalText = getValueConverter().toString(proposalText, ruleCall.getRule().getName());
String displayText = proposalText;
if (feature != null)
displayText = displayText + " - " + ruleCall.getRule().getName();
ICompletionProposal proposal = createCompletionProposal(proposalText, displayText, null, context);
if (proposal instanceof ConfigurableCompletionProposal) {
ConfigurableCompletionProposal configurable = (ConfigurableCompletionProposal) proposal;
configurable.setSelectionStart(configurable.getReplacementOffset() + 1);
configurable.setSelectionLength(proposalText.length() - 2);
configurable.setAutoInsertable(false);
configurable.setSimpleLinkedMode(context.getViewer(), proposalText.charAt(0), '\t');
}
acceptor.accept(proposal);
}
private void dottedExpressionProposals(CompletionContext context,
List<ICompletionProposal> proposals, Set<ICompletionProposal> proposalsSet) {
Predicate<IModulaSymbol> symbolFilter = createSymbolFilter(context);
IModulaSymbol symbol = context.getReferencedSymbol();
if (symbol == null) {
return;
}
if (symbol instanceof IModuleAliasSymbol) {
symbol = ((IModuleAliasSymbol)symbol).getReference();
}
ITypeSymbol typeSymbol = JavaUtils.as(ITypeSymbol.class, symbol);
if (typeSymbol != null) {
addCompletionProposalsFromTypeSymbol(proposals, proposalsSet, typeSymbol, symbolFilter);
}
else {
IModuleSymbol moduleSymbol = JavaUtils.as(IModuleSymbol.class, symbol);
if (moduleSymbol != null) {
addCompletionProposalsFromDefinitionModule(proposals, proposalsSet, moduleSymbol, symbolFilter);
}
}
}
/**
* If length of line at 'lineNum' is 'len', then validate all proposals for invocation
* index varying from '(len - numCharsCompleted)' to 'len'.
*/
private static void validateExpectedProposals(IJavaProject javaProject,
String fullyQualifiedClassName, String source, int lineNum, int numCharsCompleted,
String... expectedProposals) throws CoreException, BadLocationException {
IProgressMonitor monitor = new NullProgressMonitor();
ICompilationUnit iCompilationUnit = JavaProjectUtilities.createCompilationUnit(
javaProject, fullyQualifiedClassName, source);
CompilationUnitEditor cuEditor = (CompilationUnitEditor) JavaUI.openInEditor(iCompilationUnit);
ISourceViewer viewer = cuEditor.getViewer();
IDocument document = viewer.getDocument();
IRegion lineInformation = document.getLineInformation(lineNum);
JsniMethodBodyCompletionProposalComputer jcpc = new JsniMethodBodyCompletionProposalComputer();
for (int numCharsToOverwrite = 0; numCharsToOverwrite <= numCharsCompleted;
numCharsToOverwrite++){
int invocationOffset = lineInformation.getOffset()
+ lineInformation.getLength() - numCharsToOverwrite;
JavaContentAssistInvocationContext context = new JavaContentAssistInvocationContext(
viewer, invocationOffset, cuEditor);
List<ICompletionProposal> completions = jcpc.computeCompletionProposals(
context, monitor);
int indentationUnits = JsniMethodBodyCompletionProposalComputer.measureIndentationUnits(
document, lineNum, lineInformation.getOffset(), javaProject);
List<String> expected = createJsniBlocks(javaProject, indentationUnits,
expectedProposals);
for (int i = 0; i < expected.size(); i++){
String expectedBlock = expected.get(i).substring(numCharsCompleted - numCharsToOverwrite);
expected.set(i, expectedBlock);
}
assertExpectedProposals(expected, completions, numCharsToOverwrite);
}
}
private List<ICompletionProposal> filterTemplateProposals(ICompletionProposal[] templateProposals, String prefix) {
if (templateProposals != null && templateProposals.length > 0) {
List<ICompletionProposal> proposals = Arrays.asList(templateProposals);
if (!prefix.isEmpty()) {
return proposals.stream() //
.filter(e -> e.getDisplayString().toLowerCase().contains(prefix.toLowerCase())) //
.collect(Collectors.toList());
}
return proposals;
} else {
return Collections.emptyList();
}
}
@Override
public ICompletionProposal[] computeCompletionProposals(final ITextViewer textViewer, final int documentOffset) {
if (expressions == null) {
return new ICompletionProposal[0];
}
ICompletionProposal[] proposals = null;
proposals = buildProposals(expressions, documentOffset, textViewer);
return proposals;
}
@Override
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
IDocument document = viewer.getDocument();
try {
int lineOfOffset = document.getLineOfOffset(offset);
int lineOffset = document.getLineOffset(lineOfOffset);
// do not show any content assist in case the offset is not at the
// beginning of a line
if (offset != lineOffset) {
return new ICompletionProposal[0];
}
} catch (BadLocationException e) {
// ignore here and just continue
}
List<ICompletionProposal> completionProposals = new ArrayList<ICompletionProposal>();
for (String c : proposals) {
// Only add proposal if it is not already present
if (!(viewer.getDocument().get().contains(c))) {
completionProposals.add(new CompletionProposal(c, offset, 0, c.length()));
}
}
return completionProposals.toArray(new ICompletionProposal[completionProposals.size()]);
}
private ICompletionProposal[] allProposalsAt(RegionWithCursor offset, N4ContentAssistProcessorTestBuilder fixture) {
AtomicReference<ICompletionProposal[]> w = new AtomicReference<>();
Display.getDefault().syncExec(() -> {
try {
w.set(fixture.computeCompletionProposals(offset
.getGlobalCursorOffset()));
} catch (Exception e) {
logger.warn("Cannot compute Completion Proposals", e);
}
});
return w.get();
}
@Override
public void adjustCrossReferencePriority(ICompletionProposal proposal, String prefix) {
// if (proposal instanceof SARLCompletionProposal) {
// final SARLCompletionProposal configurableProposal = (SARLCompletionProposal) proposal;
// final EObject eobject = configurableProposal.getReferencedFeature();
// if (eobject instanceof JvmIdentifiableElement) {
// //final JvmIdentifiableElement idElement = (JvmIdentifiableElement) eobject;
// }
// }
super.adjustCrossReferencePriority(proposal, prefix);
}
/**
* {@inheritDoc} Code copied from parent. Override required to run in UI because of getSourceViewer, which creates a new Shell.
*/
public ICompletionProposal[] computeCompletionProposals(final XtextTestSource testSource, final int cursorPosition) {
Pair<ICompletionProposal[], BadLocationException> result = UiThreadDispatcher.dispatchAndWait(new Function<Pair<ICompletionProposal[], BadLocationException>>() {
@Override
public Pair<ICompletionProposal[], BadLocationException> run() {
final IXtextDocument xtextDocument = getDocument(testSource.getXtextResource(), testSource.getContent());
return internalComputeCompletionProposals(cursorPosition, xtextDocument);
}
});
if (result.getSecond() != null) {
throw new WrappedException("Error computing completion proposals.", result.getSecond());
}
return result.getFirst();
}
public static ICompletionProposal[] collectAssists(PropertiesAssistContext invocationContext) throws BadLocationException, BadPartitioningException {
ArrayList<ICompletionProposal> resultingCollections= new ArrayList<ICompletionProposal>();
getEscapeUnescapeBackslashProposals(invocationContext, resultingCollections);
getCreateFieldsInAccessorClassProposals(invocationContext, resultingCollections);
getRemovePropertiesProposals(invocationContext, resultingCollections);
getRenameKeysProposals(invocationContext, resultingCollections);
if (resultingCollections.size() == 0)
return null;
return resultingCollections.toArray(new ICompletionProposal[resultingCollections.size()]);
}
/**
* addCloseTagProposals
*
* @param lexemeProvider
* @param offset
* @param result
*/
private boolean addDefaultCloseTagProposals(LocationType fineLocation, List<ICompletionProposal> proposals,
ILexemeProvider<HTMLTokenType> lexemeProvider, int offset)
{
HTMLParseState state = null;
boolean addedProposal = false;
// Looks like no unclosed tags that make sense. Suggest every non-self-closing tag.
List<ElementElement> elements = this._queryHelper.getElements();
if (elements != null)
{
for (ElementElement element : elements)
{
if (state == null)
{
state = new HTMLParseState(_document.get());
}
if (state.isEmptyTagType(element.getName()))
{
continue;
}
proposals.add(createCloseTagProposal(element, lexemeProvider, offset,
ICommonCompletionProposal.RELEVANCE_HIGH));
addedProposal = true;
}
}
return addedProposal;
}
private ICompletionProposal createProposal(String text) {
if (isCursorPositionValid) {
return new ReplacementCompletionProposal(text, getReplaceOffset(),
getReplaceLength(), cursorPosition, null, text, image);
} else {
return new ReplacementCompletionProposal(text, getReplaceOffset(),
getReplaceLength(),
ReplacementCompletionProposal.DEFAULT_CURSOR_POSITION, null, text,
image);
}
}
public ApplyOperation(int offset,String username,String path,List<ICompletionProposal> propList){
this.offset = offset;
this.last_offset = offset;
this.username = username;
this.path = path;
this.propList = propList;
InputString.add('.');
}
/**
* Proposes a getter that is assumed to delegate to a method with the same
* name as the java method.
*/
private void proposeGetterDelegate(IJavaProject project, IMethod method,
int invocationOffset, int indentationUnits, boolean isStatic,
List<ICompletionProposal> proposals, int numCharsFilled,
int numCharsToOverwrite) throws JavaModelException {
String methodName = method.getElementName();
String[] parameterNames = method.getParameterNames();
String expression = "return "
+ createJsMethodInvocationExpression(methodName, isStatic,
parameterNames);
String code = createJsniBlock(project, expression, indentationUnits);
proposals.add(createProposal(method.getFlags(), code, invocationOffset,
numCharsFilled, numCharsToOverwrite, expression));
}
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
List<ICompletionProposal> finalProposals = new ArrayList<ICompletionProposal>();
List<String> proposals = new ArrayList<String>();
ICompletionProposal[] toReturn = null;
try {
toReturn = doComputeProposal(viewer, offset, finalProposals, proposals);
} catch (Exception ex) {
toReturn = new ICompletionProposal[proposals.size()];
return proposals.toArray(toReturn);
}
return toReturn;
}
private void createCompletionProposalsControl(Composite parent, ICompletionProposal[] proposals) {
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
GridLayout layout2= new GridLayout(1, false);
layout2.marginHeight= 0;
layout2.marginWidth= 0;
layout2.verticalSpacing= 2;
composite.setLayout(layout2);
Label separator= new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL);
GridData gridData= new GridData(SWT.FILL, SWT.CENTER, true, false);
separator.setLayoutData(gridData);
Label quickFixLabel= new Label(composite, SWT.NONE);
GridData layoutData= new GridData(SWT.BEGINNING, SWT.CENTER, false, false);
layoutData.horizontalIndent= 4;
quickFixLabel.setLayoutData(layoutData);
String text;
if (proposals.length == 1) {
text= JavaHoverMessages.AbstractAnnotationHover_message_singleQuickFix;
} else {
text= Messages.format(JavaHoverMessages.AbstractAnnotationHover_message_multipleQuickFix, new Object[] { String.valueOf(proposals.length) });
}
quickFixLabel.setText(text);
setColorAndFont(composite, parent.getForeground(), parent.getBackground(), JFaceResources.getDialogFont());
createCompletionProposalsList(composite, proposals);
}
protected String getSortString(ICompletionProposal proposal) {
String sortString;
if(proposal instanceof LangCompletionProposal) {
LangCompletionProposal langProposal = (LangCompletionProposal) proposal;
sortString = langProposal.getSortString();
} else {
sortString = proposal.getDisplayString();
}
return sortString == null ? "\uFFFF" : sortString;
}
/**
* Create the "no proposals" proposal
*
* @return
*/
private ICompletionProposal[] createNoProposal()
{
fEmptyProposal.fOffset = fFilterOffset;
fEmptyProposal.fDisplayString = JFaceTextMessages.
getString("CompletionProposalPopup.no_proposals"); //$NON-NLS-1$
modifySelection(-1, -1); // deselect everything
return new ICompletionProposal[] { fEmptyProposal };
}
@Test
public void should_computeCompletionProposals_returns_no_proposals_for_unsupported_expression() throws Exception {
when(contentAssistContext.getPerceivedCompletionNode()).thenReturn(null);
doReturn(Collections.emptyList()).when(proposalComputer).getContractInputs(context);
final List<ICompletionProposal> proposals = proposalComputer.computeCompletionProposals(context, null);
assertThat(proposals).isEmpty();
}
@Test
public void testSpellingQuickfixInMlComment() throws Exception {
xtextEditor.getDocument().set(MODEL_WITH_SPELLING_QUICKFIX_IN_ML_COLMMENT);
ICompletionProposal[] quickAssistProposals = computeQuickAssistProposals(getDocument().getLength());
List<ICompletionProposal> proposals = Arrays.asList(quickAssistProposals);
assertSpellingQuickfixProposals(proposals);
}