Last active
February 5, 2023 11:26
-
-
Save cktricky/5623966 to your computer and use it in GitHub Desktop.
Syntax highlighting for embedded gists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
To use this file, save it to a JS file and include it (<script src=) or | |
wrap it in <script type="text/javascript"> </script> tags on the page you are embedding the code on. | |
1) When you craft the script tag for including the gist assign it a class="embed-gist" | |
2) Give a file parameter, this is the name of the file, this is something absolutely necessary, | |
needs to be the first parameter (before lines) | |
3) after the file parameter, add a lines paramter | |
the parameters "lines" and values represent the line numbers. Multiple lines (example) 1-20 and single line (example) | |
= 22. | |
Looks like this: | |
<script class="embed-gist" src="https://gist.github.com/anonymous/00000.js?file=myfile.java&lines=1-20,22,33"></script> | |
Warning, do not use spaces when entering comma separate line numbers or a filename. | |
*/ | |
var fileName; | |
function setFileName(name){ | |
var nameArr = name.split('%20').join("-").toLowerCase().split('.'); | |
fileName = "file-" + nameArr.join('-') + "-LC"; | |
}; | |
function highlightLines(lines){ | |
var lineArray = lines.split('-'); | |
var begin = parseInt(lineArray[0], 10); | |
var end = parseInt(lineArray[1], 10); | |
for (var n = begin; n < end + 1; ++ n) | |
$("#"+ fileName + n).css('background-color', 'rgb(255, 255, 204)'); | |
}; | |
function beginHighlight(){ | |
$('.embed-gist').each(function() { | |
var scriptUrl = $(this).attr("src"); | |
var query = scriptUrl.split('?')[1]; | |
var params = query.split('&'); | |
$.each(params, function(i, param) { | |
var pSplit = param.split("="); | |
var key = pSplit[0]; | |
var val = pSplit[1]; | |
if (key == "lines"){ | |
lineSets = val.split(','); | |
$.each(lineSets, function(index, value) { | |
if (/-/i.test(value)) { | |
highlightLines(value); | |
} else { | |
$("#" + fileName + value).css('background-color', 'rgb(255, 255, 204)'); | |
} | |
}); | |
} else if (key == "file") { | |
setFileName(val); | |
} | |
}); | |
}); | |
}; | |
$(document).ready(beginHighlight()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment