From 876feecd6f806aa8eacd717f3565d332bf51e97e Mon Sep 17 00:00:00 2001 From: pablodanswer Date: Sun, 4 Aug 2024 09:56:48 -0700 Subject: [PATCH] Fix code pasting formatting (#2033) * fix pasting formatting * add back small comments --- web/src/app/chat/message/CodeBlock.tsx | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/web/src/app/chat/message/CodeBlock.tsx b/web/src/app/chat/message/CodeBlock.tsx index c6798333e..d7007ce42 100644 --- a/web/src/app/chat/message/CodeBlock.tsx +++ b/web/src/app/chat/message/CodeBlock.tsx @@ -64,9 +64,15 @@ export function CodeBlock({ codeLines.pop(); // Remove the last line with the trailing backticks } - // remove leading whitespace from each line for nicer copy/paste experience - const trimmedCodeLines = codeLines.map((line) => line.trimStart()); - codeText = trimmedCodeLines.join("\n"); + const minIndent = codeLines + .filter((line) => line.trim().length > 0) + .reduce((min, line) => { + const match = line.match(/^\s*/); + return Math.min(min, match ? match[0].length : 0); + }, Infinity); + + const formattedCodeLines = codeLines.map((line) => line.slice(minIndent)); + codeText = formattedCodeLines.join("\n"); } }