Skip to content

Commit

Permalink
Added implementation of relative links #7
Browse files Browse the repository at this point in the history
  • Loading branch information
wcoder committed Feb 10, 2016
1 parent 9a3553a commit 883ba5d
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 7 deletions.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,26 @@ $(document).ready(function() {
});
```

## Additional features

#### Links
```js
hljs.initLineNumbersOnLoad({
withLinks: true
});
```

```css
.hljs-line-numbers a {
text-decoration: none;
color: #999;
}
.hljs-line-numbers a:target {
color: #ff0000;
text-decoration: underline;
outline: none;
}
```

---
© 2015 Yauheni Pakala | MIT License
2 changes: 1 addition & 1 deletion dist/highlightjs-line-numbers.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

35 changes: 29 additions & 6 deletions src/highlightjs-line-numbers.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,23 @@
w.hljs.lineNumbersBlock = lineNumbersBlock;
}

function initLineNumbersOnLoad () {
var defaultOptions = {
withLinks: false
};

function initLineNumbersOnLoad (options) {
options = options || defaultOptions;

w.addEventListener('load', function () {
try {
var blocks = document.querySelectorAll('code.hljs');

for (var i in blocks) {
if (blocks.hasOwnProperty(i)) {
lineNumbersBlock(blocks[i]);
lineNumbersBlock(blocks[i], {
blockName: 'c' + i,
withLinks: options.withLinks
});
}
}
} catch (e) {
Expand All @@ -24,28 +33,37 @@
});
}

function lineNumbersBlock (element) {
function lineNumbersBlock (element, options) {
if (typeof element !== 'object') return;
if (!!options) {
options.withLinks = options.withLinks || false;
options.blockName = options.blockName || false;
} else {
options = defaultOptions;
options.blockName = '';
}

var parent = element.parentNode;
var lines = getCountLines(parent.textContent);

if (lines > 1) {
var l = '';
for (var i = 0; i < lines; i++) {
l += (i + 1) + '\n';
l += options.withLinks
? getLineWithLink(i + 1, options.blockName)
: (i + 1) + '\n';
}

var linesPanel = document.createElement('code');
linesPanel.className = 'hljs hljs-line-numbers';
linesPanel.style.float = 'left';
linesPanel.textContent = l;
linesPanel.innerHTML = l;

parent.insertBefore(linesPanel, element);
}
}

function getCountLines(text) {
function getCountLines (text) {
if (text.length === 0) return 0;

var regExp = /\r\n|\r|\n/g;
Expand All @@ -58,4 +76,9 @@

return lines;
}

function getLineWithLink (i, blockName) {
var id = blockName + '_l' + i;
return '<a href="#' + id + '" id="' + id + '">' + i + '</span>\n'
}
}(window));

0 comments on commit 883ba5d

Please sign in to comment.