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