Skip to content

fix(copy): strip inline code annotations and diff markers from copied code — fixes #2222 #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: feat/copy-button
Choose a base branch
from
Open
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
26 changes: 22 additions & 4 deletions src/components/code-example.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -190,13 +190,31 @@ export function RawHighlightedCode({
return <div className={className} dangerouslySetInnerHTML={{ __html: code }} />;
}

function cleanCodeForCopy(code:string) {
function cleanCodeForCopy(code: string) {
return code
.split('\n')
.filter(line => !line.includes('[!code highlight'))
.join('\n');
.split("\n")
.map(line => {

line = line.replace(/\s*\/\/\s*\[!code.*?\]/g, "");
line = line.replace(/\s*<!--\s*\[!code.*?\]-->/g, "");
line = line.replace(/\s*#\s*\[!code.*?\]/g, "");


if (/^[+-]/.test(line.trim())) {
line = line.trim().slice(1);
}


if (line.trim() === "…") return "";

return line;
})
.filter(line => line.trim() !== "")
.join("\n")
.trim();
}


function CodeExampleFilename({ filename, code }: { filename: string; code?: string }) {
return (
<div className="flex justify-between px-3 pt-0.5 pb-1.5 text-xs/5 text-gray-400 dark:text-white/50">
Expand Down