Skip to content

Commit 9ae7aef

Browse files
committed
prevent line number from being copied in chrome
1 parent 1d23da6 commit 9ae7aef

File tree

1 file changed

+18
-7
lines changed
  • src/librustdoc/html/static/js

1 file changed

+18
-7
lines changed

src/librustdoc/html/static/js/main.js

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2227,11 +2227,18 @@ function preLoadCss(cssUrl) {
22272227
});
22282228
}());
22292229

2230-
// This section is a bugfix for firefox: when copying text with `user-select: none`, it adds
2231-
// extra backline characters.
2230+
2231+
// Workaround for browser-specific bugs when copying code snippets.
2232+
//
2233+
// * In Firefox, copying text that includes elements with `user-select: none`
2234+
// inserts extra blank lines.
2235+
// - Firefox issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1273836
2236+
// - Rust issue: https://github.com/rust-lang/rust/issues/141464
22322237
//
2233-
// Rustdoc issue: Workaround for https://github.com/rust-lang/rust/issues/141464
2234-
// Firefox issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1273836
2238+
// * In Chromium-based browsers, `document.getSelection()` includes elements
2239+
// with `user-select: none`, causing unwanted line numbers to be copied.
2240+
// - Chromium issue: https://issues.chromium.org/issues/446539520
2241+
// - Rust issue: https://github.com/rust-lang/rust/issues/146816
22352242
(function() {
22362243
document.body.addEventListener("copy", event => {
22372244
let target = nonnull(event.target);
@@ -2248,9 +2255,13 @@ function preLoadCss(cssUrl) {
22482255
if (!isInsideCode) {
22492256
return;
22502257
}
2251-
const selection = document.getSelection();
2252-
// @ts-expect-error
2253-
nonnull(event.clipboardData).setData("text/plain", selection.toString());
2258+
const selection = nonnull(document.getSelection());
2259+
const text = Array.from({ length: selection.rangeCount }, (_, i) => {
2260+
const fragment = selection.getRangeAt(i).cloneContents();
2261+
fragment.querySelectorAll("[data-nosnippet]").forEach(el => el.remove());
2262+
return fragment.textContent;
2263+
}).join("");
2264+
nonnull(event.clipboardData).setData("text/plain", text);
22542265
event.preventDefault();
22552266
});
22562267
}());

0 commit comments

Comments
 (0)