diff --git a/src/main/java/noppes/npcs/client/gui/util/GuiScriptTextArea.java b/src/main/java/noppes/npcs/client/gui/util/GuiScriptTextArea.java index 22a5f7528..0b706089d 100644 --- a/src/main/java/noppes/npcs/client/gui/util/GuiScriptTextArea.java +++ b/src/main/java/noppes/npcs/client/gui/util/GuiScriptTextArea.java @@ -677,30 +677,42 @@ public class GuiScriptTextArea extends GuiNpcTextField { String before = getSelectionBeforeText(); String after = getSelectionAfterText(); - // Find the next non-whitespace character and its indent to decide if this brace is already closed at the same scope. - int nextNonWsIndex = -1; - for (int idx = 0; idx < after.length(); idx++) { - char ch = after.charAt(idx); - if (!Character.isWhitespace(ch)) { - nextNonWsIndex = idx; - break; + // Determine whether this opening brace already has a matching closing + // brace at the same scope (and indent). Prefer using the brace-span + // computation which skips strings/comments and handles nesting. + boolean hasMatchingCloseSameIndent = false; + try { + // Find the line index containing the opening brace (cursorPosition-1) + int openLineIdx = -1; + int bracePos = cursorPosition - 1; + for (int li = 0; li < this.container.lines.size(); li++) { + LineData ld = this.container.lines.get(li); + if (bracePos >= ld.start && bracePos < ld.end) { + openLineIdx = li; + break; + } } + + if (openLineIdx >= 0) { + List spans = computeBraceSpans(text, this.container.lines); + for (int[] span : spans) { + int spanOpen = span[1]; + int spanClose = span[2]; + if (spanOpen == openLineIdx) { + // Found a matching close; check its indent equals current indent + int closeIndent = getLineIndent(this.container.lines.get(spanClose).text); + if (closeIndent == indent.length()) { + hasMatchingCloseSameIndent = true; + } + break; + } + } + } + } catch (Exception ex) { + // Fallback: if anything goes wrong, conservatively behave as before + hasMatchingCloseSameIndent = false; } - boolean hasMatchingCloseSameIndent = false; - if (nextNonWsIndex >= 0 && after.charAt(nextNonWsIndex) == '}') { - // Compute indent of that closing brace - int lineStart = after.lastIndexOf('\n', nextNonWsIndex); - int indentLen = 0; - for (int k = lineStart + 1; k < after.length(); k++) { - char ch = after.charAt(k); - if (ch == ' ') indentLen++; else if (ch == '\t') indentLen += 4; else break; - if (k == nextNonWsIndex) break; - } - if (indentLen == indent.length()) { - hasMatchingCloseSameIndent = true; - } - } if (hasMatchingCloseSameIndent) { addText("\n" + childIndent);