/** * 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; }); }