How to use code completion in comments

Answered

EN:

How to use code completion in comments

When I enter "," in the comment, code completion does not appear. Is there any way to achieve this? 

CN:

当我在注释中输入","时,不会出现代码完成。 有什么办法可以实现这一点吗?

0
14 comments

Please always provide the full context and code.

0

Hi, I want to type "," or "@" when writing a comment to prompt some code completion. Is there any way to do this? It would be nice to have a simple example. 

I use the following code to trigger code completion. But it has no effect in the comments

 

import com.intellij.codeInsight.AutoPopupController
import com.intellij.codeInsight.editorActions.TypedHandlerDelegate
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile

class MyTypedHandler : TypedHandlerDelegate() {
    override fun charTyped(c: Char, project: Project, editor: Editor, file: PsiFile): Result {
        if (c == ',' || c == '@') {
            println("MyTypedHandler")
            AutoPopupController.getInstance(project).scheduleAutoPopup(editor)
            return Result.STOP
        }
        return Result.CONTINUE  
    }
}

 

import com.intellij.codeInsight.completion.CompletionContributor
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElementBuilder


class MyCompletionContributor : CompletionContributor() {

    override fun fillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet) {
        result.addElement(LookupElementBuilder.create("Hello"))
        result.addElement(LookupElementBuilder.create("World"))
        result.addLookupAdvertisement("This is an advertisement")
    }



}

 

0

Why do you override fillCompletionVariants() instead of implementing providers and registering them with CompletionContributor.extend()?

https://plugins.jetbrains.com/docs/intellij/completion-contributor.html

0

When I try the following code. It still didn't work.

The effect is the same as the previous picture.

 

import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.patterns.PlatformPatterns
import com.intellij.util.ProcessingContext


class MyCompletionContributor : CompletionContributor() {
//
//    override fun fillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet) {
//        result.addElement(LookupElementBuilder.create("Hello"))
//        result.addElement(LookupElementBuilder.create("World"))
//        result.addLookupAdvertisement("This is an advertisement")
//    }

    init {
        extend(
            CompletionType.BASIC, PlatformPatterns.psiElement(),
            object :
                CompletionProvider<CompletionParameters>() {
                override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext,
                                            resultSet: CompletionResultSet) {
                    resultSet.addElement(LookupElementBuilder.create("Hello"))
                    resultSet.addElement(LookupElementBuilder.create("World"))
                }
            }
        )
    }
}

 

0

If I remember correctly, I tried "CompletionContributor.extend()" I just tried again.

0

It seems that JavaDocCompletionContributor stops completion in some cases, see stopHere occurrences in https://github.com/JetBrains/intellij-community/blob/master/java/java-impl/src/com/intellij/codeInsight/completion/JavaDocCompletionContributor.java.

To fix it, add order="first" for your contributor in your plugin.xml (and always provide the full context, including registration in plugin.xml).

0

After I modified the plugin.xml file. The effect is the same as before. 

<completion.contributor
        language="JAVA"
        id="param" order="first"
        implementationClass="com.aiwan.jorm.annotation.MyCompletionContributor"/>

 

0

I don't know what can be the problem. It works for me perfectly.

Registration:

<extensions defaultExtensionNs="com.intellij">
    <completion.contributor
            language="JAVA" order="first"
            implementationClass="com.example.myplugin.MyCompletionContributor"/>
</extensions>

Implementation:

package com.example.myplugin
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.patterns.PlatformPatterns
import com.intellij.patterns.PlatformPatterns.psiElement
import com.intellij.util.ProcessingContext


class MyCompletionContributor : CompletionContributor() {

    init {
        extend(
            CompletionType.BASIC, psiElement(),
            object : CompletionProvider<CompletionParameters>() {
                override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext,
                                            resultSet: CompletionResultSet) {
                    resultSet.addElement(LookupElementBuilder.create("Hello"))
                    resultSet.addElement(LookupElementBuilder.create("World"))
                }
            }
        )
    }
}

Screenshot:

 

0

Hi Guys, I am having same Issue, Code Completion triggers out side comment but when I try totrigger it in comments, It does not work. 

class MyCompletionContributor extends CompletionContributor {

class MyCompletionContributor extends CompletionContributor {


    public MyCompletionContributor() {
        extend(CompletionType.BASIC,
                PlatformPatterns.psiElement().inside(PsiComment.class),
                new CompletionProvider<CompletionParameters>() {
                    @Override
                    public void addCompletions(@NotNull CompletionParameters parameters,
                                               @NotNull ProcessingContext context,
                                               @NotNull CompletionResultSet resultSet) {
                        resultSet.addElement(LookupElementBuilder.create("Hello"));
                        resultSet.addElement(LookupElementBuilder.create("World"));
                        resultSet.addElement(LookupElementBuilder.create("UniversalCompletionItem"));
                    }
                }
        );
    }

}

 

 

<completion.contributor
        language="JAVA" order="first"
        implementationClass="org.intellij.sdk.language.MyCompletionContributor"/>

 

 

I also tried replacing PlatformPatterns.psiElement().inside(PsiComment.class) with  psiElement()  with no luck.

 

However when I use PlatformPatterns.psiElement(PsiElement.class).withElementType(JavaTokenType.IDENTIFIER)

It doe trigger code completion but not inside the comment section.

 

 

0

Yasirfarhan 

Hi. I used another way to solve the problem.

import com.intellij.codeInsight.editorActions.TypedHandlerDelegate
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.ListPopup
import com.intellij.openapi.ui.popup.PopupStep
import com.intellij.openapi.ui.popup.util.BaseListPopupStep
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.ui.popup.list.ListPopupImpl
import org.jetbrains.kotlin.idea.KotlinLanguage

class MyTypedHandlerDelegate : TypedHandlerDelegate() {
    private val key = ','
    override fun charTyped(c: Char, project: Project, editor: Editor, file: PsiFile): Result {
        if (c == key) {
            showPopup(project, editor, file)
            return Result.CONTINUE
        }
        return Result.CONTINUE
    }

    private fun showPopup(project: Project, editor: Editor, file: PsiFile) {
        if (file.language !is KotlinLanguage) {
            return
        }
        var element = file.findElementAt(editor.caretModel.offset)
        if (element != null) {
            element = PsiTreeUtil.findFirstParent(element) { it is PsiComment }
        }
        if (element is PsiComment) {
           createPopup(project, listOf("test1", "test2", "test3")) {
               WriteCommandAction.runWriteCommandAction(project) {
               editor.document.deleteString(editor.caretModel.offset - key.toString().length, editor.caretModel.offset)
               editor.document.insertString(editor.caretModel.offset, it)
               editor.caretModel.moveToOffset(editor.caretModel.offset + it.length)
           } }.showInBestPositionFor(editor)
        }
    }
    private fun createPopup(project: Project, actions: List<String>, invokeAction: (String) -> Unit): ListPopup {
        val step = object : BaseListPopupStep<String>(null, actions) {
            override fun getTextFor(action: String) = action
            override fun onChosen(selectedValue: String, finalChoice: Boolean): PopupStep<*>? {
                invokeAction(selectedValue)
                return FINAL_CHOICE
            }
        }
        return ListPopupImpl(project, step)
    }
}

plugin.xml

<typedHandler implementation="org.your.path.MyTypedHandlerDelegate"/>

Result:  A prompt appears when I type ",".  I hope that will be helpful.

0

Thanks for the input.

Here are my observations about TypedHandlerDelegate. It is much more complex for my use case, I am trying to avoid manually handling triggers. It also triggered more frequently then the other one which can cause performance issue.

 

0

Hi,

Using type handler approach is an overkill, and it shouldn't be implemented this way. Please share your plugin source code or a minimal reproducible example plugin, so I can investigate the issue.

0

Hi,I have the same problem, I want to customize some suggestions while writing comments

 plugin.xml:

<completion.contributor
        language="JAVA" order="first"
        implementationClass="com.test.MyCompletionContributor"/>

MyCompletionContributor.java:

public MyCompletionContributor() {
    extend(CompletionType.BASIC,
        PlatformPatterns.psiElement().inside(PsiComment.class),
        new CompletionProvider<CompletionParameters>() {
            @Override
            public void addCompletions(@NotNull CompletionParameters parameters,
                @NotNull ProcessingContext context,

                @NotNull CompletionResultSet resultSet) {
 resultSet.addElement(LookupElementBuilder.create("Hello"));
 resultSet.addElement(LookupElementBuilder.create("World"));
                    }
                }
        );
    }

but it does not work while in  single line comment

it only works in comments block  while typing  @

0

Please sign in to leave a comment.