diff --git a/pom.xml b/pom.xml
index 10ac41f6..3001bd5e 100644
--- a/pom.xml
+++ b/pom.xml
@@ -152,6 +152,11 @@
3.84.0.1
+
+ 4.0.0
+ 4.0.0
+ 2.101.0
+ 0.1.0
@@ -160,6 +165,11 @@
org.scijavascijava-common
+
+ org.scijava
+ scijava-lsp
+ ${scijava-lsp.version}
+ org.scijavascijava-search
@@ -182,6 +192,24 @@
com.fifesoftlanguagesupport
+ ${languagesupport.version}
+
+
+
+ org.mozilla
+ rhino-all
+
+
+
+
+ com.fifesoft
+ autocomplete
+ ${autocomplete.version}com.miglayout
diff --git a/src/main/java/org/scijava/ui/swing/script/CodeAssistStatus.java b/src/main/java/org/scijava/ui/swing/script/CodeAssistStatus.java
new file mode 100644
index 00000000..86bba316
--- /dev/null
+++ b/src/main/java/org/scijava/ui/swing/script/CodeAssistStatus.java
@@ -0,0 +1,426 @@
+/*
+ * #%L
+ * Script Editor and Interpreter for SciJava script languages.
+ * %%
+ * Copyright (C) 2009 - 2026 SciJava developers.
+ * %%
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ * #L%
+ */
+
+package org.scijava.ui.swing.script;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.net.URL;
+import java.time.LocalTime;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.scijava.InstantiableException;
+import org.scijava.lsp.LanguageServerPlugin;
+import org.scijava.lsp.LanguageServerService;
+import org.scijava.lsp.ScriptDialect;
+import org.scijava.plugin.PluginInfo;
+import org.scijava.plugin.PluginService;
+import org.scijava.plugin.SciJavaPlugin;
+import org.scijava.script.ScriptLanguage;
+import org.scijava.util.Types;
+
+/**
+ * What code intelligence (completion, hover, problems) an editor has for its
+ * language, and why. This includes which kind of support is installed, as well
+ * as which pieces are missing or misconfigured if a broken state is detected.
+ * Shown by the status bar, to help troubleshoot non-working code intelligence.
+ *
+ * @author Curtis Rueden
+ */
+final class CodeAssistStatus {
+
+ /** How well the language is supported, as the status bar shows it. */
+ enum Level {
+ /** Full support: a language support plugin, or a language server. */
+ OK,
+ /** Some support, but not from a language server (e.g. legacy). */
+ LIMITED,
+ /** No code intelligence for the language: nothing is wrong. */
+ NONE,
+ /** Turned off by the user. */
+ OFF,
+ /** Something is installed but broken or incomplete. */
+ ERROR
+ }
+
+ /** Which kind of support is installed. */
+ enum Backend {
+ /** A heavy RSTA language support plugin, e.g. the Java parser. */
+ PLUGIN("Language support plugin"),
+ /** Language servers, via scijava-lsp. */
+ SERVER("Language server"),
+ /** RSyntaxTextArea's own built-in support for the syntax style. */
+ LEGACY("Built-in (legacy) completion"),
+ /** Java completion, as a fallback for an unsupported language. */
+ JAVA_FALLBACK("Java completion (fallback)"),
+ /** Nothing. */
+ NONE("None");
+
+ private final String label;
+
+ Backend(final String label) {
+ this.label = label;
+ }
+ }
+
+ /** One line of the report: a check that passed or failed. */
+ static final class Check {
+
+ final boolean ok;
+ final String what;
+ final String detail;
+
+ Check(final boolean ok, final String what, final String detail) {
+ this.ok = ok;
+ this.what = what;
+ this.detail = detail;
+ }
+ }
+
+ /** The last failure of a language server, as seen while editing. */
+ static final class Failure {
+
+ final String what;
+ final Throwable cause;
+ final LocalTime time = LocalTime.now();
+
+ Failure(final String what, final Throwable cause) {
+ this.what = what;
+ this.cause = cause;
+ }
+ }
+
+ /**
+ * Whether language servers can serve a script language: its dialect, the
+ * server plugin for the dialect's output language, and any such plugins that
+ * are installed but cannot be loaded.
+ */
+ static final class Servers {
+
+ /** The dialect of the language, or null if none. */
+ ScriptDialect dialect;
+ /** The LSP language the dialect makes scripts into, or null. */
+ String output;
+ /** Whether a server plugin serves {@link #output}. */
+ boolean served;
+ /** Why asking the service failed unexpectedly, or null. */
+ Throwable error;
+ final List checks = new ArrayList<>();
+ /** Plugins installed but not loadable: a likely cause of trouble. */
+ final List broken = new ArrayList<>();
+
+ /** Whether the language is served by language servers. */
+ boolean ok() {
+ return served && error == null;
+ }
+
+ /**
+ * Whether something is half-installed: a dialect without a server, or
+ * plugins that do not load.
+ */
+ boolean misconfigured() {
+ return error != null || !broken.isEmpty() || dialect != null && !served;
+ }
+ }
+
+ final Level level;
+ /** The level before any failure: what {@link #recovered()} goes back to. */
+ private final Level configured;
+ final Backend backend;
+ final String languageName;
+ /** The class of the installed support, if any. */
+ final String supportClass;
+ final boolean enabled;
+ final boolean keyless;
+ final Servers servers;
+ final Failure failure;
+
+ private CodeAssistStatus(final Level level, final Level configured,
+ final Backend backend, final String languageName,
+ final String supportClass, final boolean enabled, final boolean keyless,
+ final Servers servers, final Failure failure)
+ {
+ this.level = level;
+ this.configured = configured;
+ this.backend = backend;
+ this.languageName = languageName;
+ this.supportClass = supportClass;
+ this.enabled = enabled;
+ this.keyless = keyless;
+ this.servers = servers;
+ this.failure = failure;
+ }
+
+ /**
+ * The status of an editor of the given language.
+ *
+ * @param support The support installed, or null.
+ * @param servers What {@link #servers} says of the language.
+ */
+ static CodeAssistStatus of(final String languageName, final Backend backend,
+ final Object support, final boolean enabled, final boolean keyless,
+ final Servers servers)
+ {
+ final Level level;
+ if (servers.misconfigured() && backend != Backend.PLUGIN) level =
+ Level.ERROR;
+ else if (!enabled) level = Level.OFF;
+ else if (backend == Backend.PLUGIN || backend == Backend.SERVER) level =
+ Level.OK;
+ else if (backend == Backend.NONE) level = Level.NONE;
+ else level = Level.LIMITED;
+ return new CodeAssistStatus(level, level, backend, languageName,
+ support == null ? null : support.getClass().getName(), enabled, keyless,
+ servers, null);
+ }
+
+ /** This status, after a language server failed. */
+ CodeAssistStatus failed(final String what, final Throwable cause) {
+ return new CodeAssistStatus(Level.ERROR, configured, backend,
+ languageName, supportClass, enabled, keyless, servers, new Failure(what,
+ cause));
+ }
+
+ /** This status, as before any failure of its language server. */
+ CodeAssistStatus recovered() {
+ if (failure == null) return this;
+ return new CodeAssistStatus(configured, configured, backend, languageName,
+ supportClass, enabled, keyless, servers, null);
+ }
+
+ /**
+ * Finds out whether language servers can serve a script language, and if
+ * not, why. Never throws: a broken installation is what this reports.
+ */
+ static Servers servers(final LanguageServerService service,
+ final PluginService plugins, final ScriptLanguage language)
+ {
+ final Servers s = new Servers();
+ s.checks.add(new Check(true, "scijava-lsp", location(
+ LanguageServerService.class)));
+ final List> dialects = infos(plugins,
+ ScriptDialect.class, s);
+ final List> servers = infos(plugins,
+ LanguageServerPlugin.class, s);
+ try {
+ try {
+ s.dialect = service.dialect(language);
+ }
+ catch (final IllegalArgumentException exc) {
+ // NB: The language has no dialect.
+ }
+ if (s.dialect == null) {
+ s.checks.add(new Check(false, "Dialect for " + language
+ .getLanguageName(), "None, so language servers do not serve " +
+ "this language (" + dialects.size() +
+ " dialect plugin(s) installed: " + names(dialects) +
+ "). If they should, the language's scripting plugin (e.g. " +
+ "scripting-" + language.getLanguageName().toLowerCase() +
+ ") must be a version which provides a dialect."));
+ return s;
+ }
+ s.output = s.dialect.outputLanguage();
+ s.checks.add(new Check(true, "Dialect for " + language
+ .getLanguageName(), s.dialect.getClass().getName() + " in " +
+ location(s.dialect.getClass()) + ", making scripts into '" +
+ s.output + "' code"));
+ s.served = service.supports(s.output);
+ if (s.served) {
+ s.checks.add(new Check(true, "Language server for '" + s.output +
+ "'", "Served (" + servers.size() + " server plugin(s) installed: " +
+ names(servers) + ")"));
+ }
+ else {
+ s.checks.add(new Check(false, "Language server for '" + s.output +
+ "'", "No server plugin serves it (" + servers.size() +
+ " server plugin(s) installed: " + names(servers) +
+ "). Install " + serverArtifact(s.output) +
+ " and its dependencies into the jars folder, then restart."));
+ }
+ }
+ catch (final RuntimeException | LinkageError exc) {
+ s.error = exc;
+ s.checks.add(new Check(false, "Language server service",
+ "Failed: " + exc + ". Some JARs are probably of incompatible " +
+ "versions."));
+ }
+ return s;
+ }
+
+ /** The installed plugins of a type, noting those that do not load. */
+ private static
List> infos(
+ final PluginService plugins, final Class
");
- return summary.toString();
+ protected static String getSummaryCompletion(final Constructor> constructor,
+ final Class> c)
+ {
+ return ClassIndex.getSummaryCompletion(constructor, c);
}
-
+
/**
- * Assembles an HTML-formatted auto-completion summary with functional
- * hyperlinks
- *
- * @param constructor the constructor being documented
- * @param c the class being documented. Expected to be documented at the
- * Scijava API documentation portal.
- * @return the completion summary
+ * Placeholder RSTA completions warning that a class was unavailable. This is
+ * the one genuinely Swing/RSTA-specific helper; it stays editor-side.
*/
- protected static String getSummaryCompletion(final Constructor> constructor, final Class> c) {
- final StringBuffer summary = new StringBuffer();
- final StringBuffer replacementHeader = new StringBuffer(c.getSimpleName());
- final int bIndex = replacementHeader.length(); // remember '(' position
- replacementHeader.append("(");
- final Parameter[] params = constructor.getParameters();
- if (params.length > 0) {
- for (final Parameter parameter : params) {
- replacementHeader.append(parameter.getType().getSimpleName()).append(" ").append(parameter.getName()).append(", ");
- }
- replacementHeader.setLength(replacementHeader.length() - 2); // remove trailing ', ';
- }
- replacementHeader.append(")");
- replacementHeader.replace(bIndex, bIndex + 1, "("); // In header, highlight only method name for extra contrast
- summary.append("").append(replacementHeader);
- summary.append("
");
- summary.append("
Intantiates:");
- summary.append("
").append(c.getSimpleName());
- summary.append("
Defined in:");
- summary.append("
").append(getJavaDocLink(c));
- summary.append("
");
- return summary.toString();
- }
-
- static List classUnavailableCompletions(final CompletionProvider provider, final String pre) {
- // placeholder completions to warn users class was not available (repeated to force pop-up display)
+ static List classUnavailableCompletions(
+ final CompletionProvider provider, final String pre)
+ {
final List list = new ArrayList<>();
- final String summary = "Class not found or invalid import. See "
- + String.format("SciJavaDocs", scijava_javadoc_URL)
- + " or search for help";
+ final String summary = "Class not found or invalid import. See " + String
+ .format("SciJavaDocs", ClassIndex.SCIJAVA_JAVADOC_URL) +
+ " or search for help";
+ // Repeated to force pop-up display.
list.add(new BasicCompletion(provider, pre + "?", null, summary));
list.add(new BasicCompletion(provider, pre + "?", null, summary));
return list;
}
-
}
diff --git a/src/main/java/org/scijava/ui/swing/script/autocompletion/CompletionText.java b/src/main/java/org/scijava/ui/swing/script/autocompletion/CompletionText.java
index e06f31f7..1b9f6bee 100644
--- a/src/main/java/org/scijava/ui/swing/script/autocompletion/CompletionText.java
+++ b/src/main/java/org/scijava/ui/swing/script/autocompletion/CompletionText.java
@@ -39,6 +39,7 @@
import org.fife.ui.autocomplete.AbstractCompletion;
import org.fife.ui.autocomplete.BasicCompletion;
import org.fife.ui.autocomplete.CompletionProvider;
+import org.scijava.lsp.jvm.ClassIndex;
public class CompletionText {
@@ -59,17 +60,17 @@ public CompletionText(final String replacementText, final String summary, final
}
public CompletionText(final String replacementText, final Class> c, final Field f) {
- this(replacementText, ClassUtil.getSummaryCompletion(f, c), null);
+ this(replacementText, ClassIndex.getSummaryCompletion(f, c), null);
}
public CompletionText(final String replacementText, final Class> c, final Method m) {
- this(replacementText, ClassUtil.getSummaryCompletion(m, c), null);
+ this(replacementText, ClassIndex.getSummaryCompletion(m, c), null);
this.method_args = Arrays.asList(m.getParameters());
this.method_returnType = m.getReturnType().getCanonicalName();
}
public CompletionText(final String replacementText, final Class> c, final Constructor> constructor) {
- this(replacementText, ClassUtil.getSummaryCompletion(constructor, c), null);
+ this(replacementText, ClassIndex.getSummaryCompletion(constructor, c), null);
this.method_args = Arrays.asList(constructor.getParameters());
this.method_returnType = c.getCanonicalName();
}
diff --git a/src/main/java/org/scijava/ui/swing/script/autocompletion/DiagnosticsParser.java b/src/main/java/org/scijava/ui/swing/script/autocompletion/DiagnosticsParser.java
new file mode 100644
index 00000000..ca1c2b69
--- /dev/null
+++ b/src/main/java/org/scijava/ui/swing/script/autocompletion/DiagnosticsParser.java
@@ -0,0 +1,119 @@
+/*
+ * #%L
+ * Script Editor and Interpreter for SciJava script languages.
+ * %%
+ * Copyright (C) 2009 - 2026 SciJava developers.
+ * %%
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ * #L%
+ */
+
+package org.scijava.ui.swing.script.autocompletion;
+
+import java.util.Collections;
+import java.util.List;
+
+import javax.swing.SwingUtilities;
+import javax.swing.text.BadLocationException;
+import javax.swing.text.Element;
+
+import org.eclipse.lsp4j.Diagnostic;
+import org.eclipse.lsp4j.DiagnosticSeverity;
+import org.fife.ui.rsyntaxtextarea.RSyntaxDocument;
+import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
+import org.fife.ui.rsyntaxtextarea.parser.AbstractParser;
+import org.fife.ui.rsyntaxtextarea.parser.DefaultParseResult;
+import org.fife.ui.rsyntaxtextarea.parser.DefaultParserNotice;
+import org.fife.ui.rsyntaxtextarea.parser.ParseResult;
+import org.fife.ui.rsyntaxtextarea.parser.ParserNotice;
+import org.scijava.lsp.Positions;
+
+/**
+ * Shows the problems language servers publish for the script (e.g. syntax
+ * errors), as squiggles, with the problem as tooltip.
+ *
+ * Servers publish problems when they like (e.g. a moment after each change):
+ * each time, the text area parses anew to show them.
+ *
+ *
+ * @author Gabriel Selzer
+ */
+public class DiagnosticsParser extends AbstractParser {
+
+ private final RSyntaxTextArea textArea;
+
+ /** The problems last published. */
+ private volatile List problems = Collections.emptyList();
+
+ public DiagnosticsParser(final RSyntaxTextArea textArea) {
+ this.textArea = textArea;
+ }
+
+ /** Shows the given problems (from any thread). */
+ public void accept(final List found) {
+ SwingUtilities.invokeLater(() -> {
+ problems = found == null ? Collections.emptyList() : found;
+ textArea.forceReparsing(this);
+ });
+ }
+
+ @Override
+ public ParseResult parse(final RSyntaxDocument doc, final String style) {
+ final DefaultParseResult result = new DefaultParseResult(this);
+ final String text;
+ try {
+ text = doc.getText(0, doc.getLength());
+ }
+ catch (final BadLocationException exc) {
+ return result;
+ }
+ final Element root = doc.getDefaultRootElement();
+ for (final Diagnostic d : problems) {
+ int start = Positions.offset(text, d.getRange().getStart());
+ final int end = Positions.offset(text, d.getRange().getEnd());
+ if (start >= text.length() && text.length() > 0) {
+ start = text.length() - 1; // NB: E.g. "unexpected end of file".
+ }
+ start = Math.max(0, start);
+ final int length = Math.max(1, Math.min(end, text.length()) - start);
+ final DefaultParserNotice notice = new DefaultParserNotice(this,
+ message(d), root.getElementIndex(start), start, length);
+ notice.setLevel(level(d.getSeverity()));
+ result.addNotice(notice);
+ }
+ return result;
+ }
+
+ private static String message(final Diagnostic d) {
+ if (d.getMessage() == null) return "";
+ return d.getMessage().isLeft() ? d.getMessage().getLeft() : d.getMessage()
+ .getRight().getValue();
+ }
+
+ private static ParserNotice.Level level(final DiagnosticSeverity s) {
+ if (s == null || s == DiagnosticSeverity.Error) {
+ return ParserNotice.Level.ERROR;
+ }
+ return s == DiagnosticSeverity.Warning ? ParserNotice.Level.WARNING
+ : ParserNotice.Level.INFO;
+ }
+}
diff --git a/src/main/java/org/scijava/ui/swing/script/autocompletion/HoverToolTipSupplier.java b/src/main/java/org/scijava/ui/swing/script/autocompletion/HoverToolTipSupplier.java
new file mode 100644
index 00000000..6804623c
--- /dev/null
+++ b/src/main/java/org/scijava/ui/swing/script/autocompletion/HoverToolTipSupplier.java
@@ -0,0 +1,152 @@
+/*
+ * #%L
+ * Script Editor and Interpreter for SciJava script languages.
+ * %%
+ * Copyright (C) 2009 - 2026 SciJava developers.
+ * %%
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ * #L%
+ */
+
+package org.scijava.ui.swing.script.autocompletion;
+
+import java.awt.event.MouseEvent;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+
+import org.eclipse.lsp4j.Hover;
+import org.eclipse.lsp4j.MarkedString;
+import org.eclipse.lsp4j.MarkupContent;
+import org.eclipse.lsp4j.jsonrpc.messages.Either;
+import org.fife.ui.rtextarea.RTextArea;
+import org.fife.ui.rtextarea.ToolTipSupplier;
+import org.scijava.lsp.ScriptSession;
+import org.scijava.log.Logger;
+
+/**
+ * Shows what the language server knows about the code under the mouse
+ * ({@code textDocument/hover}), e.g. a function's documentation, as a tooltip.
+ *
+ * RSyntaxTextArea asks for tooltips as the mouse moves, on the event dispatch
+ * thread: so the server is asked once per word, and awaited only briefly;
+ * until it answers, there is no tooltip.
+ *
+ *
+ * @author Gabriel Selzer
+ */
+public class HoverToolTipSupplier implements ToolTipSupplier {
+
+ /** How long to wait for an answer, in milliseconds. */
+ private static final long BUDGET = 100;
+
+ /** How much of an answer to show, at most, in lines. */
+ private static final int MAX_LINES = 25;
+
+ private final ScriptSession session;
+ private final Logger log;
+ private volatile ServerHealthListener health;
+
+ /** The last question (text and word), and its answer. */
+ private String askedText;
+ private int askedWord = -1;
+ private CompletableFuture answer;
+
+ public HoverToolTipSupplier(final ScriptSession session, final Logger log) {
+ this.session = session;
+ this.log = log;
+ }
+
+ @Override
+ public String getToolTipText(final RTextArea textArea, final MouseEvent e) {
+ return toolTip(textArea.getText(), textArea.viewToModel2D(e.getPoint()));
+ }
+
+ /** Gets the tooltip for an offset of a text, or null if none. */
+ String toolTip(final String text, final int offset) {
+ if (offset < 0 || offset >= text.length() || !Character
+ .isJavaIdentifierPart(text.charAt(offset))) return null;
+ int word = offset;
+ while (word > 0 && Character.isJavaIdentifierPart(text.charAt(word - 1))) {
+ word--;
+ }
+ if (word != askedWord || !text.equals(askedText)) {
+ askedText = text;
+ askedWord = word;
+ answer = ask(text, offset);
+ }
+ try {
+ final String html = html(answer.get(BUDGET, TimeUnit.MILLISECONDS));
+ return html == null ? null : "" + truncate(html) + "";
+ }
+ catch (final Exception exc) {
+ return null; // NB: Not yet; or failed.
+ }
+ }
+
+ /** Sets a listener which hears whether the server fails. */
+ public void setHealthListener(final ServerHealthListener health) {
+ this.health = health;
+ }
+
+ private CompletableFuture ask(final String text, final int offset) {
+ try {
+ return session.hover(text, offset);
+ }
+ catch (final Exception | LinkageError exc) {
+ // NB: Never let a misbehaving server break the editor.
+ if (log != null) log.debug("Hover failed", exc);
+ final ServerHealthListener h = health;
+ if (h != null) h.failed("Hover documentation", exc);
+ return CompletableFuture.completedFuture(null);
+ }
+ }
+
+ /** A hover's contents, as HTML; or null if none. */
+ static String html(final Hover hover) {
+ if (hover == null || hover.getContents() == null) return null;
+ final Either>, MarkupContent> contents =
+ hover.getContents();
+ if (contents.isRight()) {
+ return SciJavaCompletionProvider.html(Either.forRight(contents
+ .getRight()));
+ }
+ final StringBuilder sb = new StringBuilder();
+ for (final Either part : contents.getLeft()) {
+ if (sb.length() > 0) sb.append("\n\n");
+ sb.append(part.isLeft() ? part.getLeft() : part.getRight().getValue());
+ }
+ return SciJavaCompletionProvider.html(Either.forLeft(sb.toString()));
+ }
+
+ /** Keeps the first lines of long answers (e.g. docstrings). */
+ static String truncate(final String html) {
+ int end = -1;
+ for (int i = 0; i < MAX_LINES; i++) {
+ end = html.indexOf('\n', end + 1);
+ if (end < 0) return html;
+ }
+ // NB: Close an open
, lest the rest of the tooltip be preformatted.
+ final String head = html.substring(0, end);
+ final boolean pre = head.lastIndexOf("
") > head.lastIndexOf("
");
+ return head + "\n…" + (pre ? "
" : "");
+ }
+}
diff --git a/src/main/java/org/scijava/ui/swing/script/autocompletion/LanguageServerLanguageSupport.java b/src/main/java/org/scijava/ui/swing/script/autocompletion/LanguageServerLanguageSupport.java
new file mode 100644
index 00000000..9c7bc9fe
--- /dev/null
+++ b/src/main/java/org/scijava/ui/swing/script/autocompletion/LanguageServerLanguageSupport.java
@@ -0,0 +1,219 @@
+/*
+ * #%L
+ * Script Editor and Interpreter for SciJava script languages.
+ * %%
+ * Copyright (C) 2009 - 2026 SciJava developers.
+ * %%
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ * #L%
+ */
+
+package org.scijava.ui.swing.script.autocompletion;
+
+import java.io.File;
+import java.util.Map;
+import java.util.WeakHashMap;
+import java.util.function.Supplier;
+
+import javax.swing.event.DocumentEvent;
+import javax.swing.event.DocumentListener;
+
+import org.fife.rsta.ac.AbstractLanguageSupport;
+import org.fife.ui.autocomplete.AutoCompletion;
+import org.fife.ui.autocomplete.DescWindowVisibility;
+import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
+import org.scijava.lsp.ScriptSession;
+import org.scijava.log.Logger;
+
+/**
+ * RSyntaxTextArea language support from language servers, via a
+ * {@link ScriptSession} per text area (usually from
+ * {@code org.scijava.lsp.LanguageServerService}): completion with
+ * parameter assistance, documentation on hover, problems as squiggles, and
+ * signatures as a call is typed. The session is told the script's text on
+ * install and with each edit, and closed on uninstall.
+ *
+ * @author Curtis Rueden
+ * @author Gabriel Selzer
+ */
+public class LanguageServerLanguageSupport extends AbstractLanguageSupport {
+
+ private final Supplier sessions;
+ private final Logger log;
+ private final Supplier file;
+ private boolean hoverEnabled = true;
+ private boolean diagnosticsEnabled = true;
+ private ServerHealthListener health;
+
+ /** What was installed in each text area, to uninstall. */
+ private final Map installed =
+ new WeakHashMap<>();
+
+ /**
+ * @param sessions Starts a session about the script, for each text area
+ * this is installed in (e.g.
+ * {@code () -> new ScriptSession(servers, language)}).
+ * @param log Where to report problems, or null.
+ * @param file Supplies the file of the script being edited (or null if
+ * unsaved).
+ */
+ public LanguageServerLanguageSupport(final Supplier sessions,
+ final Logger log, final Supplier file)
+ {
+ this.sessions = sessions;
+ this.log = log;
+ this.file = file;
+ setAutoCompleteEnabled(true);
+ setParameterAssistanceEnabled(true);
+ setDescWindowVisibility(DescWindowVisibility.ALWAYS);
+ }
+
+ /**
+ * Sets whether to show what the server knows about the code under the
+ * mouse. Applies to later installs.
+ */
+ public void setHoverEnabled(final boolean enabled) {
+ hoverEnabled = enabled;
+ }
+
+ /**
+ * Sets whether to show the problems the server finds. Applies to later
+ * installs.
+ */
+ public void setDiagnosticsEnabled(final boolean enabled) {
+ diagnosticsEnabled = enabled;
+ }
+
+ /**
+ * Sets a listener which hears whether the servers fail, e.g. to show it.
+ * Applies to later installs.
+ */
+ public void setHealthListener(final ServerHealthListener health) {
+ this.health = health;
+ }
+
+ @Override
+ public void install(final RSyntaxTextArea textArea) {
+ final ScriptSession session = sessions.get();
+ session.setFile(file);
+ final SciJavaCompletionProvider provider = new SciJavaCompletionProvider(
+ session);
+ provider.setLogger(log);
+ provider.setHealthListener(health);
+ final AutoCompletion ac = new SciJavaAutoCompletion(provider);
+ ac.setAutoCompleteEnabled(isAutoCompleteEnabled());
+ ac.setAutoActivationEnabled(isAutoActivationEnabled());
+ ac.setParameterAssistanceEnabled(isParameterAssistanceEnabled());
+ configureDescWindow(ac);
+ ac.install(textArea);
+ installImpl(textArea, ac);
+
+ // Documentation on hover, problems as squiggles, signatures as typed.
+ final Installed extras = new Installed(session);
+ if (hoverEnabled) {
+ final HoverToolTipSupplier hover = new HoverToolTipSupplier(session, log);
+ hover.setHealthListener(health);
+ textArea.setToolTipSupplier(hover);
+ }
+ if (diagnosticsEnabled) {
+ extras.parser = new DiagnosticsParser(textArea);
+ textArea.addParser(extras.parser);
+ session.setDiagnosticsListener(extras.parser::accept);
+ }
+ if (isParameterAssistanceEnabled()) {
+ extras.popup = new SignaturePopup(textArea, provider::signatureHelp);
+ extras.popup.install();
+ }
+
+ // Keep the server's copy of the script up to date: opened now (which
+ // lets the servers get ready for it), changed with each edit.
+ extras.listener = new DocumentListener() {
+
+ @Override
+ public void insertUpdate(final DocumentEvent e) {
+ changed();
+ }
+
+ @Override
+ public void removeUpdate(final DocumentEvent e) {
+ changed();
+ }
+
+ @Override
+ public void changedUpdate(final DocumentEvent e) {
+ // NB: Attributes only.
+ }
+
+ private void changed() {
+ try {
+ session.update(textArea.getText());
+ }
+ catch (final Exception | LinkageError exc) {
+ // NB: Never let a misbehaving server break the editor.
+ if (log != null) log.debug("Document sync failed", exc);
+ if (health != null) health.failed("Sending the script to the server", exc);
+ }
+ }
+ };
+ textArea.getDocument().addDocumentListener(extras.listener);
+ installed.put(textArea, extras);
+ try {
+ session.update(textArea.getText());
+ }
+ catch (final Exception | LinkageError exc) {
+ if (log != null) log.debug("Document sync failed", exc);
+ if (health != null) health.failed("Sending the script to the server", exc);
+ }
+ }
+
+ @Override
+ public void uninstall(final RSyntaxTextArea textArea) {
+ uninstallImpl(textArea);
+ final Installed extras = installed.remove(textArea);
+ if (extras == null) return;
+ textArea.getDocument().removeDocumentListener(extras.listener);
+ if (textArea.getToolTipSupplier() instanceof HoverToolTipSupplier) {
+ textArea.setToolTipSupplier(null);
+ }
+ if (extras.parser != null) textArea.removeParser(extras.parser);
+ if (extras.popup != null) extras.popup.uninstall();
+ // Let the servers release what they keep for this script.
+ try {
+ extras.session.close();
+ }
+ catch (final Exception | LinkageError exc) {
+ if (log != null) log.debug("Document close failed", exc);
+ }
+ }
+
+ private static final class Installed {
+
+ private final ScriptSession session;
+ private DiagnosticsParser parser;
+ private SignaturePopup popup;
+ private DocumentListener listener;
+
+ private Installed(final ScriptSession session) {
+ this.session = session;
+ }
+ }
+}
diff --git a/src/main/java/org/scijava/ui/swing/script/autocompletion/SciJavaAutoCompletion.java b/src/main/java/org/scijava/ui/swing/script/autocompletion/SciJavaAutoCompletion.java
new file mode 100644
index 00000000..6f0b2a2f
--- /dev/null
+++ b/src/main/java/org/scijava/ui/swing/script/autocompletion/SciJavaAutoCompletion.java
@@ -0,0 +1,133 @@
+/*
+ * #%L
+ * Script Editor and Interpreter for SciJava script languages.
+ * %%
+ * Copyright (C) 2009 - 2026 SciJava developers.
+ * %%
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ * #L%
+ */
+
+package org.scijava.ui.swing.script.autocompletion;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+
+import javax.swing.text.BadLocationException;
+import javax.swing.text.JTextComponent;
+
+import org.fife.ui.autocomplete.Completion;
+import org.fife.ui.autocomplete.CompletionProvider;
+import org.fife.ui.rtextarea.RTextArea;
+import org.scijava.ui.swing.script.autocompletion.AdditionalEdits.Edit;
+
+/**
+ * An {@link org.fife.ui.autocomplete.AutoCompletion} that, in addition to
+ * inserting the chosen completion, applies any additional edits the
+ * completion carries (see {@link SciJavaCompletion}). This is how
+ * language-neutral auto-imports are realized in the Swing editor.
+ *
+ * @author Curtis Rueden
+ */
+public class SciJavaAutoCompletion extends
+ org.fife.ui.autocomplete.AutoCompletion
+{
+
+ public SciJavaAutoCompletion(final CompletionProvider provider) {
+ super(provider);
+ // Expand threshold to describe other overloads
+ // (2000 is just a magic number)
+ setParameterDescriptionTruncateThreshold(2000);
+ if (provider instanceof SciJavaCompletionProvider) {
+ ((SciJavaCompletionProvider) provider).setUpdateListener(
+ this::refreshPopup);
+ }
+ }
+
+ /**
+ * Shows the current (just improved) completions: in the popup, if it is
+ * showing, or in a new one, if the previous result had nothing to show.
+ */
+ private void refreshPopup(final boolean previousWasEmpty) {
+ final JTextComponent comp = getTextComponent();
+ if (comp == null || !comp.isFocusOwner()) return;
+ if (!isPopupVisible() && !previousWasEmpty) return; // NB: User closed it.
+ // NB: Never insert a lone completion the user has not chosen.
+ final boolean single = getAutoCompleteSingleChoices();
+ setAutoCompleteSingleChoices(false);
+ try {
+ doCompletion();
+ }
+ finally {
+ setAutoCompleteSingleChoices(single);
+ }
+ }
+
+ @Override
+ protected void insertCompletion(final Completion c,
+ final boolean typedParamListStartChar)
+ {
+ if (!(c instanceof AdditionalEdits)) {
+ super.insertCompletion(c, typedParamListStartChar);
+ return;
+ }
+ final List edits = ((AdditionalEdits) c).getAdditionalEdits();
+ if (edits.isEmpty()) {
+ super.insertCompletion(c, typedParamListStartChar);
+ return;
+ }
+ final JTextComponent comp = getTextComponent();
+ final RTextArea area = comp instanceof RTextArea ? (RTextArea) comp : null;
+
+ if (area != null) area.beginAtomicEdit();
+ try {
+ // Insert the primary completion first (at the completion point).
+ super.insertCompletion(c, typedParamListStartChar);
+
+ // Then apply additional edits. They lie before the completion point,
+ // so applying them from highest to lowest offset keeps each offset
+ // valid, and the caret (tracked by the document) shifts accordingly.
+ final List sorted = new ArrayList<>(edits);
+ sorted.sort(Comparator.comparingInt(Edit::start).reversed());
+ for (final Edit edit : sorted) {
+ applyEdit(comp, edit);
+ }
+ }
+ finally {
+ if (area != null) area.endAtomicEdit();
+ }
+ }
+
+ private void applyEdit(final JTextComponent comp, final Edit edit) {
+ try {
+ final int len = edit.end() - edit.start();
+ if (len > 0) comp.getDocument().remove(edit.start(), len);
+ if (edit.newText() != null && !edit.newText().isEmpty()) {
+ comp.getDocument().insertString(edit.start(), edit.newText(), null);
+ }
+ }
+ catch (final BadLocationException exc) {
+ // Document changed underneath us; skip this edit rather than fail.
+ }
+ }
+}
diff --git a/src/main/java/org/scijava/ui/swing/script/autocompletion/SciJavaCompletion.java b/src/main/java/org/scijava/ui/swing/script/autocompletion/SciJavaCompletion.java
new file mode 100644
index 00000000..b91bd5c3
--- /dev/null
+++ b/src/main/java/org/scijava/ui/swing/script/autocompletion/SciJavaCompletion.java
@@ -0,0 +1,82 @@
+/*
+ * #%L
+ * Script Editor and Interpreter for SciJava script languages.
+ * %%
+ * Copyright (C) 2009 - 2026 SciJava developers.
+ * %%
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ * #L%
+ */
+
+package org.scijava.ui.swing.script.autocompletion;
+
+import java.util.List;
+import java.util.function.Supplier;
+
+import org.fife.ui.autocomplete.BasicCompletion;
+import org.fife.ui.autocomplete.CompletionProvider;
+
+/**
+ * An RSTA {@link BasicCompletion} that also carries additional edits to apply
+ * on acceptance (e.g. auto-imports). The edits are applied by
+ * {@link SciJavaAutoCompletion}.
+ *
+ * @author Curtis Rueden
+ */
+public class SciJavaCompletion extends BasicCompletion implements
+ AdditionalEdits
+{
+
+ private final List additionalEdits;
+ private final Supplier description;
+
+ public SciJavaCompletion(final CompletionProvider provider,
+ final String replacementText, final String shortDesc, final String summary,
+ final List additionalEdits)
+ {
+ this(provider, replacementText, shortDesc, () -> summary,
+ additionalEdits);
+ }
+
+ /**
+ * @param description Supplies the description shown beside the completion
+ * list, asked for only when the completion is selected.
+ */
+ public SciJavaCompletion(final CompletionProvider provider,
+ final String replacementText, final String shortDesc,
+ final Supplier description, final List additionalEdits)
+ {
+ super(provider, replacementText, shortDesc, null);
+ this.description = description;
+ this.additionalEdits = additionalEdits;
+ }
+
+ @Override
+ public String getSummary() {
+ return description == null ? null : description.get();
+ }
+
+ @Override
+ public List getAdditionalEdits() {
+ return additionalEdits;
+ }
+}
diff --git a/src/main/java/org/scijava/ui/swing/script/autocompletion/SciJavaCompletionProvider.java b/src/main/java/org/scijava/ui/swing/script/autocompletion/SciJavaCompletionProvider.java
new file mode 100644
index 00000000..08205e7f
--- /dev/null
+++ b/src/main/java/org/scijava/ui/swing/script/autocompletion/SciJavaCompletionProvider.java
@@ -0,0 +1,635 @@
+/*
+ * #%L
+ * Script Editor and Interpreter for SciJava script languages.
+ * %%
+ * Copyright (C) 2009 - 2026 SciJava developers.
+ * %%
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ * #L%
+ */
+
+package org.scijava.ui.swing.script.autocompletion;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.swing.SwingUtilities;
+import javax.swing.text.BadLocationException;
+import javax.swing.text.JTextComponent;
+
+import org.eclipse.lsp4j.CompletionItem;
+import org.eclipse.lsp4j.CompletionItemKind;
+import org.eclipse.lsp4j.CompletionList;
+import org.eclipse.lsp4j.InsertTextFormat;
+import org.eclipse.lsp4j.MarkupContent;
+import org.eclipse.lsp4j.MarkupKind;
+import org.eclipse.lsp4j.Range;
+import org.eclipse.lsp4j.SignatureHelp;
+import org.eclipse.lsp4j.SignatureInformation;
+import org.eclipse.lsp4j.TextEdit;
+import org.eclipse.lsp4j.jsonrpc.messages.Either;
+import org.fife.ui.autocomplete.BasicCompletion;
+import org.fife.ui.autocomplete.Completion;
+import org.fife.ui.autocomplete.CompletionCellRenderer;
+import org.fife.ui.autocomplete.DefaultCompletionProvider;
+import org.fife.ui.autocomplete.ParameterizedCompletion;
+import org.scijava.lsp.Positions;
+import org.scijava.lsp.ScriptSession;
+import org.scijava.log.Logger;
+
+/**
+ * The bridge between a language server (usually one standing for all of a
+ * script language's, see {@code org.scijava.lsp.LanguageServerService})
+ * and RSyntaxTextArea's completion machinery.
+ *
+ * Completions with a snippet of parameters (e.g. {@code max(${1:a},
+ * ${2:b})}) become function completions, for parameter assistance; their
+ * parameters' types come from the label details (e.g. {@code (double a,
+ * double b)}). The parameter tooltip lists the other overloads, in signature
+ * help's order. Documentation is resolved when shown. Completions slower than
+ * a moment are shown as they arrive.
+ *
+ *
+ * @author Curtis Rueden
+ * @author Gabriel Selzer
+ */
+public class SciJavaCompletionProvider extends DefaultCompletionProvider {
+
+ /** How long to wait for completions, in milliseconds. */
+ private static final long REQUEST_TIMEOUT = 2000;
+
+ /**
+ * How long the editor waits for completions as the user types, in
+ * milliseconds; those slower are shown as they arrive.
+ */
+ private static final long ANSWER_WAIT = 50;
+
+ /** How long the parameter tooltip waits for signature help, in ms. */
+ private static final long HELP_BUDGET = 150;
+
+ /** How long to wait for documentation, in milliseconds. */
+ private static final long DESCRIBE_TIMEOUT = 1000;
+
+ /** How many choices to offer for a parameter, at most. */
+ private static final int CHOICES = 10;
+
+ /** A snippet placeholder: ${1:name}, ${1} or $1. */
+ private static final Pattern PLACEHOLDER = Pattern.compile(
+ "\\$\\{(\\d+)(?::((?:[^}\\\\]|\\\\.)*))?\\}|\\$(\\d+)");
+
+ private final ScriptSession session;
+
+ /** Optional logger, for reporting server failures. */
+ private Logger log;
+ /** Optional listener, for showing server failures. */
+ private volatile ServerHealthListener health;
+
+ // Cache so getAlreadyEnteredText() and getCompletionsImpl(), which RSTA
+ // calls in quick succession for the same caret, stay consistent.
+ private int cachedCaret = -1;
+ private String cachedText;
+ private CompletionList cachedList;
+ private int cachedStart;
+
+ // The signature help for the current text and caret.
+ private String helpText;
+ private int helpCaret = -1;
+ private volatile SignatureHelp help;
+
+ /** Notified when better completions arrive for the current request. */
+ private volatile Consumer updateListener;
+
+ /** @param session Where to ask about the script being edited. */
+ public SciJavaCompletionProvider(final ScriptSession session) {
+ this.session = session;
+ setParameterizedCompletionParams('(', ", ", ')');
+ // Show each callable's parameters and return type in the popup list.
+ setListCellRenderer(new CompletionCellRenderer());
+ // Auto-activate after a letter, digit, '.' or '_'.
+ setAutoActivationRules(true, ".");
+ setParameterChoicesProvider(this::parameterChoices);
+ }
+
+ /** Where this asks about the script being edited. */
+ public ScriptSession session() {
+ return session;
+ }
+
+ /** Sets a logger with which to report server failures. */
+ public void setLogger(final Logger log) {
+ this.log = log;
+ }
+
+ /** Sets a listener which hears whether the server fails. */
+ public void setHealthListener(final ServerHealthListener health) {
+ this.health = health;
+ }
+
+ @Override
+ public boolean isValidChar(final char c) {
+ return Character.isLetterOrDigit(c) || c == '.' || c == '_';
+ }
+
+ @Override
+ public String getAlreadyEnteredText(final JTextComponent comp) {
+ compute(comp);
+ final int caret = comp.getCaretPosition();
+ final int start = Math.min(Math.max(cachedStart, 0), caret);
+ try {
+ return comp.getText(start, caret - start);
+ }
+ catch (final BadLocationException exc) {
+ return "";
+ }
+ }
+
+ @Override
+ public List getCompletionsImpl(final JTextComponent comp) {
+ compute(comp);
+ return convert(comp, cachedList, cachedText, cachedCaret, cachedStart);
+ }
+
+ /**
+ * Sets a listener to notify when completions have arrived late for the
+ * current request, e.g. to refresh the completion popup. Called on the
+ * event dispatch thread.
+ *
+ * @param listener Accepts whether the previous completions were none (so
+ * that no popup may be showing for them).
+ */
+ public void setUpdateListener(final Consumer listener) {
+ this.updateListener = listener;
+ }
+
+ /**
+ * Gets choices for a parameter being filled in: what the server completes
+ * there, variables first (the server ranks those fitting best first).
+ */
+ List parameterChoices(final JTextComponent comp,
+ final ParameterizedCompletion.Parameter param)
+ {
+ final String text = comp.getText();
+ final CompletionList list = request(text, comp.getCaretPosition());
+ final List out = new ArrayList<>();
+ for (final CompletionItem item : sorted(list)) {
+ final CompletionItemKind k = item.getKind();
+ if (k != null && k != CompletionItemKind.Variable &&
+ k != CompletionItemKind.Field && k != CompletionItemKind.Constant &&
+ k != CompletionItemKind.Value) continue;
+ final String name = plain(newText(item));
+ out.add(new BasicCompletion(this, name, item.getDetail()));
+ if (out.size() >= CHOICES) break;
+ }
+ return out;
+ }
+
+ /**
+ * Gets signature help at the caret, waiting briefly. Remembered per text
+ * and caret; an answer arriving late is used when asked again.
+ */
+ SignatureHelp signatureHelp(final JTextComponent comp) {
+ final String text;
+ try {
+ text = comp.getText(0, comp.getDocument().getLength());
+ }
+ catch (final BadLocationException exc) {
+ return null;
+ }
+ final int caret = comp.getCaretPosition();
+ if (caret == helpCaret && text.equals(helpText) && help != null) {
+ return help;
+ }
+ SignatureHelp h = null;
+ try {
+ final CompletableFuture answer = session.signatureHelp(
+ text, caret);
+ try {
+ h = answer.get(HELP_BUDGET, TimeUnit.MILLISECONDS);
+ }
+ catch (final TimeoutException exc) {
+ // NB: Not in time: keep it for when RSTA asks again.
+ answer.thenAccept(late -> {
+ if (late != null && text.equals(helpText) && caret == helpCaret) {
+ help = late;
+ }
+ });
+ }
+ }
+ catch (final Exception | LinkageError exc) {
+ // NB: Never let a misbehaving server break the editor.
+ if (log != null) log.debug("Signature help failed", exc);
+ if (health != null) health.failed("Signature help", exc);
+ }
+ helpText = text;
+ helpCaret = caret;
+ help = h;
+ return h;
+ }
+
+ /**
+ * Lists the parameters of a callable's other overloads as HTML, one
+ * overload per line, for RSTA's parameter tooltip; or returns null if there
+ * are none.
+ *
+ * If the signature help is for this call, its signatures are listed in its
+ * order (servers list those fitting the arguments typed so far first).
+ * Otherwise, {@code overloads} are listed.
+ *
+ *
+ * @param name The callable's name.
+ * @param own Its parameters (e.g. {@code double a}).
+ * @param overloads The parameters of its overloads in the completions.
+ * @param help The signature help at the caret, or null.
+ */
+ static String otherOverloads(final String name, final List own,
+ final List> overloads, final SignatureHelp help)
+ {
+ final String ownList = parameterList(own);
+ // NB: A set, since reflection can report the same signature twice.
+ final Set lines = new LinkedHashSet<>();
+ if (help != null && isFor(help, name)) {
+ for (final SignatureInformation s : help.getSignatures()) {
+ lines.add(parameterList(SignatureLabel.of(s).parameters));
+ }
+ }
+ else if (overloads != null) {
+ for (final List o : overloads) lines.add(parameterList(o));
+ }
+ lines.remove(ownList);
+ if (lines.isEmpty()) return null;
+ final StringBuilder sb = new StringBuilder();
+ for (final String line : lines) {
+ // NB: A rule between overloads (and after RSTA's own line).
+ sb.append("").append(escapeHTML(line));
+ }
+ return sb.toString();
+ }
+
+ /** Converts documentation to HTML: Markdown as is (it allows HTML). */
+ static String html(final Either doc) {
+ if (doc == null) return null;
+ final String text;
+ if (doc.isLeft()) text = "
" + escapeHTML(doc.getLeft()) + "
";
+ else if (MarkupKind.MARKDOWN.equals(doc.getRight().getKind())) {
+ text = doc.getRight().getValue();
+ }
+ else text = "
" + escapeHTML(doc.getRight().getValue()) + "
";
+ return text == null || text.isEmpty() || text.equals("") ? null
+ : text;
+ }
+
+ // -- Helper methods --
+
+ private void compute(final JTextComponent comp) {
+ final int caret = comp.getCaretPosition();
+ final String text;
+ try {
+ text = comp.getText(0, comp.getDocument().getLength());
+ }
+ catch (final BadLocationException exc) {
+ return;
+ }
+ if (caret == cachedCaret && text.equals(cachedText) && cachedList != null) {
+ return;
+ }
+ final CompletableFuture answer = ask(text, caret);
+ cachedCaret = caret;
+ cachedText = text;
+ final CompletionList now = await(answer, ANSWER_WAIT);
+ adopt(now == null ? new CompletionList() : now);
+ if (now != null) return;
+ // NB: Not in time: show the completions when they arrive, unless
+ // anything has changed since the request.
+ final CompletionList pending = cachedList;
+ answer.thenAccept(later -> SwingUtilities.invokeLater(() -> {
+ if (cachedList != pending || caret != comp.getCaretPosition() || !text
+ .equals(comp.getText())) return;
+ adopt(later);
+ final Consumer listener = updateListener;
+ if (listener != null) listener.accept(true);
+ }));
+ }
+
+ /** Asks the server for completions, waiting for them; none if it fails. */
+ private CompletionList request(final String text, final int caret) {
+ final CompletionList list = await(ask(text, caret), REQUEST_TIMEOUT);
+ return list == null ? new CompletionList() : list;
+ }
+
+ /** Asks the server for completions; none if it fails. */
+ private CompletableFuture ask(final String text,
+ final int caret)
+ {
+ try {
+ return session.completion(text, caret).whenComplete((list, exc) -> {
+ final ServerHealthListener h = health;
+ if (exc == null && h != null) h.answered();
+ }).exceptionally(exc -> {
+ failed(exc);
+ return new CompletionList();
+ });
+ }
+ catch (final Exception | LinkageError exc) {
+ failed(exc);
+ return CompletableFuture.completedFuture(new CompletionList());
+ }
+ }
+
+ /** Waits a while for completions; null if they are not done by then. */
+ private static CompletionList await(
+ final CompletableFuture answer, final long timeout)
+ {
+ try {
+ return answer.get(timeout, TimeUnit.MILLISECONDS);
+ }
+ catch (final Exception exc) {
+ return null;
+ }
+ }
+
+ private void failed(final Throwable exc) {
+ // NB: Never let a misbehaving server break the editor.
+ if (log != null) log.debug("Code completion failed", exc);
+ final ServerHealthListener h = health;
+ if (h != null) h.failed("Code completion", exc);
+ }
+
+ /** Makes the given completions current. */
+ private void adopt(final CompletionList list) {
+ cachedList = list;
+ cachedStart = replaceStart(list, cachedText, cachedCaret);
+ }
+
+ /**
+ * Where the completions' replacement starts: the earliest of their edits'
+ * starts (completions without an edit replace the word before the caret).
+ */
+ private static int replaceStart(final CompletionList list, final String text,
+ final int caret)
+ {
+ int start = caret;
+ for (final CompletionItem item : items(list)) {
+ start = Math.min(start, itemStart(item, text, caret));
+ }
+ return start;
+ }
+
+ private static int itemStart(final CompletionItem item, final String text,
+ final int caret)
+ {
+ if (item.getTextEdit() != null) {
+ final Range r = item.getTextEdit().isLeft() ? item.getTextEdit()
+ .getLeft().getRange() : item.getTextEdit().getRight().getInsert();
+ return Math.min(caret, Positions.offset(text, r.getStart()));
+ }
+ int start = Math.min(caret, text.length());
+ while (start > 0 && Character.isJavaIdentifierPart(text.charAt(start -
+ 1))) start--;
+ return start;
+ }
+
+ /** Converts the server's completions to RSTA's. */
+ private List convert(final JTextComponent comp,
+ final CompletionList list, final String text, final int caret,
+ final int start)
+ {
+ final List items = sorted(list);
+ // Group callables by name, so each can list its sibling overloads.
+ final Map>> overloads = new HashMap<>();
+ final List