Skip to content

Instantly share code, notes, and snippets.

@spiralx
Created November 13, 2015 06:34
Show Gist options
  • Save spiralx/a2946f4efb77fa085d1a to your computer and use it in GitHub Desktop.
Save spiralx/a2946f4efb77fa085d1a to your computer and use it in GitHub Desktop.
Highlight current page using the Prism highlighter
/*
http://prismjs.com/download.html?themes=prism-okaidia&languages=markup+css+clike+javascript+aspnet+bash+batch+c+bison+csharp+cpp+coffeescript+ruby+css-extras+diff+gherkin+git+go+groovy+handlebars+http+ini+jade+java+less+lua+markdown+perl+php+php-extras+powershell+python+jsx+rest+rust+sass+scss+scala+sql+stylus+typescript+wiki+yaml&plugins=line-highlight+line-numbers+show-invisibles+autolinker+wpd+highlight-keywords+remove-initial-line-feed+previewer-base+previewer-color+previewer-gradient
*/
var _self = (typeof window !== 'undefined')
? window // if in browser
: (
(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope)
? self // if in worker
: {} // if in node js
);
/**
* Prism: Lightweight, robust, elegant syntax highlighting
* MIT license http://www.opensource.org/licenses/mit-license.php/
* @author Lea Verou http://lea.verou.me
*/
var Prism = (function(){
// Private helper vars
var lang = /\blang(?:uage)?-(?!\*)(\w+)\b/i;
var _ = _self.Prism = {
util: {
encode: function (tokens) {
if (tokens instanceof Token) {
return new Token(tokens.type, _.util.encode(tokens.content), tokens.alias);
} else if (_.util.type(tokens) === 'Array') {
return tokens.map(_.util.encode);
} else {
return tokens.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\u00a0/g, ' ');
}
},
type: function (o) {
return Object.prototype.toString.call(o).match(/\[object (\w+)\]/)[1];
},
// Deep clone a language definition (e.g. to extend it)
clone: function (o) {
var type = _.util.type(o);
switch (type) {
case 'Object':
var clone = {};
for (var key in o) {
if (o.hasOwnProperty(key)) {
clone[key] = _.util.clone(o[key]);
}
}
return clone;
case 'Array':
// Check for existence for IE8
return o.map && o.map(function(v) { return _.util.clone(v); });
}
return o;
}
},
languages: {
extend: function (id, redef) {
var lang = _.util.clone(_.languages[id]);
for (var key in redef) {
lang[key] = redef[key];
}
return lang;
},
/**
* Insert a token before another token in a language literal
* As this needs to recreate the object (we cannot actually insert before keys in object literals),
* we cannot just provide an object, we need anobject and a key.
* @param inside The key (or language id) of the parent
* @param before The key to insert before. If not provided, the function appends instead.
* @param insert Object with the key/value pairs to insert
* @param root The object that contains `inside`. If equal to Prism.languages, it can be omitted.
*/
insertBefore: function (inside, before, insert, root) {
root = root || _.languages;
var grammar = root[inside];
if (arguments.length == 2) {
insert = arguments[1];
for (var newToken in insert) {
if (insert.hasOwnProperty(newToken)) {
grammar[newToken] = insert[newToken];
}
}
return grammar;
}
var ret = {};
for (var token in grammar) {
if (grammar.hasOwnProperty(token)) {
if (token == before) {
for (var newToken in insert) {
if (insert.hasOwnProperty(newToken)) {
ret[newToken] = insert[newToken];
}
}
}
ret[token] = grammar[token];
}
}
// Update references in other language definitions
_.languages.DFS(_.languages, function(key, value) {
if (value === root[inside] && key != inside) {
this[key] = ret;
}
});
return root[inside] = ret;
},
// Traverse a language definition with Depth First Search
DFS: function(o, callback, type) {
for (var i in o) {
if (o.hasOwnProperty(i)) {
callback.call(o, i, o[i], type || i);
if (_.util.type(o[i]) === 'Object') {
_.languages.DFS(o[i], callback);
}
else if (_.util.type(o[i]) === 'Array') {
_.languages.DFS(o[i], callback, i);
}
}
}
}
},
plugins: {},
highlightAll: function(async, callback) {
var elements = document.querySelectorAll('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code');
for (var i=0, element; element = elements[i++];) {
_.highlightElement(element, async === true, callback);
}
},
highlightElement: function(element, async, callback) {
// Find language
var language, grammar, parent = element;
while (parent && !lang.test(parent.className)) {
parent = parent.parentNode;
}
if (parent) {
language = (parent.className.match(lang) || [,''])[1];
grammar = _.languages[language];
}
// Set language on the element, if not present
element.className = element.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language;
// Set language on the parent, for styling
parent = element.parentNode;
if (/pre/i.test(parent.nodeName)) {
parent.className = parent.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language;
}
var code = element.textContent;
var env = {
element: element,
language: language,
grammar: grammar,
code: code
};
if (!code || !grammar) {
_.hooks.run('complete', env);
return;
}
_.hooks.run('before-highlight', env);
if (async && _self.Worker) {
var worker = new Worker(_.filename);
worker.onmessage = function(evt) {
env.highlightedCode = evt.data;
_.hooks.run('before-insert', env);
env.element.innerHTML = env.highlightedCode;
callback && callback.call(env.element);
_.hooks.run('after-highlight', env);
_.hooks.run('complete', env);
};
worker.postMessage(JSON.stringify({
language: env.language,
code: env.code,
immediateClose: true
}));
}
else {
env.highlightedCode = _.highlight(env.code, env.grammar, env.language);
_.hooks.run('before-insert', env);
env.element.innerHTML = env.highlightedCode;
callback && callback.call(element);
_.hooks.run('after-highlight', env);
_.hooks.run('complete', env);
}
},
highlight: function (text, grammar, language) {
var tokens = _.tokenize(text, grammar);
return Token.stringify(_.util.encode(tokens), language);
},
tokenize: function(text, grammar, language) {
var Token = _.Token;
var strarr = [text];
var rest = grammar.rest;
if (rest) {
for (var token in rest) {
grammar[token] = rest[token];
}
delete grammar.rest;
}
tokenloop: for (var token in grammar) {
if(!grammar.hasOwnProperty(token) || !grammar[token]) {
continue;
}
var patterns = grammar[token];
patterns = (_.util.type(patterns) === "Array") ? patterns : [patterns];
for (var j = 0; j < patterns.length; ++j) {
var pattern = patterns[j],
inside = pattern.inside,
lookbehind = !!pattern.lookbehind,
lookbehindLength = 0,
alias = pattern.alias;
pattern = pattern.pattern || pattern;
for (var i=0; i<strarr.length; i++) { // Don’t cache length as it changes during the loop
var str = strarr[i];
if (strarr.length > text.length) {
// Something went terribly wrong, ABORT, ABORT!
break tokenloop;
}
if (str instanceof Token) {
continue;
}
pattern.lastIndex = 0;
var match = pattern.exec(str);
if (match) {
if(lookbehind) {
lookbehindLength = match[1].length;
}
var from = match.index - 1 + lookbehindLength,
match = match[0].slice(lookbehindLength),
len = match.length,
to = from + len,
before = str.slice(0, from + 1),
after = str.slice(to + 1);
var args = [i, 1];
if (before) {
args.push(before);
}
var wrapped = new Token(token, inside? _.tokenize(match, inside) : match, alias);
args.push(wrapped);
if (after) {
args.push(after);
}
Array.prototype.splice.apply(strarr, args);
}
}
}
}
return strarr;
},
hooks: {
all: {},
add: function (name, callback) {
var hooks = _.hooks.all;
hooks[name] = hooks[name] || [];
hooks[name].push(callback);
},
run: function (name, env) {
var callbacks = _.hooks.all[name];
if (!callbacks || !callbacks.length) {
return;
}
for (var i=0, callback; callback = callbacks[i++];) {
callback(env);
}
}
}
};
var Token = _.Token = function(type, content, alias) {
this.type = type;
this.content = content;
this.alias = alias;
};
Token.stringify = function(o, language, parent) {
if (typeof o == 'string') {
return o;
}
if (_.util.type(o) === 'Array') {
return o.map(function(element) {
return Token.stringify(element, language, o);
}).join('');
}
var env = {
type: o.type,
content: Token.stringify(o.content, language, parent),
tag: 'span',
classes: ['token', o.type],
attributes: {},
language: language,
parent: parent
};
if (env.type == 'comment') {
env.attributes['spellcheck'] = 'true';
}
if (o.alias) {
var aliases = _.util.type(o.alias) === 'Array' ? o.alias : [o.alias];
Array.prototype.push.apply(env.classes, aliases);
}
_.hooks.run('wrap', env);
var attributes = '';
for (var name in env.attributes) {
attributes += (attributes ? ' ' : '') + name + '="' + (env.attributes[name] || '') + '"';
}
return '<' + env.tag + ' class="' + env.classes.join(' ') + '" ' + attributes + '>' + env.content + '</' + env.tag + '>';
};
if (!_self.document) {
if (!_self.addEventListener) {
// in Node.js
return _self.Prism;
}
// In worker
_self.addEventListener('message', function(evt) {
var message = JSON.parse(evt.data),
lang = message.language,
code = message.code,
immediateClose = message.immediateClose;
_self.postMessage(_.highlight(code, _.languages[lang], lang));
if (immediateClose) {
_self.close();
}
}, false);
return _self.Prism;
}
// Get current script and highlight
var script = document.getElementsByTagName('script');
script = script[script.length - 1];
if (script) {
_.filename = script.src;
if (document.addEventListener && !script.hasAttribute('data-manual')) {
document.addEventListener('DOMContentLoaded', _.highlightAll);
}
}
return _self.Prism;
})();
if (typeof module !== 'undefined' && module.exports) {
module.exports = Prism;
}
// hack for components to work correctly in node.js
if (typeof global !== 'undefined') {
global.Prism = Prism;
}
;
Prism.languages.markup = {
'comment': /<!--[\w\W]*?-->/,
'prolog': /<\?[\w\W]+?\?>/,
'doctype': /<!DOCTYPE[\w\W]+?>/,
'cdata': /<!\[CDATA\[[\w\W]*?]]>/i,
'tag': {
pattern: /<\/?(?!\d)[^\s>\/=.$<]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\\1|\\?(?!\1)[\w\W])*\1|[^\s'">=]+))?)*\s*\/?>/i,
inside: {
'tag': {
pattern: /^<\/?[^\s>\/]+/i,
inside: {
'punctuation': /^<\/?/,
'namespace': /^[^\s>\/:]+:/
}
},
'attr-value': {
pattern: /=(?:('|")[\w\W]*?(\1)|[^\s>]+)/i,
inside: {
'punctuation': /[=>"']/
}
},
'punctuation': /\/?>/,
'attr-name': {
pattern: /[^\s>\/]+/,
inside: {
'namespace': /^[^\s>\/:]+:/
}
}
}
},
'entity': /&#?[\da-z]{1,8};/i
};
// Plugin to make entity title show the real entity, idea by Roman Komarov
Prism.hooks.add('wrap', function(env) {
if (env.type === 'entity') {
env.attributes['title'] = env.content.replace(/&amp;/, '&');
}
});
Prism.languages.xml = Prism.languages.markup;
Prism.languages.html = Prism.languages.markup;
Prism.languages.mathml = Prism.languages.markup;
Prism.languages.svg = Prism.languages.markup;
Prism.languages.css = {
'comment': /\/\*[\w\W]*?\*\//,
'atrule': {
pattern: /@[\w-]+?.*?(;|(?=\s*\{))/i,
inside: {
'rule': /@[\w-]+/
// See rest below
}
},
'url': /url\((?:(["'])(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1|.*?)\)/i,
'selector': /[^\{\}\s][^\{\};]*?(?=\s*\{)/,
'string': /("|')(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1/,
'property': /(\b|\B)[\w-]+(?=\s*:)/i,
'important': /\B!important\b/i,
'function': /[-a-z0-9]+(?=\()/i,
'punctuation': /[(){};:]/
};
Prism.languages.css['atrule'].inside.rest = Prism.util.clone(Prism.languages.css);
if (Prism.languages.markup) {
Prism.languages.insertBefore('markup', 'tag', {
'style': {
pattern: /(<style[\w\W]*?>)[\w\W]*?(?=<\/style>)/i,
lookbehind: true,
inside: Prism.languages.css,
alias: 'language-css'
}
});
Prism.languages.insertBefore('inside', 'attr-value', {
'style-attr': {
pattern: /\s*style=("|').*?\1/i,
inside: {
'attr-name': {
pattern: /^\s*style/i,
inside: Prism.languages.markup.tag.inside
},
'punctuation': /^\s*=\s*['"]|['"]\s*$/,
'attr-value': {
pattern: /.+/i,
inside: Prism.languages.css
}
},
alias: 'language-css'
}
}, Prism.languages.markup.tag);
};
Prism.languages.clike = {
'comment': [
{
pattern: /(^|[^\\])\/\*[\w\W]*?\*\//,
lookbehind: true
},
{
pattern: /(^|[^\\:])\/\/.*/,
lookbehind: true
}
],
'string': /(["'])(\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
'class-name': {
pattern: /((?:\b(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/i,
lookbehind: true,
inside: {
punctuation: /(\.|\\)/
}
},
'keyword': /\b(if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/,
'boolean': /\b(true|false)\b/,
'function': /[a-z0-9_]+(?=\()/i,
'number': /\b-?(?:0x[\da-f]+|\d*\.?\d+(?:e[+-]?\d+)?)\b/i,
'operator': /--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*|\/|~|\^|%/,
'punctuation': /[{}[\];(),.:]/
};
Prism.languages.javascript = Prism.languages.extend('clike', {
'keyword': /\b(as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|var|void|while|with|yield)\b/,
'number': /\b-?(0x[\dA-Fa-f]+|0b[01]+|0o[0-7]+|\d*\.?\d+([Ee][+-]?\d+)?|NaN|Infinity)\b/,
// Allow for all non-ASCII characters (See http://stackoverflow.com/a/2008444)
'function': /[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*(?=\()/i
});
Prism.languages.insertBefore('javascript', 'keyword', {
'regex': {
pattern: /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\\\r\n])+\/[gimyu]{0,5}(?=\s*($|[\r\n,.;})]))/,
lookbehind: true
}
});
Prism.languages.insertBefore('javascript', 'class-name', {
'template-string': {
pattern: /`(?:\\`|\\?[^`])*`/,
inside: {
'interpolation': {
pattern: /\$\{[^}]+\}/,
inside: {
'interpolation-punctuation': {
pattern: /^\$\{|\}$/,
alias: 'punctuation'
},
rest: Prism.languages.javascript
}
},
'string': /[\s\S]+/
}
}
});
if (Prism.languages.markup) {
Prism.languages.insertBefore('markup', 'tag', {
'script': {
pattern: /(<script[\w\W]*?>)[\w\W]*?(?=<\/script>)/i,
lookbehind: true,
inside: Prism.languages.javascript,
alias: 'language-javascript'
}
});
}
Prism.languages.js = Prism.languages.javascript;
Prism.languages.aspnet = Prism.languages.extend('markup', {
'page-directive tag': {
pattern: /<%\s*@.*%>/i,
inside: {
'page-directive tag': /<%\s*@\s*(?:Assembly|Control|Implements|Import|Master(?:Type)?|OutputCache|Page|PreviousPageType|Reference|Register)?|%>/i,
rest: Prism.languages.markup.tag.inside
}
},
'directive tag': {
pattern: /<%.*%>/i,
inside: {
'directive tag': /<%\s*?[$=%#:]{0,2}|%>/i,
rest: Prism.languages.csharp
}
}
});
// Regexp copied from prism-markup, with a negative look-ahead added
Prism.languages.aspnet.tag.pattern = /<(?!%)\/?[^\s>\/]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\\1|\\?(?!\1)[\w\W])*\1|[^\s'">=]+))?)*\s*\/?>/i;
// match directives of attribute value foo="<% Bar %>"
Prism.languages.insertBefore('inside', 'punctuation', {
'directive tag': Prism.languages.aspnet['directive tag']
}, Prism.languages.aspnet.tag.inside["attr-value"]);
Prism.languages.insertBefore('aspnet', 'comment', {
'asp comment': /<%--[\w\W]*?--%>/
});
// script runat="server" contains csharp, not javascript
Prism.languages.insertBefore('aspnet', Prism.languages.javascript ? 'script' : 'tag', {
'asp script': {
pattern: /(<script(?=.*runat=['"]?server['"]?)[\w\W]*?>)[\w\W]*?(?=<\/script>)/i,
lookbehind: true,
inside: Prism.languages.csharp || {}
}
});
(function(Prism) {
var insideString = {
variable: [
// Arithmetic Environment
{
pattern: /\$?\(\([\w\W]+?\)\)/,
inside: {
// If there is a $ sign at the beginning highlight $(( and )) as variable
variable: [{
pattern: /(^\$\(\([\w\W]+)\)\)/,
lookbehind: true
},
/^\$\(\(/,
],
number: /\b-?(?:0x[\dA-Fa-f]+|\d*\.?\d+(?:[Ee]-?\d+)?)\b/,
// Operators according to https://www.gnu.org/software/bash/manual/bashref.html#Shell-Arithmetic
operator: /--?|-=|\+\+?|\+=|!=?|~|\*\*?|\*=|\/=?|%=?|<<=?|>>=?|<=?|>=?|==?|&&?|&=|\^=?|\|\|?|\|=|\?|:/,
// If there is no $ sign at the beginning highlight (( and )) as punctuation
punctuation: /\(\(?|\)\)?|,|;/
}
},
// Command Substitution
{
pattern: /\$\([^)]+\)|`[^`]+`/,
inside: {
variable: /^\$\(|^`|\)$|`$/
}
},
/\$(?:[a-z0-9_#\?\*!@]+|\{[^}]+\})/i
],
};
Prism.languages.bash = {
'shebang': {
pattern: /^#!\s*\/bin\/bash|^#!\s*\/bin\/sh/,
alias: 'important'
},
'comment': {
pattern: /(^|[^"{\\])#.*/,
lookbehind: true
},
'string': [
//Support for Here-Documents https://en.wikipedia.org/wiki/Here_document
{
pattern: /((?:^|[^<])<<\s*)(?:"|')?(\w+?)(?:"|')?\s*\r?\n(?:[\s\S])*?\r?\n\2/g,
lookbehind: true,
inside: insideString
},
{
pattern: /("|')(?:\\?[\s\S])*?\1/g,
inside: insideString
}
],
'variable': insideString.variable,
// Originally based on http://ss64.com/bash/
'function': {
pattern: /(^|\s|;|\||&)(?:alias|apropos|apt-get|aptitude|aspell|awk|basename|bash|bc|bg|builtin|bzip2|cal|cat|cd|cfdisk|chgrp|chmod|chown|chroot|chkconfig|cksum|clear|cmp|comm|command|cp|cron|crontab|csplit|cut|date|dc|dd|ddrescue|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|du|egrep|eject|enable|env|ethtool|eval|exec|expand|expect|export|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|getopts|git|grep|groupadd|groupdel|groupmod|groups|gzip|hash|head|help|hg|history|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|jobs|join|kill|killall|less|link|ln|locate|logname|logout|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|make|man|mkdir|mkfifo|mkisofs|mknod|more|most|mount|mtools|mtr|mv|mmv|nano|netstat|nice|nl|nohup|notify-send|nslookup|open|op|passwd|paste|pathchk|ping|pkill|popd|pr|printcap|printenv|printf|ps|pushd|pv|pwd|quota|quotacheck|quotactl|ram|rar|rcp|read|readarray|readonly|reboot|rename|renice|remsync|rev|rm|rmdir|rsync|screen|scp|sdiff|sed|seq|service|sftp|shift|shopt|shutdown|sleep|slocate|sort|source|split|ssh|stat|strace|su|sudo|sum|suspend|sync|tail|tar|tee|test|time|timeout|times|touch|top|traceroute|trap|tr|tsort|tty|type|ulimit|umask|umount|unalias|uname|unexpand|uniq|units|unrar|unshar|uptime|useradd|userdel|usermod|users|uuencode|uudecode|v|vdir|vi|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yes|zip)(?=$|\s|;|\||&)/,
lookbehind: true
},
'keyword': {
pattern: /(^|\s|;|\||&)(?:let|:|\.|if|then|else|elif|fi|for|break|continue|while|in|case|function|select|do|done|until|echo|exit|return|set|declare)(?=$|\s|;|\||&)/,
lookbehind: true
},
'boolean': {
pattern: /(^|\s|;|\||&)(?:true|false)(?=$|\s|;|\||&)/,
lookbehind: true
},
'operator': /&&?|\|\|?|==?|!=?|<<<?|>>|<=?|>=?|=~/,
'punctuation': /\$?\(\(?|\)\)?|\.\.|[{}[\];]/
};
var inside = insideString.variable[1].inside;
inside['function'] = Prism.languages.bash['function'];
inside.keyword = Prism.languages.bash.keyword;
inside.boolean = Prism.languages.bash.boolean;
inside.operator = Prism.languages.bash.operator;
inside.punctuation = Prism.languages.bash.punctuation;
})(Prism);
(function (Prism) {
var variable = /%%?[~:\w]+%?|!\S+!/;
var parameter = {
pattern: /\/[a-z?]+(?=[ :]|$):?|-[a-z]\b|--[a-z-]+\b/im,
alias: 'attr-name',
inside: {
'punctuation': /:/
}
};
var string = /"[^"]*"/;
var number = /(?:\b|-)\d+\b/;
Prism.languages.batch = {
'comment': [
/^::.*/m,
{
pattern: /((?:^|[&(])[ \t]*)rem\b(?:[^^&)\r\n]|\^(?:\r\n|[\s\S]))*/im,
lookbehind: true
}
],
'label': {
pattern: /^:.*/m,
alias: 'property'
},
'command': [
{
// FOR command
pattern: /((?:^|[&(])[ \t]*)for(?: ?\/[a-z?](?:[ :](?:"[^"]*"|\S+))?)* \S+ in \([^)]+\) do/im,
lookbehind: true,
inside: {
'keyword': /^for\b|\b(?:in|do)\b/i,
'string': string,
'parameter': parameter,
'variable': variable,
'number': number,
'punctuation': /[()',]/
}
},
{
// IF command
pattern: /((?:^|[&(])[ \t]*)if(?: ?\/[a-z?](?:[ :](?:"[^"]*"|\S+))?)* (?:not )?(?:cmdextversion \d+|defined \w+|errorlevel \d+|exist \S+|(?:"[^"]*"|\S+)?(?:==| (?:equ|neq|lss|leq|gtr|geq) )(?:"[^"]*"|\S+))/im,
lookbehind: true,
inside: {
'keyword': /^if\b|\b(?:not|cmdextversion|defined|errorlevel|exist)\b/i,
'string': string,
'parameter': parameter,
'variable': variable,
'number': number,
'operator': /\^|==|\b(?:equ|neq|lss|leq|gtr|geq)\b/i
}
},
{
// ELSE command
pattern: /((?:^|[&()])[ \t]*)else\b/im,
lookbehind: true,
inside: {
'keyword': /^else\b/i
}
},
{
// SET command
pattern: /((?:^|[&(])[ \t]*)set(?: ?\/[a-z](?:[ :](?:"[^"]*"|\S+))?)* (?:[^^&)\r\n]|\^(?:\r\n|[\s\S]))*/im,
lookbehind: true,
inside: {
'keyword': /^set\b/i,
'string': string,
'parameter': parameter,
'variable': [
variable,
/\w+(?=(?:[*\/%+\-&^|]|<<|>>)?=)/
],
'number': number,
'operator': /[*\/%+\-&^|]=?|<<=?|>>=?|[!~_=]/,
'punctuation': /[()',]/
}
},
{
// Other commands
pattern: /((?:^|[&(])[ \t]*@?)\w+\b(?:[^^&)\r\n]|\^(?:\r\n|[\s\S]))*/im,
lookbehind: true,
inside: {
'keyword': /^\w+\b/i,
'string': string,
'parameter': parameter,
'label': {
pattern: /(^\s*):\S+/m,
lookbehind: true,
alias: 'property'
},
'variable': variable,
'number': number,
'operator': /\^/
}
}
],
'operator': /[&@]/,
'punctuation': /[()']/
};
}(Prism));
Prism.languages.c = Prism.languages.extend('clike', {
'keyword': /\b(asm|typeof|inline|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|void|volatile|while)\b/,
'operator': /\-[>-]?|\+\+?|!=?|<<?=?|>>?=?|==?|&&?|\|?\||[~^%?*\/]/,
'number': /\b-?(?:0x[\da-f]+|\d*\.?\d+(?:e[+-]?\d+)?)[ful]*\b/i
});
Prism.languages.insertBefore('c', 'string', {
'macro': {
// allow for multiline macro definitions
// spaces after the # character compile fine with gcc
pattern: /(^\s*)#\s*[a-z]+([^\r\n\\]|\\.|\\(?:\r\n?|\n))*/im,
lookbehind: true,
alias: 'property',
inside: {
// highlight the path of the include statement as a string
'string': {
pattern: /(#\s*include\s*)(<.+?>|("|')(\\?.)+?\3)/,
lookbehind: true
},
// highlight macro directives as keywords
'directive': {
pattern: /(#\s*)\b(define|elif|else|endif|error|ifdef|ifndef|if|import|include|line|pragma|undef|using)\b/,
lookbehind: true,
alias: 'keyword'
}
}
},
// highlight predefined macros as constants
'constant': /\b(__FILE__|__LINE__|__DATE__|__TIME__|__TIMESTAMP__|__func__|EOF|NULL|stdin|stdout|stderr)\b/
});
delete Prism.languages.c['class-name'];
delete Prism.languages.c['boolean'];
Prism.languages.bison = Prism.languages.extend('c', {});
Prism.languages.insertBefore('bison', 'comment', {
'bison': {
// This should match all the beginning of the file
// including the prologue(s), the bison declarations and
// the grammar rules.
pattern: /^[\s\S]*?%%[\s\S]*?%%/,
inside: {
'c': {
// Allow for one level of nested braces
pattern: /%\{[\s\S]*?%\}|\{(?:\{[^}]*\}|[^{}])*\}/,
inside: {
'delimiter': {
pattern: /^%?\{|%?\}$/,
alias: 'punctuation'
},
'bison-variable': {
pattern: /[$@](?:<[^\s>]+>)?[\w$]+/,
alias: 'variable',
inside: {
'punctuation': /<|>/
}
},
rest: Prism.languages.c
}
},
'comment': Prism.languages.c.comment,
'string': Prism.languages.c.string,
'property': /\S+(?=:)/,
'keyword': /%\w+/,
'number': {
pattern: /(^|[^@])\b(?:0x[\da-f]+|\d+)/i,
lookbehind: true
},
'punctuation': /%[%?]|[|:;\[\]<>]/
}
}
});
Prism.languages.csharp = Prism.languages.extend('clike', {
'keyword': /\b(abstract|as|async|await|base|bool|break|byte|case|catch|char|checked|class|const|continue|decimal|default|delegate|do|double|else|enum|event|explicit|extern|false|finally|fixed|float|for|foreach|goto|if|implicit|in|int|interface|internal|is|lock|long|namespace|new|null|object|operator|out|override|params|private|protected|public|readonly|ref|return|sbyte|sealed|short|sizeof|stackalloc|static|string|struct|switch|this|throw|true|try|typeof|uint|ulong|unchecked|unsafe|ushort|using|virtual|void|volatile|while|add|alias|ascending|async|await|descending|dynamic|from|get|global|group|into|join|let|orderby|partial|remove|select|set|value|var|where|yield)\b/,
'string': [
/@("|')(\1\1|\\\1|\\?(?!\1)[\s\S])*\1/,
/("|')(\\?.)*?\1/
],
'number': /\b-?(0x[\da-f]+|\d*\.?\d+f?)\b/i
});
Prism.languages.insertBefore('csharp', 'keyword', {
'preprocessor': {
pattern: /(^\s*)#.*/m,
lookbehind: true,
alias: 'property',
inside: {
// highlight preprocessor directives as keywords
'directive': {
pattern: /(\s*#)\b(define|elif|else|endif|endregion|error|if|line|pragma|region|undef|warning)\b/,
lookbehind: true,
alias: 'keyword'
}
}
}
});
Prism.languages.cpp = Prism.languages.extend('c', {
'keyword': /\b(alignas|alignof|asm|auto|bool|break|case|catch|char|char16_t|char32_t|class|compl|const|constexpr|const_cast|continue|decltype|default|delete|do|double|dynamic_cast|else|enum|explicit|export|extern|float|for|friend|goto|if|inline|int|long|mutable|namespace|new|noexcept|nullptr|operator|private|protected|public|register|reinterpret_cast|return|short|signed|sizeof|static|static_assert|static_cast|struct|switch|template|this|thread_local|throw|try|typedef|typeid|typename|union|unsigned|using|virtual|void|volatile|wchar_t|while)\b/,
'boolean': /\b(true|false)\b/,
'operator': /[-+]{1,2}|!=?|<{1,2}=?|>{1,2}=?|\->|:{1,2}|={1,2}|\^|~|%|&{1,2}|\|?\||\?|\*|\/|\b(and|and_eq|bitand|bitor|not|not_eq|or|or_eq|xor|xor_eq)\b/
});
Prism.languages.insertBefore('cpp', 'keyword', {
'class-name': {
pattern: /(class\s+)[a-z0-9_]+/i,
lookbehind: true
}
});
(function(Prism) {
// Ignore comments starting with { to privilege string interpolation highlighting
var comment = /#(?!\{).+/,
interpolation = {
pattern: /#\{[^}]+\}/,
alias: 'variable'
};
Prism.languages.coffeescript = Prism.languages.extend('javascript', {
'comment': comment,
'string': [
// Strings are multiline
/'(?:\\?[^\\])*?'/,
{
// Strings are multiline
pattern: /"(?:\\?[^\\])*?"/,
inside: {
'interpolation': interpolation
}
}
],
'keyword': /\b(and|break|by|catch|class|continue|debugger|delete|do|each|else|extend|extends|false|finally|for|if|in|instanceof|is|isnt|let|loop|namespace|new|no|not|null|of|off|on|or|own|return|super|switch|then|this|throw|true|try|typeof|undefined|unless|until|when|while|window|with|yes|yield)\b/,
'class-member': {
pattern: /@(?!\d)\w+/,
alias: 'variable'
}
});
Prism.languages.insertBefore('coffeescript', 'comment', {
'multiline-comment': {
pattern: /###[\s\S]+?###/,
alias: 'comment'
},
// Block regexp can contain comments and interpolation
'block-regex': {
pattern: /\/{3}[\s\S]*?\/{3}/,
alias: 'regex',
inside: {
'comment': comment,
'interpolation': interpolation
}
}
});
Prism.languages.insertBefore('coffeescript', 'string', {
'inline-javascript': {
pattern: /`(?:\\?[\s\S])*?`/,
inside: {
'delimiter': {
pattern: /^`|`$/,
alias: 'punctuation'
},
rest: Prism.languages.javascript
}
},
// Block strings
'multiline-string': [
{
pattern: /'''[\s\S]*?'''/,
alias: 'string'
},
{
pattern: /"""[\s\S]*?"""/,
alias: 'string',
inside: {
interpolation: interpolation
}
}
]
});
Prism.languages.insertBefore('coffeescript', 'keyword', {
// Object property
'property': /(?!\d)\w+(?=\s*:(?!:))/
});
}(Prism));
/**
* Original by Samuel Flores
*
* Adds the following new token classes:
* constant, builtin, variable, symbol, regex
*/
(function(Prism) {
Prism.languages.ruby = Prism.languages.extend('clike', {
'comment': /#(?!\{[^\r\n]*?\}).*/,
'keyword': /\b(alias|and|BEGIN|begin|break|case|class|def|define_method|defined|do|each|else|elsif|END|end|ensure|false|for|if|in|module|new|next|nil|not|or|raise|redo|require|rescue|retry|return|self|super|then|throw|true|undef|unless|until|when|while|yield)\b/
});
var interpolation = {
pattern: /#\{[^}]+\}/,
inside: {
'delimiter': {
pattern: /^#\{|\}$/,
alias: 'tag'
},
rest: Prism.util.clone(Prism.languages.ruby)
}
};
Prism.languages.insertBefore('ruby', 'keyword', {
'regex': [
{
pattern: /%r([^a-zA-Z0-9\s\{\(\[<])(?:[^\\]|\\[\s\S])*?\1[gim]{0,3}/,
inside: {
'interpolation': interpolation
}
},
{
pattern: /%r\((?:[^()\\]|\\[\s\S])*\)[gim]{0,3}/,
inside: {
'interpolation': interpolation
}
},
{
// Here we need to specifically allow interpolation
pattern: /%r\{(?:[^#{}\\]|#(?:\{[^}]+\})?|\\[\s\S])*\}[gim]{0,3}/,
inside: {
'interpolation': interpolation
}
},
{
pattern: /%r\[(?:[^\[\]\\]|\\[\s\S])*\][gim]{0,3}/,
inside: {
'interpolation': interpolation
}
},
{
pattern: /%r<(?:[^<>\\]|\\[\s\S])*>[gim]{0,3}/,
inside: {
'interpolation': interpolation
}
},
{
pattern: /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\r\n])+\/[gim]{0,3}(?=\s*($|[\r\n,.;})]))/,
lookbehind: true
}
],
'variable': /[@$]+[a-zA-Z_][a-zA-Z_0-9]*(?:[?!]|\b)/,
'symbol': /:[a-zA-Z_][a-zA-Z_0-9]*(?:[?!]|\b)/
});
Prism.languages.insertBefore('ruby', 'number', {
'builtin': /\b(Array|Bignum|Binding|Class|Continuation|Dir|Exception|FalseClass|File|Stat|File|Fixnum|Fload|Hash|Integer|IO|MatchData|Method|Module|NilClass|Numeric|Object|Proc|Range|Regexp|String|Struct|TMS|Symbol|ThreadGroup|Thread|Time|TrueClass)\b/,
'constant': /\b[A-Z][a-zA-Z_0-9]*(?:[?!]|\b)/
});
Prism.languages.ruby.string = [
{
pattern: /%[qQiIwWxs]?([^a-zA-Z0-9\s\{\(\[<])(?:[^\\]|\\[\s\S])*?\1/,
inside: {
'interpolation': interpolation
}
},
{
pattern: /%[qQiIwWxs]?\((?:[^()\\]|\\[\s\S])*\)/,
inside: {
'interpolation': interpolation
}
},
{
// Here we need to specifically allow interpolation
pattern: /%[qQiIwWxs]?\{(?:[^#{}\\]|#(?:\{[^}]+\})?|\\[\s\S])*\}/,
inside: {
'interpolation': interpolation
}
},
{
pattern: /%[qQiIwWxs]?\[(?:[^\[\]\\]|\\[\s\S])*\]/,
inside: {
'interpolation': interpolation
}
},
{
pattern: /%[qQiIwWxs]?<(?:[^<>\\]|\\[\s\S])*>/,
inside: {
'interpolation': interpolation
}
},
{
pattern: /("|')(#\{[^}]+\}|\\(?:\r?\n|\r)|\\?.)*?\1/,
inside: {
'interpolation': interpolation
}
}
];
}(Prism));
Prism.languages.css.selector = {
pattern: /[^\{\}\s][^\{\}]*(?=\s*\{)/,
inside: {
'pseudo-element': /:(?:after|before|first-letter|first-line|selection)|::[-\w]+/,
'pseudo-class': /:[-\w]+(?:\(.*\))?/,
'class': /\.[-:\.\w]+/,
'id': /#[-:\.\w]+/
}
};
Prism.languages.insertBefore('css', 'function', {
'hexcode': /#[\da-f]{3,6}/i,
'entity': /\\[\da-f]{1,8}/i,
'number': /[\d%\.]+/
});
Prism.languages.diff = {
'coord': [
// Match all kinds of coord lines (prefixed by "+++", "---" or "***").
/^(?:\*{3}|-{3}|\+{3}).*$/m,
// Match "@@ ... @@" coord lines in unified diff.
/^@@.*@@$/m,
// Match coord lines in normal diff (starts with a number).
/^\d+.*$/m
],
// Match inserted and deleted lines. Support both +/- and >/< styles.
'deleted': /^[-<].+$/m,
'inserted': /^[+>].+$/m,
// Match "different" lines (prefixed with "!") in context diff.
'diff': {
'pattern': /^!(?!!).+$/m,
'alias': 'important'
}
};
Prism.languages.gherkin = {
'pystring': {
pattern: /("""|''')[\s\S]+?\1/,
alias: 'string'
},
'comment': {
pattern: /((^|\r?\n|\r)[ \t]*)#.*/,
lookbehind: true
},
'tag': {
pattern: /((^|\r?\n|\r)[ \t]*)@\S*/,
lookbehind: true
},
'feature': {
pattern: /((^|\r?\n|\r)[ \t]*)(Ability|Ahoy matey!|Arwedd|Aspekt|Besigheid Behoefte|Business Need|Caracteristica|Característica|Egenskab|Egenskap|Eiginleiki|Feature|Fīča|Fitur|Fonctionnalité|Fonksyonalite|Funcionalidade|Funcionalitat|Functionalitate|Funcţionalitate|Funcționalitate|Functionaliteit|Fungsi|Funkcia|Funkcija|Funkcionalitāte|Funkcionalnost|Funkcja|Funksie|Funktionalität|Funktionalitéit|Funzionalità|Hwaet|Hwæt|Jellemző|Karakteristik|laH|Lastnost|Mak|Mogucnost|Mogućnost|Moznosti|Možnosti|OH HAI|Omadus|Ominaisuus|Osobina|Özellik|perbogh|poQbogh malja'|Potrzeba biznesowa|Požadavek|Požiadavka|Pretty much|Qap|Qu'meH 'ut|Savybė|Tính năng|Trajto|Vermoë|Vlastnosť|Właściwość|Značilnost|Δυνατότητα|Λειτουργία|Могућност|Мөмкинлек|Особина|Свойство|Үзенчәлеклелек|Функционал|Функционалност|Функция|Функціонал|תכונה|خاصية|خصوصیت|صلاحیت|کاروبار کی ضرورت|وِیژگی|रूप लेख|ਖਾਸੀਅਤ|ਨਕਸ਼ ਨੁਹਾਰ|ਮੁਹਾਂਦਰਾ|గుణము|ಹೆಚ್ಚಳ|ความต้องการทางธุรกิจ|ความสามารถ|โครงหลัก|기능|フィーチャ|功能|機能):([^:]+(?:\r?\n|\r|$))*/,
lookbehind: true,
inside: {
'important': {
pattern: /(:)[^\r\n]+/,
lookbehind: true
},
keyword: /[^:\r\n]+:/
}
},
'scenario': {
pattern: /((^|\r?\n|\r)[ \t]*)(Abstract Scenario|Abstrakt Scenario|Achtergrond|Aer|Ær|Agtergrond|All y'all|Antecedentes|Antecedents|Atburðarás|Atburðarásir|Awww, look mate|B4|Background|Baggrund|Bakgrund|Bakgrunn|Bakgrunnur|Beispiele|Beispiller|Bối cảnh|Cefndir|Cenario|Cenário|Cenario de Fundo|Cenário de Fundo|Cenarios|Cenários|Contesto|Context|Contexte|Contexto|Conto|Contoh|Contone|Dæmi|Dasar|Dead men tell no tales|Delineacao do Cenario|Delineação do Cenário|Dis is what went down|Dữ liệu|Dyagram senaryo|Dyagram Senaryo|Egzanp|Ejemplos|Eksempler|Ekzemploj|Enghreifftiau|Esbozo do escenario|Escenari|Escenario|Esempi|Esquema de l'escenari|Esquema del escenario|Esquema do Cenario|Esquema do Cenário|Examples|EXAMPLZ|Exempel|Exemple|Exemples|Exemplos|First off|Fono|Forgatókönyv|Forgatókönyv vázlat|Fundo|Geçmiş|ghantoH|Grundlage|Hannergrond|Háttér|Heave to|Istorik|Juhtumid|Keadaan|Khung kịch bản|Khung tình huống|Kịch bản|Koncept|Konsep skenario|Kontèks|Kontekst|Kontekstas|Konteksts|Kontext|Konturo de la scenaro|Latar Belakang|lut|lut chovnatlh|lutmey|Lýsing Atburðarásar|Lýsing Dæma|Menggariskan Senario|MISHUN|MISHUN SRSLY|mo'|Náčrt Scenára|Náčrt Scénáře|Náčrt Scenáru|Oris scenarija|Örnekler|Osnova|Osnova Scenára|Osnova scénáře|Osnutek|Ozadje|Paraugs|Pavyzdžiai|Példák|Piemēri|Plan du scénario|Plan du Scénario|Plan senaryo|Plan Senaryo|Plang vum Szenario|Pozadí|Pozadie|Pozadina|Príklady|Příklady|Primer|Primeri|Primjeri|Przykłady|Raamstsenaarium|Reckon it's like|Rerefons|Scenár|Scénář|Scenarie|Scenarij|Scenarijai|Scenarijaus šablonas|Scenariji|Scenārijs|Scenārijs pēc parauga|Scenarijus|Scenario|Scénario|Scenario Amlinellol|Scenario Outline|Scenario Template|Scenariomal|Scenariomall|Scenarios|Scenariu|Scenariusz|Scenaro|Schema dello scenario|Se ðe|Se the|Se þe|Senario|Senaryo|Senaryo deskripsyon|Senaryo Deskripsyon|Senaryo taslağı|Shiver me timbers|Situācija|Situai|Situasie|Situasie Uiteensetting|Skenario|Skenario konsep|Skica|Structura scenariu|Structură scenariu|Struktura scenarija|Stsenaarium|Swa|Swa hwaer swa|Swa hwær swa|Szablon scenariusza|Szenario|Szenariogrundriss|Tapaukset|Tapaus|Tapausaihio|Taust|Tausta|Template Keadaan|Template Senario|Template Situai|The thing of it is|Tình huống|Variantai|Voorbeelde|Voorbeelden|Wharrimean is|Yo\-ho\-ho|You'll wanna|Założenia|Παραδείγματα|Περιγραφή Σεναρίου|Σενάρια|Σενάριο|Υπόβαθρο|Кереш|Контекст|Концепт|Мисаллар|Мисоллар|Основа|Передумова|Позадина|Предистория|Предыстория|Приклади|Пример|Примери|Примеры|Рамка на сценарий|Скица|Структура сценарија|Структура сценария|Структура сценарію|Сценарий|Сценарий структураси|Сценарийның төзелеше|Сценарији|Сценарио|Сценарій|Тарих|Үрнәкләр|דוגמאות|רקע|תבנית תרחיש|תרחיש|الخلفية|الگوی سناریو|امثلة|پس منظر|زمینه|سناریو|سيناريو|سيناريو مخطط|مثالیں|منظر نامے کا خاکہ|منظرنامہ|نمونه ها|उदाहरण|परिदृश्य|परिदृश्य रूपरेखा|पृष्ठभूमि|ਉਦਾਹਰਨਾਂ|ਪਟਕਥਾ|ਪਟਕਥਾ ਢਾਂਚਾ|ਪਟਕਥਾ ਰੂਪ ਰੇਖਾ|ਪਿਛੋਕੜ|ఉదాహరణలు|కథనం|నేపథ్యం|సన్నివేశం|ಉದಾಹರಣೆಗಳು|ಕಥಾಸಾರಾಂಶ|ವಿವರಣೆ|ಹಿನ್ನೆಲೆ|โครงสร้างของเหตุการณ์|ชุดของตัวอย่าง|ชุดของเหตุการณ์|แนวคิด|สรุปเหตุการณ์|เหตุการณ์|배경|시나리오|시나리오 개요|예|サンプル|シナリオ|シナリオアウトライン|シナリオテンプレ|シナリオテンプレート|テンプレ|例|例子|剧本|剧本大纲|劇本|劇本大綱|场景|场景大纲|場景|場景大綱|背景):[^:\r\n]*/,
lookbehind: true,
inside: {
'important': {
pattern: /(:)[^\r\n]*/,
lookbehind: true
},
keyword: /[^:\r\n]+:/
}
},
'table-body': {
pattern: /((?:\r?\n|\r)[ \t]*\|.+\|[^\r\n]*)+/,
lookbehind: true,
inside: {
'outline': {
pattern: /<[^>]+?>/,
alias: 'variable'
},
'td': {
pattern: /\s*[^\s|][^|]*/,
alias: 'string'
},
'punctuation': /\|/
}
},
'table-head': {
pattern: /((?:\r?\n|\r)[ \t]*\|.+\|[^\r\n]*)/,
inside: {
'th': {
pattern: /\s*[^\s|][^|]*/,
alias: 'variable'
},
'punctuation': /\|/
}
},
'atrule': {
pattern: /((?:\r?\n|\r)[ \t]+)('ach|'a|'ej|7|a|A také|A taktiež|A tiež|A zároveň|Aber|Ac|Adott|Akkor|Ak|Aleshores|Ale|Ali|Allora|Alors|Als|Ama|Amennyiben|Amikor|Ampak|an|AN|Ananging|And y'all|And|Angenommen|Anrhegedig a|An|Apabila|Atès|Atesa|Atunci|Avast!|Aye|A|awer|Bagi|Banjur|Bet|Biết|Blimey!|Buh|But at the end of the day I reckon|But y'all|But|BUT|Cal|Când|Cando|Cand|Ce|Cuando|Če|Ða ðe|Ða|Dadas|Dada|Dados|Dado|DaH ghu' bejlu'|dann|Dann|Dano|Dan|Dar|Dat fiind|Data|Date fiind|Date|Dati fiind|Dati|Daţi fiind|Dați fiind|Dato|DEN|Den youse gotta|Dengan|De|Diberi|Diyelim ki|Donada|Donat|Donitaĵo|Do|Dun|Duota|Ðurh|Eeldades|Ef|Eğer ki|Entao|Então|Entón|Entonces|En|Epi|E|És|Etant donnée|Etant donné|Et|Étant données|Étant donnée|Étant donné|Etant données|Etant donnés|Étant donnés|Fakat|Gangway!|Gdy|Gegeben seien|Gegeben sei|Gegeven|Gegewe|ghu' noblu'|Gitt|Given y'all|Given|Givet|Givun|Ha|Cho|I CAN HAZ|In|Ir|It's just unbelievable|I|Ja|Jeśli|Jeżeli|Kadar|Kada|Kad|Kai|Kaj|Když|Keď|Kemudian|Ketika|Khi|Kiedy|Ko|Kuid|Kui|Kun|Lan|latlh|Le sa a|Let go and haul|Le|Lè sa a|Lè|Logo|Lorsqu'<|Lorsque|mä|Maar|Mais|Mając|Majd|Maka|Manawa|Mas|Ma|Menawa|Men|Mutta|Nalikaning|Nalika|Nanging|Når|När|Nato|Nhưng|Niin|Njuk|O zaman|Og|Och|Oletetaan|Onda|Ond|Oraz|Pak|Pero|Però|Podano|Pokiaľ|Pokud|Potem|Potom|Privzeto|Pryd|qaSDI'|Quando|Quand|Quan|Så|Sed|Se|Siis|Sipoze ke|Sipoze Ke|Sipoze|Si|Şi|Și|Soit|Stel|Tada|Tad|Takrat|Tak|Tapi|Ter|Tetapi|Tha the|Tha|Then y'all|Then|Thì|Thurh|Toda|Too right|ugeholl|Und|Un|Và|vaj|Vendar|Ve|wann|Wanneer|WEN|Wenn|When y'all|When|Wtedy|Wun|Y'know|Yeah nah|Yna|Youse know like when|Youse know when youse got|Y|Za predpokladu|Za předpokladu|Zadani|Zadano|Zadan|Zadate|Zadato|Zakładając|Zaradi|Zatati|Þa þe|Þa|Þá|Þegar|Þurh|Αλλά|Δεδομένου|Και|Όταν|Τότε|А також|Агар|Але|Али|Аммо|А|Әгәр|Әйтик|Әмма|Бирок|Ва|Вә|Дадено|Дано|Допустим|Если|Задате|Задати|Задато|И|І|К тому же|Када|Кад|Когато|Когда|Коли|Ләкин|Лекин|Нәтиҗәдә|Нехай|Но|Онда|Припустимо, що|Припустимо|Пусть|Также|Та|Тогда|Тоді|То|Унда|Һәм|Якщо|אבל|אזי|אז|בהינתן|וגם|כאשר|آنگاه|اذاً|اگر|اما|اور|با فرض|بالفرض|بفرض|پھر|تب|ثم|جب|عندما|فرض کیا|لكن|لیکن|متى|هنگامی|و|अगर|और|कदा|किन्तु|चूंकि|जब|तथा|तदा|तब|परन्तु|पर|यदि|ਅਤੇ|ਜਦੋਂ|ਜਿਵੇਂ ਕਿ|ਜੇਕਰ|ਤਦ|ਪਰ|అప్పుడు|ఈ పరిస్థితిలో|కాని|చెప్పబడినది|మరియు|ಆದರೆ|ನಂತರ|ನೀಡಿದ|ಮತ್ತು|ಸ್ಥಿತಿಯನ್ನು|กำหนดให้|ดังนั้น|แต่|เมื่อ|และ|그러면<|그리고<|단<|만약<|만일<|먼저<|조건<|하지만<|かつ<|しかし<|ただし<|ならば<|もし<|並且<|但し<|但是<|假如<|假定<|假設<|假设<|前提<|同时<|同時<|并且<|当<|當<|而且<|那么<|那麼<)(?=[ \t]+)/,
lookbehind: true
},
'string': {
pattern: /("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/,
inside: {
'outline': {
pattern: /<[^>]+?>/,
alias: 'variable'
}
}
},
'outline': {
pattern: /<[^>]+?>/,
alias: 'variable'
}
};
Prism.languages.git = {
/*
* A simple one line comment like in a git status command
* For instance:
* $ git status
* # On branch infinite-scroll
* # Your branch and 'origin/sharedBranches/frontendTeam/infinite-scroll' have diverged,
* # and have 1 and 2 different commits each, respectively.
* nothing to commit (working directory clean)
*/
'comment': /^#.*/m,
/*
* Regexp to match the changed lines in a git diff output. Check the example below.
*/
'deleted': /^[-–].*/m,
'inserted': /^\+.*/m,
/*
* a string (double and simple quote)
*/
'string': /("|')(\\?.)*?\1/m,
/*
* a git command. It starts with a random prompt finishing by a $, then "git" then some other parameters
* For instance:
* $ git add file.txt
*/
'command': {
pattern: /^.*\$ git .*$/m,
inside: {
/*
* A git command can contain a parameter starting by a single or a double dash followed by a string
* For instance:
* $ git diff --cached
* $ git log -p
*/
'parameter': /\s(--|-)\w+/m
}
},
/*
* Coordinates displayed in a git diff command
* For instance:
* $ git diff
* diff --git file.txt file.txt
* index 6214953..1d54a52 100644
* --- file.txt
* +++ file.txt
* @@ -1 +1,2 @@
* -Here's my tetx file
* +Here's my text file
* +And this is the second line
*/
'coord': /^@@.*@@$/m,
/*
* Match a "commit [SHA1]" line in a git log output.
* For instance:
* $ git log
* commit a11a14ef7e26f2ca62d4b35eac455ce636d0dc09
* Author: lgiraudel
* Date: Mon Feb 17 11:18:34 2014 +0100
*
* Add of a new line
*/
'commit_sha1': /^commit \w{40}$/m
};
Prism.languages.go = Prism.languages.extend('clike', {
'keyword': /\b(break|case|chan|const|continue|default|defer|else|fallthrough|for|func|go(to)?|if|import|interface|map|package|range|return|select|struct|switch|type|var)\b/,
'builtin': /\b(bool|byte|complex(64|128)|error|float(32|64)|rune|string|u?int(8|16|32|64|)|uintptr|append|cap|close|complex|copy|delete|imag|len|make|new|panic|print(ln)?|real|recover)\b/,
'boolean': /\b(_|iota|nil|true|false)\b/,
'operator': /[*\/%^!=]=?|\+[=+]?|-[=-]?|\|[=|]?|&(?:=|&|\^=?)?|>(?:>=?|=)?|<(?:<=?|=|-)?|:=|\.\.\./,
'number': /\b(-?(0x[a-f\d]+|(\d+\.?\d*|\.\d+)(e[-+]?\d+)?)i?)\b/i,
'string': /("|'|`)(\\?.|\r|\n)*?\1/
});
delete Prism.languages.go['class-name'];
Prism.languages.groovy = Prism.languages.extend('clike', {
'keyword': /\b(as|def|in|abstract|assert|boolean|break|byte|case|catch|char|class|const|continue|default|do|double|else|enum|extends|final|finally|float|for|goto|if|implements|import|instanceof|int|interface|long|native|new|package|private|protected|public|return|short|static|strictfp|super|switch|synchronized|this|throw|throws|trait|transient|try|void|volatile|while)\b/,
'string': /("""|''')[\W\w]*?\1|("|'|\/)(?:\\?.)*?\2|(\$\/)(\$\/\$|[\W\w])*?\/\$/,
'number': /\b(?:0b[01_]+|0x[\da-f_]+(?:\.[\da-f_p\-]+)?|[\d_]+(?:\.[\d_]+)?(?:e[+-]?[\d]+)?)[glidf]?\b/i,
'operator': {
pattern: /(^|[^.])(~|==?~?|\?[.:]?|\*(?:[.=]|\*=?)?|\.[@&]|\.\.<|\.{1,2}(?!\.)|-[-=>]?|\+[+=]?|!=?|<(?:<=?|=>?)?|>(?:>>?=?|=)?|&[&=]?|\|[|=]?|\/=?|\^=?|%=?)/,
lookbehind: true
},
'punctuation': /\.+|[{}[\];(),:$]/
});
Prism.languages.insertBefore('groovy', 'string', {
'shebang': {
pattern: /#!.+/,
alias: 'comment'
}
});
Prism.languages.insertBefore('groovy', 'punctuation', {
'spock-block': /\b(setup|given|when|then|and|cleanup|expect|where):/
});
Prism.languages.insertBefore('groovy', 'function', {
'annotation': {
pattern: /(^|[^.])@\w+/,
lookbehind: true
}
});
// Handle string interpolation
Prism.hooks.add('wrap', function(env) {
if (env.language === 'groovy' && env.type === 'string') {
var delimiter = env.content[0];
if (delimiter != "'") {
var pattern = /([^\\])(\$(\{.*?\}|[\w\.]+))/;
if (delimiter === '$') {
pattern = /([^\$])(\$(\{.*?\}|[\w\.]+))/;
}
env.content = Prism.highlight(env.content, {
'expression': {
pattern: pattern,
lookbehind: true,
inside: Prism.languages.groovy
}
});
env.classes.push(delimiter === '/' ? 'regex' : 'gstring');
}
}
});
(function(Prism) {
var handlebars_pattern = /\{\{\{[\w\W]+?\}\}\}|\{\{[\w\W]+?\}\}/g;
Prism.languages.handlebars = Prism.languages.extend('markup', {
'handlebars': {
pattern: handlebars_pattern,
inside: {
'delimiter': {
pattern: /^\{\{\{?|\}\}\}?$/i,
alias: 'punctuation'
},
'string': /(["'])(\\?.)*?\1/,
'number': /\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee][+-]?\d+)?)\b/,
'boolean': /\b(true|false)\b/,
'block': {
pattern: /^(\s*~?\s*)[#\/]\S+?(?=\s*~?\s*$|\s)/i,
lookbehind: true,
alias: 'keyword'
},
'brackets': {
pattern: /\[[^\]]+\]/,
inside: {
punctuation: /\[|\]/,
variable: /[\w\W]+/
}
},
'punctuation': /[!"#%&'()*+,.\/;<=>@\[\\\]^`{|}~]/,
'variable': /[^!"#%&'()*+,.\/;<=>@\[\\\]^`{|}~\s]+/
}
}
});
// Comments are inserted at top so that they can
// surround markup
Prism.languages.insertBefore('handlebars', 'tag', {
'handlebars-comment': {
pattern: /\{\{![\w\W]*?\}\}/,
alias: ['handlebars','comment']
}
});
// Tokenize all inline Handlebars expressions that are wrapped in {{ }} or {{{ }}}
// This allows for easy Handlebars + markup highlighting
Prism.hooks.add('before-highlight', function(env) {
if (env.language !== 'handlebars') {
return;
}
env.tokenStack = [];
env.backupCode = env.code;
env.code = env.code.replace(handlebars_pattern, function(match) {
env.tokenStack.push(match);
return '___HANDLEBARS' + env.tokenStack.length + '___';
});
});
// Restore env.code for other plugins (e.g. line-numbers)
Prism.hooks.add('before-insert', function(env) {
if (env.language === 'handlebars') {
env.code = env.backupCode;
delete env.backupCode;
}
});
// Re-insert the tokens after highlighting
// and highlight them with defined grammar
Prism.hooks.add('after-highlight', function(env) {
if (env.language !== 'handlebars') {
return;
}
for (var i = 0, t; t = env.tokenStack[i]; i++) {
// The replace prevents $$, $&, $`, $', $n, $nn from being interpreted as special patterns
env.highlightedCode = env.highlightedCode.replace('___HANDLEBARS' + (i + 1) + '___', Prism.highlight(t, env.grammar, 'handlebars').replace(/\$/g, '$$$$'));
}
env.element.innerHTML = env.highlightedCode;
});
}(Prism));
Prism.languages.http = {
'request-line': {
pattern: /^(POST|GET|PUT|DELETE|OPTIONS|PATCH|TRACE|CONNECT)\b\shttps?:\/\/\S+\sHTTP\/[0-9.]+/m,
inside: {
// HTTP Verb
property: /^(POST|GET|PUT|DELETE|OPTIONS|PATCH|TRACE|CONNECT)\b/,
// Path or query argument
'attr-name': /:\w+/
}
},
'response-status': {
pattern: /^HTTP\/1.[01] [0-9]+.*/m,
inside: {
// Status, e.g. 200 OK
property: {
pattern: /(^HTTP\/1.[01] )[0-9]+.*/i,
lookbehind: true
}
}
},
// HTTP header name
'header-name': {
pattern: /^[\w-]+:(?=.)/m,
alias: 'keyword'
}
};
// Create a mapping of Content-Type headers to language definitions
var httpLanguages = {
'application/json': Prism.languages.javascript,
'application/xml': Prism.languages.markup,
'text/xml': Prism.languages.markup,
'text/html': Prism.languages.markup
};
// Insert each content type parser that has its associated language
// currently loaded.
for (var contentType in httpLanguages) {
if (httpLanguages[contentType]) {
var options = {};
options[contentType] = {
pattern: new RegExp('(content-type:\\s*' + contentType + '[\\w\\W]*?)(?:\\r?\\n|\\r){2}[\\w\\W]*', 'i'),
lookbehind: true,
inside: {
rest: httpLanguages[contentType]
}
};
Prism.languages.insertBefore('http', 'header-name', options);
}
}
;
Prism.languages.ini= {
'comment': /^[ \t]*;.*$/m,
'important': /\[.*?\]/,
'constant': /^[ \t]*[^\s=]+?(?=[ \t]*=)/m,
'attr-value': {
pattern: /=.*/,
inside: {
'punctuation': /^[=]/
}
}
};
(function(Prism) {
// TODO:
// - Add CSS highlighting inside <style> tags
// - Add support for multi-line code blocks
// - Add support for interpolation #{} and !{}
// - Add support for tag interpolation #[]
// - Add explicit support for plain text using |
// - Add support for markup embedded in plain text
Prism.languages.jade = {
// Multiline stuff should appear before the rest
// This handles both single-line and multi-line comments
'comment': {
pattern: /(^([\t ]*))\/\/.*((?:\r?\n|\r)\2[\t ]+.+)*/m,
lookbehind: true
},
// All the tag-related part is in lookbehind
// so that it can be highlighted by the "tag" pattern
'multiline-script': {
pattern: /(^([\t ]*)script\b.*\.[\t ]*)((?:\r?\n|\r(?!\n))(?:\2[\t ]+.+|\s*?(?=\r?\n|\r)))+/m,
lookbehind: true,
inside: {
rest: Prism.languages.javascript
}
},
// See at the end of the file for known filters
'filter': {
pattern: /(^([\t ]*)):.+((?:\r?\n|\r(?!\n))(?:\2[\t ]+.+|\s*?(?=\r?\n|\r)))+/m,
lookbehind: true,
inside: {
'filter-name': {
pattern: /^:[\w-]+/,
alias: 'variable'
}
}
},
'multiline-plain-text': {
pattern: /(^([\t ]*)[\w\-#.]+\.[\t ]*)((?:\r?\n|\r(?!\n))(?:\2[\t ]+.+|\s*?(?=\r?\n|\r)))+/m,
lookbehind: true
},
'markup': {
pattern: /(^[\t ]*)<.+/m,
lookbehind: true,
inside: {
rest: Prism.languages.markup
}
},
'doctype': {
pattern: /((?:^|\n)[\t ]*)doctype(?: .+)?/,
lookbehind: true
},
// This handle all conditional and loop keywords
'flow-control': {
pattern: /(^[\t ]*)(?:if|unless|else|case|when|default|each|while)\b(?: .+)?/m,
lookbehind: true,
inside: {
'each': {
pattern: /^each .+? in\b/,
inside: {
'keyword': /\b(?:each|in)\b/,
'punctuation': /,/
}
},
'branch': {
pattern: /^(?:if|unless|else|case|when|default|while)\b/,
alias: 'keyword'
},
rest: Prism.languages.javascript
}
},
'keyword': {
pattern: /(^[\t ]*)(?:block|extends|include|append|prepend)\b.+/m,
lookbehind: true
},
'mixin': [
// Declaration
{
pattern: /(^[\t ]*)mixin .+/m,
lookbehind: true,
inside: {
'keyword': /^mixin/,
'function': /\w+(?=\s*\(|\s*$)/,
'punctuation': /[(),.]/
}
},
// Usage
{
pattern: /(^[\t ]*)\+.+/m,
lookbehind: true,
inside: {
'name': {
pattern: /^\+\w+/,
alias: 'function'
},
'rest': Prism.languages.javascript
}
}
],
'script': {
pattern: /(^[\t ]*script(?:(?:&[^(]+)?\([^)]+\))*[\t ]+).+/m,
lookbehind: true,
inside: {
rest: Prism.languages.javascript
}
},
'plain-text': {
pattern: /(^[\t ]*(?!-)[\w\-#.]*[\w\-](?:(?:&[^(]+)?\([^)]+\))*\/?[\t ]+).+/m,
lookbehind: true
},
'tag': {
pattern: /(^[\t ]*)(?!-)[\w\-#.]*[\w\-](?:(?:&[^(]+)?\([^)]+\))*\/?:?/m,
lookbehind: true,
inside: {
'attributes': [
{
pattern: /&[^(]+\([^)]+\)/,
inside: {
rest: Prism.languages.javascript
}
},
{
pattern: /\([^)]+\)/,
inside: {
'attr-value': {
pattern: /(=\s*)(?:\{[^}]*\}|[^,)\r\n]+)/,
lookbehind: true,
inside: {
rest: Prism.languages.javascript
}
},
'attr-name': /[\w-]+(?=\s*!?=|\s*[,)])/,
'punctuation': /[!=(),]+/
}
}
],
'punctuation': /:/
}
},
'code': [
{
pattern: /(^[\t ]*(?:-|!?=)).+/m,
lookbehind: true,
inside: {
rest: Prism.languages.javascript
}
}
],
'punctuation': /[.\-!=|]+/
};
var filter_pattern = '(^([\\t ]*)):{{filter_name}}((?:\\r?\\n|\\r(?!\\n))(?:\\2[\\t ]+.+|\\s*?(?=\\r?\\n|\\r)))+';
// Non exhaustive list of available filters and associated languages
var filters = [
{filter:'atpl',language:'twig'},
{filter:'coffee',language:'coffeescript'},
'ejs',
'handlebars',
'hogan',
'less',
'livescript',
'markdown',
'mustache',
'plates',
{filter:'sass',language:'scss'},
'stylus',
'swig'
];
var all_filters = {};
for (var i = 0, l = filters.length; i < l; i++) {
var filter = filters[i];
filter = typeof filter === 'string' ? {filter: filter, language: filter} : filter;
if (Prism.languages[filter.language]) {
all_filters['filter-' + filter.filter] = {
pattern: RegExp(filter_pattern.replace('{{filter_name}}', filter.filter), 'm'),
lookbehind: true,
inside: {
'filter-name': {
pattern: /^:[\w-]+/,
alias: 'variable'
},
rest: Prism.languages[filter.language]
}
}
}
}
Prism.languages.insertBefore('jade', 'filter', all_filters);
}(Prism));
Prism.languages.java = Prism.languages.extend('clike', {
'keyword': /\b(abstract|continue|for|new|switch|assert|default|goto|package|synchronized|boolean|do|if|private|this|break|double|implements|protected|throw|byte|else|import|public|throws|case|enum|instanceof|return|transient|catch|extends|int|short|try|char|final|interface|static|void|class|finally|long|strictfp|volatile|const|float|native|super|while)\b/,
'number': /\b0b[01]+\b|\b0x[\da-f]*\.?[\da-fp\-]+\b|\b\d*\.?\d+(?:e[+-]?\d+)?[df]?\b/i,
'operator': {
pattern: /(^|[^.])(?:\+[+=]?|-[-=]?|!=?|<<?=?|>>?>?=?|==?|&[&=]?|\|[|=]?|\*=?|\/=?|%=?|\^=?|[?:~])/m,
lookbehind: true
}
});
/* FIXME :
:extend() is not handled specifically : its highlighting is buggy.
Mixin usage must be inside a ruleset to be highlighted.
At-rules (e.g. import) containing interpolations are buggy.
Detached rulesets are highlighted as at-rules.
A comment before a mixin usage prevents the latter to be properly highlighted.
*/
Prism.languages.less = Prism.languages.extend('css', {
'comment': [
/\/\*[\w\W]*?\*\//,
{
pattern: /(^|[^\\])\/\/.*/,
lookbehind: true
}
],
'atrule': {
pattern: /@[\w-]+?(?:\([^{}]+\)|[^(){};])*?(?=\s*\{)/i,
inside: {
'punctuation': /[:()]/
}
},
// selectors and mixins are considered the same
'selector': {
pattern: /(?:@\{[\w-]+\}|[^{};\s@])(?:@\{[\w-]+\}|\([^{}]*\)|[^{};@])*?(?=\s*\{)/,
inside: {
// mixin parameters
'variable': /@+[\w-]+/
}
},
'property': /(?:@\{[\w-]+\}|[\w-])+(?:\+_?)?(?=\s*:)/i,
'punctuation': /[{}();:,]/,
'operator': /[+\-*\/]/
});
// Invert function and punctuation positions
Prism.languages.insertBefore('less', 'punctuation', {
'function': Prism.languages.less.function
});
Prism.languages.insertBefore('less', 'property', {
'variable': [
// Variable declaration (the colon must be consumed!)
{
pattern: /@[\w-]+\s*:/,
inside: {
"punctuation": /:/
}
},
// Variable usage
/@@?[\w-]+/
],
'mixin-usage': {
pattern: /([{;]\s*)[.#](?!\d)[\w-]+.*?(?=[(;])/,
lookbehind: true,
alias: 'function'
}
});
Prism.languages.lua = {
'comment': /^#!.+|--(?:\[(=*)\[[\s\S]*?\]\1\]|.*)/m,
// \z may be used to skip the following space
'string': /(["'])(?:(?!\1)[^\\\r\n]|\\z(?:\r\n|\s)|\\(?:\r\n|[\s\S]))*\1|\[(=*)\[[\s\S]*?\]\2\]/,
'number': /\b0x[a-f\d]+\.?[a-f\d]*(?:p[+-]?\d+)?\b|\b\d+(?:\.\B|\.?\d*(?:e[+-]?\d+)?\b)|\B\.\d+(?:e[+-]?\d+)?\b/i,
'keyword': /\b(?:and|break|do|else|elseif|end|false|for|function|goto|if|in|local|nil|not|or|repeat|return|then|true|until|while)\b/,
'function': /(?!\d)\w+(?=\s*(?:[({]))/,
'operator': [
/[-+*%^&|#]|\/\/?|<[<=]?|>[>=]?|[=~]=?/,
{
// Match ".." but don't break "..."
pattern: /(^|[^.])\.\.(?!\.)/,
lookbehind: true
}
],
'punctuation': /[\[\](){},;]|\.+|:+/
};
Prism.languages.markdown = Prism.languages.extend('markup', {});
Prism.languages.insertBefore('markdown', 'prolog', {
'blockquote': {
// > ...
pattern: /^>(?:[\t ]*>)*/m,
alias: 'punctuation'
},
'code': [
{
// Prefixed by 4 spaces or 1 tab
pattern: /^(?: {4}|\t).+/m,
alias: 'keyword'
},
{
// `code`
// ``code``
pattern: /``.+?``|`[^`\n]+`/,
alias: 'keyword'
}
],
'title': [
{
// title 1
// =======
// title 2
// -------
pattern: /\w+.*(?:\r?\n|\r)(?:==+|--+)/,
alias: 'important',
inside: {
punctuation: /==+$|--+$/
}
},
{
// # title 1
// ###### title 6
pattern: /(^\s*)#+.+/m,
lookbehind: true,
alias: 'important',
inside: {
punctuation: /^#+|#+$/
}
}
],
'hr': {
// ***
// ---
// * * *
// -----------
pattern: /(^\s*)([*-])([\t ]*\2){2,}(?=\s*$)/m,
lookbehind: true,
alias: 'punctuation'
},
'list': {
// * item
// + item
// - item
// 1. item
pattern: /(^\s*)(?:[*+-]|\d+\.)(?=[\t ].)/m,
lookbehind: true,
alias: 'punctuation'
},
'url-reference': {
// [id]: http://example.com "Optional title"
// [id]: http://example.com 'Optional title'
// [id]: http://example.com (Optional title)
// [id]: <http://example.com> "Optional title"
pattern: /!?\[[^\]]+\]:[\t ]+(?:\S+|<(?:\\.|[^>\\])+>)(?:[\t ]+(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\)))?/,
inside: {
'variable': {
pattern: /^(!?\[)[^\]]+/,
lookbehind: true
},
'string': /(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\))$/,
'punctuation': /^[\[\]!:]|[<>]/
},
alias: 'url'
},
'bold': {
// **strong**
// __strong__
// Allow only one line break
pattern: /(^|[^\\])(\*\*|__)(?:(?:\r?\n|\r)(?!\r?\n|\r)|.)+?\2/,
lookbehind: true,
inside: {
'punctuation': /^\*\*|^__|\*\*$|__$/
}
},
'italic': {
// *em*
// _em_
// Allow only one line break
pattern: /(^|[^\\])([*_])(?:(?:\r?\n|\r)(?!\r?\n|\r)|.)+?\2/,
lookbehind: true,
inside: {
'punctuation': /^[*_]|[*_]$/
}
},
'url': {
// [example](http://example.com "Optional title")
// [example] [id]
pattern: /!?\[[^\]]+\](?:\([^\s)]+(?:[\t ]+"(?:\\.|[^"\\])*")?\)| ?\[[^\]\n]*\])/,
inside: {
'variable': {
pattern: /(!?\[)[^\]]+(?=\]$)/,
lookbehind: true
},
'string': {
pattern: /"(?:\\.|[^"\\])*"(?=\)$)/
}
}
}
});
Prism.languages.markdown['bold'].inside['url'] = Prism.util.clone(Prism.languages.markdown['url']);
Prism.languages.markdown['italic'].inside['url'] = Prism.util.clone(Prism.languages.markdown['url']);
Prism.languages.markdown['bold'].inside['italic'] = Prism.util.clone(Prism.languages.markdown['italic']);
Prism.languages.markdown['italic'].inside['bold'] = Prism.util.clone(Prism.languages.markdown['bold']);
Prism.languages.perl = {
'comment': [
{
// POD
pattern: /(^\s*)=\w+[\s\S]*?=cut.*/m,
lookbehind: true
},
{
pattern: /(^|[^\\$])#.*/,
lookbehind: true
}
],
// TODO Could be nice to handle Heredoc too.
'string': [
// q/.../
/\b(?:q|qq|qx|qw)\s*([^a-zA-Z0-9\s\{\(\[<])(?:[^\\]|\\[\s\S])*?\1/,
// q a...a
/\b(?:q|qq|qx|qw)\s+([a-zA-Z0-9])(?:[^\\]|\\[\s\S])*?\1/,
// q(...)
/\b(?:q|qq|qx|qw)\s*\((?:[^()\\]|\\[\s\S])*\)/,
// q{...}
/\b(?:q|qq|qx|qw)\s*\{(?:[^{}\\]|\\[\s\S])*\}/,
// q[...]
/\b(?:q|qq|qx|qw)\s*\[(?:[^[\]\\]|\\[\s\S])*\]/,
// q<...>
/\b(?:q|qq|qx|qw)\s*<(?:[^<>\\]|\\[\s\S])*>/,
// "...", `...`
/("|`)(?:[^\\]|\\[\s\S])*?\1/,
// '...'
// FIXME Multi-line single-quoted strings are not supported as they would break variables containing '
/'(?:[^'\\\r\n]|\\.)*'/
],
'regex': [
// m/.../
/\b(?:m|qr)\s*([^a-zA-Z0-9\s\{\(\[<])(?:[^\\]|\\[\s\S])*?\1[msixpodualngc]*/,
// m a...a
/\b(?:m|qr)\s+([a-zA-Z0-9])(?:[^\\]|\\.)*?\1[msixpodualngc]*/,
// m(...)
/\b(?:m|qr)\s*\((?:[^()\\]|\\[\s\S])*\)[msixpodualngc]*/,
// m{...}
/\b(?:m|qr)\s*\{(?:[^{}\\]|\\[\s\S])*\}[msixpodualngc]*/,
// m[...]
/\b(?:m|qr)\s*\[(?:[^[\]\\]|\\[\s\S])*\][msixpodualngc]*/,
// m<...>
/\b(?:m|qr)\s*<(?:[^<>\\]|\\[\s\S])*>[msixpodualngc]*/,
// The lookbehinds prevent -s from breaking
// FIXME We don't handle change of separator like s(...)[...]
// s/.../.../
{
pattern: /(^|[^-]\b)(?:s|tr|y)\s*([^a-zA-Z0-9\s\{\(\[<])(?:[^\\]|\\[\s\S])*?\2(?:[^\\]|\\[\s\S])*?\2[msixpodualngcer]*/,
lookbehind: true
},
// s a...a...a
{
pattern: /(^|[^-]\b)(?:s|tr|y)\s+([a-zA-Z0-9])(?:[^\\]|\\[\s\S])*?\2(?:[^\\]|\\[\s\S])*?\2[msixpodualngcer]*/,
lookbehind: true
},
// s(...)(...)
{
pattern: /(^|[^-]\b)(?:s|tr|y)\s*\((?:[^()\\]|\\[\s\S])*\)\s*\((?:[^()\\]|\\[\s\S])*\)[msixpodualngcer]*/,
lookbehind: true
},
// s{...}{...}
{
pattern: /(^|[^-]\b)(?:s|tr|y)\s*\{(?:[^{}\\]|\\[\s\S])*\}\s*\{(?:[^{}\\]|\\[\s\S])*\}[msixpodualngcer]*/,
lookbehind: true
},
// s[...][...]
{
pattern: /(^|[^-]\b)(?:s|tr|y)\s*\[(?:[^[\]\\]|\\[\s\S])*\]\s*\[(?:[^[\]\\]|\\[\s\S])*\][msixpodualngcer]*/,
lookbehind: true
},
// s<...><...>
{
pattern: /(^|[^-]\b)(?:s|tr|y)\s*<(?:[^<>\\]|\\[\s\S])*>\s*<(?:[^<>\\]|\\[\s\S])*>[msixpodualngcer]*/,
lookbehind: true
},
// /.../
// The look-ahead tries to prevent two divisions on
// the same line from being highlighted as regex.
// This does not support multi-line regex.
/\/(?:[^\/\\\r\n]|\\.)*\/[msixpodualngc]*(?=\s*(?:$|[\r\n,.;})&|\-+*~<>!?^]|(lt|gt|le|ge|eq|ne|cmp|not|and|or|xor|x)\b))/
],
// FIXME Not sure about the handling of ::, ', and #
'variable': [
// ${^POSTMATCH}
/[&*$@%]\{\^[A-Z]+\}/,
// $^V
/[&*$@%]\^[A-Z_]/,
// ${...}
/[&*$@%]#?(?=\{)/,
// $foo
/[&*$@%]#?((::)*'?(?!\d)[\w$]+)+(::)*/i,
// $1
/[&*$@%]\d+/,
// $_, @_, %!
// The negative lookahead prevents from breaking the %= operator
/(?!%=)[$@%][!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/
],
'filehandle': {
// <>, <FOO>, _
pattern: /<(?![<=])\S*>|\b_\b/,
alias: 'symbol'
},
'vstring': {
// v1.2, 1.2.3
pattern: /v\d+(\.\d+)*|\d+(\.\d+){2,}/,
alias: 'string'
},
'function': {
pattern: /sub [a-z0-9_]+/i,
inside: {
keyword: /sub/
}
},
'keyword': /\b(any|break|continue|default|delete|die|do|else|elsif|eval|for|foreach|given|goto|if|last|local|my|next|our|package|print|redo|require|say|state|sub|switch|undef|unless|until|use|when|while)\b/,
'number': /\b-?(0x[\dA-Fa-f](_?[\dA-Fa-f])*|0b[01](_?[01])*|(\d(_?\d)*)?\.?\d(_?\d)*([Ee][+-]?\d+)?)\b/,
'operator': /-[rwxoRWXOezsfdlpSbctugkTBMAC]\b|\+[+=]?|-[-=>]?|\*\*?=?|\/\/?=?|=[=~>]?|~[~=]?|\|\|?=?|&&?=?|<(?:=>?|<=?)?|>>?=?|![~=]?|[%^]=?|\.(?:=|\.\.?)?|[\\?]|\bx(?:=|\b)|\b(lt|gt|le|ge|eq|ne|cmp|not|and|or|xor)\b/,
'punctuation': /[{}[\];(),:]/
};
/**
* Original by Aaron Harun: http://aahacreative.com/2012/07/31/php-syntax-highlighting-prism/
* Modified by Miles Johnson: http://milesj.me
*
* Supports the following:
* - Extends clike syntax
* - Support for PHP 5.3+ (namespaces, traits, generators, etc)
* - Smarter constant and function matching
*
* Adds the following new token classes:
* constant, delimiter, variable, function, package
*/
Prism.languages.php = Prism.languages.extend('clike', {
'keyword': /\b(and|or|xor|array|as|break|case|cfunction|class|const|continue|declare|default|die|do|else|elseif|enddeclare|endfor|endforeach|endif|endswitch|endwhile|extends|for|foreach|function|include|include_once|global|if|new|return|static|switch|use|require|require_once|var|while|abstract|interface|public|implements|private|protected|parent|throw|null|echo|print|trait|namespace|final|yield|goto|instanceof|finally|try|catch)\b/i,
'constant': /\b[A-Z0-9_]{2,}\b/,
'comment': {
pattern: /(^|[^\\])(?:\/\*[\w\W]*?\*\/|\/\/.*)/,
lookbehind: true
}
});
// Shell-like comments are matched after strings, because they are less
// common than strings containing hashes...
Prism.languages.insertBefore('php', 'class-name', {
'shell-comment': {
pattern: /(^|[^\\])#.*/,
lookbehind: true,
alias: 'comment'
}
});
Prism.languages.insertBefore('php', 'keyword', {
'delimiter': /\?>|<\?(?:php)?/i,
'variable': /\$\w+\b/i,
'package': {
pattern: /(\\|namespace\s+|use\s+)[\w\\]+/,
lookbehind: true,
inside: {
punctuation: /\\/
}
}
});
// Must be defined after the function pattern
Prism.languages.insertBefore('php', 'operator', {
'property': {
pattern: /(->)[\w]+/,
lookbehind: true
}
});
// Add HTML support of the markup language exists
if (Prism.languages.markup) {
// Tokenize all inline PHP blocks that are wrapped in <?php ?>
// This allows for easy PHP + markup highlighting
Prism.hooks.add('before-highlight', function(env) {
if (env.language !== 'php') {
return;
}
env.tokenStack = [];
env.backupCode = env.code;
env.code = env.code.replace(/(?:<\?php|<\?)[\w\W]*?(?:\?>)/ig, function(match) {
env.tokenStack.push(match);
return '{{{PHP' + env.tokenStack.length + '}}}';
});
});
// Restore env.code for other plugins (e.g. line-numbers)
Prism.hooks.add('before-insert', function(env) {
if (env.language === 'php') {
env.code = env.backupCode;
delete env.backupCode;
}
});
// Re-insert the tokens after highlighting
Prism.hooks.add('after-highlight', function(env) {
if (env.language !== 'php') {
return;
}
for (var i = 0, t; t = env.tokenStack[i]; i++) {
// The replace prevents $$, $&, $`, $', $n, $nn from being interpreted as special patterns
env.highlightedCode = env.highlightedCode.replace('{{{PHP' + (i + 1) + '}}}', Prism.highlight(t, env.grammar, 'php').replace(/\$/g, '$$$$'));
}
env.element.innerHTML = env.highlightedCode;
});
// Wrap tokens in classes that are missing them
Prism.hooks.add('wrap', function(env) {
if (env.language === 'php' && env.type === 'markup') {
env.content = env.content.replace(/(\{\{\{PHP[0-9]+\}\}\})/g, "<span class=\"token php\">$1</span>");
}
});
// Add the rules before all others
Prism.languages.insertBefore('php', 'comment', {
'markup': {
pattern: /<[^?]\/?(.*?)>/,
inside: Prism.languages.markup
},
'php': /\{\{\{PHP[0-9]+\}\}\}/
});
}
;
Prism.languages.insertBefore('php', 'variable', {
'this': /\$this\b/,
'global': /\$(?:_(?:SERVER|GET|POST|FILES|REQUEST|SESSION|ENV|COOKIE)|GLOBALS|HTTP_RAW_POST_DATA|argc|argv|php_errormsg|http_response_header)/,
'scope': {
pattern: /\b[\w\\]+::/,
inside: {
keyword: /(static|self|parent)/,
punctuation: /(::|\\)/
}
}
});
Prism.languages.powershell = {
'comment': [
{
pattern: /(^|[^`])<#[\w\W]*?#>/,
lookbehind: true
},
{
pattern: /(^|[^`])#.+/,
lookbehind: true
}
],
'string': [
{
pattern: /"(`?[\w\W])*?"/,
inside: {
'function': {
pattern: /[^`]\$\(.*?\)/,
// Populated at end of file
inside: {}
}
}
},
/'([^']|'')*'/
],
// Matches name spaces as well as casts, attribute decorators. Force starting with letter to avoid matching array indices
'namespace': /\[[a-z][\w\W]*?\]/i,
'boolean': /\$(true|false)\b/i,
'variable': /\$\w+\b/i,
// Cmdlets and aliases. Aliases should come last, otherwise "write" gets preferred over "write-host" for example
// Get-Command | ?{ $_.ModuleName -match "Microsoft.PowerShell.(Util|Core|Management)" }
// Get-Alias | ?{ $_.ReferencedCommand.Module.Name -match "Microsoft.PowerShell.(Util|Core|Management)" }
'function': [
/\b(Add-(Computer|Content|History|Member|PSSnapin|Type)|Checkpoint-Computer|Clear-(Content|EventLog|History|Item|ItemProperty|Variable)|Compare-Object|Complete-Transaction|Connect-PSSession|ConvertFrom-(Csv|Json|StringData)|Convert-Path|ConvertTo-(Csv|Html|Json|Xml)|Copy-(Item|ItemProperty)|Debug-Process|Disable-(ComputerRestore|PSBreakpoint|PSRemoting|PSSessionConfiguration)|Disconnect-PSSession|Enable-(ComputerRestore|PSBreakpoint|PSRemoting|PSSessionConfiguration)|Enter-PSSession|Exit-PSSession|Export-(Alias|Clixml|Console|Csv|FormatData|ModuleMember|PSSession)|ForEach-Object|Format-(Custom|List|Table|Wide)|Get-(Alias|ChildItem|Command|ComputerRestorePoint|Content|ControlPanelItem|Culture|Date|Event|EventLog|EventSubscriber|FormatData|Help|History|Host|HotFix|Item|ItemProperty|Job|Location|Member|Module|Process|PSBreakpoint|PSCallStack|PSDrive|PSProvider|PSSession|PSSessionConfiguration|PSSnapin|Random|Service|TraceSource|Transaction|TypeData|UICulture|Unique|Variable|WmiObject)|Group-Object|Import-(Alias|Clixml|Csv|LocalizedData|Module|PSSession)|Invoke-(Command|Expression|History|Item|RestMethod|WebRequest|WmiMethod)|Join-Path|Limit-EventLog|Measure-(Command|Object)|Move-(Item|ItemProperty)|New-(Alias|Event|EventLog|Item|ItemProperty|Module|ModuleManifest|Object|PSDrive|PSSession|PSSessionConfigurationFile|PSSessionOption|PSTransportOption|Service|TimeSpan|Variable|WebServiceProxy)|Out-(Default|File|GridView|Host|Null|Printer|String)|Pop-Location|Push-Location|Read-Host|Receive-(Job|PSSession)|Register-(EngineEvent|ObjectEvent|PSSessionConfiguration|WmiEvent)|Remove-(Computer|Event|EventLog|Item|ItemProperty|Job|Module|PSBreakpoint|PSDrive|PSSession|PSSnapin|TypeData|Variable|WmiObject)|Rename-(Computer|Item|ItemProperty)|Reset-ComputerMachinePassword|Resolve-Path|Restart-(Computer|Service)|Restore-Computer|Resume-(Job|Service)|Save-Help|Select-(Object|String|Xml)|Send-MailMessage|Set-(Alias|Content|Date|Item|ItemProperty|Location|PSBreakpoint|PSDebug|PSSessionConfiguration|Service|StrictMode|TraceSource|Variable|WmiInstance)|Show-(Command|ControlPanelItem|EventLog)|Sort-Object|Split-Path|Start-(Job|Process|Service|Sleep|Transaction)|Stop-(Computer|Job|Process|Service)|Suspend-(Job|Service)|Tee-Object|Test-(ComputerSecureChannel|Connection|ModuleManifest|Path|PSSessionConfigurationFile)|Trace-Command|Unblock-File|Undo-Transaction|Unregister-(Event|PSSessionConfiguration)|Update-(FormatData|Help|List|TypeData)|Use-Transaction|Wait-(Event|Job|Process)|Where-Object|Write-(Debug|Error|EventLog|Host|Output|Progress|Verbose|Warning))\b/i,
/\b(ac|cat|chdir|clc|cli|clp|clv|compare|copy|cp|cpi|cpp|cvpa|dbp|del|diff|dir|ebp|echo|epal|epcsv|epsn|erase|fc|fl|ft|fw|gal|gbp|gc|gci|gcs|gdr|gi|gl|gm|gp|gps|group|gsv|gu|gv|gwmi|iex|ii|ipal|ipcsv|ipsn|irm|iwmi|iwr|kill|lp|ls|measure|mi|mount|move|mp|mv|nal|ndr|ni|nv|ogv|popd|ps|pushd|pwd|rbp|rd|rdr|ren|ri|rm|rmdir|rni|rnp|rp|rv|rvpa|rwmi|sal|saps|sasv|sbp|sc|select|set|shcm|si|sl|sleep|sls|sort|sp|spps|spsv|start|sv|swmi|tee|trcm|type|write)\b/i
],
// per http://technet.microsoft.com/en-us/library/hh847744.aspx
'keyword': /\b(Begin|Break|Catch|Class|Continue|Data|Define|Do|DynamicParam|Else|ElseIf|End|Exit|Filter|Finally|For|ForEach|From|Function|If|InlineScript|Parallel|Param|Process|Return|Sequence|Switch|Throw|Trap|Try|Until|Using|Var|While|Workflow)\b/i,
'operator': {
pattern: /(\W?)(!|-(eq|ne|gt|ge|lt|le|sh[lr]|not|b?(and|x?or)|(Not)?(Like|Match|Contains|In)|Replace|Join|is(Not)?|as)\b|-[-=]?|\+[+=]?|[*\/%]=?)/i,
lookbehind: true
},
'punctuation': /[|{}[\];(),.]/
};
// Variable interpolation inside strings, and nested expressions
Prism.languages.powershell.string[0].inside.boolean = Prism.languages.powershell.boolean;
Prism.languages.powershell.string[0].inside.variable = Prism.languages.powershell.variable;
Prism.languages.powershell.string[0].inside.function.inside = Prism.util.clone(Prism.languages.powershell);
Prism.languages.python= {
'triple-quoted-string': {
pattern: /"""[\s\S]+?"""|'''[\s\S]+?'''/,
alias: 'string'
},
'comment': {
pattern: /(^|[^\\])#.*/,
lookbehind: true
},
'string': /("|')(?:\\?.)*?\1/,
'function' : {
pattern: /((?:^|\s)def[ \t]+)[a-zA-Z_][a-zA-Z0-9_]*(?=\()/g,
lookbehind: true
},
'class-name': {
pattern: /(\bclass\s+)[a-z0-9_]+/i,
lookbehind: true
},
'keyword' : /\b(?:as|assert|async|await|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|pass|print|raise|return|try|while|with|yield)\b/,
'boolean' : /\b(?:True|False)\b/,
'number' : /\b-?(?:0[bo])?(?:(?:\d|0x[\da-f])[\da-f]*\.?\d*|\.\d+)(?:e[+-]?\d+)?j?\b/i,
'operator' : /[-+%=]=?|!=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]|\b(?:or|and|not)\b/,
'punctuation' : /[{}[\];(),.:]/
};
(function(Prism) {
var javascript = Prism.util.clone(Prism.languages.javascript);
Prism.languages.jsx = Prism.languages.extend('markup', javascript);
Prism.languages.jsx.tag.pattern= /<\/?[\w:-]+\s*(?:\s+[\w:-]+(?:=(?:("|')(\\?[\w\W])*?\1|[^\s'">=]+|(\{[\w\W]*?\})))?\s*)*\/?>/i;
Prism.languages.jsx.tag.inside['attr-value'].pattern = /=[^\{](?:('|")[\w\W]*?(\1)|[^\s>]+)/i;
Prism.languages.insertBefore('inside', 'attr-value',{
'script': {
// Allow for one level of nesting
pattern: /=(\{(?:\{[^}]*\}|[^}])+\})/i,
inside: {
'function' : Prism.languages.javascript.function,
'punctuation': /[={}[\];(),.:]/,
'keyword': Prism.languages.javascript.keyword,
'boolean': Prism.languages.javascript.boolean
},
'alias': 'language-javascript'
}
}, Prism.languages.jsx.tag);
}(Prism));
Prism.languages.rest = {
'table': [
{
pattern: /(\s*)(?:\+[=-]+)+\+(?:\r?\n|\r)(?:\1(?:[+|].+)+[+|](?:\r?\n|\r))+\1(?:\+[=-]+)+\+/,
lookbehind: true,
inside: {
'punctuation': /\||(?:\+[=-]+)+\+/
}
},
{
pattern: /(\s*)(?:=+ +)+=+((?:\r?\n|\r)\1.+)+(?:\r?\n|\r)\1(?:=+ +)+=+(?=(?:\r?\n|\r){2}|\s*$)/,
lookbehind: true,
inside: {
'punctuation': /[=-]+/
}
}
],
// Directive-like patterns
'substitution-def': {
pattern: /(^\s*\.\. )\|(?:[^|\s](?:[^|]*[^|\s])?)\| [^:]+::/m,
lookbehind: true,
inside: {
'substitution': {
pattern: /^\|(?:[^|\s]|[^|\s][^|]*[^|\s])\|/,
alias: 'attr-value',
inside: {
'punctuation': /^\||\|$/
}
},
'directive': {
pattern: /( +)[^:]+::/,
lookbehind: true,
alias: 'function',
inside: {
'punctuation': /::$/
}
}
}
},
'link-target': [
{
pattern: /(^\s*\.\. )\[[^\]]+\]/m,
lookbehind: true,
alias: 'string',
inside: {
'punctuation': /^\[|\]$/
}
},
{
pattern: /(^\s*\.\. )_(?:`[^`]+`|(?:[^:\\]|\\.)+):/m,
lookbehind: true,
alias: 'string',
inside: {
'punctuation': /^_|:$/
}
}
],
'directive': {
pattern: /(^\s*\.\. )[^:]+::/m,
lookbehind: true,
alias: 'function',
inside: {
'punctuation': /::$/
}
},
'comment': {
// The two alternatives try to prevent highlighting of blank comments
pattern: /(^\s*\.\.)(?:(?: .+)?(?:(?:\r?\n|\r).+)+| .+)(?=(?:\r?\n|\r){2}|$)/m,
lookbehind: true
},
'title': [
// Overlined and underlined
{
pattern: /^(([!"#$%&'()*+,\-.\/:;<=>?@\[\\\]^_`{|}~])\2+)(?:\r?\n|\r).+(?:\r?\n|\r)\1$/m,
inside: {
'punctuation': /^[!"#$%&'()*+,\-.\/:;<=>?@\[\\\]^_`{|}~]+|[!"#$%&'()*+,\-.\/:;<=>?@\[\\\]^_`{|}~]+$/,
'important': /.+/
}
},
// Underlined only
{
pattern: /(^|(?:\r?\n|\r){2}).+(?:\r?\n|\r)([!"#$%&'()*+,\-.\/:;<=>?@\[\\\]^_`{|}~])\2+(?=\r?\n|\r|$)/,
lookbehind: true,
inside: {
'punctuation': /[!"#$%&'()*+,\-.\/:;<=>?@\[\\\]^_`{|}~]+$/,
'important': /.+/
}
}
],
'hr': {
pattern: /((?:\r?\n|\r){2})([!"#$%&'()*+,\-.\/:;<=>?@\[\\\]^_`{|}~])\2{3,}(?=(?:\r?\n|\r){2})/,
lookbehind: true,
alias: 'punctuation'
},
'field': {
pattern: /(^\s*):[^:\r\n]+:(?= )/m,
lookbehind: true,
alias: 'attr-name'
},
'command-line-option': {
pattern: /(^\s*)(?:[+-][a-z\d]|(?:\-\-|\/)[a-z\d-]+)(?:[ =](?:[a-z][a-z\d_-]*|<[^<>]+>))?(?:, (?:[+-][a-z\d]|(?:\-\-|\/)[a-z\d-]+)(?:[ =](?:[a-z][a-z\d_-]*|<[^<>]+>))?)*(?=(?:\r?\n|\r)? {2,}\S)/im,
lookbehind: true,
alias: 'symbol'
},
'literal-block': {
pattern: /::(?:\r?\n|\r){2}([ \t]+).+(?:(?:\r?\n|\r)\1.+)*/,
inside: {
'literal-block-punctuation': {
pattern: /^::/,
alias: 'punctuation'
}
}
},
'quoted-literal-block': {
pattern: /::(?:\r?\n|\r){2}([!"#$%&'()*+,\-.\/:;<=>?@\[\\\]^_`{|}~]).*(?:(?:\r?\n|\r)\1.*)*/,
inside: {
'literal-block-punctuation': {
pattern: /^(?:::|([!"#$%&'()*+,\-.\/:;<=>?@\[\\\]^_`{|}~])\1*)/m,
alias: 'punctuation'
}
}
},
'list-bullet': {
pattern: /(^\s*)(?:[*+\-•‣⁃]|\(?(?:\d+|[a-z]|[ivxdclm]+)\)|(?:\d+|[a-z]|[ivxdclm]+)\.)(?= )/im,
lookbehind: true,
alias: 'punctuation'
},
'doctest-block': {
pattern: /(^\s*)>>> .+(?:(?:\r?\n|\r).+)*/m,
lookbehind: true,
inside: {
'punctuation': /^>>>/
}
},
'inline': [
{
pattern: /(^|[\s\-:\/'"<(\[{])(?::[^:]+:`.*?`|`.*?`:[^:]+:|(\*\*?|``?|\|)(?!\s).*?[^\s]\2(?=[\s\-.,:;!?\\\/'")\]}]|$))/m,
lookbehind: true,
inside: {
'bold': {
pattern: /(^\*\*).+(?=\*\*$)/,
lookbehind: true
},
'italic': {
pattern: /(^\*).+(?=\*$)/,
lookbehind: true
},
'inline-literal': {
pattern: /(^``).+(?=``$)/,
lookbehind: true,
alias: 'symbol'
},
'role': {
pattern: /^:[^:]+:|:[^:]+:$/,
alias: 'function',
inside: {
'punctuation': /^:|:$/
}
},
'interpreted-text': {
pattern: /(^`).+(?=`$)/,
lookbehind: true,
alias: 'attr-value'
},
'substitution': {
pattern: /(^\|).+(?=\|$)/,
lookbehind: true,
alias: 'attr-value'
},
'punctuation': /\*\*?|``?|\|/
}
}
],
'link': [
{
pattern: /\[[^\]]+\]_(?=[\s\-.,:;!?\\\/'")\]}]|$)/,
alias: 'string',
inside: {
'punctuation': /^\[|\]_$/
}
},
{
pattern: /(?:\b[a-z\d](?:[_.:+]?[a-z\d]+)*_?_|`[^`]+`_?_|_`[^`]+`)(?=[\s\-.,:;!?\\\/'")\]}]|$)/i,
alias: 'string',
inside: {
'punctuation': /^_?`|`$|`?_?_$/
}
}
],
// Line block start,
// quote attribution,
// explicit markup start,
// and anonymous hyperlink target shortcut (__)
'punctuation': {
pattern: /(^\s*)(?:\|(?= |$)|(?:---?|—|\.\.|__)(?= )|\.\.$)/m,
lookbehind: true
}
};
/* TODO
Add support for Markdown notation inside doc comments
Add support for nested block comments...
Match closure params even when not followed by dash or brace
Add better support for macro definition
*/
Prism.languages.rust = {
'comment': [
{
pattern: /(^|[^\\])\/\*[\w\W]*?\*\//,
lookbehind: true
},
{
pattern: /(^|[^\\:])\/\/.*/,
lookbehind: true
}
],
'string': [
/b?r(#*)"(?:\\?.)*?"\1/,
/b?("|')(?:\\?.)*?\1/
],
'keyword': /\b(?:abstract|alignof|as|be|box|break|const|continue|crate|do|else|enum|extern|false|final|fn|for|if|impl|in|let|loop|match|mod|move|mut|offsetof|once|override|priv|pub|pure|ref|return|sizeof|static|self|struct|super|true|trait|type|typeof|unsafe|unsized|use|virtual|where|while|yield)\b/,
'attribute': {
pattern: /#!?\[.+?\]/,
alias: 'attr-name'
},
'function': [
/[a-z0-9_]+(?=\s*\()/i,
// Macros can use parens or brackets
/[a-z0-9_]+!(?=\s*\(|\[)/i
],
'macro-rules': {
pattern: /[a-z0-9_]+!/i,
alias: 'function'
},
// Hex, oct, bin, dec numbers with visual separators and type suffix
'number': /\b-?(?:0x[\dA-Fa-f](?:_?[\dA-Fa-f])*|0o[0-7](?:_?[0-7])*|0b[01](?:_?[01])*|(\d(_?\d)*)?\.?\d(_?\d)*([Ee][+-]?\d+)?)(?:_?(?:[iu](?:8|16|32|64)?|f32|f64))?\b/,
// Closure params should not be confused with bitwise OR |
'closure-params': {
pattern: /\|[^|]*\|(?=\s*[{-])/,
inside: {
'punctuation': /[\|:,]/,
'operator': /[&*]/
}
},
'punctuation': /[{}[\];(),:]|\.+|->/,
'operator': /[-+*\/%!^=]=?|@|&[&=]?|\|[|=]?|<<?=?|>>?=?/
};
(function(Prism) {
Prism.languages.sass = Prism.languages.extend('css', {
// Sass comments don't need to be closed, only indented
'comment': {
pattern: /^([ \t]*)\/[\/*].*(?:(?:\r?\n|\r)\1[ \t]+.+)*/m,
lookbehind: true
}
});
Prism.languages.insertBefore('sass', 'atrule', {
// We want to consume the whole line
'atrule-line': {
// Includes support for = and + shortcuts
pattern: /^(?:[ \t]*)[@+=].+/m,
inside: {
'atrule': /(?:@[\w-]+|[+=])/m
}
}
});
delete Prism.languages.sass.atrule;
var variable = /((\$[-_\w]+)|(#\{\$[-_\w]+\}))/i;
var operator = [
/[+*\/%]|[=!]=|<=?|>=?|\b(?:and|or|not)\b/,
{
pattern: /(\s+)-(?=\s)/,
lookbehind: true
}
];
Prism.languages.insertBefore('sass', 'property', {
// We want to consume the whole line
'variable-line': {
pattern: /^[ \t]*\$.+/m,
inside: {
'punctuation': /:/,
'variable': variable,
'operator': operator
}
},
// We want to consume the whole line
'property-line': {
pattern: /^[ \t]*(?:[^:\s]+ *:.*|:[^:\s]+.*)/m,
inside: {
'property': [
/[^:\s]+(?=\s*:)/,
{
pattern: /(:)[^:\s]+/,
lookbehind: true
}
],
'punctuation': /:/,
'variable': variable,
'operator': operator,
'important': Prism.languages.sass.important
}
}
});
delete Prism.languages.sass.property;
delete Prism.languages.sass.important;
// Now that whole lines for other patterns are consumed,
// what's left should be selectors
delete Prism.languages.sass.selector;
Prism.languages.insertBefore('sass', 'punctuation', {
'selector': {
pattern: /([ \t]*)\S(?:,?[^,\r\n]+)*(?:,(?:\r?\n|\r)\1[ \t]+\S(?:,?[^,\r\n]+)*)*/,
lookbehind: true
}
});
}(Prism));
Prism.languages.scss = Prism.languages.extend('css', {
'comment': {
pattern: /(^|[^\\])(?:\/\*[\w\W]*?\*\/|\/\/.*)/,
lookbehind: true
},
'atrule': {
pattern: /@[\w-]+(?:\([^()]+\)|[^(])*?(?=\s+[{;])/,
inside: {
'rule': /@[\w-]+/
// See rest below
}
},
// url, compassified
'url': /(?:[-a-z]+-)*url(?=\()/i,
// CSS selector regex is not appropriate for Sass
// since there can be lot more things (var, @ directive, nesting..)
// a selector must start at the end of a property or after a brace (end of other rules or nesting)
// it can contain some characters that aren't used for defining rules or end of selector, & (parent selector), or interpolated variable
// the end of a selector is found when there is no rules in it ( {} or {\s}) or if there is a property (because an interpolated var
// can "pass" as a selector- e.g: proper#{$erty})
// this one was hard to do, so please be careful if you edit this one :)
'selector': {
// Initial look-ahead is used to prevent matching of blank selectors
pattern: /(?=\S)[^@;\{\}\(\)]?([^@;\{\}\(\)]|&|#\{\$[-_\w]+\})+(?=\s*\{(\}|\s|[^\}]+(:|\{)[^\}]+))/m,
inside: {
'placeholder': /%[-_\w]+/
}
}
});
Prism.languages.insertBefore('scss', 'atrule', {
'keyword': [
/@(?:if|else(?: if)?|for|each|while|import|extend|debug|warn|mixin|include|function|return|content)/i,
{
pattern: /( +)(?:from|through)(?= )/,
lookbehind: true
}
]
});
Prism.languages.insertBefore('scss', 'property', {
// var and interpolated vars
'variable': /\$[-_\w]+|#\{\$[-_\w]+\}/
});
Prism.languages.insertBefore('scss', 'function', {
'placeholder': {
pattern: /%[-_\w]+/,
alias: 'selector'
},
'statement': /\B!(?:default|optional)\b/i,
'boolean': /\b(?:true|false)\b/,
'null': /\bnull\b/,
'operator': {
pattern: /(\s)(?:[-+*\/%]|[=!]=|<=?|>=?|and|or|not)(?=\s)/,
lookbehind: true
}
});
Prism.languages.scss['atrule'].inside.rest = Prism.util.clone(Prism.languages.scss);
Prism.languages.scala = Prism.languages.extend('java', {
'keyword': /<-|=>|\b(?:abstract|case|catch|class|def|do|else|extends|final|finally|for|forSome|if|implicit|import|lazy|match|new|null|object|override|package|private|protected|return|sealed|self|super|this|throw|trait|try|type|val|var|while|with|yield)\b/,
'string': /"""[\W\w]*?"""|"(?:[^"\\\r\n]|\\.)*"|'(?:[^\\\r\n']|\\.[^\\']*)'/,
'builtin': /\b(?:String|Int|Long|Short|Byte|Boolean|Double|Float|Char|Any|AnyRef|AnyVal|Unit|Nothing)\b/,
'number': /\b(?:0x[\da-f]*\.?[\da-f]+|\d*\.?\d+e?\d*[dfl]?)\b/i,
'symbol': /'[^\d\s\\]\w*/
});
delete Prism.languages.scala['class-name'];
delete Prism.languages.scala['function'];
Prism.languages.sql= {
'comment': {
pattern: /(^|[^\\])(?:\/\*[\w\W]*?\*\/|(?:--|\/\/|#).*)/,
lookbehind: true
},
'string' : {
pattern: /(^|[^@\\])("|')(?:\\?[\s\S])*?\2/,
lookbehind: true
},
'variable': /@[\w.$]+|@("|'|`)(?:\\?[\s\S])+?\1/,
'function': /\b(?:COUNT|SUM|AVG|MIN|MAX|FIRST|LAST|UCASE|LCASE|MID|LEN|ROUND|NOW|FORMAT)(?=\s*\()/i, // Should we highlight user defined functions too?
'keyword': /\b(?:ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR VARYING|CHARACTER (?:SET|VARYING)|CHARSET|CHECK|CHECKPOINT|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMN|COLUMNS|COMMENT|COMMIT|COMMITTED|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS|CONTAINSTABLE|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|DATA(?:BASES?)?|DATETIME|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE(?: PRECISION)?|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE KEY|ELSE|ENABLE|ENCLOSED BY|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPE(?:D BY)?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|IDENTITY(?:_INSERT|COL)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTO|INVOKER|ISOLATION LEVEL|JOIN|KEYS?|KILL|LANGUAGE SQL|LAST|LEFT|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MODIFIES SQL DATA|MODIFY|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL(?: CHAR VARYING| CHARACTER(?: VARYING)?| VARCHAR)?|NATURAL|NCHAR(?: VARCHAR)?|NEXT|NO(?: SQL|CHECK|CYCLE)?|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READ(?:S SQL DATA|TEXT)?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEATABLE|REPLICATION|REQUIRE|RESTORE|RESTRICT|RETURNS?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE MODE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|START(?:ING BY)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED BY|TEXT(?:SIZE)?|THEN|TIMESTAMP|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNPIVOT|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?)\b/i,
'boolean': /\b(?:TRUE|FALSE|NULL)\b/i,
'number': /\b-?(?:0x)?\d*\.?[\da-f]+\b/,
'operator': /[-+*\/=%^~]|&&?|\|?\||!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|IN|LIKE|NOT|OR|IS|DIV|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/i,
'punctuation': /[;[\]()`,.]/
};
(function (Prism) {
var inside = {
'url': /url\((["']?).*?\1\)/i,
'string': /("|')(?:[^\\\r\n]|\\(?:\r\n|[\s\S]))*?\1/,
'interpolation': null, // See below
'func': null, // See below
'important': /\B!(?:important|optional)\b/i,
'keyword': {
pattern: /(^|\s+)(?:(?:if|else|for|return|unless)(?=\s+|$)|@[\w-]+)/,
lookbehind: true
},
'hexcode': /#[\da-f]{3,6}/i,
'number': /\b\d+(?:\.\d+)?%?/,
'boolean': /\b(?:true|false)\b/,
'operator': [
// We want non-word chars around "-" because it is
// accepted in property names.
/~|[+!\/%<>?=]=?|[-:]=|\*[*=]?|\.+|&&|\|\||\B-\B|\b(?:and|in|is(?: a| defined| not|nt)?|not|or)\b/
],
'punctuation': /[{}()\[\];:,]/
};
inside['interpolation'] = {
pattern: /\{[^\r\n}:]+\}/,
alias: 'variable',
inside: Prism.util.clone(inside)
};
inside['func'] = {
pattern: /[\w-]+\([^)]*\).*/,
inside: {
'function': /^[^(]+/,
rest: Prism.util.clone(inside)
}
};
Prism.languages.stylus = {
'comment': {
pattern: /(^|[^\\])(\/\*[\w\W]*?\*\/|\/\/.*)/,
lookbehind: true
},
'atrule-declaration': {
pattern: /(^\s*)@.+/m,
lookbehind: true,
inside: {
'atrule': /^@[\w-]+/,
rest: inside
}
},
'variable-declaration': {
pattern: /(^[ \t]*)[\w$-]+\s*.?=[ \t]*(?:(?:\{[^}]*\}|.+)|$)/m,
lookbehind: true,
inside: {
'variable': /^\S+/,
rest: inside
}
},
'statement': {
pattern: /(^[ \t]*)(?:if|else|for|return|unless)[ \t]+.+/m,
lookbehind: true,
inside: {
keyword: /^\S+/,
rest: inside
}
},
// A property/value pair cannot end with a comma or a brace
// It cannot have indented content unless it ended with a semicolon
'property-declaration': {
pattern: /((?:^|\{)([ \t]*))(?:[\w-]|\{[^}\r\n]+\})+(?:\s*:\s*|[ \t]+)[^{\r\n]*(?:;|[^{\r\n,](?=$)(?!(\r?\n|\r)(?:\{|\2[ \t]+)))/m,
lookbehind: true,
inside: {
'property': {
pattern: /^[^\s:]+/,
inside: {
'interpolation': inside.interpolation
}
},
rest: inside
}
},
// A selector can contain parentheses only as part of a pseudo-element
// It can span multiple lines.
// It must end with a comma or an accolade or have indented content.
'selector': {
pattern: /(^[ \t]*)(?:(?=\S)(?:[^{}\r\n:()]|::?[\w-]+(?:\([^)\r\n]*\))?|\{[^}\r\n]+\})+)(?:(?:\r?\n|\r)(?:\1(?:(?=\S)(?:[^{}\r\n:()]|::?[\w-]+(?:\([^)\r\n]*\))?|\{[^}\r\n]+\})+)))*(?:,$|\{|(?=(?:\r?\n|\r)(?:\{|\1[ \t]+)))/m,
lookbehind: true,
inside: {
'interpolation': inside.interpolation,
'punctuation': /[{},]/
}
},
'func': inside.func,
'string': inside.string,
'interpolation': inside.interpolation,
'punctuation': /[{}()\[\];:.]/
};
}(Prism));
Prism.languages.typescript = Prism.languages.extend('javascript', {
'keyword': /\b(break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|function|get|if|implements|import|in|instanceof|interface|let|new|null|package|private|protected|public|return|set|static|super|switch|this|throw|true|try|typeof|var|void|while|with|yield|module|declare|constructor|string|Function|any|number|boolean|Array|enum)\b/
});
Prism.languages.wiki = Prism.languages.extend('markup', {
'block-comment': {
pattern: /(^|[^\\])\/\*[\w\W]*?\*\//,
lookbehind: true,
alias: 'comment'
},
'heading': {
pattern: /^(=+).+?\1/m,
inside: {
'punctuation': /^=+|=+$/,
'important': /.+/
}
},
'emphasis': {
// TODO Multi-line
pattern: /('{2,5}).+?\1/,
inside: {
'bold italic': {
pattern: /(''''').+?(?=\1)/,
lookbehind: true
},
'bold': {
pattern: /(''')[^'](?:.*?[^'])?(?=\1)/,
lookbehind: true
},
'italic': {
pattern: /('')[^'](?:.*?[^'])?(?=\1)/,
lookbehind: true
},
'punctuation': /^''+|''+$/
}
},
'hr': {
pattern: /^-{4,}/m,
alias: 'punctuation'
},
'url': [
/ISBN +(?:97[89][ -]?)?(?:\d[ -]?){9}[\dx]\b|(?:RFC|PMID) +\d+/i,
/\[\[.+?\]\]|\[.+?\]/
],
'variable': [
/__[A-Z]+__/,
// FIXME Nested structures should be handled
// {{formatnum:{{#expr:{{{3}}}}}}}
/\{{3}.+?\}{3}/,
/\{\{.+?}}/
],
'symbol': [
/^#redirect/im,
/~{3,5}/
],
// Handle table attrs:
// {|
// ! style="text-align:left;"| Item
// |}
'table-tag': {
pattern: /((?:^|[|!])[|!])[^|\r\n]+\|(?!\|)/m,
lookbehind: true,
inside: {
'table-bar': {
pattern: /\|$/,
alias: 'punctuation'
},
rest: Prism.languages.markup['tag'].inside
}
},
'punctuation': /^(?:\{\||\|\}|\|-|[*#:;!|])|\|\||!!/m
});
Prism.languages.insertBefore('wiki', 'tag', {
// Prevent highlighting inside <nowiki>, <source> and <pre> tags
'nowiki': {
pattern: /<(nowiki|pre|source)\b[\w\W]*?>[\w\W]*?<\/\1>/i,
inside: {
'tag': {
pattern: /<(?:nowiki|pre|source)\b[\w\W]*?>|<\/(?:nowiki|pre|source)>/i,
inside: Prism.languages.markup['tag'].inside
}
}
}
});
Prism.languages.yaml = {
'scalar': {
pattern: /([\-:]\s*(![^\s]+)?[ \t]*[|>])[ \t]*(?:((?:\r?\n|\r)[ \t]+)[^\r\n]+(?:\3[^\r\n]+)*)/,
lookbehind: true,
alias: 'string'
},
'comment': /#.*/,
'key': {
pattern: /(\s*[:\-,[{\r\n?][ \t]*(![^\s]+)?[ \t]*)[^\r\n{[\]},#]+?(?=\s*:\s)/,
lookbehind: true,
alias: 'atrule'
},
'directive': {
pattern: /(^[ \t]*)%.+/m,
lookbehind: true,
alias: 'important'
},
'datetime': {
pattern: /([:\-,[{]\s*(![^\s]+)?[ \t]*)(\d{4}-\d\d?-\d\d?([tT]|[ \t]+)\d\d?:\d{2}:\d{2}(\.\d*)?[ \t]*(Z|[-+]\d\d?(:\d{2})?)?|\d{4}-\d{2}-\d{2}|\d\d?:\d{2}(:\d{2}(\.\d*)?)?)(?=[ \t]*($|,|]|}))/m,
lookbehind: true,
alias: 'number'
},
'boolean': {
pattern: /([:\-,[{]\s*(![^\s]+)?[ \t]*)(true|false)[ \t]*(?=$|,|]|})/im,
lookbehind: true,
alias: 'important'
},
'null': {
pattern: /([:\-,[{]\s*(![^\s]+)?[ \t]*)(null|~)[ \t]*(?=$|,|]|})/im,
lookbehind: true,
alias: 'important'
},
'string': {
pattern: /([:\-,[{]\s*(![^\s]+)?[ \t]*)("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')(?=[ \t]*($|,|]|}))/m,
lookbehind: true
},
'number': {
pattern: /([:\-,[{]\s*(![^\s]+)?[ \t]*)[+\-]?(0x[\da-f]+|0o[0-7]+|(\d+\.?\d*|\.?\d+)(e[\+\-]?\d+)?|\.inf|\.nan)[ \t]*(?=$|,|]|})/im,
lookbehind: true
},
'tag': /![^\s]+/,
'important': /[&*][\w]+/,
'punctuation': /---|[:[\]{}\-,|>?]|\.\.\./
};
(function(){
if (typeof self === 'undefined' || !self.Prism || !self.document || !document.querySelector) {
return;
}
function $$(expr, con) {
return Array.prototype.slice.call((con || document).querySelectorAll(expr));
}
function hasClass(element, className) {
className = " " + className + " ";
return (" " + element.className + " ").replace(/[\n\t]/g, " ").indexOf(className) > -1
}
// Some browsers round the line-height, others don't.
// We need to test for it to position the elements properly.
var isLineHeightRounded = (function() {
var res;
return function() {
if(typeof res === 'undefined') {
var d = document.createElement('div');
d.style.fontSize = '13px';
d.style.lineHeight = '1.5';
d.style.padding = 0;
d.style.border = 0;
d.innerHTML = '&nbsp;<br />&nbsp;';
document.body.appendChild(d);
// Browsers that round the line-height should have offsetHeight === 38
// The others should have 39.
res = d.offsetHeight === 38;
document.body.removeChild(d);
}
return res;
}
}());
function highlightLines(pre, lines, classes) {
var ranges = lines.replace(/\s+/g, '').split(','),
offset = +pre.getAttribute('data-line-offset') || 0;
var parseMethod = isLineHeightRounded() ? parseInt : parseFloat;
var lineHeight = parseMethod(getComputedStyle(pre).lineHeight);
for (var i=0, range; range = ranges[i++];) {
range = range.split('-');
var start = +range[0],
end = +range[1] || start;
var line = document.createElement('div');
line.textContent = Array(end - start + 2).join(' \n');
line.className = (classes || '') + ' line-highlight';
//if the line-numbers plugin is enabled, then there is no reason for this plugin to display the line numbers
if(!hasClass(pre, 'line-numbers')) {
line.setAttribute('data-start', start);
if(end > start) {
line.setAttribute('data-end', end);
}
}
line.style.top = (start - offset - 1) * lineHeight + 'px';
//allow this to play nicely with the line-numbers plugin
if(hasClass(pre, 'line-numbers')) {
//need to attack to pre as when line-numbers is enabled, the code tag is relatively which screws up the positioning
pre.appendChild(line);
} else {
(pre.querySelector('code') || pre).appendChild(line);
}
}
}
function applyHash() {
var hash = location.hash.slice(1);
// Remove pre-existing temporary lines
$$('.temporary.line-highlight').forEach(function (line) {
line.parentNode.removeChild(line);
});
var range = (hash.match(/\.([\d,-]+)$/) || [,''])[1];
if (!range || document.getElementById(hash)) {
return;
}
var id = hash.slice(0, hash.lastIndexOf('.')),
pre = document.getElementById(id);
if (!pre) {
return;
}
if (!pre.hasAttribute('data-line')) {
pre.setAttribute('data-line', '');
}
highlightLines(pre, range, 'temporary ');
document.querySelector('.temporary.line-highlight').scrollIntoView();
}
var fakeTimer = 0; // Hack to limit the number of times applyHash() runs
Prism.hooks.add('complete', function(env) {
var pre = env.element.parentNode;
var lines = pre && pre.getAttribute('data-line');
if (!pre || !lines || !/pre/i.test(pre.nodeName)) {
return;
}
clearTimeout(fakeTimer);
$$('.line-highlight', pre).forEach(function (line) {
line.parentNode.removeChild(line);
});
highlightLines(pre, lines);
fakeTimer = setTimeout(applyHash, 1);
});
if(window.addEventListener) {
window.addEventListener('hashchange', applyHash);
}
})();
(function() {
if (typeof self === 'undefined' || !self.Prism || !self.document) {
return;
}
Prism.hooks.add('complete', function (env) {
if (!env.code) {
return;
}
// works only for <code> wrapped inside <pre> (not inline)
var pre = env.element.parentNode;
var clsReg = /\s*\bline-numbers\b\s*/;
if (
!pre || !/pre/i.test(pre.nodeName) ||
// Abort only if nor the <pre> nor the <code> have the class
(!clsReg.test(pre.className) && !clsReg.test(env.element.className))
) {
return;
}
if (env.element.querySelector(".line-numbers-rows")) {
// Abort if line numbers already exists
return;
}
if (clsReg.test(env.element.className)) {
// Remove the class "line-numbers" from the <code>
env.element.className = env.element.className.replace(clsReg, '');
}
if (!clsReg.test(pre.className)) {
// Add the class "line-numbers" to the <pre>
pre.className += ' line-numbers';
}
var match = env.code.match(/\n(?!$)/g);
var linesNum = match ? match.length + 1 : 1;
var lineNumbersWrapper;
var lines = new Array(linesNum + 1);
lines = lines.join('<span></span>');
lineNumbersWrapper = document.createElement('span');
lineNumbersWrapper.className = 'line-numbers-rows';
lineNumbersWrapper.innerHTML = lines;
if (pre.hasAttribute('data-start')) {
pre.style.counterReset = 'linenumber ' + (parseInt(pre.getAttribute('data-start'), 10) - 1);
}
env.element.appendChild(lineNumbersWrapper);
});
}());
(function(){
if (
typeof self !== 'undefined' && !self.Prism ||
typeof global !== 'undefined' && !global.Prism
) {
return;
}
for (var language in Prism.languages) {
var tokens = Prism.languages[language];
tokens.tab = /\t/g;
tokens.crlf = /\r\n/g;
tokens.lf = /\n/g;
tokens.cr = /\r/g;
}
})();
(function(){
if (
typeof self !== 'undefined' && !self.Prism ||
typeof global !== 'undefined' && !global.Prism
) {
return;
}
var url = /\b([a-z]{3,7}:\/\/|tel:)[\w\-+%~/.:#=?&amp;]+/,
email = /\b\S+@[\w.]+[a-z]{2}/,
linkMd = /\[([^\]]+)]\(([^)]+)\)/,
// Tokens that may contain URLs and emails
candidates = ['comment', 'url', 'attr-value', 'string'];
Prism.hooks.add('before-highlight', function(env) {
// Abort if grammar has already been processed
if (!env.grammar || env.grammar['url-link']) {
return;
}
Prism.languages.DFS(env.grammar, function (key, def, type) {
if (candidates.indexOf(type) > -1 && Prism.util.type(def) !== 'Array') {
if (!def.pattern) {
def = this[key] = {
pattern: def
};
}
def.inside = def.inside || {};
if (type == 'comment') {
def.inside['md-link'] = linkMd;
}
if (type == 'attr-value') {
Prism.languages.insertBefore('inside', 'punctuation', { 'url-link': url }, def);
}
else {
def.inside['url-link'] = url;
}
def.inside['email-link'] = email;
}
});
env.grammar['url-link'] = url;
env.grammar['email-link'] = email;
});
Prism.hooks.add('wrap', function(env) {
if (/-link$/.test(env.type)) {
env.tag = 'a';
var href = env.content;
if (env.type == 'email-link' && href.indexOf('mailto:') != 0) {
href = 'mailto:' + href;
}
else if (env.type == 'md-link') {
// Markdown
var match = env.content.match(linkMd);
href = match[2];
env.content = match[1];
}
env.attributes.href = href;
}
});
})();
(function(){
if (
typeof self !== 'undefined' && !self.Prism ||
typeof global !== 'undefined' && !global.Prism
) {
return;
}
if (Prism.languages.css) {
Prism.languages.css.atrule.inside['atrule-id'] = /^@[\w-]+/;
// check whether the selector is an advanced pattern before extending it
if (Prism.languages.css.selector.pattern)
{
Prism.languages.css.selector.inside['pseudo-class'] = /:[\w-]+/;
Prism.languages.css.selector.inside['pseudo-element'] = /::[\w-]+/;
}
else
{
Prism.languages.css.selector = {
pattern: Prism.languages.css.selector,
inside: {
'pseudo-class': /:[\w-]+/,
'pseudo-element': /::[\w-]+/
}
};
}
}
if (Prism.languages.markup) {
Prism.languages.markup.tag.inside.tag.inside['tag-id'] = /[\w-]+/;
var Tags = {
HTML: {
'a': 1, 'abbr': 1, 'acronym': 1, 'b': 1, 'basefont': 1, 'bdo': 1, 'big': 1, 'blink': 1, 'cite': 1, 'code': 1, 'dfn': 1, 'em': 1, 'kbd': 1, 'i': 1,
'rp': 1, 'rt': 1, 'ruby': 1, 's': 1, 'samp': 1, 'small': 1, 'spacer': 1, 'strike': 1, 'strong': 1, 'sub': 1, 'sup': 1, 'time': 1, 'tt': 1, 'u': 1,
'var': 1, 'wbr': 1, 'noframes': 1, 'summary': 1, 'command': 1, 'dt': 1, 'dd': 1, 'figure': 1, 'figcaption': 1, 'center': 1, 'section': 1, 'nav': 1,
'article': 1, 'aside': 1, 'hgroup': 1, 'header': 1, 'footer': 1, 'address': 1, 'noscript': 1, 'isIndex': 1, 'main': 1, 'mark': 1, 'marquee': 1,
'meter': 1, 'menu': 1
},
SVG: {
'animateColor': 1, 'animateMotion': 1, 'animateTransform': 1, 'glyph': 1, 'feBlend': 1, 'feColorMatrix': 1, 'feComponentTransfer': 1,
'feFuncR': 1, 'feFuncG': 1, 'feFuncB': 1, 'feFuncA': 1, 'feComposite': 1, 'feConvolveMatrix': 1, 'feDiffuseLighting': 1, 'feDisplacementMap': 1,
'feFlood': 1, 'feGaussianBlur': 1, 'feImage': 1, 'feMerge': 1, 'feMergeNode': 1, 'feMorphology': 1, 'feOffset': 1, 'feSpecularLighting': 1,
'feTile': 1, 'feTurbulence': 1, 'feDistantLight': 1, 'fePointLight': 1, 'feSpotLight': 1, 'linearGradient': 1, 'radialGradient': 1, 'altGlyph': 1,
'textPath': 1, 'tref': 1, 'altglyph': 1, 'textpath': 1, 'altglyphdef': 1, 'altglyphitem': 1, 'clipPath': 1, 'color-profile': 1, 'cursor': 1,
'font-face': 1, 'font-face-format': 1, 'font-face-name': 1, 'font-face-src': 1, 'font-face-uri': 1, 'foreignObject': 1, 'glyphRef': 1,
'hkern': 1, 'vkern': 1
},
MathML: {}
}
}
var language;
Prism.hooks.add('wrap', function(env) {
if ((env.type == 'tag-id'
|| (env.type == 'property' && env.content.indexOf('-') != 0)
|| (env.type == 'atrule-id'&& env.content.indexOf('@-') != 0)
|| (env.type == 'pseudo-class'&& env.content.indexOf(':-') != 0)
|| (env.type == 'pseudo-element'&& env.content.indexOf('::-') != 0)
|| (env.type == 'attr-name' && env.content.indexOf('data-') != 0)
) && env.content.indexOf('<') === -1
) {
var searchURL = 'w/index.php?fulltext&search=';
env.tag = 'a';
var href = 'http://docs.webplatform.org/';
if (env.language == 'css') {
href += 'wiki/css/';
if (env.type == 'property') {
href += 'properties/';
}
else if (env.type == 'atrule-id') {
href += 'atrules/';
}
else if (env.type == 'pseudo-class') {
href += 'selectors/pseudo-classes/';
}
else if (env.type == 'pseudo-element') {
href += 'selectors/pseudo-elements/';
}
}
else if (env.language == 'markup') {
if (env.type == 'tag-id') {
// Check language
language = getLanguage(env.content) || language;
if (language) {
href += 'wiki/' + language + '/elements/';
}
else {
href += searchURL;
}
}
else if (env.type == 'attr-name') {
if (language) {
href += 'wiki/' + language + '/attributes/';
}
else {
href += searchURL;
}
}
}
href += env.content;
env.attributes.href = href;
env.attributes.target = '_blank';
}
});
function getLanguage(tag) {
var tagL = tag.toLowerCase();
if (Tags.HTML[tagL]) {
return 'html';
}
else if (Tags.SVG[tag]) {
return 'svg';
}
else if (Tags.MathML[tag]) {
return 'mathml';
}
// Not in dictionary, perform check
if (Tags.HTML[tagL] !== 0 && typeof document !== 'undefined') {
var htmlInterface = (document.createElement(tag).toString().match(/\[object HTML(.+)Element\]/) || [])[1];
if (htmlInterface && htmlInterface != 'Unknown') {
Tags.HTML[tagL] = 1;
return 'html';
}
}
Tags.HTML[tagL] = 0;
if (Tags.SVG[tag] !== 0 && typeof document !== 'undefined') {
var svgInterface = (document.createElementNS('http://www.w3.org/2000/svg', tag).toString().match(/\[object SVG(.+)Element\]/) || [])[1];
if (svgInterface && svgInterface != 'Unknown') {
Tags.SVG[tag] = 1;
return 'svg';
}
}
Tags.SVG[tag] = 0;
// Lame way to detect MathML, but browsers don’t expose interface names there :(
if (Tags.MathML[tag] !== 0) {
if (tag.indexOf('m') === 0) {
Tags.MathML[tag] = 1;
return 'mathml';
}
}
Tags.MathML[tag] = 0;
return null;
}
})();
(function(){
if (
typeof self !== 'undefined' && !self.Prism ||
typeof global !== 'undefined' && !global.Prism
) {
return;
}
Prism.hooks.add('wrap', function(env) {
if (env.type !== "keyword") {
return;
}
env.classes.push('keyword-' + env.content);
});
})();
(function() {
if (typeof self === 'undefined' || !self.Prism || !self.document) {
return;
}
Prism.hooks.add('before-highlight', function (env) {
if (env.code) {
var pre = env.element.parentNode;
var clsReg = /\s*\bkeep-initial-line-feed\b\s*/;
if (
pre && pre.nodeName.toLowerCase() === 'pre' &&
// Apply only if nor the <pre> or the <code> have the class
(!clsReg.test(pre.className) && !clsReg.test(env.element.className))
) {
env.code = env.code.replace(/^(?:\r?\n|\r)/, '');
}
}
});
}());
(function() {
if (typeof self === 'undefined' || !self.Prism || !self.document || !Function.prototype.bind) {
return;
}
/**
* Returns the absolute X, Y offsets for an element
* @param {HTMLElement} element
* @returns {{top: number, right: number, bottom: number, left: number}}
*/
var getOffset = function (element) {
var left = 0, top = 0, el = element;
if (el.parentNode) {
do {
left += el.offsetLeft;
top += el.offsetTop;
} while ((el = el.offsetParent) && el.nodeType < 9);
el = element;
do {
left -= el.scrollLeft;
top -= el.scrollTop;
} while ((el = el.parentNode) && !/body/i.test(el.nodeName));
}
return {
top: top,
right: innerWidth - left - element.offsetWidth,
bottom: innerHeight - top - element.offsetHeight,
left: left
};
};
var tokenRegexp = /(?:^|\s)token(?=$|\s)/;
var activeRegexp = /(?:^|\s)active(?=$|\s)/g;
var flippedRegexp = /(?:^|\s)flipped(?=$|\s)/g;
/**
* Previewer constructor
* @param {string} type Unique previewer type
* @param {function} updater Function that will be called on mouseover.
* @param {string[]|string=} supportedLanguages Aliases of the languages this previewer must be enabled for. Defaults to "*", all languages.
* @constructor
*/
var Previewer = function (type, updater, supportedLanguages, initializer) {
this._elt = null;
this._type = type;
this._clsRegexp = RegExp('(?:^|\\s)' + type + '(?=$|\\s)');
this._token = null;
this.updater = updater;
this._mouseout = this.mouseout.bind(this);
this.initializer = initializer;
var self = this;
if (!supportedLanguages) {
supportedLanguages = ['*'];
}
if (Prism.util.type(supportedLanguages) !== 'Array') {
supportedLanguages = [supportedLanguages];
}
supportedLanguages.forEach(function (lang) {
if (typeof lang !== 'string') {
lang = lang.lang;
}
if (!Previewer.byLanguages[lang]) {
Previewer.byLanguages[lang] = [];
}
if (Previewer.byLanguages[lang].indexOf(self) < 0) {
Previewer.byLanguages[lang].push(self);
}
});
Previewer.byType[type] = this;
};
/**
* Creates the HTML element for the previewer.
*/
Previewer.prototype.init = function () {
if (this._elt) {
return;
}
this._elt = document.createElement('div');
this._elt.className = 'prism-previewer prism-previewer-' + this._type;
document.body.appendChild(this._elt);
if(this.initializer) {
this.initializer();
}
};
/**
* Checks the class name of each hovered element
* @param token
*/
Previewer.prototype.check = function (token) {
do {
if (tokenRegexp.test(token.className) && this._clsRegexp.test(token.className)) {
break;
}
} while(token = token.parentNode);
if (token && token !== this._token) {
this._token = token;
this.show();
}
};
/**
* Called on mouseout
*/
Previewer.prototype.mouseout = function() {
this._token.removeEventListener('mouseout', this._mouseout, false);
this._token = null;
this.hide();
};
/**
* Shows the previewer positioned properly for the current token.
*/
Previewer.prototype.show = function () {
if (!this._elt) {
this.init();
}
if (!this._token) {
return;
}
if (this.updater.call(this._elt, this._token.textContent)) {
this._token.addEventListener('mouseout', this._mouseout, false);
var offset = getOffset(this._token);
this._elt.className += ' active';
if (offset.top - this._elt.offsetHeight > 0) {
this._elt.className = this._elt.className.replace(flippedRegexp, '');
this._elt.style.top = offset.top + 'px';
this._elt.style.bottom = '';
} else {
this._elt.className += ' flipped';
this._elt.style.bottom = offset.bottom + 'px';
this._elt.style.top = '';
}
this._elt.style.left = offset.left + Math.min(200, this._token.offsetWidth / 2) + 'px';
} else {
this.hide();
}
};
/**
* Hides the previewer.
*/
Previewer.prototype.hide = function () {
this._elt.className = this._elt.className.replace(activeRegexp, '');
};
/**
* Map of all registered previewers by language
* @type {{}}
*/
Previewer.byLanguages = {};
/**
* Map of all registered previewers by type
* @type {{}}
*/
Previewer.byType = {};
/**
* Initializes the mouseover event on the code block.
* @param {HTMLElement} elt The code block (env.element)
* @param {string} lang The language (env.language)
*/
Previewer.initEvents = function (elt, lang) {
var previewers = [];
if (Previewer.byLanguages[lang]) {
previewers = previewers.concat(Previewer.byLanguages[lang]);
}
if (Previewer.byLanguages['*']) {
previewers = previewers.concat(Previewer.byLanguages['*']);
}
elt.addEventListener('mouseover', function (e) {
var target = e.target;
previewers.forEach(function (previewer) {
previewer.check(target);
});
}, false);
};
Prism.plugins.Previewer = Previewer;
// Initialize the previewers only when needed
Prism.hooks.add('after-highlight', function (env) {
if(Previewer.byLanguages['*'] || Previewer.byLanguages[env.language]) {
Previewer.initEvents(env.element, env.language);
}
});
}());
(function() {
if (
typeof self !== 'undefined' && !self.Prism ||
typeof global !== 'undefined' && !global.Prism
) {
return;
}
var languages = {
'css': true,
'less': true,
'markup': {
lang: 'markup',
before: 'punctuation',
inside: 'inside',
root: Prism.languages.markup && Prism.languages.markup['tag'].inside['attr-value']
},
'sass': [
{
lang: 'sass',
before: 'punctuation',
inside: 'inside',
root: Prism.languages.sass && Prism.languages.sass['variable-line']
},
{
lang: 'sass',
inside: 'inside',
root: Prism.languages.sass && Prism.languages.sass['property-line']
}
],
'scss': true,
'stylus': [
{
lang: 'stylus',
before: 'hexcode',
inside: 'rest',
root: Prism.languages.stylus && Prism.languages.stylus['property-declaration'].inside
},
{
lang: 'stylus',
before: 'hexcode',
inside: 'rest',
root: Prism.languages.stylus && Prism.languages.stylus['variable-declaration'].inside
}
]
};
Prism.hooks.add('before-highlight', function (env) {
if (env.language && languages[env.language] && !languages[env.language].initialized) {
var lang = languages[env.language];
if (Prism.util.type(lang) !== 'Array') {
lang = [lang];
}
lang.forEach(function(lang) {
var before, inside, root, skip;
if (lang === true) {
before = 'important';
inside = env.language;
lang = env.language;
} else {
before = lang.before || 'important';
inside = lang.inside || lang.lang;
root = lang.root || Prism.languages;
skip = lang.skip;
lang = env.language;
}
if (!skip && Prism.languages[lang]) {
Prism.languages.insertBefore(inside, before, {
'color': /\B#(?:[0-9a-f]{3}){1,2}\b|\b(?:rgb|hsl)\(\s*\d{1,3}\s*,\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*\)\B|\b(?:rgb|hsl)a\(\s*\d{1,3}\s*,\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*,\s*(?:0|0?\.\d+|1)\s*\)\B|\b(?:AliceBlue|AntiqueWhite|Aqua|Aquamarine|Azure|Beige|Bisque|Black|BlanchedAlmond|Blue|BlueViolet|Brown|BurlyWood|CadetBlue|Chartreuse|Chocolate|Coral|CornflowerBlue|Cornsilk|Crimson|Cyan|DarkBlue|DarkCyan|DarkGoldenRod|DarkGray|DarkGreen|DarkKhaki|DarkMagenta|DarkOliveGreen|DarkOrange|DarkOrchid|DarkRed|DarkSalmon|DarkSeaGreen|DarkSlateBlue|DarkSlateGray|DarkTurquoise|DarkViolet|DeepPink|DeepSkyBlue|DimGray|DodgerBlue|FireBrick|FloralWhite|ForestGreen|Fuchsia|Gainsboro|GhostWhite|Gold|GoldenRod|Gray|Green|GreenYellow|HoneyDew|HotPink|IndianRed|Indigo|Ivory|Khaki|Lavender|LavenderBlush|LawnGreen|LemonChiffon|LightBlue|LightCoral|LightCyan|LightGoldenRodYellow|LightGray|LightGreen|LightPink|LightSalmon|LightSeaGreen|LightSkyBlue|LightSlateGray|LightSteelBlue|LightYellow|Lime|LimeGreen|Linen|Magenta|Maroon|MediumAquaMarine|MediumBlue|MediumOrchid|MediumPurple|MediumSeaGreen|MediumSlateBlue|MediumSpringGreen|MediumTurquoise|MediumVioletRed|MidnightBlue|MintCream|MistyRose|Moccasin|NavajoWhite|Navy|OldLace|Olive|OliveDrab|Orange|OrangeRed|Orchid|PaleGoldenRod|PaleGreen|PaleTurquoise|PaleVioletRed|PapayaWhip|PeachPuff|Peru|Pink|Plum|PowderBlue|Purple|Red|RosyBrown|RoyalBlue|SaddleBrown|Salmon|SandyBrown|SeaGreen|SeaShell|Sienna|Silver|SkyBlue|SlateBlue|SlateGray|Snow|SpringGreen|SteelBlue|Tan|Teal|Thistle|Tomato|Turquoise|Violet|Wheat|White|WhiteSmoke|Yellow|YellowGreen)\b/i
}, root);
env.grammar = Prism.languages[lang];
languages[env.language] = {initialized: true};
}
});
}
});
if (Prism.plugins.Previewer) {
new Prism.plugins.Previewer('color', function(value) {
this.style.backgroundColor = '';
this.style.backgroundColor = value;
return !!this.style.backgroundColor;
});
}
}());
(function() {
if (
typeof self !== 'undefined' && !self.Prism ||
typeof global !== 'undefined' && !global.Prism
) {
return;
}
var languages = {
'css': true,
'less': true,
'sass': [
{
lang: 'sass',
before: 'punctuation',
inside: 'inside',
root: Prism.languages.sass && Prism.languages.sass['variable-line']
},
{
lang: 'sass',
before: 'punctuation',
inside: 'inside',
root: Prism.languages.sass && Prism.languages.sass['property-line']
}
],
'scss': true,
'stylus': [
{
lang: 'stylus',
before: 'func',
inside: 'rest',
root: Prism.languages.stylus && Prism.languages.stylus['property-declaration'].inside
},
{
lang: 'stylus',
before: 'func',
inside: 'rest',
root: Prism.languages.stylus && Prism.languages.stylus['variable-declaration'].inside
}
]
};
Prism.hooks.add('before-highlight', function (env) {
if (env.language && languages[env.language] && !languages[env.language].initialized) {
var lang = languages[env.language];
if (Prism.util.type(lang) !== 'Array') {
lang = [lang];
}
lang.forEach(function(lang) {
var before, inside, root, skip;
if (lang === true) {
// Insert before color previewer if it exists
before = Prism.plugins.Previewer && Prism.plugins.Previewer.byType['color'] ? 'color' : 'important';
inside = env.language;
lang = env.language;
} else {
before = lang.before || 'important';
inside = lang.inside || lang.lang;
root = lang.root || Prism.languages;
skip = lang.skip;
lang = env.language;
}
if (!skip && Prism.languages[lang]) {
Prism.languages.insertBefore(inside, before, {
'gradient': {
pattern: /(?:\b|\B-[a-z]{1,10}-)(?:repeating-)?(?:linear|radial)-gradient\((?:(?:rgb|hsl)a?\(.+?\)|[^\)])+\)/gi,
inside: {
'function': /[\w-]+(?=\()/,
'punctuation': /[(),]/
}
}
}, root);
env.grammar = Prism.languages[lang];
languages[env.language] = {initialized: true};
}
});
}
});
// Stores already processed gradients so that we don't
// make the conversion every time the previewer is shown
var cache = {};
/**
* Returns a W3C-valid linear gradient
* @param {string} prefix Vendor prefix if any ("-moz-", "-webkit-", etc.)
* @param {string} func Gradient function name ("linear-gradient")
* @param {string[]} values Array of the gradient function parameters (["0deg", "red 0%", "blue 100%"])
*/
var convertToW3CLinearGradient = function(prefix, func, values) {
// Default value for angle
var angle = '180deg';
if (/^(?:-?\d*\.?\d+(?:deg|rad)|to\b|top|right|bottom|left)/.test(values[0])) {
angle = values.shift();
if (angle.indexOf('to ') < 0) {
// Angle uses old keywords
// W3C syntax uses "to" + opposite keywords
if (angle.indexOf('top') >= 0) {
if (angle.indexOf('left') >= 0) {
angle = 'to bottom right';
} else if (angle.indexOf('right') >= 0) {
angle = 'to bottom left';
} else {
angle = 'to bottom';
}
} else if (angle.indexOf('bottom') >= 0) {
if (angle.indexOf('left') >= 0) {
angle = 'to top right';
} else if (angle.indexOf('right') >= 0) {
angle = 'to top left';
} else {
angle = 'to top';
}
} else if (angle.indexOf('left') >= 0) {
angle = 'to right';
} else if (angle.indexOf('right') >= 0) {
angle = 'to left';
} else if (prefix) {
// Angle is shifted by 90deg in prefixed gradients
if (angle.indexOf('deg') >= 0) {
angle = (90 - parseFloat(angle)) + 'deg';
} else if (angle.indexOf('rad') >= 0) {
angle = (Math.PI / 2 - parseFloat(angle)) + 'rad';
}
}
}
}
return func + '(' + angle + ',' + values.join(',') + ')';
};
/**
* Returns a W3C-valid radial gradient
* @param {string} prefix Vendor prefix if any ("-moz-", "-webkit-", etc.)
* @param {string} func Gradient function name ("linear-gradient")
* @param {string[]} values Array of the gradient function parameters (["0deg", "red 0%", "blue 100%"])
*/
var convertToW3CRadialGradient = function(prefix, func, values) {
if (values[0].indexOf('at') < 0) {
// Looks like old syntax
// Default values
var position = 'center';
var shape = 'ellipse';
var size = 'farthest-corner';
if (/\bcenter|top|right|bottom|left\b|^\d+/.test(values[0])) {
// Found a position
// Remove angle value, if any
position = values.shift().replace(/\s*-?\d+(?:rad|deg)\s*/, '');
}
if (/\bcircle|ellipse|closest|farthest|contain|cover\b/.test(values[0])) {
// Found a shape and/or size
var shapeSizeParts = values.shift().split(/\s+/);
if (shapeSizeParts[0] && (shapeSizeParts[0] === 'circle' || shapeSizeParts[0] === 'ellipse')) {
shape = shapeSizeParts.shift();
}
if (shapeSizeParts[0]) {
size = shapeSizeParts.shift();
}
// Old keywords are converted to their synonyms
if (size === 'cover') {
size = 'farthest-corner';
} else if (size === 'contain') {
size = 'clothest-side';
}
}
return func + '(' + shape + ' ' + size + ' at ' + position + ',' + values.join(',') + ')';
}
return func + '(' + values.join(',') + ')';
};
/**
* Converts a gradient to a W3C-valid one
* Does not support old webkit syntax (-webkit-gradient(linear...) and -webkit-gradient(radial...))
* @param {string} gradient The CSS gradient
*/
var convertToW3CGradient = function(gradient) {
if (cache[gradient]) {
return cache[gradient];
}
var parts = gradient.match(/^(\b|\B-[a-z]{1,10}-)((?:repeating-)?(?:linear|radial)-gradient)/);
// "", "-moz-", etc.
var prefix = parts && parts[1];
// "linear-gradient", "radial-gradient", etc.
var func = parts && parts[2];
var values = gradient.replace(/^(?:\b|\B-[a-z]{1,10}-)(?:repeating-)?(?:linear|radial)-gradient\(|\)$/g, '').split(/\s*,\s*/);
if (func.indexOf('linear') >= 0) {
return cache[gradient] = convertToW3CLinearGradient(prefix, func, values);
} else if (func.indexOf('radial') >= 0) {
return cache[gradient] = convertToW3CRadialGradient(prefix, func, values);
}
return cache[gradient] = func + '(' + values.join(',') + ')';
};
if (Prism.plugins.Previewer) {
new Prism.plugins.Previewer('gradient', function(value) {
this.firstChild.style.backgroundImage = '';
this.firstChild.style.backgroundImage = convertToW3CGradient(value);
return !!this.firstChild.style.backgroundImage;
}, '*', function () {
this._elt.innerHTML = '<div></div>';
});
}
}());
body {
margin: 0;
padding: 0;
font-size: 12pt;
line-height: 1.44em;
}
body > pre {
margin: 0;
border: none;
padding: 1.5rem 2rem;
}
.token.keyword,
.token.operator {
font-weight: bold;
}
.token.operator,
.token.punctuation {
color: #f88;
}
.token.lf {
opacity: 0.3;
}
/*
http://prismjs.com/download.html?themes=prism-okaidia&languages=markup+css+clike+javascript+aspnet+bash+batch+c+bison+csharp+cpp+coffeescript+ruby+css-extras+diff+gherkin+git+go+groovy+handlebars+http+ini+jade+java+less+lua+markdown+perl+php+php-extras+powershell+python+jsx+rest+rust+sass+scss+scala+sql+stylus+typescript+wiki+yaml&plugins=line-highlight+line-numbers+show-invisibles+autolinker+wpd+highlight-keywords+remove-initial-line-feed+previewer-base+previewer-color+previewer-gradient
*/
/**
* okaidia theme for JavaScript, CSS and HTML
* Loosely based on Monokai textmate theme by http://www.monokai.nl/
* @author ocodia
*/
code[class*="language-"],
pre[class*="language-"] {
color: #f8f8f2;
text-shadow: 0 1px rgba(0, 0, 0, 0.3);
font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
direction: ltr;
text-align: left;
white-space: pre;
word-spacing: normal;
word-break: normal;
word-wrap: normal;
line-height: 1.5;
-moz-tab-size: 4;
-o-tab-size: 4;
tab-size: 4;
-webkit-hyphens: none;
-moz-hyphens: none;
-ms-hyphens: none;
hyphens: none;
}
/* Code blocks */
pre[class*="language-"] {
padding: 1em;
margin: .5em 0;
overflow: auto;
border-radius: 0.3em;
}
:not(pre) > code[class*="language-"],
pre[class*="language-"] {
background: #272822;
}
/* Inline code */
:not(pre) > code[class*="language-"] {
padding: .1em;
border-radius: .3em;
white-space: normal;
}
.token.comment,
.token.prolog,
.token.doctype,
.token.cdata {
color: slategray;
}
.token.punctuation {
color: #f8f8f2;
}
.namespace {
opacity: .7;
}
.token.property,
.token.tag,
.token.constant,
.token.symbol,
.token.deleted {
color: #f92672;
}
.token.boolean,
.token.number {
color: #ae81ff;
}
.token.selector,
.token.attr-name,
.token.string,
.token.char,
.token.builtin,
.token.inserted {
color: #a6e22e;
}
.token.operator,
.token.entity,
.token.url,
.language-css .token.string,
.style .token.string,
.token.variable {
color: #f8f8f2;
}
.token.atrule,
.token.attr-value,
.token.function {
color: #e6db74;
}
.token.keyword {
color: #66d9ef;
}
.token.regex,
.token.important {
color: #fd971f;
}
.token.important,
.token.bold {
font-weight: bold;
}
.token.italic {
font-style: italic;
}
.token.entity {
cursor: help;
}
pre[data-line] {
position: relative;
padding: 1em 0 1em 3em;
}
.line-highlight {
position: absolute;
left: 0;
right: 0;
padding: inherit 0;
margin-top: 1em; /* Same as .prism’s padding-top */
background: hsla(24, 20%, 50%,.08);
background: -moz-linear-gradient(left, hsla(24, 20%, 50%,.1) 70%, hsla(24, 20%, 50%,0));
background: -webkit-linear-gradient(left, hsla(24, 20%, 50%,.1) 70%, hsla(24, 20%, 50%,0));
background: -o-linear-gradient(left, hsla(24, 20%, 50%,.1) 70%, hsla(24, 20%, 50%,0));
background: linear-gradient(left, hsla(24, 20%, 50%,.1) 70%, hsla(24, 20%, 50%,0));
pointer-events: none;
line-height: inherit;
white-space: pre;
}
.line-highlight:before,
.line-highlight[data-end]:after {
content: attr(data-start);
position: absolute;
top: .4em;
left: .6em;
min-width: 1em;
padding: 0 .5em;
background-color: hsla(24, 20%, 50%,.4);
color: hsl(24, 20%, 95%);
font: bold 65%/1.5 sans-serif;
text-align: center;
vertical-align: .3em;
border-radius: 999px;
text-shadow: none;
box-shadow: 0 1px white;
}
.line-highlight[data-end]:after {
content: attr(data-end);
top: auto;
bottom: .4em;
}
pre.line-numbers {
position: relative;
padding-left: 3.8em;
counter-reset: linenumber;
}
pre.line-numbers > code {
position: relative;
}
.line-numbers .line-numbers-rows {
position: absolute;
pointer-events: none;
top: 0;
font-size: 100%;
left: -3.8em;
width: 3em; /* works for line-numbers below 1000 lines */
letter-spacing: -1px;
border-right: 1px solid #999;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.line-numbers-rows > span {
pointer-events: none;
display: block;
counter-increment: linenumber;
}
.line-numbers-rows > span:before {
content: counter(linenumber);
color: #999;
display: block;
padding-right: 0.8em;
text-align: right;
}
.token.tab:not(:empty):before,
.token.cr:before,
.token.lf:before {
color: hsl(24, 20%, 85%);
}
.token.tab:not(:empty):before {
content: '\21E5';
}
.token.cr:before {
content: '\240D';
}
.token.crlf:before {
content: '\240D\240A';
}
.token.lf:before {
content: '\240A';
}
.token a {
color: inherit;
}
code[class*="language-"] a[href],
pre[class*="language-"] a[href] {
cursor: help;
text-decoration: none;
}
code[class*="language-"] a[href]:hover,
pre[class*="language-"] a[href]:hover {
cursor: help;
text-decoration: underline;
}
.prism-previewer,
.prism-previewer:before,
.prism-previewer:after {
position: absolute;
pointer-events: none;
}
.prism-previewer,
.prism-previewer:after {
left: 50%;
}
.prism-previewer {
margin-top: -48px;
width: 32px;
height: 32px;
margin-left: -16px;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=$opacity)";
filter: alpha(opacity=0);
-khtml-opacity: 0;
-moz-opacity: 0;
opacity: 0;
-webkit-transition: opacity .25s;
-moz-transition: opacity .25s;
-o-transition: opacity .25s;
transition: opacity .25s;
}
.prism-previewer.flipped {
margin-top: 0;
margin-bottom: -48px;
}
.prism-previewer:before,
.prism-previewer:after {
content: '';
position: absolute;
pointer-events: none;
}
.prism-previewer:before {
top: -5px;
right: -5px;
left: -5px;
bottom: -5px;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
border: 5px solid #fff;
-webkit-box-shadow: 0 0 3px rgba(0, 0, 0, 0.5) inset, 0 0 10px rgba(0, 0, 0, 0.75);
-moz-box-shadow: 0 0 3px rgba(0, 0, 0, 0.5) inset, 0 0 10px rgba(0, 0, 0, 0.75);
-ms-box-shadow: 0 0 3px rgba(0, 0, 0, 0.5) inset, 0 0 10px rgba(0, 0, 0, 0.75);
-o-box-shadow: 0 0 3px rgba(0, 0, 0, 0.5) inset, 0 0 10px rgba(0, 0, 0, 0.75);
box-shadow: 0 0 3px rgba(0, 0, 0, 0.5) inset, 0 0 10px rgba(0, 0, 0, 0.75);
}
.prism-previewer:after {
top: 100%;
width: 0;
height: 0;
margin: 5px 0 0 -7px;
border: 7px solid transparent;
border-color: rgba(255, 0, 0, 0);
border-top-color: #fff;
}
.prism-previewer.flipped:after {
top: auto;
bottom: 100%;
margin-top: 0;
margin-bottom: 5px;
border-top-color: rgba(255, 0, 0, 0);
border-bottom-color: #fff;
}
.prism-previewer.active {
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=$opacity)";
filter: alpha(opacity=1);
-khtml-opacity: 1;
-moz-opacity: 1;
opacity: 1;
}
.prism-previewer-color {
background-image: linear-gradient(45deg, #bbb 25%, transparent 25%, transparent 75%, #bbb 75%, #bbb), linear-gradient(45deg, #bbb 25%, #eee 25%, #eee 75%, #bbb 75%, #bbb);
background-size: 10px 10px;
background-position: 0 0, 5px 5px;
}
.prism-previewer-color:before {
background-color: inherit;
background-clip: padding-box;
}
.prism-previewer-gradient {
background-image: linear-gradient(45deg, #bbb 25%, transparent 25%, transparent 75%, #bbb 75%, #bbb), linear-gradient(45deg, #bbb 25%, #eee 25%, #eee 75%, #bbb 75%, #bbb);
background-size: 10px 10px;
background-position: 0 0, 5px 5px;
width: 64px;
margin-left: -32px;
}
.prism-previewer-gradient:before {
content: none;
}
.prism-previewer-gradient div {
position: absolute;
top: -5px;
left: -5px;
right: -5px;
bottom: -5px;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
border: 5px solid #fff;
-webkit-box-shadow: 0 0 3px rgba(0, 0, 0, 0.5) inset, 0 0 10px rgba(0, 0, 0, 0.75);
-moz-box-shadow: 0 0 3px rgba(0, 0, 0, 0.5) inset, 0 0 10px rgba(0, 0, 0, 0.75);
-ms-box-shadow: 0 0 3px rgba(0, 0, 0, 0.5) inset, 0 0 10px rgba(0, 0, 0, 0.75);
-o-box-shadow: 0 0 3px rgba(0, 0, 0, 0.5) inset, 0 0 10px rgba(0, 0, 0, 0.75);
box-shadow: 0 0 3px rgba(0, 0, 0, 0.5) inset, 0 0 10px rgba(0, 0, 0, 0.75);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment