From fe084e18438db6f24ba8aa1a8664244d8b271f20 Mon Sep 17 00:00:00 2001
From: Aran Roig
Date: Thu, 8 Oct 2026 14:00:22 +0200
Subject: [PATCH] More things editor is now more stable
---
AGENTS.md | 25 +-
docs/lua-api.md | 2 +
.../client/editor/CompletionItem.java | 32 +-
.../client/editor/CompletionProvider.java | 23 +-
.../aranroig/client/editor/DocLibraries.java | 94 ++++
.../aranroig/client/editor/EditHistory.java | 226 ++++++++
.../client/editor/EditorDocsPanel.java | 439 +++++++++++++--
.../client/editor/EditorFileView.java | 518 +++++++++++++++++-
.../aranroig/client/editor/EditorFindBar.java | 317 +++++++++++
.../aranroig/client/editor/EditorManager.java | 102 +++-
.../client/editor/EditorSearchPopup.java | 320 +++++++++++
.../aranroig/client/editor/EditorTheme.java | 47 +-
.../client/editor/EditorThemePopup.java | 178 ++++++
.../aranroig/client/editor/EditorTopBar.java | 21 +-
.../aranroig/client/editor/EventsLibrary.java | 30 -
.../aranroig/client/editor/LiveDocument.java | 15 +
.../aranroig/client/editor/LuaLibrary.java | 7 +-
.../client/editor/MinecraftLibraries.java | 28 -
.../client/editor/TextEditorScreen.java | 14 +
.../aranroig/client/editor/WorldLibrary.java | 33 --
src/main/java/com/aranroig/editor/Edit.java | 32 ++
21 files changed, 2323 insertions(+), 180 deletions(-)
create mode 100644 src/client/java/com/aranroig/client/editor/DocLibraries.java
create mode 100644 src/client/java/com/aranroig/client/editor/EditHistory.java
create mode 100644 src/client/java/com/aranroig/client/editor/EditorFindBar.java
create mode 100644 src/client/java/com/aranroig/client/editor/EditorSearchPopup.java
create mode 100644 src/client/java/com/aranroig/client/editor/EditorThemePopup.java
delete mode 100644 src/client/java/com/aranroig/client/editor/EventsLibrary.java
delete mode 100644 src/client/java/com/aranroig/client/editor/MinecraftLibraries.java
delete mode 100644 src/client/java/com/aranroig/client/editor/WorldLibrary.java
diff --git a/AGENTS.md b/AGENTS.md
index 6b0bc23..b35cc0e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -9,6 +9,22 @@ Codecraft is a Fabric mod (mod id `codecraft`, group `com.aranroig`) that lets p
- `./gradlew runDatagen` — regenerate data (lang files) into `src/main/generated/`.
- Requires JDK 25. CI (`.github/workflows/build.yml`) builds on ubuntu-24.04 with JDK 25 (Microsoft distribution).
+## Fast task-oriented reading
+
+Do not read the whole source tree just to get oriented. Start with the files named in the task, then follow only the callers, callees, and data types needed to understand that change. Use `rg` to find a symbol or payload's other endpoints when needed. Check `git status --short` first and preserve pre-existing user changes; avoid touching unrelated files.
+
+Use this map to find the likely starting point:
+
+- **Editor input, layout, and panes:** `TextEditorScreen`, `EditorScreen`, `Widget`, `EditorTopBar`, `EditorFileTree`, `EditorPaneContainer`, `EditorFileView` under `src/client/java/com/aranroig/client/editor/`.
+- **Text editing, completion, and syntax colors:** `EditorFileView`, `LiveDocument`, `EditHistory`, `CompletionProvider`, and `LuaHighlighter` in that same package. For edit networking, follow the corresponding payloads to `DocumentManager`.
+- **Project files, collaboration, and persistence:** `Codecraft` registers packet handlers; `DocumentManager` owns live shared documents; `ProjectStore` reads/writes files; `ProjectPath` defines file names; `SavedProjectData` only handles legacy migration. Follow only the subsystem involved in the task.
+- **Lua execution and API behavior:** `Codecraft` handles the run request; `ScriptRuntimeManager` owns server-side runtimes and event dispatch; `ScriptRuntime` owns one Lua state; API bindings are in `src/main/java/com/aranroig/wrapper/` and `listeners/`. Read `docs/lua-api.md` first for documented user-facing behavior.
+- **In-game Lua documentation and completion libraries:** `docs/lua-api.md` is the human-authored reference; `src/main/resources/data/codecraft/docs/lua-api.json` is the packaged data; `LuaApiDocs`, `DocLibraries`, and `CompletionProvider` load or expose it in the editor. For translation changes, edit `CodecraftEnglishLangProvider`, not generated output.
+- **Terminal pane and server shell:** `EditorTerminalPane` and `TerminalEmulator` are client-side; `ShellManager` and `ShellSession` are server-side; shell payloads connect them.
+- **Mod setup, versions, and metadata:** `gradle.properties`, `build.gradle`, `src/main/resources/fabric.mod.json`, and the mixin configs. Do not inspect editor code for a build or metadata-only task.
+
+Generated files under `src/main/generated/` should only be inspected when the generated output itself is relevant. Change its provider/input and regenerate it instead of editing it by hand.
+
## Versions
All versions live in `gradle.properties` (check https://fabricmc.net/develop): Minecraft `26.2`, loader `0.19.3`, loom `1.17-SNAPSHOT`, Fabric API `0.153.0+26.2`. Java release/target is 25. Mod version comes from `mod_version` and is expanded into `fabric.mod.json` at build time — never hardcode the version there.
@@ -17,7 +33,7 @@ All versions live in `gradle.properties` (check https://fabricmc.net/develop): M
Loom uses `splitEnvironmentSourceSets()`:
-- `src/main/java` — common/server code. Entrypoint `com.aranroig.Codecraft` (registers payloads, handles them server-side). Lua execution belongs here eventually.
+- `src/main/java` — common/server code. Entrypoint `com.aranroig.Codecraft` registers payloads and handles them server-side; Lua execution and its API bindings also run here.
- `src/client/java` — client-only code. Entrypoints `com.aranroig.client.CodecraftClient` (keybind, default `J`, toggles the editor) and `com.aranroig.client.CodecraftDataGenerator` (datagen).
- `src/main/resources` — `fabric.mod.json`, mixins config, assets.
- `src/main/generated` — datagen output (e.g. `assets/codecraft/lang/en_us.json`). Do not hand-edit; add translations in `CodecraftEnglishLangProvider` and run `runDatagen`.
@@ -28,8 +44,8 @@ Flow: client editor → custom payloads → server → persisted project.
- **Networking** (`com.aranroig.payloads`): one record per message implementing `CustomPacketPayload` with a static `TYPE` and `StreamCodec`. Serverbound payloads must be registered in `Codecraft.onInitialize()` via `PayloadTypeRegistry.serverboundPlay().register(...)`, and received with `ServerPlayNetworking.registerGlobalReceiver(...)`.
- **Persistence** (`com.aranroig.project.ProjectStore`): the project lives on the server's disk under `config/codecraft/` as plain `.lua` files mirroring the project paths (`lib/gui/theme` → `config/codecraft/lib/gui/theme.lua`), so it can also be edited with external editors — the project is re-read from disk every time the editor opens. Explicit saves write synchronously; keystrokes go to a pending map a daemon thread flushes ~1s after typing settles, and everything pending is flushed on server stop. Names are sanitized (`..` etc. refused) before touching the filesystem. `SavedProjectData` (world `SavedData`) is legacy: kept only to migrate a world's scripts into the config folder once, on `SERVER_STARTED`, when the config folder holds no scripts yet. The project is now per server-install, not per world.
-- **Editor UI** (`com.aranroig.client.editor`): a custom immediate-mode-ish GUI system, not vanilla widgets. `EditorScreen` routes key/mouse input to `Widget`s by hit-testing (`inside()`) and z-index; scrolling goes to the widget under the mouse. `EditorManager` owns the widgets and editor actions (save/run/etc.); `EditorFileTree`, `EditorTopBar`, `EditorPaneContainer` are the three panels. `EditorPaneContainer` tiles the editing area into one or more `EditorFileView` panes (split right/below from the pane headers, the View menu, or Ctrl+\ / Ctrl+Shift+\), each header naming its file; the sashes between panes drag to resize them, and the "active pane" (last pane clicked) is where files from the tree open and where saving applies. `EditorFileView` is the actual text editor; `LuaHighlighter` tokenizes lines into colored `Span`s and `CompletionProvider` handles autocomplete.
-- **Lua runtime**: `EditorManager.run()` sends a `ServerboundRunCodePayload` with the entrypoint name; the server handler in `Codecraft.java` is a TODO (currently just prints). Example of embedding: `Lua l = new LuaJ(); l.register("print", Logger.print()); l.run(code);` — `com.aranroig.client.wrapper.Logger` adapts a `LuaFunction` to print into the player chat. Decide carefully whether Lua runs client- or server-side; server-side is the apparent direction.
+- **Editor UI** (`com.aranroig.client.editor`): custom widgets, not vanilla widgets. `EditorScreen` routes input to hit-tested `Widget`s. `EditorManager` owns editor actions; `EditorFileTree`, `EditorTopBar`, and `EditorPaneContainer` make up the main layout. The pane container manages one or more `EditorFileView`s; edits are tracked per pane and shared through the live-document payloads. See the task-oriented map above before opening more UI classes.
+- **Lua runtime**: `EditorManager.run()` sends a `ServerboundRunCodePayload`; `Codecraft` reads the entrypoint from `ProjectStore` and starts a fresh per-player runtime through `ScriptRuntimeManager`. Lua runs on the server thread. `docs/lua-api.md` documents the exposed API; the server bindings live under `src/main/java/com/aranroig/wrapper/` and `listeners/`.
## Conventions
@@ -42,6 +58,7 @@ Flow: client editor → custom payloads → server → persisted project.
## Status / gotchas
-- Work in progress: `EditorManager.newFile/undo/redo/stop` are empty stubs, server-side code execution is unimplemented, `com.aranroig.editor.Project` is a stub that is meant to replace the raw `List` usage, and `EditorManager.files` is never populated (loading files from the server is an open TODO; `toggleVisible()` will NPE on `files.getFirst()`).
+- `EditorManager.stop()` is currently empty. `com.aranroig.editor.Project` remains a stub; file lists are still represented as `List`.
+- Lua execution, event listeners, API bindings, live document collaboration, project loading, persistence, and the terminal shell are implemented. Check the relevant task-map entries before assuming one of these is still a TODO.
- Some TODOs/comments are written in Spanish/Catalan; leave them unless resolving them.
- Minecraft 26.2 uses the newer class/mapping names (`Identifier`, `GuiGraphicsExtractor`, `MouseButtonEvent`, `Component`, etc.) — don't rename them back to older MCP/Yarn-era names.
diff --git a/docs/lua-api.md b/docs/lua-api.md
index 496d2a8..89429e0 100644
--- a/docs/lua-api.md
+++ b/docs/lua-api.md
@@ -6,6 +6,8 @@ Scripts are written in the in-game editor (`J` by default, rebindable under
This same documentation is browsable in-game from the editor:
**Help → Lua API Documentation**, or press **F1** on a function while editing.
+The browser has a search box above its function list — press **Ctrl+F** and
+type to filter functions by name or description.
Because a script runs on the server thread from start to finish, everything it does
happens at once and the game waits for it to finish. Loops that place millions of
diff --git a/src/client/java/com/aranroig/client/editor/CompletionItem.java b/src/client/java/com/aranroig/client/editor/CompletionItem.java
index 6a05baf..bbb7806 100644
--- a/src/client/java/com/aranroig/client/editor/CompletionItem.java
+++ b/src/client/java/com/aranroig/client/editor/CompletionItem.java
@@ -1,5 +1,7 @@
package com.aranroig.client.editor;
+import com.aranroig.docs.FunctionDoc;
+
/**
* A single autocomplete suggestion.
*
@@ -8,8 +10,25 @@ package com.aranroig.client.editor;
* but can differ (e.g. snippets with a trailing "(" etc.).
* @param detail Short right-aligned annotation shown in the dropdown (e.g. "method", "keyword").
* @param kind Category used for the icon/colour badge.
+ * @param docs Optional documentation rendered as a multi-line box below the
+ * popup for the highlighted item; null for items without docs.
*/
-public record CompletionItem(String label, String insert, String detail, Kind kind) {
+public record CompletionItem(String label, String insert, String detail, Kind kind, Docs docs) {
+
+ /** Convenience constructor for items without documentation. */
+ public CompletionItem(String label, String insert, String detail, Kind kind) {
+ this(label, insert, detail, kind, null);
+ }
+
+ /**
+ * The API documentation attached to a completion.
+ *
+ * @param name Fully qualified name (e.g. {@code world.set_block} or {@code world}).
+ * @param blurb Description of a plain table; null for documented functions.
+ * @param function The full function doc; null for plain tables.
+ */
+ public record Docs(String name, String blurb, FunctionDoc function) {
+ }
public enum Kind {
KEYWORD, // language keywords
@@ -35,4 +54,15 @@ public record CompletionItem(String label, String insert, String detail, Kind ki
public static CompletionItem snippet(String label, String insert, String detail) {
return new CompletionItem(label, insert, detail, Kind.SNIPPET);
}
+
+ /** A method/function documented in the Lua API catalog. */
+ public static CompletionItem documentedMethod(String label, String insert, FunctionDoc function) {
+ return new CompletionItem(label, insert, "method", Kind.METHOD,
+ new Docs(function.name(), null, function));
+ }
+
+ /** A global table documented in the Lua API catalog. */
+ public static CompletionItem documentedType(String name, String blurb) {
+ return new CompletionItem(name, name, "type", Kind.TYPE, new Docs(name, blurb, null));
+ }
}
\ No newline at end of file
diff --git a/src/client/java/com/aranroig/client/editor/CompletionProvider.java b/src/client/java/com/aranroig/client/editor/CompletionProvider.java
index 8210d26..a3e0324 100644
--- a/src/client/java/com/aranroig/client/editor/CompletionProvider.java
+++ b/src/client/java/com/aranroig/client/editor/CompletionProvider.java
@@ -12,7 +12,9 @@ import java.util.regex.Pattern;
* {@link LuaSnippets snippets}.
* Words already present in the buffer (user-defined functions/variables).
* Library member completion after a "." or ":" trigger, backed by the
- * {@link LuaLibrary} instances loaded in {@link #registerLibraries()}.
+ * {@link LuaLibrary} instances loaded in {@link #registerLibraries()} —
+ * Lua's own standard library plus the codecraft globals generated from
+ * the {@link com.aranroig.docs.LuaApiDocs} catalog.
*
*
* None of this requires a real LSP – it is "good-enough" IDE-lite completion
@@ -30,6 +32,11 @@ public class CompletionProvider {
static {
List items = new ArrayList<>();
+ // ── Codecraft globals, generated from the Lua API docs catalog ─────
+ // First in the list so their documented versions win over the plain
+ // duplicates below when labels collide.
+ items.addAll(DocLibraries.topLevelItems());
+
// ── Lua keywords ─────────────────────────────────────────────────
for (String kw : new String[]{
"and", "break", "do", "else", "elseif", "end",
@@ -42,7 +49,7 @@ public class CompletionProvider {
for (String fn : new String[]{
"assert", "collectgarbage", "dofile", "error", "getmetatable",
"ipairs", "load", "loadfile", "next", "pairs",
- "pcall", "print", "run", "rawequal", "rawget", "rawlen", "rawset",
+ "pcall", "rawequal", "rawget", "rawlen", "rawset",
"require", "select", "setmetatable", "tonumber", "tostring",
"type", "unpack", "xpcall"
}) items.add(CompletionItem.method(fn + "(", fn + "("));
@@ -50,7 +57,7 @@ public class CompletionProvider {
// ── Built-in global tables (as types) ────────────────────────────
for (String lib : new String[]{
"string", "table", "math", "io", "os", "coroutine",
- "package", "utf8", "debug", "_G", "_VERSION", "world", "events"
+ "package", "utf8", "debug", "_G", "_VERSION"
}) items.add(CompletionItem.type(lib));
// ── Common snippets ───────────────────────────────────────────────
@@ -63,15 +70,15 @@ public class CompletionProvider {
/**
* Loads the libraries whose members are offered after a dot or colon.
- * To expose a new codecraft-provided table in the autocomplete popup,
- * implement {@link LuaLibrary} and add an instance here.
+ * Codecraft-provided tables come from the {@link com.aranroig.docs.LuaApiDocs}
+ * catalog, so documenting a function in {@code lua-api.json} is all it takes
+ * to make it complete in the editor. To expose a plain Lua table, implement
+ * {@link LuaLibrary} and add an instance here.
*/
private static Map> registerLibraries() {
List libraries = new ArrayList<>();
libraries.addAll(LuaStandardLibraries.all()); // Lua's own standard library
- libraries.add(new WorldLibrary()); // block access provided by codecraft
- libraries.add(new EventsLibrary()); // game event listeners provided by codecraft
- libraries.addAll(MinecraftLibraries.all()); // server-side Minecraft APIs
+ libraries.addAll(DocLibraries.libraries()); // codecraft globals, from the docs
Map> members = new LinkedHashMap<>();
for (LuaLibrary library : libraries) {
diff --git a/src/client/java/com/aranroig/client/editor/DocLibraries.java b/src/client/java/com/aranroig/client/editor/DocLibraries.java
new file mode 100644
index 0000000..e7777b8
--- /dev/null
+++ b/src/client/java/com/aranroig/client/editor/DocLibraries.java
@@ -0,0 +1,94 @@
+package com.aranroig.client.editor;
+
+import com.aranroig.docs.FunctionDoc;
+import com.aranroig.docs.LuaApiDocs;
+import com.aranroig.docs.Topic;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Autocomplete data for every codecraft-provided Lua global, generated from the
+ * {@link LuaApiDocs} catalog ({@code data/codecraft/docs/lua-api.json}) instead
+ * of hand-maintained lists — anything documented in the in-game docs panel is
+ * completed in the editor automatically, with its full documentation rendered
+ * as a multi-line box below the completion popup.
+ *
+ * Functions whose name is dotted ({@code world.set_block}) become members of
+ * the table before the first dot; functions with a bare name ({@code run},
+ * {@code print}) are offered as top-level completions.
+ */
+public final class DocLibraries {
+
+ private DocLibraries() {
+ }
+
+ /** One {@link LuaLibrary} per documented table, for completion after a dot. */
+ public static List libraries() {
+ Map> members = new LinkedHashMap<>();
+ for (FunctionDoc function : LuaApiDocs.functions()) {
+ String table = tableOf(function.name());
+ if (table.isEmpty()) continue; // bare globals are top-level items
+ members.computeIfAbsent(table, t -> new ArrayList<>())
+ .add(CompletionItem.documentedMethod(
+ memberOf(function.name()), memberOf(function.name()) + "(", function));
+ }
+
+ List libraries = new ArrayList<>();
+ for (Map.Entry> entry : members.entrySet()) {
+ String name = entry.getKey();
+ List items = List.copyOf(entry.getValue());
+ libraries.add(new LuaLibrary() {
+ @Override public String name() { return name; }
+ @Override public List members() { return items; }
+ });
+ }
+ return libraries;
+ }
+
+ /**
+ * Top-level completion items from the catalog: documented tables as types
+ * (with the topic blurb) and bare documented functions as methods.
+ */
+ public static List topLevelItems() {
+ List items = new ArrayList<>();
+ Set seenTables = new LinkedHashSet<>();
+ for (FunctionDoc function : LuaApiDocs.functions()) {
+ String table = tableOf(function.name());
+ if (table.isEmpty()) {
+ items.add(CompletionItem.documentedMethod(
+ function.name(), function.name() + "(", function));
+ } else if (seenTables.add(table)) {
+ String blurb = blurbOf(table);
+ items.add(CompletionItem.documentedType(table, blurb.isEmpty() ? null : blurb));
+ }
+ }
+ return items;
+ }
+
+ // ── Derivation helpers ────────────────────────────────────────────────
+
+ /** The table part of a dotted function name, or "" when it is a bare global. */
+ private static String tableOf(String functionName) {
+ int dot = functionName.indexOf('.');
+ return dot < 0 ? "" : functionName.substring(0, dot);
+ }
+
+ /** The member part of a dotted function name (the whole name when bare). */
+ private static String memberOf(String functionName) {
+ int dot = functionName.indexOf('.');
+ return dot < 0 ? functionName : functionName.substring(dot + 1);
+ }
+
+ /** The blurb of the topic whose title names the table, "" when unknown. */
+ private static String blurbOf(String table) {
+ for (Topic topic : LuaApiDocs.topics()) {
+ if (topic.title().equals(table)) return topic.blurb().replace('\n', ' ').trim();
+ }
+ return "";
+ }
+}
diff --git a/src/client/java/com/aranroig/client/editor/EditHistory.java b/src/client/java/com/aranroig/client/editor/EditHistory.java
new file mode 100644
index 0000000..710f8b6
--- /dev/null
+++ b/src/client/java/com/aranroig/client/editor/EditHistory.java
@@ -0,0 +1,226 @@
+package com.aranroig.client.editor;
+
+import com.aranroig.editor.Edit;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.List;
+import java.util.UUID;
+
+/**
+ * What a file view remembers so Ctrl+Z and Ctrl+Shift+Z have something to
+ * take back and give forward again.
+ *
+ * Each remembered change is kept as an {@link Edit} — the same walk over
+ * the text the editor sends around — that undoes (or redoes) it, written
+ * against the buffer as the view holds it. That is what lets undo survive
+ * somebody else editing the same file: every edit that arrives from them
+ * rewrites the remembered walks along with the buffer ({@link
+ * #rebaseAgainst}), so taking a change back lands on it wherever the text
+ * around it has drifted.
+ *
+ * Among the player's own changes the stacks need no rewriting: undo walks
+ * them last-to-first, and each remembered step was taken out of exactly the
+ * buffer the step before it puts back.
+ */
+final class EditHistory {
+
+ /**
+ * One remembered change: the walk that undoes (or redoes) it, and the
+ * caret and selection to come back with it.
+ */
+ record Entry(Edit operation, int caret, int selectionAnchor) {}
+
+ /** How far back undo — and redo — reach. */
+ private static final int MAX_ENTRIES = 512;
+
+ /**
+ * Changes this close together that keep writing on, erase back or delete
+ * forward count as one gesture: a single Ctrl+Z takes the word away
+ * instead of one letter at a time.
+ */
+ private static final long MERGE_INTERVAL_MS = 500;
+
+ /**
+ * The author remembered walks carry. They never go out on the wire — an
+ * undo is sent as an edit with this client's real id — they only name
+ * them so that, when one is transformed against an incoming edit, it is
+ * never mistaken for another player's.
+ */
+ private static final UUID AUTHOR = new UUID(0L, 0L);
+
+ /** Changes to take back, oldest first: the last one is the next to undo. */
+ private final Deque undo = new ArrayDeque<>();
+
+ /** What undo gave back, oldest first: the last one is the next to redo. */
+ private final Deque redo = new ArrayDeque<>();
+
+ private long sequence;
+ private long lastEditAt;
+
+ /**
+ * Remembers a change the player just made. {@code deleted} is what came
+ * out of the buffer at {@code position} and {@code inserted} what went in
+ * its place; the caret and selection say where undo should bring them
+ * back. Whatever was waiting to be redone falls away: the story carries
+ * on from here.
+ */
+ void recordLocalEdit(int position, String deleted, String inserted, int caret, int selectionAnchor) {
+ if (deleted.isEmpty() && inserted.isEmpty()) return;
+ redo.clear();
+
+ long now = System.currentTimeMillis();
+ boolean sameGesture = now - lastEditAt <= MERGE_INTERVAL_MS;
+ lastEditAt = now;
+
+ Edit step = Edit.replace(AUTHOR, sequence++, position, inserted.length(), deleted);
+ if (sameGesture && mergeIntoLast(step)) return;
+
+ undo.addLast(new Entry(step, caret, selectionAnchor));
+ trim(undo);
+ }
+
+ /** The next change to take back, or {@code null} once there is none. */
+ Entry takeUndo() {
+ lastEditAt = 0; // typing after an undo belongs to a gesture of its own
+ return undo.pollLast();
+ }
+
+ /** The next change to put back in, or {@code null} once there is none. */
+ Entry takeRedo() {
+ lastEditAt = 0;
+ return redo.pollLast();
+ }
+
+ /** Puts a change that undo took onto the redo stack. */
+ void putRedo(Entry entry) {
+ redo.addLast(entry);
+ trim(redo);
+ }
+
+ /** Puts a change that redo undid back onto the undo stack. */
+ void putUndo(Entry entry) {
+ undo.addLast(entry);
+ trim(undo);
+ }
+
+ /**
+ * Somebody else's edit is about to be applied to the buffer. Everything
+ * remembered was written against the text as it stands before that, so
+ * every walk — and every caret it would restore — is rewritten against
+ * the text as it will stand after.
+ */
+ void rebaseAgainst(Edit incoming) {
+ if (incoming.isEmpty()) return;
+ rebase(undo, incoming);
+ rebase(redo, incoming);
+ }
+
+ /** Forgets everything: the buffer is about to become somebody else's text. */
+ void clear() {
+ undo.clear();
+ redo.clear();
+ }
+
+ // ── Folding one gesture into a single step ────────────────────────────
+
+ /**
+ * Folds {@code step} into the last remembered change when the two are one
+ * gesture carried on: typing forward, erasing back, or the Delete key
+ * eating forward. The caret of the earlier step is kept — that is where
+ * the gesture started. False when this step stands on its own.
+ */
+ private boolean mergeIntoLast(Edit step) {
+ Entry last = undo.peekLast();
+ if (last == null) return false;
+ Edit previous = last.operation();
+
+ int[] cutBefore = cutOf(previous);
+ int[] cut = cutOf(step);
+ if (cutBefore != null && cut != null && adjacent(cutBefore, cut)) {
+ return replaceLast(new Entry(Edit.deletion(AUTHOR, sequence++,
+ Math.min(cutBefore[0], cut[0]), cutBefore[1] + cut[1]),
+ last.caret(), last.selectionAnchor()));
+ }
+
+ Writing wroteBefore = writtenOf(previous);
+ Writing wrote = writtenOf(step);
+ if (wroteBefore != null && wrote != null) {
+ if (wrote.at() == wroteBefore.at() + wroteBefore.text().length())
+ return replaceLast(rejoined(last, wroteBefore.at(), wroteBefore.text() + wrote.text()));
+ if (wroteBefore.at() == wrote.at() + wrote.text().length())
+ return replaceLast(rejoined(last, wrote.at(), wrote.text() + wroteBefore.text()));
+ if (wrote.at() == wroteBefore.at())
+ return replaceLast(rejoined(last, wroteBefore.at(), wroteBefore.text() + wrote.text()));
+ }
+ return false;
+ }
+
+ private boolean replaceLast(Entry merged) {
+ undo.pollLast();
+ undo.addLast(merged);
+ return true;
+ }
+
+ /** A last step replaced by one that writes both runs back in their order. */
+ private Entry rejoined(Entry last, int at, String text) {
+ return new Entry(Edit.insertion(AUTHOR, sequence++, at, text), last.caret(), last.selectionAnchor());
+ }
+
+ /** Whether two erased runs touch: end to end, or the very same place again. */
+ private static boolean adjacent(int[] first, int[] second) {
+ return first[0] + first[1] == second[0]
+ || second[0] + second[1] == first[0]
+ || first[0] == second[0];
+ }
+
+ /** {@code {position, length}} when the walk erases one run of the text, else {@code null}. */
+ private static int[] cutOf(Edit edit) {
+ List components = edit.components();
+ int position = 0;
+ for (int i = 0; i < components.size(); i++) {
+ Edit.Component component = components.get(i);
+ if (component instanceof Edit.Retain retain) position += retain.count();
+ else if (component instanceof Edit.Delete delete && i == components.size() - 1)
+ return new int[]{position, delete.count()};
+ else return null;
+ }
+ return null;
+ }
+
+ /** Where and what, when the walk writes one run and erases nothing, else {@code null}. */
+ private static Writing writtenOf(Edit edit) {
+ List components = edit.components();
+ int position = 0;
+ for (int i = 0; i < components.size(); i++) {
+ Edit.Component component = components.get(i);
+ if (component instanceof Edit.Retain retain) position += retain.count();
+ else if (component instanceof Edit.Insert insert && i == components.size() - 1)
+ return new Writing(position, insert.text());
+ else return null;
+ }
+ return null;
+ }
+
+ /** One run an undo step writes back. */
+ private record Writing(int at, String text) {}
+
+ // ── Following the other editors ───────────────────────────────────────
+
+ private static void rebase(Deque remembered, Edit incoming) {
+ List rewritten = new ArrayList<>(remembered.size());
+ for (Entry entry : remembered) {
+ rewritten.add(new Entry(
+ entry.operation().transformAgainst(incoming),
+ incoming.shiftPosition(entry.caret()),
+ entry.selectionAnchor() < 0 ? -1 : incoming.shiftPosition(entry.selectionAnchor())));
+ }
+ remembered.clear();
+ remembered.addAll(rewritten);
+ }
+
+ private static void trim(Deque remembered) {
+ while (remembered.size() > MAX_ENTRIES) remembered.removeFirst();
+ }
+}
diff --git a/src/client/java/com/aranroig/client/editor/EditorDocsPanel.java b/src/client/java/com/aranroig/client/editor/EditorDocsPanel.java
index d103578..96a79aa 100644
--- a/src/client/java/com/aranroig/client/editor/EditorDocsPanel.java
+++ b/src/client/java/com/aranroig/client/editor/EditorDocsPanel.java
@@ -14,14 +14,23 @@ import net.minecraft.client.input.MouseButtonEvent;
import org.jspecify.annotations.NonNull;
import java.util.ArrayList;
+import java.util.HashSet;
import java.util.List;
+import java.util.Set;
/**
* Modal documentation browser for the Lua functions this mod adds.
*
* Covers the whole editor screen (z-index 2, set in {@link EditorManager})
* while visible: a dimmed backdrop, a scrollable list of topics/functions on
- * the left and the rendered documentation of the selection on the right.
+ * the left and the rendered documentation of the selection on the right. The
+ * list is collapsible — the button at the left of the title bar, or Ctrl+B —
+ * which gives the documentation page the panel's full width, and each topic
+ * header folds away the functions under it like the file tree's folders.
+ *
+ * A search box above the list filters the functions by name and
+ * description while typing: Ctrl+F focuses it, the arrow keys walk the
+ * matches, Escape empties it and — once empty — lets go of it again.
*
* Opened through {@link #open()} / {@link #open(String)} — the top bar's
* Help → Lua API Documentation menu and F1 in the file view.
@@ -48,6 +57,22 @@ public class EditorDocsPanel extends Widget {
/** Index into {@link #rows} of the current selection. */
private int selectedRow = 0;
+ /** Whether the topic list on the left is hidden, leaving the page the full width. */
+ private boolean sidebarCollapsed = false;
+
+ /**
+ * Topics whose functions are folded away, keyed by their index into
+ * {@link #topics}. View state only — the list of topics is fixed.
+ */
+ private final Set foldedTopics = new HashSet<>();
+
+ /** Text of the search box above the list; blank means no filtering. */
+ private String searchQuery = "";
+ /** Caret offset into {@link #searchQuery}. */
+ private int searchCursor = 0;
+ /** Whether typing goes to the search box rather than being swallowed. */
+ private boolean searchFocused = false;
+
private int listScroll = 0;
private int detailScroll = 0;
/** Height of the rendered detail page, measured while drawing, for clamping. */
@@ -73,6 +98,65 @@ public class EditorDocsPanel extends Widget {
private static final int FUNC_INDENT = 10;
private static final int SCROLL_SPEED = 3;
+ /** From the panel's left inset to a topic title (after its fold arrow) / to its functions. */
+ private static final int TOPIC_TEXT_X = PAD + 10;
+ private static final int FUNC_TEXT_X = PAD + 16;
+
+ // Pixel-pattern icons, '#' a pixel of the icon's colour and '.' nothing —
+ // the same style as the file tree's chevrons, so they stay sharp at any
+ // GUI scale.
+
+ /** Pointing left: clicking folds the topic list away. */
+ private static final String[] ICON_COLLAPSE = {
+ "...#",
+ "..#.",
+ ".#..",
+ "#...",
+ ".#..",
+ "..#.",
+ "...#",
+ };
+
+ /** Pointing right: clicking brings the topic list back. */
+ private static final String[] ICON_EXPAND = {
+ "#...",
+ ".#..",
+ "..#.",
+ "...#",
+ "..#.",
+ ".#..",
+ "#...",
+ };
+
+ /** Pointing right: the topic's functions are folded away. */
+ private static final String[] ICON_TOPIC_FOLDED = {
+ "#...",
+ ".#..",
+ "..#.",
+ "...#",
+ "..#.",
+ ".#..",
+ "#...",
+ };
+
+ /** Pointing down: the topic is unfolded and its functions are listed. */
+ private static final String[] ICON_TOPIC_OPEN = {
+ "#.....#",
+ ".#...#.",
+ "..#.#..",
+ "...#...",
+ };
+
+ /** A magnifier: drawn at the left of the search box. */
+ private static final String[] ICON_SEARCH = {
+ ".###..",
+ "#...#.",
+ "#...#.",
+ "#...#.",
+ ".####.",
+ ".....#",
+ };
+
public EditorDocsPanel(EditorManager editorManager) {
super(editorManager);
}
@@ -116,6 +200,9 @@ public class EditorDocsPanel extends Widget {
public void close() {
visible = false;
selectingCode = false;
+ searchFocused = false;
+ searchQuery = "";
+ searchCursor = 0;
if (editorScreen != null && editorScreen.selectedWidget == this) {
editorScreen.selectedWidget = null;
}
@@ -126,11 +213,14 @@ public class EditorDocsPanel extends Widget {
}
private void selectByName(String word) {
+ // A jump shows the whole list again: a leftover filter could hide the row.
+ searchQuery = "";
+ searchCursor = 0;
// Exact match first, then the unqualified last segment.
for (int i = 0; i < rows.size(); i++) {
Row row = rows.get(i);
if (row.isFunction() && row.label().equalsIgnoreCase(word)) {
- selectRow(i);
+ revealRow(i);
return;
}
}
@@ -138,12 +228,97 @@ public class EditorDocsPanel extends Widget {
Row row = rows.get(i);
if (row.isFunction()
&& row.label().toLowerCase().endsWith("." + word.toLowerCase())) {
- selectRow(i);
+ revealRow(i);
return;
}
}
}
+ /** Folds or unfolds a topic: its functions come and go with it. */
+ private void toggleTopicFolded(int topic) {
+ if (!foldedTopics.remove(topic)) foldedTopics.add(topic);
+ clampListScroll();
+ }
+
+ /** Selects a row, unfolding its topic first so the list shows what was picked. */
+ private void revealRow(int index) {
+ foldedTopics.remove(rows.get(index).topic());
+ selectRow(index);
+ }
+
+ /**
+ * Indices into {@link #rows} of the rows on display: while the search box
+ * is blank, every topic plus the functions of those unfolded; while it
+ * holds a query, the functions whose name or description match, and the
+ * headers of the topics that match or hold a match — folding is ignored
+ * while searching, so every match is reachable. Positions and scrolling
+ * work on these.
+ */
+ private List visibleRows() {
+ String query = searchQuery.trim().toLowerCase();
+ List visible = new ArrayList<>(rows.size());
+ for (int i = 0; i < rows.size(); i++) {
+ Row row = rows.get(i);
+ if (query.isEmpty()) {
+ if (!row.isFunction() || !foldedTopics.contains(row.topic())) visible.add(i);
+ } else if (row.isFunction()) {
+ if (functionMatches(topics.get(row.topic()).functions().get(row.function()), query)) {
+ visible.add(i);
+ }
+ } else if (topicMatches(row.topic(), query)) {
+ visible.add(i);
+ }
+ }
+ return visible;
+ }
+
+ private static boolean functionMatches(FunctionDoc function, String query) {
+ return matches(function.name(), query) || matches(function.summary(), query);
+ }
+
+ /** The topic itself or one of its functions matches; keeps its header on display. */
+ private boolean topicMatches(int topic, String query) {
+ Topic t = topics.get(topic);
+ if (matches(t.title(), query) || matches(t.blurb(), query)) return true;
+ for (FunctionDoc function : t.functions()) {
+ if (functionMatches(function, query)) return true;
+ }
+ return false;
+ }
+
+ private static boolean matches(String text, String query) {
+ return text != null && text.toLowerCase().contains(query);
+ }
+
+ /**
+ * The search query changed: keep the selection while it is still on
+ * display, else follow the first matching function (or first row left).
+ */
+ private void onSearchEdited() {
+ List visible = visibleRows();
+ if (!visible.contains(selectedRow)) {
+ int next = -1;
+ for (int i : visible) {
+ if (rows.get(i).isFunction()) { next = i; break; }
+ if (next < 0) next = i; // a header, when there are no function matches at all
+ }
+ if (next >= 0) selectRow(next);
+ }
+ listScroll = 0;
+ scrollSelectionIntoView();
+ }
+
+ /** Moves the selection by one visible row and scrolls it into view (arrow keys). */
+ private void selectRelative(int step) {
+ List visible = visibleRows();
+ if (visible.isEmpty()) return;
+ int pos = visible.indexOf(selectedRow);
+ if (pos < 0) pos = step > 0 ? -1 : 0; // hidden by a folded topic: restart from the top
+ pos = Math.max(0, Math.min(pos + step, visible.size() - 1));
+ selectRow(visible.get(pos));
+ scrollSelectionIntoView();
+ }
+
private void selectRow(int index) {
selectedRow = index;
detailScroll = 0;
@@ -153,13 +328,15 @@ public class EditorDocsPanel extends Widget {
}
private void scrollSelectionIntoView() {
+ int pos = visibleRows().indexOf(selectedRow);
+ if (pos < 0) return; // hidden by a folded topic, nothing to scroll to
int rowH = rowHeight();
- int top = rowHeight() * selectedRow - listScroll;
+ int top = rowH * pos - listScroll;
int viewH = listAreaBottom() - listTop();
if (top < 0) {
- listScroll = rowHeight() * selectedRow;
+ listScroll = rowH * pos;
} else if (top + rowH > viewH) {
- listScroll = rowHeight() * selectedRow + rowH - viewH;
+ listScroll = rowH * pos + rowH - viewH;
}
clampListScroll();
}
@@ -175,14 +352,23 @@ public class EditorDocsPanel extends Widget {
private int panelX2() { return getEndX() - MARGIN; }
private int panelY2() { return getEndY() - MARGIN; }
- private int listX2() { return panelX1() + LIST_WIDTH; }
- private int listTop() { return panelY1() + titleHeight(); }
+ /** The list's right edge; at the panel's left edge while collapsed. */
+ private int listX2() { return panelX1() + (sidebarCollapsed ? 0 : LIST_WIDTH); }
+ /** Below the title bar, where both content columns start. */
+ private int detailAreaTop() { return panelY1() + titleHeight(); }
+ private int listTop() { return detailAreaTop() + (sidebarCollapsed ? 0 : searchHeight()); }
private int listAreaBottom() { return panelY2(); }
private int detailX() { return listX2() + PAD + 1; }
- private int detailTop() { return listTop() + PAD; }
+ private int detailTop() { return detailAreaTop() + PAD; }
+
+ private int searchTop() { return detailAreaTop(); }
+ private int searchBottom() { return detailAreaTop() + searchHeight(); }
+ private int searchHeight() { return lineHeight() + PAD; }
+ /** Where the query text begins, after the magnifier icon. */
+ private int searchTextX() { return panelX1() + PAD + ICON_SEARCH[0].length() + 6; }
private int maxListScroll() {
- return Math.max(0, rows.size() * rowHeight() - (listAreaBottom() - listTop()));
+ return Math.max(0, visibleRows().size() * rowHeight() - (listAreaBottom() - listTop()));
}
private void clampListScroll() {
@@ -195,6 +381,17 @@ public class EditorDocsPanel extends Widget {
&& my >= panelY1() && my < panelY1() + buttonSize;
}
+ private boolean insideSidebarToggle(int mx, int my) {
+ int buttonSize = titleHeight();
+ return mx >= panelX1() + 1 && mx < panelX1() + 1 + buttonSize
+ && my >= panelY1() && my < panelY1() + buttonSize;
+ }
+
+ private boolean insideSearchBox(int mx, int my) {
+ return !sidebarCollapsed && mx >= panelX1() + 1 && mx < listX2() - 1
+ && my >= searchTop() && my < searchBottom();
+ }
+
private FunctionDoc selectedFunction() {
Row row = rows.get(selectedRow);
return row.isFunction() ? topics.get(row.topic()).functions().get(row.function()) : null;
@@ -216,7 +413,7 @@ public class EditorDocsPanel extends Widget {
clampListScroll();
detailScroll = Math.max(0, Math.min(detailScroll,
- Math.max(0, detailContentHeight - (panelY2() - listTop() - PAD * 2))));
+ Math.max(0, detailContentHeight - (panelY2() - detailTop() - PAD))));
// Backdrop + panel
graphics.fill(getStartX(), getStartY(), getEndX(), getEndY(), editorManager.theme().overlay());
@@ -227,8 +424,11 @@ public class EditorDocsPanel extends Widget {
graphics.fill(panelX2() - 1, panelY1(), panelX2(), panelY2(), editorManager.theme().border()); // right
drawTitleBar(graphics);
+ drawSearchBox(graphics);
drawList(graphics, mouseX, mouseY);
- graphics.fill(listX2() - 1, listTop(), listX2(), panelY2() - 1, editorManager.theme().border());
+ if (!sidebarCollapsed) {
+ graphics.fill(listX2() - 1, detailAreaTop(), listX2(), panelY2() - 1, editorManager.theme().border());
+ }
drawDetail(graphics);
}
@@ -236,11 +436,22 @@ public class EditorDocsPanel extends Widget {
int titleH = titleHeight();
graphics.fill(panelX1() + 1, panelY1(), panelX2() - 1, panelY1() + titleH, editorManager.theme().raisedBackground());
+ // Sidebar toggle, sitting at the top of the list it shows and hides.
+ int buttonSize = titleH;
+ int toggleX = panelX1() + 1;
+ boolean toggleHovered = mouseX >= toggleX && mouseX < toggleX + buttonSize
+ && mouseY >= panelY1() && mouseY < panelY1() + titleH;
+ if (toggleHovered) {
+ graphics.fill(toggleX, panelY1(), toggleX + buttonSize, panelY1() + titleH, editorManager.theme().hoverBackground());
+ }
+ drawIcon(graphics, sidebarCollapsed ? ICON_EXPAND : ICON_COLLAPSE,
+ toggleX, panelY1(), buttonSize, editorManager.theme().mutedText());
+
+ int titleX = toggleX + buttonSize;
graphics.text(font, "Lua API documentation",
- panelX1() + PAD, panelY1() + (titleH - lineHeight()) / 2, editorManager.theme().text(), false);
+ titleX, panelY1() + (titleH - lineHeight()) / 2, editorManager.theme().text(), false);
// Close button
- int buttonSize = titleH;
int bx = panelX2() - buttonSize;
boolean hovered = mouseX >= bx && mouseX < panelX2() && mouseY >= panelY1() && mouseY < panelY1() + titleH;
if (hovered) {
@@ -251,24 +462,106 @@ public class EditorDocsPanel extends Widget {
panelY1() + (titleH - lineHeight()) / 2, editorManager.theme().text(), false);
// Hint, right-aligned before the button
- String hint = "F1 in the editor opens docs on the word under the cursor";
+ String hint = "Ctrl+F searches · F1 in the editor opens docs on the word under the cursor";
int hintX = bx - 8 - font.width(hint);
- if (hintX > panelX1() + font.width("Lua API documentation") + 12) {
+ if (hintX > titleX + font.width("Lua API documentation") + 12) {
graphics.text(font, hint, hintX, panelY1() + (titleH - lineHeight()) / 2, editorManager.theme().hint(), false);
}
}
+ /**
+ * The search box between title bar and topic list: magnifier, placeholder
+ * or query, and a blinking caret while focused. Long queries shift left so
+ * the caret stays visible.
+ */
+ private void drawSearchBox(@NonNull GuiGraphicsExtractor graphics) {
+ if (sidebarCollapsed) return;
+ int top = searchTop();
+ int bottom = searchBottom();
+ int textY = top + (searchHeight() - lineHeight()) / 2;
+ int textX = searchTextX();
+
+ graphics.fill(panelX1() + 1, top, listX2() - 1, bottom, editorManager.theme().raisedBackground());
+ graphics.fill(panelX1() + 1, bottom - 1, listX2() - 1, bottom, editorManager.theme().border());
+
+ drawRowIcon(graphics, ICON_SEARCH, panelX1() + PAD - 1, top, searchHeight(),
+ searchFocused ? editorManager.theme().text() : editorManager.theme().mutedText());
+
+ if (searchQuery.isEmpty()) {
+ graphics.text(font, "Search…", textX, textY, editorManager.theme().hint(), false);
+ } else {
+ int shift = searchShift();
+ graphics.enableScissor(textX, top, listX2() - 2, bottom - 1);
+ graphics.text(font, searchQuery, textX - shift, textY, editorManager.theme().text(), false);
+ graphics.disableScissor();
+ }
+ if (searchFocused && (System.currentTimeMillis() / 500) % 2 == 0) {
+ int caretX = textX - searchShift()
+ + font.width(searchQuery.substring(0, searchCursor));
+ if (caretX >= textX && caretX < listX2() - 1) {
+ graphics.fill(caretX, textY, caretX + 1, textY + lineHeight(),
+ editorManager.theme().cursor());
+ }
+ }
+ }
+
+ /** How far the query shifts left so the caret does not leave the box. */
+ private int searchShift() {
+ int caretWidth = font.width(searchQuery.substring(0, searchCursor));
+ return Math.max(0, caretWidth - (listX2() - 2 - searchTextX()) + 4);
+ }
+
+ /** Caret offset of a click inside the search box. */
+ private int searchCaretAt(int mx) {
+ int x = mx + searchShift();
+ int best = 0;
+ for (int i = 1; i <= searchQuery.length(); i++) {
+ if (x >= searchTextX() + font.width(searchQuery.substring(0, i))) best = i;
+ }
+ return best;
+ }
+
+ /** Centres a pixel glyph in a square button and paints it pixel by pixel. */
+ private static void drawIcon(GuiGraphicsExtractor graphics, String[] glyph, int x, int y, int buttonSize, int colour) {
+ x += (buttonSize - glyph[0].length()) / 2;
+ y += (buttonSize - glyph.length) / 2;
+ paintGlyph(graphics, glyph, x, y, colour);
+ }
+
+ /** Centres a pixel glyph vertically in a list row, flush at {@code x}. */
+ private static void drawRowIcon(GuiGraphicsExtractor graphics, String[] glyph, int x, int y, int rowH, int colour) {
+ paintGlyph(graphics, glyph, x, y + (rowH - glyph.length) / 2, colour);
+ }
+
+ /** Paints a glyph pixel by pixel, top-left at {@code (x, y)}. */
+ private static void paintGlyph(GuiGraphicsExtractor graphics, String[] glyph, int x, int y, int colour) {
+ for (int row = 0; row < glyph.length; row++) {
+ String pixels = glyph[row];
+ for (int column = 0; column < pixels.length(); column++) {
+ if (pixels.charAt(column) == '.') continue;
+ graphics.fill(x + column, y + row, x + column + 1, y + row + 1, colour);
+ }
+ }
+ }
+
private void drawList(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY) {
+ if (sidebarCollapsed) return;
graphics.enableScissor(panelX1() + 1, listTop(), listX2() - 1, panelY2() - 1);
graphics.fill(panelX1() + 1, listTop(), listX2() - 1, panelY2() - 1, editorManager.theme().sidebarBackground());
int rowH = rowHeight();
- for (int i = 0; i < rows.size(); i++) {
- Row row = rows.get(i);
+ List visible = visibleRows();
+ if (visible.isEmpty() && !searchQuery.isBlank()) {
+ graphics.text(font, "No matches", panelX1() + FUNC_TEXT_X,
+ listTop() + PAD, editorManager.theme().mutedText(), false);
+ }
+ for (int i = 0; i < visible.size(); i++) {
+ int rowIndex = visible.get(i);
+ Row row = rows.get(rowIndex);
int y = listTop() + i * rowH - listScroll;
if (y + rowH < listTop() || y > panelY2()) continue;
- boolean selected = i == selectedRow;
+ boolean selected = rowIndex == selectedRow;
boolean hovered = mouseX >= panelX1() && mouseX < listX2()
&& mouseY >= y && mouseY < y + rowH;
if (selected) {
@@ -278,10 +571,13 @@ public class EditorDocsPanel extends Widget {
}
if (row.isFunction()) {
- graphics.text(font, row.label(), panelX1() + PAD + FUNC_INDENT,
+ graphics.text(font, row.label(), panelX1() + FUNC_TEXT_X,
y + ROW_PAD / 2, editorManager.theme().text(), false);
} else {
- graphics.text(font, row.label(), panelX1() + PAD,
+ boolean folded = foldedTopics.contains(row.topic());
+ drawRowIcon(graphics, folded ? ICON_TOPIC_FOLDED : ICON_TOPIC_OPEN,
+ panelX1() + PAD, y, rowH, editorManager.theme().mutedText());
+ graphics.text(font, row.label(), panelX1() + TOPIC_TEXT_X,
y + ROW_PAD / 2, editorManager.theme().syntaxBuiltin(), true);
}
}
@@ -296,7 +592,7 @@ public class EditorDocsPanel extends Widget {
int maxWidth = panelX2() - PAD - x;
int y = detailTop() - detailScroll;
- graphics.enableScissor(listX2(), listTop(), panelX2() - 1, panelY2() - 1);
+ graphics.enableScissor(listX2(), detailAreaTop(), panelX2() - 1, panelY2() - 1);
FunctionDoc function = selectedFunction();
if (function == null) {
@@ -467,7 +763,7 @@ public class EditorDocsPanel extends Widget {
}
private CodeBlockLayout codeBlockAt(double x, double y) {
- if (x < listX2() || x >= panelX2() - 1 || y < listTop() || y >= panelY2() - 1) return null;
+ if (x < listX2() || x >= panelX2() - 1 || y < detailAreaTop() || y >= panelY2() - 1) return null;
for (CodeBlockLayout block : codeBlocks) {
if (x >= block.x() && x <= block.x() + block.width()
&& y >= block.y() && y < block.y() + block.height()) return block;
@@ -519,16 +815,35 @@ public class EditorDocsPanel extends Widget {
close();
return true;
}
+ if (insideSidebarToggle(mx, my)) {
+ sidebarCollapsed = !sidebarCollapsed;
+ if (sidebarCollapsed) searchFocused = false; // the box hides with the list
+ else scrollSelectionIntoView();
+ return true;
+ }
- // Left list: select the clicked row.
+ // Search box: focus it and place the caret where the click landed.
+ if (insideSearchBox(mx, my)) {
+ searchFocused = true;
+ searchCursor = searchCaretAt(mx);
+ selectingCode = false;
+ activeExample = -1;
+ return true;
+ }
+
+ // Left list: select the clicked row, folding or unfolding on a topic.
if (mx < listX2() && my >= listTop()) {
selectingCode = false;
activeExample = -1;
selectionAnchor = -1;
selectionCursor = -1;
- int index = (my - listTop() + listScroll) / rowHeight();
- if (index >= 0 && index < rows.size()) {
- selectRow(index);
+ int pos = (my - listTop() + listScroll) / rowHeight();
+ List visible = visibleRows();
+ if (pos >= 0 && pos < visible.size()) {
+ int rowIndex = visible.get(pos);
+ Row row = rows.get(rowIndex);
+ if (!row.isFunction()) toggleTopicFolded(row.topic());
+ selectRow(rowIndex);
}
return true;
}
@@ -546,6 +861,7 @@ public class EditorDocsPanel extends Widget {
selectionAnchor = -1;
selectionCursor = -1;
selectingCode = false;
+ searchFocused = false; // clicking the page takes the keyboard off the search box
// Anything else inside the panel is consumed (scrolling happens per-column).
return true;
@@ -554,6 +870,55 @@ public class EditorDocsPanel extends Widget {
@Override
public boolean handleKeyPressed(KeyEvent event) {
if (!visible) return false;
+ if (event.key() == 66 && event.hasControlDown()) { // Ctrl+B — fold/unfold the topic list, like in the editor
+ sidebarCollapsed = !sidebarCollapsed;
+ if (sidebarCollapsed) searchFocused = false;
+ else scrollSelectionIntoView();
+ return true;
+ }
+ if (event.key() == 70 && event.hasControlDown()) { // Ctrl+F — focus the search box
+ sidebarCollapsed = false; // the box lives with the list
+ searchFocused = true;
+ scrollSelectionIntoView();
+ return true;
+ }
+ if (searchFocused) {
+ switch (event.key()) {
+ case 259 -> { // Backspace
+ if (searchCursor > 0) {
+ searchQuery = searchQuery.substring(0, searchCursor - 1)
+ + searchQuery.substring(searchCursor);
+ searchCursor--;
+ onSearchEdited();
+ }
+ return true;
+ }
+ case 261 -> { // Delete
+ if (searchCursor < searchQuery.length()) {
+ searchQuery = searchQuery.substring(0, searchCursor)
+ + searchQuery.substring(searchCursor + 1);
+ onSearchEdited();
+ }
+ return true;
+ }
+ case 263 -> { searchCursor = Math.max(0, searchCursor - 1); return true; } // Left
+ case 262 -> { searchCursor = Math.min(searchQuery.length(), searchCursor + 1); return true; } // Right
+ case 268 -> { searchCursor = 0; return true; } // Home
+ case 269 -> { searchCursor = searchQuery.length(); return true; } // End
+ case 257 -> { searchFocused = false; return true; } // Enter — settle on the highlighted match
+ case 256 -> { // Escape — first empties the box, then lets go of it
+ if (!searchQuery.isEmpty()) {
+ searchQuery = "";
+ searchCursor = 0;
+ onSearchEdited();
+ } else {
+ searchFocused = false;
+ }
+ return true;
+ }
+ }
+ // Up and Down still walk the filtered list, handled below.
+ }
if (activeExample >= 0 && event.hasControlDown()) {
CodeBlockLayout block = activeCodeBlock();
if (block != null) {
@@ -578,13 +943,11 @@ public class EditorDocsPanel extends Widget {
return true;
}
case 264 -> { // Down
- selectRow(Math.min(selectedRow + 1, rows.size() - 1));
- scrollSelectionIntoView();
+ selectRelative(1);
return true;
}
case 265 -> { // Up
- selectRow(Math.max(selectedRow - 1, 0));
- scrollSelectionIntoView();
+ selectRelative(-1);
return true;
}
}
@@ -593,7 +956,19 @@ public class EditorDocsPanel extends Widget {
@Override
public boolean handleCharTyped(CharacterEvent event) {
- return visible; // swallow typing while the modal is open
+ if (!visible) return false;
+ if (searchFocused) {
+ int codePoint = event.codepoint();
+ if (codePoint >= 32 && codePoint != 127) { // printable characters filter the list
+ String typed = Character.toString(codePoint);
+ searchQuery = searchQuery.substring(0, searchCursor) + typed
+ + searchQuery.substring(searchCursor);
+ searchCursor += typed.length();
+ onSearchEdited();
+ }
+ return true;
+ }
+ return true; // swallow typing while the modal is open
}
@Override
diff --git a/src/client/java/com/aranroig/client/editor/EditorFileView.java b/src/client/java/com/aranroig/client/editor/EditorFileView.java
index 0a75baa..fa6dc9f 100644
--- a/src/client/java/com/aranroig/client/editor/EditorFileView.java
+++ b/src/client/java/com/aranroig/client/editor/EditorFileView.java
@@ -1,5 +1,7 @@
package com.aranroig.client.editor;
+import com.aranroig.docs.FunctionDoc;
+import com.aranroig.docs.ParamDoc;
import com.aranroig.editor.Edit;
import com.aranroig.editor.EditorFile;
import com.aranroig.editor.EditorPresence;
@@ -11,6 +13,7 @@ import net.minecraft.client.input.KeyEvent;
import net.minecraft.client.input.MouseButtonEvent;
import org.jspecify.annotations.NonNull;
+import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -59,6 +62,9 @@ public class EditorFileView extends EditorPane {
private final CompletionProvider completionProvider = new CompletionProvider();
private final LuaHighlighter luaHighlighter = new LuaHighlighter();
+ /** What Ctrl+Z and Ctrl+Shift+Z take back and give forward again. */
+ private final EditHistory history = new EditHistory();
+
/**
* Per-line multiline-string continuation state, rebuilt whenever the text
* changes. Index {@code i} is {@code true} when line {@code i} is inside a
@@ -82,6 +88,12 @@ public class EditorFileView extends EditorPane {
private static final int POPUP_WIDTH = 240;
private static final int KIND_BADGE_WIDTH = 4; // coloured left strip
+ // Documentation box shown next to the completion popup
+ private static final int DOC_MAX_WIDTH = 340; // clamped to the pane width
+ private static final int DOC_GAP = 3; // popup ↔ documentation box
+ private static final int DOC_PADDING = 4;
+ private static final int DOC_INDENT = 8; // wrapped parameter descriptions
+
// ─────────────────────────────────────────────────────────────────────
private String[] getLines() {
@@ -198,16 +210,20 @@ public class EditorFileView extends EditorPane {
/**
* The only place the buffer changes because the local player asked for it:
- * applies the change here and reports it to {@link EditorManager}, which
- * forwards it to the server so everyone else editing this file sees it.
- * Every keystroke goes through this, so the shared copy of the file stays
- * complete without waiting for a save.
+ * remembers the change for undo, applies it here and reports it to
+ * {@link EditorManager}, which forwards it to the server so everyone else
+ * editing this file sees it. Every keystroke goes through this, so the
+ * shared copy of the file stays complete without waiting for a save.
*/
private void applyLocalEdit(int position, int deleteLength, String insert) {
int start = Math.max(0, Math.min(position, text.length()));
int end = Math.max(start, Math.min(start + deleteLength, text.length()));
+
+ String deleted = text.substring(start, end);
text.replace(start, end, insert);
+ history.recordLocalEdit(start, deleted, insert, cursorPos, selectionAnchor);
+
if (currentEditorFile != null) {
editorManager.submitEdit(currentEditorFile, text.toString(), start, end - start, insert);
}
@@ -228,6 +244,11 @@ public class EditorFileView extends EditorPane {
editorManager.requestDocumentSync(currentEditorFile);
}
+ // Everything remembered for undo was written against the text as it
+ // stands before this lands; rewrite the walks — and the carets they
+ // would restore — to speak about the text as it will stand after.
+ history.rebaseAgainst(edit);
+
int newCursor = edit.shiftPosition(cursorPos);
if (selectionAnchor >= 0) selectionAnchor = edit.shiftPosition(selectionAnchor);
@@ -261,9 +282,50 @@ public class EditorFileView extends EditorPane {
cursorPos = Math.min(cursorPos, text.length());
if (selectionAnchor > text.length()) selectionAnchor = text.length();
if (currentEditorFile != null) currentEditorFile.setText(serverText);
+ history.clear(); // the buffer is the server's text now: nothing remembered fits it
dismissCompletions();
}
+ // ── Undo and redo ─────────────────────────────────────────────────────
+
+ /**
+ * Ctrl+Z: takes the last change remembered here back. Applying it is an
+ * edit like any other — the buffer changes at once and the server and the
+ * other editors are told, so undoing is itself a change everyone sees —
+ * and what it gives back goes onto the redo stack for {@link #redo()}.
+ */
+ public void undo() {
+ applyRemembered(history.takeUndo(), true);
+ }
+
+ /** Ctrl+Shift+Z: takes away again what {@link #undo()} gave back. */
+ public void redo() {
+ applyRemembered(history.takeRedo(), false);
+ }
+
+ private void applyRemembered(EditHistory.Entry step, boolean undoing) {
+ if (step == null || currentEditorFile == null) return;
+
+ // What this step writes back, going the other way again has to take
+ // out; worked out while the buffer still holds what is being erased.
+ Edit inverse = step.operation().invert(text.toString());
+ int caretBefore = cursorPos;
+ int anchorBefore = selectionAnchor;
+
+ text = new StringBuilder(step.operation().apply(text.toString()));
+ editorManager.submitEdit(currentEditorFile, text.toString(), step.operation());
+
+ cursorPos = Math.min(step.caret(), text.length());
+ selectionAnchor = step.selectionAnchor() < 0 ? -1 : Math.min(step.selectionAnchor(), text.length());
+
+ EditHistory.Entry otherWay = new EditHistory.Entry(inverse, caretBefore, anchorBefore);
+ if (undoing) history.putRedo(otherWay);
+ else history.putUndo(otherWay);
+
+ dismissCompletions();
+ scrollToCursor();
+ }
+
/** Who else has this file open, and where their carets are. */
private List remoteEditors = Collections.emptyList();
@@ -449,6 +511,12 @@ public class EditorFileView extends EditorPane {
transparent(editor.color(), 0x4D));
}
+ List findMatches = editorManager.findMatchOffsets(this);
+ int findMatchLength = editorManager.findQueryLength(this);
+ int activeFindOffset = editorManager.activeFindMatchOffset(this);
+ int lineStartOffset = 0;
+ for (int i = 0; i < firstLine; i++) lineStartOffset += lines[i].length() + 1;
+
// Line numbers + text
for (int i = firstLine; i <= lastLine; i++) {
int screenY = start_y + i * lineH - scrollY;
@@ -459,8 +527,11 @@ public class EditorFileView extends EditorPane {
gutterDivX() - 4 - numW,
screenY, editorManager.theme().mutedText(), false);
+ drawFindHighlights(graphics, lines[i], lineStartOffset, screenY,
+ findMatches, findMatchLength, activeFindOffset);
boolean lineInMultiline = (i < multilineState.length) && multilineState[i];
drawHighlightedLine(graphics, lines[i], textAreaX() - scrollX, screenY, lineInMultiline);
+ lineStartOffset += lines[i].length() + 1;
}
// Other players' carets in this file, each in the colour the server gave them
@@ -521,6 +592,28 @@ public class EditorFileView extends EditorPane {
}
}
+ /** Draws every in-file find hit behind its source text, with the current hit brighter. */
+ private void drawFindHighlights(GuiGraphicsExtractor graphics, String line, int lineStart, int screenY,
+ List matches, int matchLength, int activeOffset) {
+ if (matchLength <= 0 || matches.isEmpty()) return;
+ int lineEnd = lineStart + line.length();
+ for (int offset : matches) {
+ int matchEnd = offset + matchLength;
+ int from = Math.max(offset, lineStart);
+ int to = Math.min(matchEnd, lineEnd);
+ if (from >= to) continue;
+
+ int fromColumn = from - lineStart;
+ int toColumn = to - lineStart;
+ int x = textAreaX() + widthUpTo(line, fromColumn) - scrollX;
+ int right = textAreaX() + widthUpTo(line, toColumn) - scrollX;
+ int color = offset == activeOffset
+ ? transparent(editorManager.theme().accent(), 0xA0)
+ : transparent(editorManager.theme().folder(), 0x66);
+ graphics.fill(x, screenY, Math.max(x + 1, right), screenY + font.lineHeight, color);
+ }
+ }
+
/**
* Draws one remote player's caret, in the colour the server assigned them,
* with their name next to it so several people in the same file are
@@ -634,12 +727,343 @@ public class EditorFileView extends EditorPane {
}
}
- // Hint line below the popup when more than one item is present
- if (completions.size() > 1) {
- int hintY = py + popupH + 2;
- String hint = "↑↓ navigate Tab/Enter accept Esc dismiss";
- graphics.text(font, hint, px, hintY, editorManager.theme().hint(), false);
+ // Documentation for the highlighted item, rendered as a multi-line box
+ // below (or above) the popup, followed by the navigation hint.
+ drawCompletionDocs(graphics, px, py, popupH);
+ }
+
+ // ── Completion documentation box ──────────────────────────────────────
+
+ /** One styled run inside a documentation line. */
+ private record DocRun(String text, int color, boolean bold) {}
+
+ /** One documentation line built of coloured runs; empty runs = blank line. */
+ private record DocLine(List runs) {
+ static final DocLine BLANK = new DocLine(List.of());
+ }
+
+ /**
+ * Renders the API documentation of the highlighted completion in a
+ * multi-line box — the same sections as the documentation panel
+ * (signature, description, parameters, returns, notes), minus examples.
+ * Prefers the space below the popup, falls back above it, and truncates
+ * with an ellipsis when neither side can hold it.
+ */
+ private void drawCompletionDocs(GuiGraphicsExtractor graphics, int px, int py, int popupH) {
+ CompletionItem.Docs docs = completions.get(completionIndex).docs();
+ int width = Math.min(DOC_MAX_WIDTH, getEndX() - getStartX() - 4);
+ int boxX = Math.max(getStartX() + 2, Math.min(px, getEndX() - width - 2));
+
+ List lines = docs == null
+ ? List.of()
+ : layoutCompletionDocs(docs, width - DOC_PADDING * 2);
+ int boxY = -1;
+
+ if (!lines.isEmpty()) {
+ int docsH = lines.size() * font.lineHeight + DOC_PADDING * 2;
+ if (py + popupH + DOC_GAP + docsH <= getEndY()) {
+ boxY = py + popupH + DOC_GAP; // fits below the popup
+ } else if (py - DOC_GAP - docsH >= getStartY()) {
+ boxY = py - DOC_GAP - docsH; // fits above the popup
+ } else {
+ // Neither side holds it whole: clip below the popup, marked with …
+ int visible = (getEndY() - (py + popupH + DOC_GAP) - DOC_PADDING * 2) / font.lineHeight - 1;
+ if (visible >= 1) {
+ lines = new ArrayList<>(lines.subList(0, Math.min(visible, lines.size())));
+ lines.add(new DocLine(List.of(
+ new DocRun("…", editorManager.theme().mutedText(), false))));
+ boxY = py + popupH + DOC_GAP;
+ }
+ }
}
+
+ if (boxY < 0) {
+ drawCompletionHint(graphics, px, py + popupH + 2);
+ return;
+ }
+
+ // Shadow + background + border, in the popup's style.
+ int docsH = lines.size() * font.lineHeight + DOC_PADDING * 2;
+ graphics.fill(boxX + 2, boxY + 2, boxX + width + 2, boxY + docsH + 2,
+ transparent(editorManager.theme().background(), 0x55));
+ graphics.fill(boxX, boxY, boxX + width, boxY + docsH, editorManager.theme().raisedBackground());
+ graphics.fill(boxX, boxY, boxX + width, boxY + 1, editorManager.theme().border());
+ graphics.fill(boxX, boxY + docsH - 1, boxX + width, boxY + docsH, editorManager.theme().border());
+ graphics.fill(boxX, boxY, boxX + 1, boxY + docsH, editorManager.theme().border());
+ graphics.fill(boxX + width - 1, boxY, boxX + width, boxY + docsH, editorManager.theme().border());
+
+ int textY = boxY + DOC_PADDING;
+ for (DocLine line : lines) {
+ int textX = boxX + DOC_PADDING;
+ for (DocRun run : line.runs()) {
+ graphics.text(font, run.text(), textX, textY, run.color(), run.bold());
+ textX += font.width(run.text());
+ }
+ textY += font.lineHeight;
+ }
+
+ // Hint under whichever element ends last (box above the popup would
+ // otherwise overlap the popup with it).
+ int hintY = (boxY + docsH <= py) ? py + popupH + 2 : boxY + docsH + 2;
+ drawCompletionHint(graphics, boxX, hintY);
+ }
+
+ private void drawCompletionHint(GuiGraphicsExtractor graphics, int x, int y) {
+ if (completions.size() <= 1 || y + font.lineHeight > getEndY()) return;
+ graphics.text(font, "↑↓ navigate Tab/Enter accept Esc dismiss", x, y,
+ editorManager.theme().hint(), false);
+ }
+
+ /** Builds the wrapped, coloured documentation lines for one completion. */
+ private List layoutCompletionDocs(CompletionItem.Docs docs, int maxWidth) {
+ EditorTheme.Palette theme = editorManager.theme();
+ List lines = new ArrayList<>();
+ FunctionDoc function = docs.function();
+
+ if (function == null) {
+ // Plain documented table: its name and the topic blurb.
+ lines.add(docHeader(docs.name(), theme.syntaxBuiltin()));
+ addWrapped(lines, docs.blurb(), maxWidth, theme.syntaxDefault(), 0);
+ return lines;
+ }
+
+ addWrapped(lines, function.signature(), maxWidth, theme.syntaxMethod(), 0);
+
+ if (!function.summary().isEmpty()) {
+ lines.add(DocLine.BLANK);
+ lines.add(docHeader("Description", theme.syntaxKeyword()));
+ addWrapped(lines, function.summary(), maxWidth, theme.syntaxDefault(), 0);
+ }
+
+ if (!function.params().isEmpty()) {
+ lines.add(DocLine.BLANK);
+ lines.add(docHeader("Parameters", theme.syntaxKeyword()));
+ for (ParamDoc param : function.params()) {
+ String suffix = param.optional() ? " (optional)" : "";
+ lines.add(new DocLine(List.of(
+ new DocRun(param.name(), theme.syntaxParam(), false),
+ new DocRun(" · " + param.type() + suffix, theme.mutedText(), false))));
+ addWrapped(lines, param.description(), maxWidth, theme.syntaxDefault(), DOC_INDENT);
+ }
+ }
+
+ if (!function.returns().isEmpty()) {
+ lines.add(DocLine.BLANK);
+ lines.add(docHeader("Returns", theme.syntaxKeyword()));
+ addWrapped(lines, function.returns(), maxWidth, theme.syntaxDefault(), 0);
+ }
+
+ if (!function.notes().isEmpty()) {
+ lines.add(DocLine.BLANK);
+ lines.add(docHeader("Notes", theme.syntaxKeyword()));
+ String bullet = "• ";
+ String pad = spacesToWidth(font.width(bullet));
+ for (String note : function.notes()) {
+ boolean first = true;
+ for (String line : wrap(note, maxWidth - font.width(bullet))) {
+ lines.add(new DocLine(List.of(
+ new DocRun(first ? bullet : pad, theme.mutedText(), false),
+ new DocRun(line, theme.syntaxDefault(), false))));
+ first = false;
+ }
+ }
+ }
+ return lines;
+ }
+
+ /** A bold section header line. */
+ private DocLine docHeader(String title, int color) {
+ return new DocLine(List.of(new DocRun(title, color, true)));
+ }
+
+ /** Appends text as word-wrapped paragraph lines with an optional indent. */
+ private void addWrapped(List lines, String text, int maxWidth, int color, int indent) {
+ if (text == null || text.isEmpty()) return;
+ for (String paragraph : text.split("\n")) {
+ for (String line : wrap(paragraph, maxWidth - indent)) {
+ List runs = new ArrayList<>(2);
+ if (indent > 0) runs.add(new DocRun(spacesToWidth(indent), color, false));
+ runs.add(new DocRun(line, color, false));
+ lines.add(new DocLine(runs));
+ }
+ }
+ }
+
+ /** Spaces roughly as wide as {@code width} pixels. */
+ private String spacesToWidth(int width) {
+ int spaceW = Math.max(1, font.width(" "));
+ return " ".repeat(Math.max(0, (width + spaceW - 1) / spaceW));
+ }
+
+ /** Greedy word wrap on spaces; the same algorithm as the docs panel. */
+ private List wrap(String text, int maxWidth) {
+ List lines = new ArrayList<>();
+ if (text == null || text.isEmpty()) {
+ lines.add("");
+ return lines;
+ }
+ StringBuilder current = new StringBuilder();
+ for (String word : text.split(" ")) {
+ String candidate = current.isEmpty() ? word : current + " " + word;
+ if (!current.isEmpty() && font.width(candidate) > maxWidth) {
+ lines.add(current.toString());
+ current.setLength(0);
+ current.append(word);
+ } else {
+ if (!current.isEmpty()) current.append(' ');
+ current.append(word);
+ }
+ }
+ lines.add(current.toString());
+ return lines;
+ }
+
+ // ── Auto-indent ───────────────────────────────────────────────────────
+
+ /** One level of indentation: stored as a tab, drawn expanded. */
+ private static final String INDENT_UNIT = "\t";
+
+ /** Spaces per level when taking indentation off. */
+ private static final int SPACE_STOP = 4;
+
+ /** Leading whitespace of {@code line}. */
+ private static String indentOf(String line) {
+ int i = 0;
+ while (i < line.length() && (line.charAt(i) == ' ' || line.charAt(i) == '\t')) i++;
+ return line.substring(0, i);
+ }
+
+ /**
+ * Whether a fresh line under this code belongs one level deeper: Lua's
+ * block keywords and opening brackets. A {@code --} starts a comment and
+ * is cut off, so {@code if x then -- guard} still indents.
+ */
+ private static boolean opensBlock(String code) {
+ int comment = code.indexOf("--");
+ if (comment >= 0) code = code.substring(0, comment);
+ code = code.stripTrailing();
+ if (code.endsWith("{") || code.endsWith("(")) return true;
+ for (String keyword : new String[]{"then", "do", "repeat", "else"}) {
+ int start = code.length() - keyword.length();
+ if (start >= 0 && code.endsWith(keyword)
+ && (start == 0 || !Character.isJavaIdentifierPart(code.charAt(start - 1)))) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /** A closing token by itself: {@code end}, {@code }} … */
+ private static boolean isCloser(String trimmed) {
+ return switch (trimmed) {
+ case "end", "until", "}", ")", "]" -> true;
+ default -> false;
+ };
+ }
+
+ /**
+ * Enter: breaks the line keeping its indentation, one level deeper after
+ * a block opener. When the rest of the line is just a closer
+ * ({@code end}, {@code }} …) that closer keeps the outer level on a line
+ * of its own and the caret lands on the fresh line between the two.
+ * Spaces around the caret are cleaned away rather than left behind as
+ * trailing whitespace.
+ */
+ private void insertNewlineIndented() {
+ String[] lines = getLines();
+ int[] lc = offsetToLineCol(cursorPos);
+ String line = lines[lc[0]];
+ int lineStart = lineColToOffset(lc[0], 0);
+ String indent = indentOf(line);
+ String before = line.substring(0, lc[1]);
+ String after = line.substring(lc[1]);
+
+ boolean splitCloser = isCloser(after.strip());
+ String newIndent = opensBlock(before) ? indent + INDENT_UNIT : indent;
+ String insert = splitCloser ? "\n" + newIndent + "\n" + indent : "\n" + newIndent;
+
+ // Trim the spaces left of the caret, and the gap up to the closer
+ // when there is one: both would only become trailing whitespace.
+ int contentEnd = before.stripTrailing().length();
+ int gapEnd = splitCloser
+ ? lc[1] + after.length() - after.stripLeading().length()
+ : lc[1];
+
+ applyLocalEdit(lineStart + contentEnd, gapEnd - contentEnd, insert);
+ cursorPos = lineStart + contentEnd + insert.length()
+ - (splitCloser ? 1 + indent.length() : 0);
+ selectionAnchor = -1;
+ scrollToCursor();
+ dismissCompletions();
+ }
+
+ /**
+ * Backspace along a line's indentation: removes one tab, or the spaces
+ * down to the previous {@value #SPACE_STOP}-space stop, instead of a
+ * single character. False when the cursor is not over indentation and
+ * the key should delete normally.
+ */
+ private boolean deleteOneIndentLevel() {
+ int lineStart = lineColToOffset(offsetToLineCol(cursorPos)[0], 0);
+ if (lineStart >= cursorPos) return false;
+ String prefix = text.substring(lineStart, cursorPos);
+ if (!prefix.chars().allMatch(c -> c == ' ' || c == '\t')) return false;
+
+ int spaces = 0;
+ while (spaces < prefix.length() && prefix.charAt(prefix.length() - 1 - spaces) == ' ') spaces++;
+ int remove = spaces == 0 ? 1 : Math.min(spaces, (spaces - 1) % SPACE_STOP + 1);
+
+ applyLocalEdit(cursorPos - remove, remove, "");
+ cursorPos -= remove;
+ return true;
+ }
+
+ /**
+ * Re-indents every line the selection touches: one level off with Shift
+ * (a tab, or up to four leading spaces), one on otherwise. The selection
+ * goes with the text.
+ */
+ private void reindentSelection(boolean outdent) {
+ int lo = Math.min(selectionAnchor, cursorPos);
+ int hi = Math.max(selectionAnchor, cursorPos);
+
+ // Line/column positions are only valid before the buffer changes.
+ int[] anchorLC = offsetToLineCol(selectionAnchor);
+ int[] cursorLC = offsetToLineCol(cursorPos);
+ int firstLine = Math.min(anchorLC[0], cursorLC[0]);
+ int blockStart = lineColToOffset(firstLine, 0);
+
+ String[] blockLines = text.substring(blockStart, hi).split("\n", -1);
+ int[] cut = new int[blockLines.length];
+ if (outdent) {
+ for (int i = 0; i < blockLines.length; i++) {
+ String src = blockLines[i];
+ if (src.startsWith("\t")) cut[i] = 1;
+ else while (cut[i] < SPACE_STOP && cut[i] < src.length() && src.charAt(cut[i]) == ' ') cut[i]++;
+ }
+ }
+
+ StringBuilder updated = new StringBuilder();
+ int[] lineStarts = new int[blockLines.length]; // where each line begins in `updated`
+ for (int i = 0; i < blockLines.length; i++) {
+ lineStarts[i] = updated.length();
+ if (!outdent) updated.append(INDENT_UNIT);
+ updated.append(blockLines[i], cut[i], blockLines[i].length());
+ if (i + 1 < blockLines.length) updated.append('\n');
+ }
+
+ applyLocalEdit(blockStart, hi - blockStart, updated.toString());
+ selectionAnchor = blockStart + lineStarts[anchorLC[0] - firstLine]
+ + reindentedColumn(anchorLC[1], cut[anchorLC[0] - firstLine], outdent);
+ cursorPos = blockStart + lineStarts[cursorLC[0] - firstLine]
+ + reindentedColumn(cursorLC[1], cut[cursorLC[0] - firstLine], outdent);
+ scrollToCursor();
+ dismissCompletions();
+ }
+
+ /** Where the caret lands in a re-indented line: one unit right, or back over the level taken off. */
+ private static int reindentedColumn(int column, int cut, boolean outdent) {
+ return outdent ? Math.max(0, column - cut) : column + INDENT_UNIT.length();
}
// ── Input handlers ────────────────────────────────────────────────────
@@ -771,27 +1195,29 @@ public class EditorFileView extends EditorPane {
// ── Normal key handling ──────────────────────────────────────────
switch (key) {
- case 257 -> { // Enter
+ case 257 -> { // Enter — newline with auto-indent
if (hasSelection()) deleteSelection();
- applyLocalEdit(cursorPos, 0, "\n");
- cursorPos++;
- selectionAnchor = -1;
- scrollToCursor();
- dismissCompletions();
+ insertNewlineIndented();
return true;
}
- case 258 -> { // Tab (no popup)
- if (hasSelection()) deleteSelection();
- applyLocalEdit(cursorPos, 0, "\t");
- cursorPos++;
- selectionAnchor = -1;
- scrollToCursor();
- dismissCompletions();
+ case 258 -> { // Tab (no popup): indents every selected line,
+ // Shift+Tab takes one level off; alone it types a tab
+ if (hasSelection()) {
+ reindentSelection(shift);
+ } else {
+ applyLocalEdit(cursorPos, 0, "\t");
+ cursorPos++;
+ selectionAnchor = -1;
+ scrollToCursor();
+ dismissCompletions();
+ }
return true;
}
case 259 -> { // Backspace
if (hasSelection()) { deleteSelection(); }
- else if (cursorPos > 0) { applyLocalEdit(cursorPos - 1, 1, ""); cursorPos--; }
+ else if (cursorPos > 0 && !deleteOneIndentLevel()) {
+ applyLocalEdit(cursorPos - 1, 1, ""); cursorPos--;
+ }
selectionAnchor = -1;
scrollToCursor();
updateCompletions(); // re-compute after deletion
@@ -910,6 +1336,13 @@ public class EditorFileView extends EditorPane {
return true;
}
}
+ case 90 -> { // Ctrl+Z takes the last change back, Ctrl+Shift+Z the one before that
+ if (ctrl) {
+ if (shift) redo();
+ else undo();
+ return true;
+ }
+ }
case 83 -> { // Ctrl+S
saveEditorFile();
}
@@ -966,11 +1399,12 @@ public class EditorFileView extends EditorPane {
dismissCompletions();
if (!sameFile) {
- // Caret and scroll belonged to the file we just left.
+ // Caret, scroll and remembered changes belonged to the file we left.
cursorPos = 0;
selectionAnchor = -1;
scrollX = 0;
scrollY = 0;
+ history.clear();
}
// Join this file's live session (and re-show who is in it).
@@ -990,6 +1424,7 @@ public class EditorFileView extends EditorPane {
scrollX = 0;
scrollY = 0;
remoteEditors = Collections.emptyList();
+ history.clear();
dismissCompletions();
}
@@ -1033,4 +1468,39 @@ public class EditorFileView extends EditorPane {
public EditorFile getCurrentEditorFile() {
return currentEditorFile;
}
+
+ String textForSearch() {
+ return text.toString();
+ }
+
+ int caretOffset() {
+ return cursorPos;
+ }
+
+ int searchAnchorOffset() {
+ return hasSelection() ? Math.min(selectionAnchor, cursorPos) : cursorPos;
+ }
+
+ String searchSeed() {
+ if (hasSelection()) {
+ return text.substring(Math.min(selectionAnchor, cursorPos), Math.max(selectionAnchor, cursorPos));
+ }
+ return wordUnderCursor();
+ }
+
+ /** Selects a search hit and moves the editor caret to it. */
+ void selectSearchMatch(int offset, int length) {
+ if (currentEditorFile == null) return;
+ int start = Math.max(0, Math.min(offset, text.length()));
+ cursorPos = Math.min(text.length(), start + Math.max(0, length));
+ selectionAnchor = start;
+ dismissCompletions();
+ scrollToCursor();
+ sendCursorIfMoved();
+ }
+
+ /** Removes the selection left by a previous find hit when the query stops matching. */
+ void clearSearchSelection() {
+ if (hasSelection()) selectionAnchor = -1;
+ }
}
diff --git a/src/client/java/com/aranroig/client/editor/EditorFindBar.java b/src/client/java/com/aranroig/client/editor/EditorFindBar.java
new file mode 100644
index 0000000..8d61703
--- /dev/null
+++ b/src/client/java/com/aranroig/client/editor/EditorFindBar.java
@@ -0,0 +1,317 @@
+package com.aranroig.client.editor;
+
+import com.aranroig.editor.EditorFile;
+import net.minecraft.client.gui.Font;
+import net.minecraft.client.gui.GuiGraphicsExtractor;
+import net.minecraft.client.input.CharacterEvent;
+import net.minecraft.client.input.KeyEvent;
+import net.minecraft.client.input.MouseButtonEvent;
+import org.jspecify.annotations.NonNull;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+/** A small, non-modal find control anchored to the top-right of the editor. */
+final class EditorFindBar extends Widget {
+
+ private static final int HEIGHT = 22;
+ private static final int PAD = 5;
+ private static final int BUTTON_WIDTH = 17;
+
+ private EditorFileView target;
+ private Widget restoreFocus;
+ private String query = "";
+ private int queryCursor;
+ private int querySelectionAnchor = -1;
+ private int activeOffset = -1;
+ private Font font;
+ private String cachedText;
+ private String cachedQuery;
+ private List cachedOffsets = List.of();
+
+ EditorFindBar(EditorManager editorManager) {
+ super(editorManager);
+ setZIndex(3);
+ }
+
+ void open(EditorScreen screen, EditorFileView pane) {
+ boolean alreadyOpenForPane = editorScreen == screen && screen.widgets.contains(this) && target == pane;
+ if (!alreadyOpenForPane) {
+ target = pane;
+ restoreFocus = pane;
+ query = pane.searchSeed();
+ queryCursor = query.length();
+ querySelectionAnchor = query.isEmpty() ? -1 : 0;
+ activeOffset = -1;
+ }
+ if (editorScreen != screen || !screen.widgets.contains(this)) addToEditorScreen(screen);
+ screen.selectedWidget = this;
+ if (!query.isEmpty()) selectFromCaret(true);
+ }
+
+ boolean isTarget(EditorFileView pane) {
+ return editorManager.isFindVisible(this) && target == pane;
+ }
+
+ EditorFileView targetPane() { return target; }
+
+ List matchOffsets(EditorFileView pane) {
+ if (pane == null || !isTarget(pane) || query.isEmpty()) return List.of();
+ EditorFile file = pane.getCurrentEditorFile();
+ if (file == null) return List.of();
+ String text = pane.textForSearch();
+ if (text.equals(cachedText) && query.equals(cachedQuery)) return cachedOffsets;
+ String lower = text.toLowerCase(Locale.ROOT);
+ String needle = query.toLowerCase(Locale.ROOT);
+ List offsets = new ArrayList<>();
+ int from = 0;
+ while (from <= lower.length() - needle.length()) {
+ int offset = lower.indexOf(needle, from);
+ if (offset < 0) break;
+ offsets.add(offset);
+ from = offset + Math.max(1, needle.length());
+ }
+ cachedText = text;
+ cachedQuery = query;
+ cachedOffsets = offsets;
+ return cachedOffsets;
+ }
+
+ int activeMatchOffset(EditorFileView pane) {
+ return isTarget(pane) ? activeOffset : -1;
+ }
+
+ int queryLength(EditorFileView pane) {
+ return isTarget(pane) ? query.length() : 0;
+ }
+
+ private int barWidth() {
+ return Math.max(120, Math.min(360, editorScreen.width - 16));
+ }
+
+ private int barX() { return Math.max(4, editorScreen.width - barWidth() - 8); }
+ private int barY() { return 16; }
+ private int inputX() { return barX() + PAD; }
+ private int inputEndX() { return barX() + barWidth() - (BUTTON_WIDTH * 3 + 42); }
+ private int previousX() { return barX() + barWidth() - BUTTON_WIDTH * 3 - 2; }
+ private int nextX() { return previousX() + BUTTON_WIDTH; }
+ private int closeX() { return nextX() + BUTTON_WIDTH; }
+
+ @Override
+ public void draw(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY, double delta) {
+ font = editorScreen.getFont();
+ int x = barX(), y = barY(), w = barWidth();
+ int bottom = y + HEIGHT;
+ graphics.fill(x + 2, y + 2, x + w + 2, bottom + 2, 0x55000000);
+ graphics.fill(x, y, x + w, bottom, editorManager.theme().raisedBackground());
+ graphics.fill(x, y, x + w, y + 1, editorManager.theme().border());
+ graphics.fill(x, bottom - 1, x + w, bottom, editorManager.theme().border());
+ graphics.fill(x, y, x + 1, bottom, editorManager.theme().border());
+ graphics.fill(x + w - 1, y, x + w, bottom, editorManager.theme().border());
+
+ int inputLeft = inputX();
+ int inputRight = Math.max(inputLeft + 30, inputEndX());
+ graphics.fill(inputLeft, y + 3, inputRight, bottom - 3, editorManager.theme().background());
+ graphics.fill(inputLeft, y + 3, inputLeft + 2, bottom - 3,
+ query.isEmpty() ? editorManager.theme().border() : editorManager.theme().accent());
+ String shown = query.isEmpty() ? "Find" : query;
+ int textY = y + (HEIGHT - font.lineHeight) / 2;
+ int textX = inputLeft + 7;
+ int shift = queryShift(inputRight - textX - 3);
+ graphics.enableScissor(textX, y + 2, inputRight - 3, bottom - 2);
+ if (querySelectionAnchor >= 0 && querySelectionAnchor != queryCursor) {
+ int selectionStart = Math.min(querySelectionAnchor, queryCursor);
+ int selectionEnd = Math.max(querySelectionAnchor, queryCursor);
+ int selectionX0 = textX - shift + font.width(query.substring(0, selectionStart));
+ int selectionX1 = textX - shift + font.width(query.substring(0, selectionEnd));
+ graphics.fill(selectionX0, y + 4, selectionX1, bottom - 4, editorManager.theme().selection());
+ }
+ graphics.text(font, shown, textX - shift, textY,
+ query.isEmpty() ? editorManager.theme().mutedText() : editorManager.theme().text(), false);
+ if (editorScreen.selectedWidget == this && !query.isEmpty()
+ && (System.currentTimeMillis() / 500) % 2 == 0) {
+ int caretX = textX - shift
+ + font.width(query.substring(0, Math.min(queryCursor, query.length())));
+ graphics.fill(caretX, y + 5, caretX + 1, bottom - 5, editorManager.theme().cursor());
+ }
+ graphics.disableScissor();
+
+ List matches = matchOffsets(target);
+ int activeIndex = matches.indexOf(activeOffset);
+ String count = matches.isEmpty() ? (query.isEmpty() ? "" : "0/0")
+ : (activeIndex + 1) + "/" + matches.size();
+ int countWidth = font.width(count);
+ graphics.text(font, count, previousX() - countWidth - 3, textY,
+ matches.isEmpty() && !query.isEmpty() ? editorManager.theme().danger() : editorManager.theme().mutedText(), false);
+ drawButton(graphics, "↑", previousX(), mouseX, mouseY);
+ drawButton(graphics, "↓", nextX(), mouseX, mouseY);
+ drawButton(graphics, "×", closeX(), mouseX, mouseY);
+ }
+
+ private int queryShift(int availableWidth) {
+ int caretWidth = font.width(query.substring(0, Math.min(queryCursor, query.length())));
+ return Math.max(0, caretWidth - availableWidth + 4);
+ }
+
+ private void drawButton(GuiGraphicsExtractor graphics, String label, int x, int mouseX, int mouseY) {
+ int y = barY();
+ boolean hovered = mouseX >= x && mouseX < x + BUTTON_WIDTH && mouseY >= y && mouseY < y + HEIGHT;
+ if (hovered) graphics.fill(x, y + 2, x + BUTTON_WIDTH, y + HEIGHT - 2, editorManager.theme().hoverBackground());
+ graphics.text(font, label, x + (BUTTON_WIDTH - font.width(label)) / 2,
+ y + (HEIGHT - font.lineHeight) / 2, editorManager.theme().text(), false);
+ }
+
+ @Override
+ public boolean inside(double x, double y) {
+ return x >= barX() && x < barX() + barWidth() && y >= barY() && y < barY() + HEIGHT;
+ }
+
+ @Override
+ public boolean handleKeyPressed(KeyEvent event) {
+ int key = event.key();
+ if (event.hasControlDown() && key == 65) {
+ querySelectionAnchor = 0;
+ queryCursor = query.length();
+ return true;
+ }
+ switch (key) {
+ case 256 -> { close(); return true; } // Escape
+ case 259 -> { // Backspace
+ if (hasQuerySelection()) {
+ removeQuerySelection();
+ changedQuery();
+ } else if (queryCursor > 0) {
+ query = query.substring(0, queryCursor - 1) + query.substring(queryCursor);
+ queryCursor--;
+ changedQuery();
+ }
+ return true;
+ }
+ case 261 -> { // Delete
+ if (hasQuerySelection()) {
+ removeQuerySelection();
+ changedQuery();
+ } else if (queryCursor < query.length()) {
+ query = query.substring(0, queryCursor) + query.substring(queryCursor + 1);
+ changedQuery();
+ }
+ return true;
+ }
+ case 263 -> { queryCursor = hasQuerySelection() ? Math.min(querySelectionAnchor, queryCursor) : Math.max(0, queryCursor - 1); querySelectionAnchor = -1; return true; }
+ case 262 -> { queryCursor = hasQuerySelection() ? Math.max(querySelectionAnchor, queryCursor) : Math.min(query.length(), queryCursor + 1); querySelectionAnchor = -1; return true; }
+ case 268 -> { queryCursor = 0; querySelectionAnchor = -1; return true; }
+ case 269 -> { queryCursor = query.length(); querySelectionAnchor = -1; return true; }
+ case 265 -> { move(-1); return true; } // Up
+ case 264 -> { move(1); return true; } // Down
+ case 257 -> { move(event.hasShiftDown() ? -1 : 1); return true; } // Enter
+ default -> { return true; }
+ }
+ }
+
+ @Override
+ public boolean handleCharTyped(CharacterEvent event) {
+ int cp = event.codepoint();
+ if (cp >= 32 && cp != 127) {
+ String chars = Character.toString(cp);
+ if (hasQuerySelection()) removeQuerySelection();
+ query = query.substring(0, queryCursor) + chars + query.substring(queryCursor);
+ queryCursor += chars.length();
+ changedQuery();
+ }
+ return true;
+ }
+
+ private void changedQuery() {
+ querySelectionAnchor = -1;
+ activeOffset = -1;
+ selectFromCaret(true);
+ }
+
+ private boolean hasQuerySelection() {
+ return querySelectionAnchor >= 0 && querySelectionAnchor != queryCursor;
+ }
+
+ private void removeQuerySelection() {
+ int start = Math.min(querySelectionAnchor, queryCursor);
+ int end = Math.max(querySelectionAnchor, queryCursor);
+ query = query.substring(0, start) + query.substring(end);
+ queryCursor = start;
+ querySelectionAnchor = -1;
+ }
+
+ private void selectFromCaret(boolean forward) {
+ List matches = matchOffsets(target);
+ if (matches.isEmpty() || target == null) {
+ activeOffset = -1;
+ if (target != null) target.clearSearchSelection();
+ return;
+ }
+ int caret = target.searchAnchorOffset();
+ int selected = forward ? matches.getFirst() : matches.getLast();
+ for (int offset : matches) {
+ if (offset <= caret && offset + query.length() >= caret) {
+ selected = offset;
+ break;
+ }
+ if (forward && offset >= caret) {
+ selected = offset;
+ break;
+ }
+ if (!forward && offset < caret) selected = offset;
+ }
+ select(selected);
+ }
+
+ private void move(int direction) {
+ List matches = matchOffsets(target);
+ if (matches.isEmpty()) return;
+ int index = matches.indexOf(activeOffset);
+ if (index < 0) index = direction > 0 ? -1 : 0;
+ index = (index + direction + matches.size()) % matches.size();
+ select(matches.get(index));
+ }
+
+ private void select(int offset) {
+ activeOffset = offset;
+ if (target != null) target.selectSearchMatch(offset, query.length());
+ }
+
+ private int inputCaretAt(int mouseX) {
+ int textX = inputX() + 7;
+ int inputRight = Math.max(textX + 1, inputEndX());
+ int shift = queryShift(inputRight - textX - 3);
+ int x = mouseX + shift;
+ int best = 0;
+ for (int i = 1; i <= query.length(); i++) {
+ if (x >= textX + font.width(query.substring(0, i))) best = i;
+ }
+ return best;
+ }
+
+ @Override
+ public boolean handleMouseClicked(MouseButtonEvent event, boolean doubleClick) {
+ if (event.button() != 0) return true;
+ int mx = (int) event.x(), my = (int) event.y();
+ if (my < barY() || my >= barY() + HEIGHT) return true;
+ if (mx >= closeX() && mx < closeX() + BUTTON_WIDTH) {
+ close();
+ } else if (mx >= nextX() && mx < nextX() + BUTTON_WIDTH) {
+ move(1);
+ } else if (mx >= previousX() && mx < previousX() + BUTTON_WIDTH) {
+ move(-1);
+ } else {
+ queryCursor = inputCaretAt(mx);
+ querySelectionAnchor = -1;
+ }
+ return true;
+ }
+
+ private void close() {
+ editorManager.closeFind(this, restoreFocus);
+ }
+
+ @Override public boolean handleMouseDragged(MouseButtonEvent event) { return true; }
+ @Override public boolean handleMouseReleased(MouseButtonEvent event) { return true; }
+ @Override public boolean handleMouseScrolled(double scrollY) { return true; }
+}
diff --git a/src/client/java/com/aranroig/client/editor/EditorManager.java b/src/client/java/com/aranroig/client/editor/EditorManager.java
index c39bbed..491928e 100644
--- a/src/client/java/com/aranroig/client/editor/EditorManager.java
+++ b/src/client/java/com/aranroig/client/editor/EditorManager.java
@@ -46,6 +46,9 @@ public class EditorManager {
EditorPaneContainer paneContainer;
EditorDocsPanel editorDocsPanel;
EditorTerminalPane editorTerminal;
+ private final EditorFindBar findBar;
+ private EditorSearchPopup searchPopup;
+ private EditorThemePopup themePopup;
List files = new ArrayList<>();
@@ -85,6 +88,7 @@ public class EditorManager {
paneContainer = new EditorPaneContainer(this);
editorDocsPanel = new EditorDocsPanel(this);
editorTerminal = new EditorTerminalPane(this);
+ findBar = new EditorFindBar(this);
}
public EditorTheme.Palette theme() {
@@ -95,8 +99,11 @@ public class EditorManager {
return theme;
}
+ void previewTheme(EditorTheme theme) {
+ this.theme = theme;
+ }
+
public void setTheme(EditorTheme theme) {
- if (this.theme == theme) return;
this.theme = theme;
Path path = themeConfigPath();
@@ -201,6 +208,76 @@ public class EditorManager {
editorDocsPanel.open(word);
}
+ /** Opens one of the editor's find, project search, or file picker popups. */
+ public void openSearch(EditorSearchPopup.Mode mode) {
+ if (currentScreen == null) return;
+ if (searchPopup == null) searchPopup = new EditorSearchPopup(this);
+ searchPopup.open(currentScreen, mode, currentScreen.selectedWidget);
+ }
+
+ /** Opens the inline find bar for the currently focused editor pane. */
+ public void openFind() {
+ if (currentScreen == null) return;
+ EditorFileView pane = currentScreen.selectedWidget instanceof EditorFileView selected
+ ? selected : currentScreen.selectedWidget == findBar ? findBar.targetPane() : paneContainer.activeFilePane();
+ if (pane == null) return;
+ findBar.open(currentScreen, pane);
+ }
+
+ void closeFind(EditorFindBar bar, Widget restoreFocus) {
+ if (findBar != bar || currentScreen == null) return;
+ currentScreen.removeWidget(bar);
+ currentScreen.selectedWidget = restoreFocus != null && currentScreen.widgets.contains(restoreFocus)
+ ? restoreFocus : paneContainer.activePane();
+ }
+
+ List findMatchOffsets(EditorFileView pane) {
+ return findBar.matchOffsets(pane);
+ }
+
+ int activeFindMatchOffset(EditorFileView pane) {
+ return findBar.activeMatchOffset(pane);
+ }
+
+ int findQueryLength(EditorFileView pane) {
+ return findBar.queryLength(pane);
+ }
+
+ boolean isFindVisible(EditorFindBar bar) {
+ return currentScreen != null && currentScreen.widgets.contains(bar);
+ }
+
+ /** Opens the modal theme chooser from View → Change theme. */
+ public void openThemePicker() {
+ if (currentScreen == null) return;
+ if (themePopup == null) themePopup = new EditorThemePopup(this);
+ themePopup.open(currentScreen, paneContainer.activePane());
+ }
+
+ void closeThemePicker(EditorThemePopup popup, Widget restoreFocus) {
+ if (themePopup != popup) return;
+ if (currentScreen != null) {
+ currentScreen.removeWidget(popup);
+ currentScreen.selectedWidget = restoreFocus != null && currentScreen.widgets.contains(restoreFocus)
+ ? restoreFocus : paneContainer.activePane();
+ }
+ }
+
+ void closeSearch(EditorSearchPopup popup, Widget restoreFocus) {
+ if (searchPopup != popup) return;
+ if (currentScreen != null) {
+ currentScreen.removeWidget(popup);
+ currentScreen.selectedWidget = restoreFocus != null && currentScreen.widgets.contains(restoreFocus)
+ ? restoreFocus : paneContainer.activePane();
+ }
+ }
+
+ /** Searches the newest text we have, including unsaved text in an open pane. */
+ String textForSearch(EditorFile file) {
+ List openPanes = panesEditing(file.getName());
+ return openPanes.isEmpty() ? file.getText() : openPanes.getFirst().textForSearch();
+ }
+
/** Asks the server for the current project files; the reply lands in {@link #setFiles(List)}. */
public void requestProjectFiles() {
if (!connected()) return;
@@ -401,6 +478,23 @@ public class EditorManager {
ClientPlayNetworking.send(new ServerboundEditPayload(file.getName(), doc.base(), edit));
}
+ /**
+ * Forwards one local change that is already a whole walk over the text —
+ * an undo or a redo, which once rewritten against what other players
+ * typed in the meantime can cover more than one stretch of it. Like
+ * typing, the buffer has already been changed and this records it as in
+ * flight against the version it was applied to.
+ */
+ public void submitEdit(EditorFile file, String buffer, Edit operation) {
+ file.setText(buffer);
+ if (!connected()) return;
+
+ LiveDocument doc = liveDocument(file.getName());
+ Edit edit = doc.submit(operation);
+ if (edit == null) return; // the change amounted to nothing
+ ClientPlayNetworking.send(new ServerboundEditPayload(file.getName(), doc.base(), edit));
+ }
+
/**
* Someone else's edit of a file we are watching. Every pane showing that
* file gets it; if no pane shows it, it is merged into our stored copy of
@@ -707,7 +801,10 @@ public class EditorManager {
editorTerminal.markClosed(reason);
}
+ /** Edit → Undo: takes the last change back in the pane being typed in. */
public void undo() {
+ EditorFileView pane = activePane();
+ if (pane != null) pane.undo();
}
public void run() {
@@ -728,7 +825,10 @@ public class EditorManager {
*/
}
+ /** Edit → Redo: puts back what undo took, in the pane being typed in. */
public void redo() {
+ EditorFileView pane = activePane();
+ if (pane != null) pane.redo();
}
public void stop() {
diff --git a/src/client/java/com/aranroig/client/editor/EditorSearchPopup.java b/src/client/java/com/aranroig/client/editor/EditorSearchPopup.java
new file mode 100644
index 0000000..32c35ae
--- /dev/null
+++ b/src/client/java/com/aranroig/client/editor/EditorSearchPopup.java
@@ -0,0 +1,320 @@
+package com.aranroig.client.editor;
+
+import com.aranroig.editor.EditorFile;
+import net.minecraft.client.gui.Font;
+import net.minecraft.client.gui.GuiGraphicsExtractor;
+import net.minecraft.client.input.CharacterEvent;
+import net.minecraft.client.input.KeyEvent;
+import net.minecraft.client.input.MouseButtonEvent;
+import org.jspecify.annotations.NonNull;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+/** Modal find, project search, and file picker for the editor. */
+final class EditorSearchPopup extends Widget {
+
+ enum Mode { FIND, PROJECT, FILE }
+
+ private record Result(EditorFile file, int offset, int length, int line, String preview) {}
+
+ private static final int MAX_RESULTS = 200;
+ private static final int ROW_HEIGHT = 14;
+ private static final int PAD = 8;
+
+ private Mode mode;
+ private String query = "";
+ private int queryCursor;
+ private int selected;
+ private int scroll;
+ private int lastFindStart = -1;
+ private String lastFindQuery = "";
+ private Widget restoreFocus;
+ private Font font;
+
+ EditorSearchPopup(EditorManager editorManager) {
+ super(editorManager);
+ setZIndex(3);
+ }
+
+ void open(EditorScreen screen, Mode mode, Widget restoreFocus) {
+ this.mode = mode;
+ this.restoreFocus = restoreFocus == this && this.restoreFocus != null ? this.restoreFocus : restoreFocus;
+ this.query = mode == Mode.FIND && restoreFocus instanceof EditorFileView view ? view.searchSeed() : "";
+ this.queryCursor = query.length();
+ this.selected = 0;
+ this.scroll = 0;
+ this.lastFindStart = -1;
+ this.lastFindQuery = "";
+ setSize(0, 0, -1, -1);
+ if (editorScreen != screen || !screen.widgets.contains(this)) addToEditorScreen(screen);
+ screen.selectedWidget = this;
+ if (mode == Mode.FIND && !query.isEmpty()) findFromCaret(true);
+ }
+
+ private String title() {
+ return switch (mode) {
+ case FIND -> "Find in file";
+ case PROJECT -> "Find in project";
+ case FILE -> "Go to file";
+ };
+ }
+
+ private List results() {
+ List found = new ArrayList<>();
+ String needle = query.toLowerCase(Locale.ROOT);
+ if (mode == Mode.FIND) {
+ EditorFileView pane = editorManager.activePane();
+ EditorFile file = pane == null ? null : pane.getCurrentEditorFile();
+ if (file == null || needle.isEmpty()) return found;
+ addTextMatches(found, file, pane.textForSearch(), needle);
+ return found;
+ }
+
+ for (EditorFile file : editorManager.getFiles()) {
+ if (mode == Mode.FILE) {
+ if (needle.isEmpty() || file.getName().toLowerCase(Locale.ROOT).contains(needle)) {
+ found.add(new Result(file, -1, 0, 0, file.getName()));
+ if (found.size() >= MAX_RESULTS) break;
+ }
+ } else if (!needle.isEmpty()) {
+ addTextMatches(found, file, editorManager.textForSearch(file), needle);
+ if (found.size() >= MAX_RESULTS) break;
+ }
+ }
+ return found;
+ }
+
+ private static void addTextMatches(List results, EditorFile file, String text, String needle) {
+ String lower = text.toLowerCase(Locale.ROOT);
+ int from = 0;
+ while (results.size() < MAX_RESULTS) {
+ int offset = lower.indexOf(needle, from);
+ if (offset < 0) break;
+ int lineStart = offset == 0 ? 0 : text.lastIndexOf('\n', offset - 1) + 1;
+ int lineEnd = text.indexOf('\n', offset);
+ if (lineEnd < 0) lineEnd = text.length();
+ int lineNumber = 1;
+ for (int i = 0; i < lineStart; i++) if (text.charAt(i) == '\n') lineNumber++;
+ String line = text.substring(lineStart, lineEnd).strip();
+ if (line.length() > 120) line = line.substring(0, 117) + "...";
+ results.add(new Result(file, offset, needle.length(), lineNumber, line));
+ from = offset + Math.max(1, needle.length());
+ }
+ }
+
+ private int panelWidth() { return Math.min(520, Math.max(260, editorScreen.width - 32)); }
+ private int panelX() { return (editorScreen.width - panelWidth()) / 2; }
+ private int panelY() { return Math.max(18, editorScreen.height / 5); }
+ private int panelHeight() { return Math.min(editorScreen.height - 32, 250); }
+ private int inputY() { return panelY() + 31; }
+ private int listY() { return inputY() + 23; }
+ private int maxVisibleRows() { return Math.max(1, (panelY() + panelHeight() - PAD - listY()) / ROW_HEIGHT); }
+
+ @Override
+ public void draw(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY, double delta) {
+ font = editorScreen.getFont();
+ int x = panelX(), y = panelY(), w = panelWidth(), h = panelHeight();
+ graphics.fill(0, 0, editorScreen.width, editorScreen.height, editorManager.theme().overlay());
+ graphics.fill(x + 2, y + 2, x + w + 2, y + h + 2, 0x55000000);
+ graphics.fill(x, y, x + w, y + h, editorManager.theme().background());
+ graphics.fill(x, y, x + w, y + 1, editorManager.theme().border());
+ graphics.fill(x, y + h - 1, x + w, y + h, editorManager.theme().border());
+ graphics.fill(x, y, x + 1, y + h, editorManager.theme().border());
+ graphics.fill(x + w - 1, y, x + w, y + h, editorManager.theme().border());
+ graphics.text(font, title(), x + PAD, y + PAD, editorManager.theme().text(), false);
+
+ int ix = x + PAD, iw = w - PAD * 2;
+ graphics.fill(ix, inputY(), ix + iw, inputY() + 18, editorManager.theme().raisedBackground());
+ graphics.fill(ix, inputY(), ix + iw, inputY() + 1, editorManager.theme().accent());
+ String shown = query.isEmpty() ? "Type to search…" : query;
+ graphics.text(font, shown, ix + 5, inputY() + 5,
+ query.isEmpty() ? editorManager.theme().mutedText() : editorManager.theme().text(), false);
+ if (!query.isEmpty() && (System.currentTimeMillis() / 500) % 2 == 0) {
+ int caretX = ix + 5 + font.width(query.substring(0, Math.min(queryCursor, query.length())));
+ graphics.fill(caretX, inputY() + 4, caretX + 1, inputY() + 15, editorManager.theme().cursor());
+ }
+
+ List rows = results();
+ if (selected >= rows.size()) selected = Math.max(0, rows.size() - 1);
+ if (selected < scroll) scroll = selected;
+ if (selected >= scroll + maxVisibleRows()) scroll = selected - maxVisibleRows() + 1;
+ graphics.enableScissor(x + 1, listY(), x + w - 1, y + h - PAD);
+ int shownRows = Math.min(rows.size() - scroll, maxVisibleRows());
+ for (int i = 0; i < shownRows; i++) {
+ int index = scroll + i;
+ Result result = rows.get(index);
+ int rowY = listY() + i * ROW_HEIGHT;
+ if (index == selected) graphics.fill(x + 1, rowY, x + w - 1, rowY + ROW_HEIGHT, editorManager.theme().selection());
+ String label;
+ if (mode == Mode.FILE) label = result.file().getName();
+ else label = result.file().getName() + ":" + result.line() + " " + result.preview();
+ int available = w - PAD * 2 - 4;
+ if (font.width(label) > available) {
+ while (!label.isEmpty() && font.width(label + "…") > available) label = label.substring(0, label.length() - 1);
+ label += "…";
+ }
+ graphics.text(font, label, x + PAD, rowY + 3,
+ index == selected ? editorManager.theme().text() : editorManager.theme().mutedText(), false);
+ }
+ graphics.disableScissor();
+ String count = mode == Mode.FIND
+ ? (rows.isEmpty() ? "No matches" : (selected + 1) + " / " + rows.size() + " · Enter next, Shift+Enter previous")
+ : rows.size() + (rows.size() == MAX_RESULTS ? "+" : "") + " results · ↑↓ select, Enter open, Esc close";
+ graphics.text(font, count, x + PAD, y + h - font.lineHeight - 4, editorManager.theme().hint(), false);
+ }
+
+ @Override
+ public boolean handleKeyPressed(KeyEvent event) {
+ int key = event.key();
+ boolean ctrl = event.hasControlDown();
+ if (ctrl && key == 65) { queryCursor = query.length(); return true; }
+ switch (key) {
+ case 256 -> { close(); return true; }
+ case 259 -> { // Backspace
+ if (queryCursor > 0) {
+ query = query.substring(0, queryCursor - 1) + query.substring(queryCursor);
+ queryCursor--;
+ changedQuery();
+ }
+ return true;
+ }
+ case 261 -> {
+ if (queryCursor < query.length()) {
+ query = query.substring(0, queryCursor) + query.substring(queryCursor + 1);
+ changedQuery();
+ }
+ return true;
+ }
+ case 263 -> { queryCursor = Math.max(0, queryCursor - 1); return true; }
+ case 262 -> { queryCursor = Math.min(query.length(), queryCursor + 1); return true; }
+ case 268 -> { queryCursor = 0; return true; }
+ case 269 -> { queryCursor = query.length(); return true; }
+ case 265 -> { moveSelection(-1); return true; }
+ case 264 -> { moveSelection(1); return true; }
+ case 257 -> {
+ if (mode == Mode.FIND) findFromCaret(!event.hasShiftDown());
+ else openSelected();
+ return true;
+ }
+ }
+ return true;
+ }
+
+ @Override
+ public boolean handleCharTyped(CharacterEvent event) {
+ int cp = event.codepoint();
+ if (cp >= 32 && cp != 127) {
+ String chars = Character.toString(cp);
+ query = query.substring(0, queryCursor) + chars + query.substring(queryCursor);
+ queryCursor += chars.length();
+ changedQuery();
+ }
+ return true;
+ }
+
+ private void changedQuery() {
+ selected = 0;
+ scroll = 0;
+ if (mode == Mode.FIND) {
+ lastFindQuery = "";
+ findFromCaret(true);
+ }
+ }
+
+ private void moveSelection(int direction) {
+ List rows = results();
+ if (rows.isEmpty()) return;
+ selected = (selected + direction + rows.size()) % rows.size();
+ if (mode == Mode.FIND) selectFindResult(rows.get(selected));
+ }
+
+ private void findFromCaret(boolean forward) {
+ List rows = results();
+ if (rows.isEmpty()) return;
+ EditorFileView pane = editorManager.activePane();
+ int caret = pane == null ? 0 : pane.searchAnchorOffset();
+ int start = forward ? 0 : rows.size() - 1;
+ if (query.equalsIgnoreCase(lastFindQuery) && lastFindStart >= 0) {
+ for (int i = 0; i < rows.size(); i++) {
+ int index = forward ? (selected + 1 + i) % rows.size() : (selected - 1 - i + rows.size() * 2) % rows.size();
+ if (rows.get(index).offset() >= 0) { start = index; break; }
+ }
+ } else {
+ // Prefer the occurrence under the caret (or the selection that
+ // seeded Ctrl+F); subsequent Enter presses walk from that match.
+ boolean located = false;
+ for (int i = 0; i < rows.size(); i++) {
+ Result result = rows.get(i);
+ if (result.offset() <= caret && result.offset() + result.length() >= caret) {
+ start = i;
+ located = true;
+ break;
+ }
+ }
+ if (!located && forward) {
+ for (int i = 0; i < rows.size(); i++) if (rows.get(i).offset() >= caret) { start = i; break; }
+ } else if (!located) {
+ for (int i = rows.size() - 1; i >= 0; i--) if (rows.get(i).offset() < caret) { start = i; break; }
+ }
+ }
+ selected = start;
+ lastFindQuery = query;
+ lastFindStart = rows.get(selected).offset();
+ selectFindResult(rows.get(selected));
+ }
+
+ private void selectFindResult(Result result) {
+ EditorFileView pane = editorManager.activePane();
+ if (pane != null && result.offset() >= 0) pane.selectSearchMatch(result.offset(), result.length());
+ }
+
+ private void openSelected() {
+ List rows = results();
+ if (selected < 0 || selected >= rows.size()) return;
+ Result result = rows.get(selected);
+ close();
+ editorManager.openFile(result.file());
+ if (mode == Mode.PROJECT) {
+ EditorFileView pane = editorManager.activePane();
+ if (pane != null) pane.selectSearchMatch(result.offset(), result.length());
+ }
+ }
+
+ private void close() {
+ editorManager.closeSearch(this, restoreFocus);
+ }
+
+ @Override
+ public boolean handleMouseClicked(MouseButtonEvent event, boolean doubleClick) {
+ if (event.button() != 0) return true;
+ int x = panelX(), y = panelY(), w = panelWidth();
+ int mx = (int) event.x(), my = (int) event.y();
+ if (mx < x || mx >= x + w || my < y || my >= y + panelHeight()) {
+ close();
+ return true;
+ }
+ if (my >= listY()) {
+ int index = scroll + (my - listY()) / ROW_HEIGHT;
+ if (index >= 0 && index < results().size()) {
+ selected = index;
+ if (mode == Mode.FIND) selectFindResult(results().get(index));
+ else openSelected();
+ }
+ }
+ return true;
+ }
+
+ @Override public boolean handleMouseDragged(MouseButtonEvent event) { return true; }
+ @Override public boolean handleMouseReleased(MouseButtonEvent event) { return true; }
+
+ @Override
+ public boolean handleMouseScrolled(double scrollY) {
+ List rows = results();
+ if (rows.isEmpty()) return true;
+ selected = Math.max(0, Math.min(rows.size() - 1, selected - (int) Math.signum(scrollY)));
+ if (mode == Mode.FIND) selectFindResult(rows.get(selected));
+ return true;
+ }
+}
diff --git a/src/client/java/com/aranroig/client/editor/EditorTheme.java b/src/client/java/com/aranroig/client/editor/EditorTheme.java
index 57cd900..4930938 100644
--- a/src/client/java/com/aranroig/client/editor/EditorTheme.java
+++ b/src/client/java/com/aranroig/client/editor/EditorTheme.java
@@ -37,7 +37,52 @@ public enum EditorTheme {
0xFFF8F8F2, 0x66F8F8F2,
0xFFF8F8F2, 0xFFF92672, 0xFFA6E22E, 0xFFE6DB74, 0xFFAE81FF,
0xFF75715E, 0xFFFD971F, 0xFFA6E22E, 0xFF75715E,
- 0xFF1E1F1A, 0xFF909185, 0xFF1E1F1A, 0xB0000000));
+ 0xFF1E1F1A, 0xFF909185, 0xFF1E1F1A, 0xB0000000)),
+ DRACULA("Dracula", new Palette(
+ 0xFF282A36, 0xFF21222C, 0xFF343746, 0xFF44475A, 0xFF383A4A,
+ 0xFFF8F8F2, 0xFFB8B8C8, 0xFF515366, 0xFFBD93F9, 0xFFD0AEFF,
+ 0xFF44475A, 0xFF515366, 0xFFFF5555,
+ 0xFFFFB86C, 0xFFFFCC8A, 0xFF9A714C, 0xFF8BE9FD, 0xFF6272A4,
+ 0xFFF8F8F2, 0x66F8F8F2,
+ 0xFFF8F8F2, 0xFFFF79C6, 0xFF8BE9FD, 0xFFF1FA8C, 0xFFBD93F9,
+ 0xFF6272A4, 0xFFFFB86C, 0xFF50FA7B, 0xFF6272A4,
+ 0xFF191A21, 0xFFB8B8C8, 0xFF191A21, 0xB0000000)),
+ SOLARIZED_DARK("Solarized Dark", new Palette(
+ 0xFF002B36, 0xFF00232C, 0xFF073642, 0xFF164550, 0xFF0B3A45,
+ 0xFFEEE8D5, 0xFF93A1A1, 0xFF586E75, 0xFF268BD2, 0xFF4AA3DF,
+ 0xFF164550, 0xFF1D5360, 0xFFDC322F,
+ 0xFFB58900, 0xFFD0A629, 0xFF806000, 0xFF2AA198, 0xFF657B83,
+ 0xFFEEE8D5, 0x66EEE8D5,
+ 0xFF839496, 0xFF859900, 0xFF268BD2, 0xFF2AA198, 0xFFCB4B16,
+ 0xFF586E75, 0xFFB58900, 0xFF6C71C4, 0xFF657B83,
+ 0xFF00232C, 0xFF93A1A1, 0xFF00232C, 0xB0000000)),
+ SOLARIZED_LIGHT("Solarized Light", new Palette(
+ 0xFFFDF6E3, 0xFFEEE8D5, 0xFFF5EEDB, 0xFFE5DDC8, 0xFFF0E8D3,
+ 0xFF586E75, 0xFF839496, 0xFFB7AE98, 0xFF268BD2, 0xFF4AA3DF,
+ 0xFFE5DDC8, 0xFFDAD1BA, 0xFFDC322F,
+ 0xFFB58900, 0xFFD0A629, 0xFF806000, 0xFF2AA198, 0xFF657B83,
+ 0xFF586E75, 0x66586E75,
+ 0xFF586E75, 0xFF859900, 0xFF268BD2, 0xFF2AA198, 0xFFCB4B16,
+ 0xFF93A1A1, 0xFFB58900, 0xFF6C71C4, 0xFF839496,
+ 0xFFEEE8D5, 0xFF839496, 0xFFEEE8D5, 0xB0000000)),
+ GRUVBOX_DARK("Gruvbox Dark", new Palette(
+ 0xFF282828, 0xFF1D2021, 0xFF32302F, 0xFF3C3836, 0xFF353230,
+ 0xFFEBDBB2, 0xFFA89984, 0xFF504945, 0xFF83A598, 0xFF9DB9AD,
+ 0xFF504945, 0xFF665C54, 0xFFFB4934,
+ 0xFFD79921, 0xFFE7B84A, 0xFF8F6416, 0xFF8EC07C, 0xFF928374,
+ 0xFFEBDBB2, 0x66EBDBB2,
+ 0xFFEBDBB2, 0xFFFB4934, 0xFF8EC07C, 0xFFB8BB26, 0xFFD79921,
+ 0xFF928374, 0xFF83A598, 0xFFD3869B, 0xFF928374,
+ 0xFF1D2021, 0xFFA89984, 0xFF1D2021, 0xB0000000)),
+ TOKYO_NIGHT("Tokyo Night", new Palette(
+ 0xFF1A1B26, 0xFF16161E, 0xFF24283B, 0xFF2F3549, 0xFF292E42,
+ 0xFFC0CAF5, 0xFF787C99, 0xFF414868, 0xFF7AA2F7, 0xFF91B4FF,
+ 0xFF364A82, 0xFF414F78, 0xFFF7768E,
+ 0xFFE0AF68, 0xFFF0C77E, 0xFF977647, 0xFF7DCFFF, 0xFF565F89,
+ 0xFFC0CAF5, 0x66C0CAF5,
+ 0xFFC0CAF5, 0xFFBB9AF7, 0xFF7DCFFF, 0xFF9ECE6A, 0xFFFF9E64,
+ 0xFF565F89, 0xFF7AA2F7, 0xFF2AC3DE, 0xFF565F89,
+ 0xFF15161E, 0xFF787C99, 0xFF15161E, 0xB0000000));
private final String displayName;
private final Palette palette;
diff --git a/src/client/java/com/aranroig/client/editor/EditorThemePopup.java b/src/client/java/com/aranroig/client/editor/EditorThemePopup.java
new file mode 100644
index 0000000..3b1f8d1
--- /dev/null
+++ b/src/client/java/com/aranroig/client/editor/EditorThemePopup.java
@@ -0,0 +1,178 @@
+package com.aranroig.client.editor;
+
+import net.minecraft.client.gui.Font;
+import net.minecraft.client.gui.GuiGraphicsExtractor;
+import net.minecraft.client.input.CharacterEvent;
+import net.minecraft.client.input.KeyEvent;
+import net.minecraft.client.input.MouseButtonEvent;
+import org.jspecify.annotations.NonNull;
+
+/** Modal theme chooser opened from View → Change theme. */
+final class EditorThemePopup extends Widget {
+
+ private static final int PAD = 9;
+ private static final int ROW_HEIGHT = 17;
+ private static final int MAX_PANEL_HEIGHT = 236;
+
+ private Widget restoreFocus;
+ private EditorTheme originalTheme;
+ private int selected;
+ private int scroll;
+ private Font font;
+
+ EditorThemePopup(EditorManager editorManager) {
+ super(editorManager);
+ setZIndex(4);
+ }
+
+ void open(EditorScreen screen, Widget restoreFocus) {
+ this.restoreFocus = restoreFocus;
+ originalTheme = editorManager.currentTheme();
+ selected = originalTheme.ordinal();
+ scroll = 0;
+ setSize(0, 0, -1, -1);
+ if (editorScreen != screen || !screen.widgets.contains(this)) addToEditorScreen(screen);
+ screen.selectedWidget = this;
+ }
+
+ private int panelWidth() { return Math.min(300, Math.max(1, editorScreen.width - 24)); }
+ private int panelHeight() { return Math.max(1, Math.min(MAX_PANEL_HEIGHT, editorScreen.height - 24)); }
+ private int panelX() { return (editorScreen.width - panelWidth()) / 2; }
+ private int panelY() { return (editorScreen.height - panelHeight()) / 2; }
+ private int listTop() { return panelY() + 30; }
+ private int listBottom() { return panelY() + panelHeight() - 24; }
+ private int visibleRows() { return Math.max(1, (listBottom() - listTop()) / ROW_HEIGHT); }
+
+ @Override
+ public void draw(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY, double delta) {
+ font = editorScreen.getFont();
+ int x = panelX(), y = panelY(), w = panelWidth(), h = panelHeight();
+ int right = x + w, bottom = y + h;
+
+ graphics.fill(0, 0, editorScreen.width, editorScreen.height, editorManager.theme().overlay());
+ graphics.fill(x + 2, y + 2, right + 2, bottom + 2, 0x55000000);
+ graphics.fill(x, y, right, bottom, editorManager.theme().background());
+ graphics.fill(x, y, right, y + 1, editorManager.theme().border());
+ graphics.fill(x, bottom - 1, right, bottom, editorManager.theme().border());
+ graphics.fill(x, y, x + 1, bottom, editorManager.theme().border());
+ graphics.fill(right - 1, y, right, bottom, editorManager.theme().border());
+
+ graphics.text(font, "Choose editor theme", x + PAD, y + 8, editorManager.theme().text(), false);
+ graphics.fill(x + 1, y + 24, right - 1, y + 25, editorManager.theme().border());
+
+ EditorTheme[] themes = EditorTheme.values();
+ ensureVisible(themes.length);
+ graphics.enableScissor(x + 1, listTop(), right - 1, listBottom());
+ int shownRows = Math.min(visibleRows(), themes.length - scroll);
+ for (int i = 0; i < shownRows; i++) {
+ int index = scroll + i;
+ EditorTheme theme = themes[index];
+ int rowY = listTop() + i * ROW_HEIGHT;
+ if (index == selected) {
+ graphics.fill(x + 1, rowY, right - 1, rowY + ROW_HEIGHT, editorManager.theme().selection());
+ graphics.fill(x + 1, rowY, x + 3, rowY + ROW_HEIGHT, editorManager.theme().accent());
+ }
+
+ EditorTheme.Palette palette = theme.palette();
+ graphics.fill(x + PAD, rowY + 4, x + PAD + 14, rowY + 13, palette.background());
+ graphics.fill(x + PAD + 10, rowY + 4, x + PAD + 14, rowY + 8, palette.accent());
+ String label = theme.displayName() + (theme == editorManager.currentTheme() ? " (current)" : "");
+ graphics.text(font, label, x + PAD + 22, rowY + 4,
+ index == selected ? editorManager.theme().text() : editorManager.theme().mutedText(), false);
+ }
+ graphics.disableScissor();
+
+ String hint = "↑↓ or ←→ select · Enter apply · Esc close";
+ graphics.text(font, hint, x + PAD, bottom - font.lineHeight - 6, editorManager.theme().hint(), false);
+ }
+
+ @Override
+ public boolean handleKeyPressed(KeyEvent event) {
+ int key = event.key();
+ switch (key) {
+ case 256 -> close(); // Escape
+ case 257, 32 -> applySelection(); // Enter or Space
+ case 265, 263 -> moveSelection(-1); // Up or Left
+ case 264, 262 -> moveSelection(1); // Down or Right
+ case 268 -> { selected = 0; ensureVisible(EditorTheme.values().length); previewSelection(); }
+ case 269 -> { selected = EditorTheme.values().length - 1; ensureVisible(EditorTheme.values().length); previewSelection(); }
+ default -> { }
+ }
+ return true;
+ }
+
+ private void moveSelection(int amount) {
+ int count = EditorTheme.values().length;
+ selected = (selected + amount + count) % count;
+ ensureVisible(count);
+ previewSelection();
+ }
+
+ private void previewSelection() {
+ editorManager.previewTheme(EditorTheme.values()[selected]);
+ }
+
+ private void ensureVisible(int count) {
+ int rows = visibleRows();
+ if (selected < scroll) scroll = selected;
+ else if (selected >= scroll + rows) scroll = selected - rows + 1;
+ scroll = Math.max(0, Math.min(scroll, Math.max(0, count - rows)));
+ }
+
+ private void applySelection() {
+ editorManager.setTheme(EditorTheme.values()[selected]);
+ editorManager.closeThemePicker(this, restoreFocus);
+ }
+
+ private void close() {
+ editorManager.previewTheme(originalTheme);
+ editorManager.closeThemePicker(this, restoreFocus);
+ }
+
+ @Override public boolean handleCharTyped(CharacterEvent event) { return true; }
+
+ @Override
+ public boolean handleMouseClicked(MouseButtonEvent event, boolean doubleClick) {
+ int x = panelX(), y = panelY(), w = panelWidth();
+ int mx = (int) event.x(), my = (int) event.y();
+ if (mx < x || mx >= x + w || my < y || my >= y + panelHeight()) {
+ close();
+ return true;
+ }
+
+ if (my >= listTop() && my < listBottom()) {
+ int index = scroll + (my - listTop()) / ROW_HEIGHT;
+ if (index >= 0 && index < EditorTheme.values().length) {
+ selected = index;
+ applySelection();
+ }
+ }
+ return true;
+ }
+
+ @Override public boolean handleMouseDragged(MouseButtonEvent event) { return true; }
+ @Override public boolean handleMouseReleased(MouseButtonEvent event) { return true; }
+
+ @Override
+ public boolean handleMouseScrolled(double scrollY) {
+ int maxScroll = Math.max(0, EditorTheme.values().length - visibleRows());
+ scroll = Math.max(0, Math.min(maxScroll, scroll - (int) Math.signum(scrollY)));
+ boolean selectionChanged = false;
+ if (selected < scroll) {
+ selected = scroll;
+ selectionChanged = true;
+ } else if (selected >= scroll + visibleRows()) {
+ selected = scroll + visibleRows() - 1;
+ selectionChanged = true;
+ }
+ if (selectionChanged) previewSelection();
+ return true;
+ }
+
+ @Override
+ public boolean inside(double x, double y) {
+ // Own the whole screen so clicks outside the dialog dismiss it without
+ // activating an editor control underneath.
+ return x >= getStartX() && x <= getEndX() && y >= getStartY() && y <= getEndY();
+ }
+}
diff --git a/src/client/java/com/aranroig/client/editor/EditorTopBar.java b/src/client/java/com/aranroig/client/editor/EditorTopBar.java
index 61b42f8..414a1f4 100644
--- a/src/client/java/com/aranroig/client/editor/EditorTopBar.java
+++ b/src/client/java/com/aranroig/client/editor/EditorTopBar.java
@@ -66,10 +66,7 @@ public class EditorTopBar extends Widget {
MenuItem.separator(),
MenuItem.item("Close Pane"),
MenuItem.separator(),
- MenuItem.item("Midnight"),
- MenuItem.item("Light"),
- MenuItem.item("Nord"),
- MenuItem.item("Monokai")
+ MenuItem.item("Change theme...")
),
// Help
List.of(
@@ -297,7 +294,7 @@ public class EditorTopBar extends Widget {
graphics.fill(tabX + 1, curY, dropX2 - 1, curY + itemH, editorManager.theme().accentHover());
}
- graphics.text(font, displayLabel(tabIndex, i),
+ graphics.text(font, displayLabel(item),
tabX + TAB_PADDING_X,
curY + TAB_PADDING_Y,
editorManager.theme().text(), false);
@@ -320,6 +317,7 @@ public class EditorTopBar extends Widget {
case "Save" -> editorManager.save();
case "Undo" -> editorManager.undo();
case "Redo" -> editorManager.redo();
+ case "Find..." -> editorManager.openFind();
case "Run Script" -> editorManager.run();
case "Stop" -> editorManager.stop();
case "Toggle Sidebar" -> editorManager.toggleSidebar();
@@ -327,10 +325,7 @@ public class EditorTopBar extends Widget {
case "Split Below" -> editorManager.splitBelow();
case "Close Pane" -> editorManager.closeActivePane();
case "Lua API Documentation" -> editorManager.openDocs();
- case "Midnight" -> editorManager.setTheme(EditorTheme.MIDNIGHT);
- case "Light" -> editorManager.setTheme(EditorTheme.LIGHT);
- case "Nord" -> editorManager.setTheme(EditorTheme.NORD);
- case "Monokai" -> editorManager.setTheme(EditorTheme.MONOKAI);
+ case "Change theme..." -> editorManager.openThemePicker();
// Add remaining cases as needed
default -> System.out.println("[TopBar] Clicked: " + item.label());
}
@@ -344,17 +339,13 @@ public class EditorTopBar extends Widget {
for (int i = 0; i < items.size(); i++) {
MenuItem item = items.get(i);
if (!item.isSeparator()) {
- maxW = Math.max(maxW, font.width(displayLabel(tabIndex, i)) + TAB_PADDING_X * 2 + 8);
+ maxW = Math.max(maxW, font.width(displayLabel(item)) + TAB_PADDING_X * 2 + 8);
}
}
return maxW;
}
- private String displayLabel(int tabIndex, int itemIndex) {
- MenuItem item = TAB_ITEMS.get(tabIndex).get(itemIndex);
- if (tabIndex == 3 && item.label().equals(editorManager.currentTheme().displayName())) {
- return "✓ " + item.label();
- }
+ private String displayLabel(MenuItem item) {
return item.label();
}
diff --git a/src/client/java/com/aranroig/client/editor/EventsLibrary.java b/src/client/java/com/aranroig/client/editor/EventsLibrary.java
deleted file mode 100644
index 28a3e8d..0000000
--- a/src/client/java/com/aranroig/client/editor/EventsLibrary.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package com.aranroig.client.editor;
-
-import java.util.List;
-
-/**
- * Completion for the {@code events} global — game event listeners provided by
- * codecraft itself. Keep in sync with the listener registration and
- * {@code LuaApiDocs}.
- */
-public class EventsLibrary implements LuaLibrary {
-
- private static final List MEMBERS = List.of(
- CompletionItem.method("on_use_item", "on_use_item("),
- CompletionItem.method("on_break_block", "on_break_block("),
- CompletionItem.method("on_chat", "on_chat("),
- CompletionItem.method("on_player_join", "on_player_join("),
- CompletionItem.method("on_player_leave", "on_player_leave("),
- CompletionItem.method("on_tick", "on_tick(")
- );
-
- @Override
- public String name() {
- return "events";
- }
-
- @Override
- public List members() {
- return MEMBERS;
- }
-}
diff --git a/src/client/java/com/aranroig/client/editor/LiveDocument.java b/src/client/java/com/aranroig/client/editor/LiveDocument.java
index 52e83cb..6a75c42 100644
--- a/src/client/java/com/aranroig/client/editor/LiveDocument.java
+++ b/src/client/java/com/aranroig/client/editor/LiveDocument.java
@@ -55,6 +55,21 @@ public final class LiveDocument {
return edit;
}
+ /**
+ * Records a change that is already built as a walk over the text — an
+ * undo or a redo, which once rewritten against what others typed in the
+ * meantime can cover more than one stretch of it — under the next
+ * sequence number of ours. Returns {@code null} when it amounts to
+ * nothing, so it is not queued or sent at all.
+ */
+ public Edit submit(Edit operation) {
+ if (operation.isEmpty()) return null;
+ Edit edit = new Edit(author, sequence, operation.components());
+ sequence++;
+ pending.addLast(edit);
+ return edit;
+ }
+
/** The version of the server's copy this buffer was written against. */
public int base() {
return base;
diff --git a/src/client/java/com/aranroig/client/editor/LuaLibrary.java b/src/client/java/com/aranroig/client/editor/LuaLibrary.java
index d24be5f..f1ae48b 100644
--- a/src/client/java/com/aranroig/client/editor/LuaLibrary.java
+++ b/src/client/java/com/aranroig/client/editor/LuaLibrary.java
@@ -7,9 +7,10 @@ import java.util.List;
* trigger — Lua's own standard libraries ({@code string}, {@code math}, …) and
* the tables codecraft itself injects ({@code world}, {@code events}).
*
- * To make a new library's members appear in the autocomplete popup,
- * implement this interface and add an instance to
- * {@link CompletionProvider}.
+ * Codecraft's own tables do not implement this by hand: they are generated
+ * from the Lua API docs catalog by {@link DocLibraries}. To make a new plain
+ * Lua table's members appear in the autocomplete popup, implement this
+ * interface and add an instance to {@link CompletionProvider}.
*/
public interface LuaLibrary {
diff --git a/src/client/java/com/aranroig/client/editor/MinecraftLibraries.java b/src/client/java/com/aranroig/client/editor/MinecraftLibraries.java
deleted file mode 100644
index 8617340..0000000
--- a/src/client/java/com/aranroig/client/editor/MinecraftLibraries.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package com.aranroig.client.editor;
-
-import java.util.List;
-
-/** Autocomplete members for server-side Minecraft APIs exposed to Lua. */
-public final class MinecraftLibraries {
- private MinecraftLibraries() {
- }
-
- public static List all() {
- return List.of(
- library("entities", "nearby", "spawn", "get", "teleport", "remove", "set_name", "set_health"),
- library("scoreboard", "create_objective", "remove_objective", "set", "add", "get", "reset", "display"),
- library("hud", "title", "subtitle", "action_bar", "title_times", "clear_titles", "bossbar_add", "bossbar_remove", "bossbar_value", "bossbar_max", "bossbar_visible"),
- library("items", "give", "count", "clear", "get_slot", "set_slot")
- );
- }
-
- private static LuaLibrary library(String name, String... names) {
- List members = java.util.Arrays.stream(names)
- .map(member -> CompletionItem.method(member, member + "("))
- .toList();
- return new LuaLibrary() {
- @Override public String name() { return name; }
- @Override public List members() { return members; }
- };
- }
-}
diff --git a/src/client/java/com/aranroig/client/editor/TextEditorScreen.java b/src/client/java/com/aranroig/client/editor/TextEditorScreen.java
index 873de5f..a70a499 100644
--- a/src/client/java/com/aranroig/client/editor/TextEditorScreen.java
+++ b/src/client/java/com/aranroig/client/editor/TextEditorScreen.java
@@ -32,6 +32,20 @@ public class TextEditorScreen extends EditorScreen {
@Override
public boolean keyPressed(KeyEvent event) {
+ if (event.hasControlDown()) {
+ if (event.key() == 70 && event.hasShiftDown()) { // Ctrl+Shift+F
+ editorManager.openSearch(EditorSearchPopup.Mode.PROJECT);
+ return true;
+ }
+ if (event.key() == 80) { // Ctrl+P
+ editorManager.openSearch(EditorSearchPopup.Mode.FILE);
+ return true;
+ }
+ if (event.key() == 70 && (selectedWidget instanceof EditorFileView || selectedWidget instanceof EditorFindBar)) { // Ctrl+F
+ editorManager.openFind();
+ return true;
+ }
+ }
if (event.key() == 66 && event.hasControlDown()) { // Ctrl+B
editorManager.toggleSidebar();
return true;
diff --git a/src/client/java/com/aranroig/client/editor/WorldLibrary.java b/src/client/java/com/aranroig/client/editor/WorldLibrary.java
deleted file mode 100644
index 52a5078..0000000
--- a/src/client/java/com/aranroig/client/editor/WorldLibrary.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package com.aranroig.client.editor;
-
-import java.util.List;
-
-/**
- * Completion for the {@code world} global — block access provided by codecraft
- * itself. Keep in sync with the runtime wrapper and {@code LuaApiDocs}.
- */
-public class WorldLibrary implements LuaLibrary {
-
- private static final List MEMBERS = List.of(
- CompletionItem.method("set_block", "set_block("),
- CompletionItem.method("remove_block", "remove_block("),
- CompletionItem.method("get_block", "get_block("),
- CompletionItem.method("get_dimension", "get_dimension("),
- CompletionItem.method("get_time", "get_time("),
- CompletionItem.method("set_time", "set_time("),
- CompletionItem.method("get_weather", "get_weather("),
- CompletionItem.method("set_weather", "set_weather("),
- CompletionItem.method("get_biome", "get_biome("),
- CompletionItem.method("players", "players(")
- );
-
- @Override
- public String name() {
- return "world";
- }
-
- @Override
- public List members() {
- return MEMBERS;
- }
-}
diff --git a/src/main/java/com/aranroig/editor/Edit.java b/src/main/java/com/aranroig/editor/Edit.java
index 9a65af5..3ba5a80 100644
--- a/src/main/java/com/aranroig/editor/Edit.java
+++ b/src/main/java/com/aranroig/editor/Edit.java
@@ -194,6 +194,38 @@ public record Edit(UUID author, long seq, List components) {
return written;
}
+ // ── Undoing ───────────────────────────────────────────────────────────
+
+ /**
+ * The walk that takes this one back: run it over the text this edit
+ * produced and the earlier text comes out again. Removals become writes
+ * of exactly what was removed — which is why the text the edit ran over
+ * has to be at hand — and writes become removals of the same length.
+ * {@code base} is the text this edit was applied to, and counts that do
+ * not fit it are clamped the same way {@link #apply} clamps them.
+ */
+ public Edit invert(String base) {
+ List inverse = new ArrayList<>(components.size());
+ int index = 0;
+
+ for (Component component : components) {
+ if (component instanceof Retain retain) {
+ int count = Math.min(retain.count(), base.length() - index);
+ if (count <= 0) break;
+ add(inverse, new Retain(count));
+ index += count;
+ } else if (component instanceof Delete delete) {
+ int count = Math.min(delete.count(), base.length() - index);
+ if (count <= 0) break;
+ add(inverse, new Insert(base.substring(index, index + count)));
+ index += count;
+ } else if (component instanceof Insert insert) {
+ add(inverse, new Delete(insert.text().length()));
+ }
+ }
+ return new Edit(author, seq, inverse);
+ }
+
// ── Transforming ──────────────────────────────────────────────────────
/**