@@ -7,20 +7,53 @@ function CopyCode(clipboard) {
7
7
8
8
button . addEventListener ( 'click' , async ( ) => {
9
9
try {
10
- await clipboard . writeText (
11
- codeBlock . textContent
12
- . replace ( / ^ \s * \d + \s / gm, '' ) // remove line numbers
13
- . replace ( / ^ \s * | \s * $ / g, '' ) // remove carriage returns at top and bottom of block
14
- ) ;
10
+ let codeText = codeBlock . textContent
11
+ . replace ( / ^ \s * \d + \s / gm, '' ) // Remove line numbers
12
+ . replace ( / ^ \s * | \s * $ / g, '' ) ; // Trim whitespace at top/bottom
15
13
14
+ // Find nested <code> element
15
+ const codeElement = codeBlock . querySelector ( 'code' ) ;
16
+ if ( codeElement ) {
17
+ const classAttr = codeElement . getAttribute ( 'class' ) || '' ;
18
+ const dataLangAttr = codeElement . getAttribute ( 'data-lang' ) || '' ;
19
+
20
+ if (
21
+ classAttr . includes ( 'language-bash' ) ||
22
+ classAttr . includes ( 'language-console' ) ||
23
+ dataLangAttr === 'bash' ||
24
+ dataLangAttr === 'console'
25
+ ) {
26
+ codeText = codeText
27
+ . split ( '\n' )
28
+ . map ( ( line ) => {
29
+ let cleanedLine = line . trim ( ) ;
30
+
31
+ // Remove `$` (non-root) or `#` (root) command indicators
32
+ if ( / ^ [ $ # ] \s ? / . test ( cleanedLine ) ) {
33
+ cleanedLine = cleanedLine . replace ( / ^ [ $ # ] \s ? / , '' ) ; // Remove `$` or `#`
34
+ }
35
+
36
+ // Remove inline comments that come *after* a command
37
+ const withoutComments = cleanedLine . replace ( / \s + # .* / , '' ) ;
38
+
39
+ return withoutComments ;
40
+ } )
41
+ . filter ( ( line ) => line . trim ( ) !== '' ) // Remove empty lines
42
+ . join ( '\n' ) ;
43
+ }
44
+ } else {
45
+ console . warn ( 'No nested <code> element found in:' , codeBlock ) ;
46
+ }
47
+
48
+ await clipboard . writeText ( codeText ) ;
16
49
button . blur ( ) ; /* Chrome fix */
17
50
button . innerHTML = '<i class="fas fa-check"></i> Copied!' ;
18
51
setTimeout ( ( ) => {
19
52
button . innerHTML = '<i class="fas fa-copy"></i> Copy' ;
20
53
} , 2000 ) ;
21
54
} catch ( error ) {
22
55
button . innerHTML = '<i class="fas fa-exclamation"></i> Error' ;
23
- console . error ( error ) ;
56
+ console . error ( 'Copy error:' , error ) ;
24
57
}
25
58
} ) ;
26
59
0 commit comments