completions contributor for strings
Hi,
I would like to provide some suggestions for a given method, where only certain strings are applicable. Eg:
class Bar {
void foo(String str) {}
}
// usage
new Bar().foo(<caret>) // should suggest: Aaaa, Bbbb etc
This would be very similar to that provided for charsets, for example.

After some puzzling I found that this is implemented through an EncodingReferenceInjector, and an EncodingReference which implements getVariants. The actual relevant places where this reference should be used are defined in javaInjections.xml (which looks a little cumbersome).
The other way of implementing this, as far as I can tell, is using CompletionContributor. But there I have problems in finding out what the fully qualified method is in which the completions have been invoked, in order to tell whether to provide any suggestions or not.
I guess my questions are:
1. Which method should one normally use.
2. Is there any example of the latter, or a way of say given this doc: "".substring(<caret>) - getting the method reference to String.substring(int). I can do it when the caret is in the method name, but struggling when the caret is in the parens.
Thanks in advance,
jamie
Please sign in to leave a comment.
In CompletionContributor, you have CompletionParameters#getPosition. You can traverse its PSI upwards (using getParent or PsiTreeUtil.getParentOfType) and find a PsiMethodCallExpression, which has resolveMethod. Is this what you're looking for?
Yes, I have that working for some test code - I just wanted to validate this approach. . So you recommend this approach over the other one (reference injector)?
I''m using PlatformPatterns.psiElement() for the ElementPattern (in com.intellij.codeInsight.completion.CompletionContributor#extend), and wondered if I should be using that to filter?
Yes, I'd recommend this approach, as it's usually easier to debug (although less declarative).
For filtering, you can also use psiElement().withParent(PsiJavaPatterns.literalExpression().methodCallParameter()).
Awesome, thanks Peter.