1
0
mirror of https://github.com/golang/go synced 2024-11-05 11:36:10 -07:00

godoc: make line numbers unselectable

Insert line numbers via a ::before pseudo-element so you can't select
them when you copy text. See the code comment for more information.

Fixes golang/go#20077.

Change-Id: I24a5b17786a52c8107b4f830e824526ba03bc38d
Reviewed-on: https://go-review.googlesource.com/41418
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
This commit is contained in:
Kevin Burke 2017-04-21 19:13:36 -07:00 committed by Brad Fitzpatrick
parent 7745887299
commit 75e5ff36f3
3 changed files with 20 additions and 1 deletions

View File

@ -621,7 +621,16 @@ func formatGoSource(buf *bytes.Buffer, text []byte, links []analysis.Link, patte
// linkWriter, so we have to add line spans as another pass.
n := 1
for _, line := range bytes.Split(buf.Bytes(), []byte("\n")) {
fmt.Fprintf(saved, "<span id=\"L%d\" class=\"ln\">%6d\t</span>", n, n)
// The line numbers are inserted into the document via a CSS ::before
// pseudo-element. This prevents them from being copied when users
// highlight and copy text.
// ::before is supported in 98% of browsers: https://caniuse.com/#feat=css-gencontent
// This is also the trick Github uses to hide line numbers.
//
// The first tab for the code snippet needs to start in column 9, so
// it indents a full 8 spaces, hence the two nbsp's. Otherwise the tab
// character only indents about two spaces.
fmt.Fprintf(saved, `<span id="L%d" class="ln" data-content="%6d">&nbsp;&nbsp;</span>`, n, n)
n++
saved.Write(line)
saved.WriteByte('\n')

View File

@ -2932,6 +2932,11 @@ pre .ln {
-ms-user-select: none;
user-select: none;
}
.ln::before {
/* Inserting the line numbers as a ::before pseudo-element avoids making
* them selectable; it's the trick Github uses as well. */
content: attr(data-content);
}
body {
color: #222;
}

View File

@ -37,6 +37,11 @@ pre .ln {
-ms-user-select: none;
user-select: none;
}
.ln::before {
/* Inserting the line numbers as a ::before pseudo-element avoids making
* them selectable; it's the trick Github uses as well. */
content: attr(data-content);
}
body {
color: #222;
}