Skip to content

Instantly share code, notes, and snippets.

@henriquegogo
Last active December 17, 2022 05:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save henriquegogo/d751e7885a87887fc0b73c8785e4b0e0 to your computer and use it in GitHub Desktop.
Save henriquegogo/d751e7885a87887fc0b73c8785e4b0e0 to your computer and use it in GitHub Desktop.
Syntax highlighter
// Syntax highliter
// License: MIT
// Author: henriquegogo
// Description: A small generic highlighter easy to plug and use in any code sample.
// Works better with JavaScript, C, Python and HTML
function highlight(selector) {
document.body.innerHTML += `
<style>${selector} span * { color: inherit !important }</style>
`;
document.querySelectorAll(selector).forEach((element) => {
element.style.backgroundColor = "#334";
element.style.color = "#FFF";
element.style.fontFamily = "monospace";
element.style.padding = "25px";
element.style.whiteSpace = "pre-wrap";
element.innerHTML = element.innerHTML.startsWith("&lt;")
? element.innerHTML
.replace( // Comments
/(&lt;!--.+--&gt;)/gs,
"<span style =color:#808080>$1</span>"
).replace( // Attributes
/(\w+)=/g,
"<span style =color:#87afd7>$1</span>="
).replace( // Strings
/([^>])(")(.*?)(")|([^>])(')(.*?)(')/g,
"$1<span style =color:#afd700>$2$3$4</span>"
).replace( // Tag open
/&lt;(\w*)/g,
"<span style =color:#87afd7>&lt;</span><span style =color:#8787af>$1</span>"
).replace( // Tag close
/(\w*)&gt;/g,
"<span style =color:#8787af>$1</span><span style =color:#87afd7>&gt;</span>"
)
: element.innerHTML
.replace( // Comments
/(\/\/ .+|# .+)/g,
"<span style =color:#808080>$1</span>"
).replace( // Comments
/(\/\*.+\*\/)/gs,
"<span style =color:#808080>$1</span>"
).replace( // Declarations
/([^\w]|^)(struct|var|let|const|new|def|fn|class|function|int|enum|void|float|char|str|string|public|pub|private|interface|impl|from|import|with)([^\w])/g,
"$1<span style =color:#87afd7>$2</span>$3"
).replace( // Statements
/([^\w]|^| )(=>|===|==|!=|<=|>=|\+=|-=|\+|-|\/|\*|=|return|if|else|elsif|then|switch|case|default|while|for|foreach|in|of|or|and|not|try|except|finally|throw|catch)([^\w])/g,
"$1<span style =color:#8787af>$2</span>$3"
).replace( // Consts and keywords
/([^\w]|^)(true|false|True|False|None|Null|NULL|this|self|document|window|console|Math|[A-Z_]{3,})([^\w])/g,
"$1<span style =color:#ff8700>$2</span>$3"
).replace( // Functions
/(\w+)\(/g,
"<span style =color:#ffffaf>$1</span>("
).replace( // JSON Strings
/: ("|')(.*?)("|')/g,
": <span style =color:#87afd7>$1$2$3</span>"
).replace( // Strings
/([^>])(")(.*?)(")|([^>])(')(.*?)(')/g,
"$1<span style =color:#afd700>$2$3$4</span>"
);
});
}
highlight("pre");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment