Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-copy-code-block-trailing-newline.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@haphazarddev/pi-copy-code-block": patch
---

Remove the extra trailing newline when copying code blocks so single-line commands paste cleanly.
8 changes: 7 additions & 1 deletion extensions/pi-copy-code-block/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,12 @@ function getPreview(code: string): string {
return lines.length > 1 ? `${linePreview} ⏎ …` : linePreview;
}

function normalizeExtractedCode(code: string): string {
// The newline immediately before the closing fence is Markdown structure, not
// usually part of the code users expect to paste/run.
return code.replace(/\n$/, "");
}

function extractCodeBlocks(text: string): CodeBlock[] {
const extracted: Array<Pick<CodeBlock, "language" | "code">> = [];
const fencePattern = /^```([^\n`]*)\r?\n([\s\S]*?)^```[ \t]*$/gm;
Expand All @@ -98,7 +104,7 @@ function extractCodeBlocks(text: string): CodeBlock[] {
while (match) {
const infoString = match[1]?.trim() ?? "";
const language = infoString.split(/\s+/)[0] || "text";
const code = match[2]?.replace(/\r\n/g, "\n") ?? "";
const code = normalizeExtractedCode(match[2]?.replace(/\r\n/g, "\n") ?? "");

extracted.push({ language, code });
match = fencePattern.exec(text);
Expand Down
Loading