-
-
Notifications
You must be signed in to change notification settings - Fork 66
Google auto complete
Dmitry Kandalov edited this page Sep 12, 2021
·
11 revisions
This is a mini-plugin for IntelliJ which adds Google search results to auto-complete menu. Absolutely useless and hipster thing to do but still a lot of fun. The main point though is that auto-completion contributors can be added and modified at runtime.
(Source code can be executed inside this plugin https://github.com/dkandalov/live-plugin)
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.lang.Language
import com.intellij.openapi.Disposable
import com.intellij.patterns.ElementPattern
import com.intellij.util.ProcessingContext
import groovy.json.JsonSlurper
import org.jetbrains.annotations.NotNull
import static com.intellij.codeInsight.completion.CompletionType.BASIC
import static com.intellij.patterns.PlatformPatterns.psiElement
import static liveplugin.PluginUtil.show
if (isIdeStartup) return
def groovy = Language.findLanguageByID("Groovy")
registerCompletionContributor(groovy, BASIC, psiElement(), pluginDisposable) { parameters, context, CompletionResultSet result ->
def suggestions = googleSuggestionsFor(result.prefixMatcher.prefix).collect { toCamelHumps(it) }
result.addAllElements(suggestions.collect { LookupElementBuilder.create(it) })
}
show("Loaded auto-completion contributors")
static registerCompletionContributor(Language language, CompletionType completionType, ElementPattern elementPattern, Disposable disposable, Closure callback) {
CompletionContributor.INSTANCE.clearCache()
def contributor = new CompletionContributor() {}
contributor.extend(completionType, elementPattern, new CompletionProvider<CompletionParameters>() {
@Override protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) {
callback(parameters, context, result)
}
})
CompletionContributor.INSTANCE.addExplicitExtension(language, contributor, disposable)
}
static List<String> googleSuggestionsFor(String text) {
text = URLEncoder.encode(text, "UTF-8")
def json = "https://suggestqueries.google.com/complete/search?client=firefox&q=$text".toURL().text
new JsonSlurper().parseText(json)[1].toList()
}
static String toCamelHumps(String s) {
def i = s.indexOf(" ")
if (i == -1) s
else {
def beforeSpace = s[0..<i]
def restOfString = (s.length() > i + 2 ? s[i + 2..-1] : "")
toCamelHumps(beforeSpace + s[i + 1].toUpperCase() + restOfString)
}
}