Skip to content

Commit c1dbba9

Browse files
committed
Improve language detection when using class attribute to supply language information to prevent presentational styles from getting interpreted as language choies.
1 parent cfc3d41 commit c1dbba9

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

tasks/build.js

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,21 @@ grunt.registerHelper("syntax-highlight", function( options, callback ) {
100100
// receives the innerHTML of a <code> element and if the first character
101101
// is an encoded left angle bracket, we'll "conclude" the "language" is html
102102
function crudeHTMLcheck ( input ) {
103-
return input.indexOf("&lt;") === 0 ? "html" : "";
103+
return input.trim().indexOf("&lt;") === 0 ? "html" : "";
104+
}
105+
106+
// when parsing the class attribute, make sure a class matches an actually
107+
// highlightable language, instead of being presentational (e.g. 'example')
108+
function getLanguageFromClass( str ) {
109+
str = str || "";
110+
var classes = str.split(" "),
111+
c = classes.length;
112+
while (--c) {
113+
if ( nsh.getLanguage( classes[c] ) ) {
114+
return classes[c];
115+
}
116+
}
117+
return "";
104118
}
105119

106120
var html = options.file ? grunt.file.read( options.file ) : options.cmd.stdout,
@@ -110,7 +124,7 @@ grunt.registerHelper("syntax-highlight", function( options, callback ) {
110124
highlight.each( function( index, el ) {
111125
var $t = $(this),
112126
code = $t.html(),
113-
lang = $t.attr("data-lang") || $t.attr("class") || crudeHTMLcheck( code ),
127+
lang = $t.attr("data-lang") || getLanguageFromClass( $t.attr("class") ) || crudeHTMLcheck( code ),
114128
linenum = $t.attr("data-linenum") || 1,
115129
brush = nsh.getLanguage( lang ) || nsh.getLanguage( "js" ),
116130
highlighted = nsh.highlight( code, brush, {

0 commit comments

Comments
 (0)