8
8
w . hljs . lineNumbersBlock = lineNumbersBlock ;
9
9
}
10
10
11
- function initLineNumbersOnLoad ( ) {
11
+ var defaultOptions = {
12
+ withLinks : false
13
+ } ;
14
+
15
+ function initLineNumbersOnLoad ( options ) {
16
+ options = options || defaultOptions ;
17
+
12
18
w . addEventListener ( 'load' , function ( ) {
13
19
try {
14
20
var blocks = document . querySelectorAll ( 'code.hljs' ) ;
15
21
16
22
for ( var i in blocks ) {
17
23
if ( blocks . hasOwnProperty ( i ) ) {
18
- lineNumbersBlock ( blocks [ i ] ) ;
24
+ lineNumbersBlock ( blocks [ i ] , {
25
+ blockName : 'c' + i ,
26
+ withLinks : options . withLinks
27
+ } ) ;
19
28
}
20
29
}
21
30
} catch ( e ) {
24
33
} ) ;
25
34
}
26
35
27
- function lineNumbersBlock ( element ) {
36
+ function lineNumbersBlock ( element , options ) {
28
37
if ( typeof element !== 'object' ) return ;
38
+ if ( ! ! options ) {
39
+ options . withLinks = options . withLinks || false ;
40
+ options . blockName = options . blockName || false ;
41
+ } else {
42
+ options = defaultOptions ;
43
+ options . blockName = '' ;
44
+ }
29
45
30
46
var parent = element . parentNode ;
31
47
var lines = getCountLines ( parent . textContent ) ;
32
48
33
49
if ( lines > 1 ) {
34
50
var l = '' ;
35
51
for ( var i = 0 ; i < lines ; i ++ ) {
36
- l += ( i + 1 ) + '\n' ;
52
+ l += options . withLinks
53
+ ? getLineWithLink ( i + 1 , options . blockName )
54
+ : ( i + 1 ) + '\n' ;
37
55
}
38
56
39
57
var linesPanel = document . createElement ( 'code' ) ;
40
58
linesPanel . className = 'hljs hljs-line-numbers' ;
41
59
linesPanel . style . float = 'left' ;
42
- linesPanel . textContent = l ;
60
+ linesPanel . innerHTML = l ;
43
61
44
62
parent . insertBefore ( linesPanel , element ) ;
45
63
}
46
64
}
47
65
48
- function getCountLines ( text ) {
66
+ function getCountLines ( text ) {
49
67
if ( text . length === 0 ) return 0 ;
50
68
51
69
var regExp = / \r \n | \r | \n / g;
58
76
59
77
return lines ;
60
78
}
79
+
80
+ function getLineWithLink ( i , blockName ) {
81
+ var id = blockName + '_l' + i ;
82
+ return '<a href="#' + id + '" id="' + id + '">' + i + '</span>\n'
83
+ }
61
84
} ( window ) ) ;
0 commit comments