diff --git a/src/editor/lsp/semantic/java/copyString.test.ts b/src/editor/lsp/semantic/java/copyString.test.ts new file mode 100644 index 0000000000..c0f5709660 --- /dev/null +++ b/src/editor/lsp/semantic/java/copyString.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from "vitest"; +import { EditorState } from "@codemirror/state"; +import { ensureSyntaxTree } from "@codemirror/language"; +import { java } from "@codemirror/lang-java"; +import { copiedString, textBlockValue, unescape } from "./copyString"; + +/** `doc` with the caret at `|`. */ +function at(doc: string) { + const pos = doc.indexOf("|"); + const state = EditorState.create({ doc: doc.slice(0, pos) + doc.slice(pos + 1), extensions: java() }); + ensureSyntaxTree(state, state.doc.length, 5000); + return copiedString(state, pos); +} + +describe("Copy string concatenation text to the clipboard", () => { + it("puts ? for each operand that isn't a literal", () => { + expect(at(`class X { void p(String s, String t) { System.out.println("s: " + s + " t|: " + t); } }`)).toEqual({ + concatenation: true, + text: "s: ? t: ?", + }); + }); + + it("is offered with the caret on any part of the expression", () => { + expect(at(`class X { String f(int n) { return "not " + n| + " yet"; } }`)?.text).toBe("not ? yet"); + expect(at(`class X { String f(int n) { return "a" +| n; } }`)?.text).toBe("a?"); + }); + + it("keeps the lines of a concatenation split over lines", () => { + const code = [ + "class X {", + " String html(String body) {", + ' return "\\n" +', + ' " \\n" +', + " bo|dy +", + ' " \\n" +', + ' "\\n";', + " }", + "}", + ].join("\n"); + expect(at(code)?.text).toBe("\n \n?\n \n\n"); + const sql = ['class X { String q = "select a" +|', ' " from t" +', ' " where id = " + 1; }'].join("\n"); + expect(at(sql)?.text).toBe("select a\n from t\n where id = 1"); + }); + + it("takes the values of character, number and parenthesized literals", () => { + expect(at(`class X { String s = "a" + 'b' + 12 + ("c") + true + 0x1F|; }`)?.text).toBe("ab12ctrue?"); + }); + + it("copies a lone string literal's value", () => { + expect(at(`class X { String s = "a\\tb|\\u0041\\""; }`)).toEqual({ concatenation: false, text: 'a\tbA"' }); + }); + + it("is not offered outside strings or for other operators", () => { + expect(at(`class X { int n = 1 +| 2; }`)).toBeNull(); + expect(at(`class X { boolean b = "a" == s|; }`)).toBeNull(); + expect(at(`class X { int n| = 1; }`)).toBeNull(); + }); +}); + +describe("Java string values", () => { + it("strips a text block's incidental indentation", () => { + expect(textBlockValue('"""\n \n \n \n """')).toBe( + "\n \n\n", + ); + expect(textBlockValue('"""\n a\n b"""')).toBe(" a\nb"); + expect(textBlockValue('"""\n one \\\n two\\s\n """')).toBe("one two \n"); + }); + + it("interprets escapes", () => { + expect(unescape("\\101\\0\\u00e9\\\\\\'")).toBe("A\0é\\'"); + }); +}); diff --git a/src/editor/lsp/semantic/java/copyString.ts b/src/editor/lsp/semantic/java/copyString.ts new file mode 100644 index 0000000000..ed6f3431e0 --- /dev/null +++ b/src/editor/lsp/semantic/java/copyString.ts @@ -0,0 +1,152 @@ +/** + * Copy String Concatenation Text to the Clipboard and Copy String Literal Text to the Clipboard: + * the text a string concatenation at the caret builds, with `?` for each operand that isn't a + * literal, or the value of the string literal at the caret. + */ +import { syntaxTree } from "@codemirror/language"; +import type { EditorState } from "@codemirror/state"; +import type { EditorView } from "@codemirror/view"; +import type { SyntaxNode } from "@lezer/common"; +import type { ContributedIntention } from "@/editor/api"; +import { writeClipboardText } from "@/platform/clipboard"; +import { tx } from "@/platform/i18n"; + +const STRINGS = new Set(["StringLiteral", "TextBlock"]); + +/** What the intention at `pos` copies: a concatenation's text or a literal's value. */ +export function copiedString(state: EditorState, pos: number): { concatenation: boolean; text: string } | null { + const tree = syntaxTree(state); + for (const side of [1, -1] as const) { + const at = tree.resolveInner(pos, side); + const concat = concatenationAt(state, at); + if (concat) return { concatenation: true, text: concatenationText(state, concat) }; + const literal = enclosing(at, (n) => STRINGS.has(n.name)); + if (literal && pos > literal.from && pos < literal.to) + return { concatenation: false, text: literalValue(state, literal) ?? "" }; + } + return null; +} + +export function javaCopyStringIntentions(view: EditorView): ContributedIntention[] { + const { main } = view.state.selection; + if (!main.empty) return []; + const copied = copiedString(view.state, main.head); + if (!copied) return []; + return [ + { + id: copied.concatenation ? "java.copyConcatenatedString" : "java.copyStringLiteral", + label: copied.concatenation + ? tx("Copy string concatenation text to the clipboard") + : tx("Copy string literal text to the clipboard"), + icon: "bulb", + run: () => writeClipboardText(copied.text), + }, + ]; +} + +function enclosing(node: SyntaxNode | null, test: (n: SyntaxNode) => boolean): SyntaxNode | null { + for (let n = node; n; n = n.parent) { + if (test(n)) return n; + if (/Statement$|Declaration$|^Block$|^LambdaExpression$/.test(n.name)) return null; + } + return null; +} + +const isPlus = (state: EditorState, n: SyntaxNode) => n.name === "BinaryExpression" && operatorOf(state, n) === "+"; + +function operatorOf(state: EditorState, n: SyntaxNode): string | null { + const left = n.firstChild; + const op = left?.nextSibling; + return op ? state.sliceDoc(op.from, op.to) : null; +} + +/** The whole `a + b + …` chain at `at` when one of its operands is a string literal. */ +function concatenationAt(state: EditorState, at: SyntaxNode): SyntaxNode | null { + let chain = enclosing(at, (n) => isPlus(state, n)); + if (!chain) return null; + while (chain.parent && isPlus(state, chain.parent)) chain = chain.parent; + return operands(state, chain).some((o) => STRINGS.has(o.name)) ? chain : null; +} + +function operands(state: EditorState, chain: SyntaxNode): SyntaxNode[] { + const out: SyntaxNode[] = []; + let n: SyntaxNode | null = chain; + while (n && isPlus(state, n)) { + const right = n.lastChild; + if (right) out.unshift(right); + n = n.firstChild; + } + if (n) out.unshift(n); + return out; +} + +function concatenationText(state: EditorState, chain: SyntaxNode): string { + let out = ""; + let prev: SyntaxNode | null = null; + for (const operand of operands(state, chain)) { + // An operand on a new line starts a new line of the text, unless the text already did. + if (prev && state.sliceDoc(prev.to, operand.from).includes("\n") && out && !out.endsWith("\n")) out += "\n"; + out += literalValue(state, operand) ?? "?"; + prev = operand; + } + return out; +} + +/** The value of a literal operand, or null when it isn't one. */ +function literalValue(state: EditorState, node: SyntaxNode): string | null { + const text = state.sliceDoc(node.from, node.to); + switch (node.name) { + case "StringLiteral": + return text.length >= 2 && text.endsWith('"') ? unescape(text.slice(1, -1)) : null; + case "CharacterLiteral": + return text.length >= 3 && text.endsWith("'") ? unescape(text.slice(1, -1)) : null; + case "TextBlock": + return textBlockValue(text); + case "BooleanLiteral": + return text; + case "IntegerLiteral": + return /^(0|[1-9][0-9]*)$/.test(text) ? text : null; + case "ParenthesizedExpression": { + const inner = node.firstChild?.nextSibling; + return inner && inner.nextSibling ? literalValue(state, inner) : null; + } + default: + return null; + } +} + +/** A text block's value: incidental indentation and trailing spaces removed, escapes interpreted. */ +export function textBlockValue(text: string): string | null { + const open = /^"""[ \t\f]*(\r\n|\r|\n)/.exec(text); + if (!open || !text.endsWith('"""') || text.length < open[0].length + 3) return null; + const lines = text.slice(open[0].length, -3).split(/\r\n|\r|\n/); + const blank = (line: string) => /^[ \t\f]*$/.test(line); + const last = lines.length - 1; + const indent = Math.min( + ...lines.filter((line, i) => i === last || !blank(line)).map((line) => /^[ \t\f]*/.exec(line)![0].length), + ); + const stripped = lines.map((line) => (blank(line) ? "" : line.slice(indent).replace(/[ \t\f]+$/, ""))); + return unescape(stripped.join("\n")); +} + +const ESCAPES: Record = { + b: "\b", + t: "\t", + n: "\n", + f: "\f", + r: "\r", + s: " ", + '"': '"', + "'": "'", + "\\": "\\", +}; + +/** Java escape sequences, including octal, unicode and (in text blocks) line continuations. */ +export function unescape(text: string): string { + return text.replace(/\\(u+[0-9a-fA-F]{4}|[0-3][0-7]{0,2}|[4-7][0-7]?|\n|.)/g, (all, e: string) => { + if (e[0] === "u") return String.fromCharCode(parseInt(e.slice(-4), 16)); + if (/^[0-7]/.test(e)) return String.fromCharCode(parseInt(e, 8)); + if (e === "\n") return ""; + return ESCAPES[e] ?? all; + }); +} diff --git a/src/editor/lsp/semantic/java/index.ts b/src/editor/lsp/semantic/java/index.ts index 6b1da94c94..f083df3a81 100644 --- a/src/editor/lsp/semantic/java/index.ts +++ b/src/editor/lsp/semantic/java/index.ts @@ -1,6 +1,7 @@ import type { Tree } from "@lezer/common"; import type { Text } from "@codemirror/state"; import { registerLanguageSemantics, type LanguageSemantics, type SemanticRange } from "../languages"; +import { javaCopyStringIntentions } from "./copyString"; import { javaDeclarationRanges, javaFieldClass } from "./declarations"; import { javaEscapeRanges } from "./escapes"; import { isReassignedAt } from "./reassigned"; @@ -87,6 +88,7 @@ const javaSemantics: LanguageSemantics = { else if (type === "class" && modifiers.includes("abstract")) classes.push("cm-sem-java-abstract-class"); if (tree && isReassignedAt(tree, doc, from)) classes.push("cm-sem-mutable"); }, + intentions: javaCopyStringIntentions, }; registerLanguageSemantics("java", javaSemantics); diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index e9572942d0..b72be55bca 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1,4 +1,6 @@ { + "Copy string concatenation text to the clipboard": "Copy string concatenation text to the clipboard", + "Copy string literal text to the clipboard": "Copy string literal text to the clipboard", "GitHub Issues": "GitHub Issues", "GitHub Issues uses the": "GitHub Issues uses the", "Sign in with GitHub CLI to view issues.": "Sign in with GitHub CLI to view issues.", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 04e076147f..3c95e93470 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -1,4 +1,6 @@ { + "Copy string concatenation text to the clipboard": "将字符串拼接文本复制到剪贴板", + "Copy string literal text to the clipboard": "将字符串字面量文本复制到剪贴板", "GitHub Issues": "GitHub 议题", "GitHub Issues uses the": "GitHub 议题使用", "Sign in with GitHub CLI to view issues.": "请登录 GitHub CLI 以查看议题。",