prism.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  1. /* **********************************************
  2. Begin prism-core.js
  3. ********************************************** */
  4. self = (typeof window !== 'undefined')
  5. ? window // if in browser
  6. : (
  7. (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope)
  8. ? self // if in worker
  9. : {} // if in node js
  10. );
  11. /**
  12. * Prism: Lightweight, robust, elegant syntax highlighting
  13. * MIT license http://www.opensource.org/licenses/mit-license.php/
  14. * @author Lea Verou http://lea.verou.me
  15. */
  16. var Prism = (function(){
  17. // Private helper vars
  18. var lang = /\blang(?:uage)?-(?!\*)(\w+)\b/i;
  19. var _ = self.Prism = {
  20. util: {
  21. encode: function (tokens) {
  22. if (tokens instanceof Token) {
  23. return new Token(tokens.type, _.util.encode(tokens.content), tokens.alias);
  24. } else if (_.util.type(tokens) === 'Array') {
  25. return tokens.map(_.util.encode);
  26. } else {
  27. return tokens.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\u00a0/g, ' ');
  28. }
  29. },
  30. type: function (o) {
  31. return Object.prototype.toString.call(o).match(/\[object (\w+)\]/)[1];
  32. },
  33. // Deep clone a language definition (e.g. to extend it)
  34. clone: function (o) {
  35. var type = _.util.type(o);
  36. switch (type) {
  37. case 'Object':
  38. var clone = {};
  39. for (var key in o) {
  40. if (o.hasOwnProperty(key)) {
  41. clone[key] = _.util.clone(o[key]);
  42. }
  43. }
  44. return clone;
  45. case 'Array':
  46. return o.map(function(v) { return _.util.clone(v); });
  47. }
  48. return o;
  49. }
  50. },
  51. languages: {
  52. extend: function (id, redef) {
  53. var lang = _.util.clone(_.languages[id]);
  54. for (var key in redef) {
  55. lang[key] = redef[key];
  56. }
  57. return lang;
  58. },
  59. /**
  60. * Insert a token before another token in a language literal
  61. * As this needs to recreate the object (we cannot actually insert before keys in object literals),
  62. * we cannot just provide an object, we need anobject and a key.
  63. * @param inside The key (or language id) of the parent
  64. * @param before The key to insert before. If not provided, the function appends instead.
  65. * @param insert Object with the key/value pairs to insert
  66. * @param root The object that contains `inside`. If equal to Prism.languages, it can be omitted.
  67. */
  68. insertBefore: function (inside, before, insert, root) {
  69. root = root || _.languages;
  70. var grammar = root[inside];
  71. if (arguments.length == 2) {
  72. insert = arguments[1];
  73. for (var newToken in insert) {
  74. if (insert.hasOwnProperty(newToken)) {
  75. grammar[newToken] = insert[newToken];
  76. }
  77. }
  78. return grammar;
  79. }
  80. var ret = {};
  81. for (var token in grammar) {
  82. if (grammar.hasOwnProperty(token)) {
  83. if (token == before) {
  84. for (var newToken in insert) {
  85. if (insert.hasOwnProperty(newToken)) {
  86. ret[newToken] = insert[newToken];
  87. }
  88. }
  89. }
  90. ret[token] = grammar[token];
  91. }
  92. }
  93. // Update references in other language definitions
  94. _.languages.DFS(_.languages, function(key, value) {
  95. if (value === root[inside] && key != inside) {
  96. this[key] = ret;
  97. }
  98. });
  99. return root[inside] = ret;
  100. },
  101. // Traverse a language definition with Depth First Search
  102. DFS: function(o, callback, type) {
  103. for (var i in o) {
  104. if (o.hasOwnProperty(i)) {
  105. callback.call(o, i, o[i], type || i);
  106. if (_.util.type(o[i]) === 'Object') {
  107. _.languages.DFS(o[i], callback);
  108. }
  109. else if (_.util.type(o[i]) === 'Array') {
  110. _.languages.DFS(o[i], callback, i);
  111. }
  112. }
  113. }
  114. }
  115. },
  116. highlightAll: function(async, callback) {
  117. var elements = document.querySelectorAll('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code');
  118. for (var i=0, element; element = elements[i++];) {
  119. _.highlightElement(element, async === true, callback);
  120. }
  121. },
  122. highlightElement: function(element, async, callback) {
  123. // Find language
  124. var language, grammar, parent = element;
  125. while (parent && !lang.test(parent.className)) {
  126. parent = parent.parentNode;
  127. }
  128. if (parent) {
  129. language = (parent.className.match(lang) || [,''])[1];
  130. grammar = _.languages[language];
  131. }
  132. if (!grammar) {
  133. return;
  134. }
  135. // Set language on the element, if not present
  136. element.className = element.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language;
  137. // Set language on the parent, for styling
  138. parent = element.parentNode;
  139. if (/pre/i.test(parent.nodeName)) {
  140. parent.className = parent.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language;
  141. }
  142. var code = element.textContent;
  143. if(!code) {
  144. return;
  145. }
  146. code = code.replace(/^(?:\r?\n|\r)/,'');
  147. var env = {
  148. element: element,
  149. language: language,
  150. grammar: grammar,
  151. code: code
  152. };
  153. _.hooks.run('before-highlight', env);
  154. if (async && self.Worker) {
  155. var worker = new Worker(_.filename);
  156. worker.onmessage = function(evt) {
  157. env.highlightedCode = Token.stringify(JSON.parse(evt.data), language);
  158. _.hooks.run('before-insert', env);
  159. env.element.innerHTML = env.highlightedCode;
  160. callback && callback.call(env.element);
  161. _.hooks.run('after-highlight', env);
  162. };
  163. worker.postMessage(JSON.stringify({
  164. language: env.language,
  165. code: env.code
  166. }));
  167. }
  168. else {
  169. env.highlightedCode = _.highlight(env.code, env.grammar, env.language);
  170. _.hooks.run('before-insert', env);
  171. env.element.innerHTML = env.highlightedCode;
  172. callback && callback.call(element);
  173. _.hooks.run('after-highlight', env);
  174. }
  175. },
  176. highlight: function (text, grammar, language) {
  177. var tokens = _.tokenize(text, grammar);
  178. return Token.stringify(_.util.encode(tokens), language);
  179. },
  180. tokenize: function(text, grammar, language) {
  181. var Token = _.Token;
  182. var strarr = [text];
  183. var rest = grammar.rest;
  184. if (rest) {
  185. for (var token in rest) {
  186. grammar[token] = rest[token];
  187. }
  188. delete grammar.rest;
  189. }
  190. tokenloop: for (var token in grammar) {
  191. if(!grammar.hasOwnProperty(token) || !grammar[token]) {
  192. continue;
  193. }
  194. var patterns = grammar[token];
  195. patterns = (_.util.type(patterns) === "Array") ? patterns : [patterns];
  196. for (var j = 0; j < patterns.length; ++j) {
  197. var pattern = patterns[j],
  198. inside = pattern.inside,
  199. lookbehind = !!pattern.lookbehind,
  200. lookbehindLength = 0,
  201. alias = pattern.alias;
  202. pattern = pattern.pattern || pattern;
  203. for (var i=0; i<strarr.length; i++) { // Don’t cache length as it changes during the loop
  204. var str = strarr[i];
  205. if (strarr.length > text.length) {
  206. // Something went terribly wrong, ABORT, ABORT!
  207. break tokenloop;
  208. }
  209. if (str instanceof Token) {
  210. continue;
  211. }
  212. pattern.lastIndex = 0;
  213. var match = pattern.exec(str);
  214. if (match) {
  215. if(lookbehind) {
  216. lookbehindLength = match[1].length;
  217. }
  218. var from = match.index - 1 + lookbehindLength,
  219. match = match[0].slice(lookbehindLength),
  220. len = match.length,
  221. to = from + len,
  222. before = str.slice(0, from + 1),
  223. after = str.slice(to + 1);
  224. var args = [i, 1];
  225. if (before) {
  226. args.push(before);
  227. }
  228. var wrapped = new Token(token, inside? _.tokenize(match, inside) : match, alias);
  229. args.push(wrapped);
  230. if (after) {
  231. args.push(after);
  232. }
  233. Array.prototype.splice.apply(strarr, args);
  234. }
  235. }
  236. }
  237. }
  238. return strarr;
  239. },
  240. hooks: {
  241. all: {},
  242. add: function (name, callback) {
  243. var hooks = _.hooks.all;
  244. hooks[name] = hooks[name] || [];
  245. hooks[name].push(callback);
  246. },
  247. run: function (name, env) {
  248. var callbacks = _.hooks.all[name];
  249. if (!callbacks || !callbacks.length) {
  250. return;
  251. }
  252. for (var i=0, callback; callback = callbacks[i++];) {
  253. callback(env);
  254. }
  255. }
  256. }
  257. };
  258. var Token = _.Token = function(type, content, alias) {
  259. this.type = type;
  260. this.content = content;
  261. this.alias = alias;
  262. };
  263. Token.stringify = function(o, language, parent) {
  264. if (typeof o == 'string') {
  265. return o;
  266. }
  267. if (_.util.type(o) === 'Array') {
  268. return o.map(function(element) {
  269. return Token.stringify(element, language, o);
  270. }).join('');
  271. }
  272. var env = {
  273. type: o.type,
  274. content: Token.stringify(o.content, language, parent),
  275. tag: 'span',
  276. classes: ['token', o.type],
  277. attributes: {},
  278. language: language,
  279. parent: parent
  280. };
  281. if (env.type == 'comment') {
  282. env.attributes['spellcheck'] = 'true';
  283. }
  284. if (o.alias) {
  285. var aliases = _.util.type(o.alias) === 'Array' ? o.alias : [o.alias];
  286. Array.prototype.push.apply(env.classes, aliases);
  287. }
  288. _.hooks.run('wrap', env);
  289. var attributes = '';
  290. for (var name in env.attributes) {
  291. attributes += name + '="' + (env.attributes[name] || '') + '"';
  292. }
  293. return '<' + env.tag + ' class="' + env.classes.join(' ') + '" ' + attributes + '>' + env.content + '</' + env.tag + '>';
  294. };
  295. if (!self.document) {
  296. if (!self.addEventListener) {
  297. // in Node.js
  298. return self.Prism;
  299. }
  300. // In worker
  301. self.addEventListener('message', function(evt) {
  302. var message = JSON.parse(evt.data),
  303. lang = message.language,
  304. code = message.code;
  305. self.postMessage(JSON.stringify(_.util.encode(_.tokenize(code, _.languages[lang]))));
  306. self.close();
  307. }, false);
  308. return self.Prism;
  309. }
  310. // Get current script and highlight
  311. var script = document.getElementsByTagName('script');
  312. script = script[script.length - 1];
  313. if (script) {
  314. _.filename = script.src;
  315. if (document.addEventListener && !script.hasAttribute('data-manual')) {
  316. document.addEventListener('DOMContentLoaded', _.highlightAll);
  317. }
  318. }
  319. return self.Prism;
  320. })();
  321. if (typeof module !== 'undefined' && module.exports) {
  322. module.exports = Prism;
  323. }
  324. /* **********************************************
  325. Begin prism-markup.js
  326. ********************************************** */
  327. Prism.languages.markup = {
  328. 'comment': /<!--[\w\W]*?-->/,
  329. 'prolog': /<\?.+?\?>/,
  330. 'doctype': /<!DOCTYPE.+?>/,
  331. 'cdata': /<!\[CDATA\[[\w\W]*?]]>/i,
  332. 'tag': {
  333. pattern: /<\/?[\w:-]+\s*(?:\s+[\w:-]+(?:=(?:("|')(\\?[\w\W])*?\1|[^\s'">=]+))?\s*)*\/?>/i,
  334. inside: {
  335. 'tag': {
  336. pattern: /^<\/?[\w:-]+/i,
  337. inside: {
  338. 'punctuation': /^<\/?/,
  339. 'namespace': /^[\w-]+?:/
  340. }
  341. },
  342. 'attr-value': {
  343. pattern: /=(?:('|")[\w\W]*?(\1)|[^\s>]+)/i,
  344. inside: {
  345. 'punctuation': /=|>|"/
  346. }
  347. },
  348. 'punctuation': /\/?>/,
  349. 'attr-name': {
  350. pattern: /[\w:-]+/,
  351. inside: {
  352. 'namespace': /^[\w-]+?:/
  353. }
  354. }
  355. }
  356. },
  357. 'entity': /&#?[\da-z]{1,8};/i
  358. };
  359. // Plugin to make entity title show the real entity, idea by Roman Komarov
  360. Prism.hooks.add('wrap', function(env) {
  361. if (env.type === 'entity') {
  362. env.attributes['title'] = env.content.replace(/&amp;/, '&');
  363. }
  364. });
  365. /* **********************************************
  366. Begin prism-css.js
  367. ********************************************** */
  368. Prism.languages.css = {
  369. 'comment': /\/\*[\w\W]*?\*\//,
  370. 'atrule': {
  371. pattern: /@[\w-]+?.*?(;|(?=\s*\{))/i,
  372. inside: {
  373. 'punctuation': /[;:]/
  374. }
  375. },
  376. 'url': /url\((?:(["'])(\\\n|\\?.)*?\1|.*?)\)/i,
  377. 'selector': /[^\{\}\s][^\{\};]*(?=\s*\{)/,
  378. 'string': /("|')(\\\n|\\?.)*?\1/,
  379. 'property': /(\b|\B)[\w-]+(?=\s*:)/i,
  380. 'important': /\B!important\b/i,
  381. 'punctuation': /[\{\};:]/,
  382. 'function': /[-a-z0-9]+(?=\()/i
  383. };
  384. if (Prism.languages.markup) {
  385. Prism.languages.insertBefore('markup', 'tag', {
  386. 'style': {
  387. pattern: /<style[\w\W]*?>[\w\W]*?<\/style>/i,
  388. inside: {
  389. 'tag': {
  390. pattern: /<style[\w\W]*?>|<\/style>/i,
  391. inside: Prism.languages.markup.tag.inside
  392. },
  393. rest: Prism.languages.css
  394. },
  395. alias: 'language-css'
  396. }
  397. });
  398. Prism.languages.insertBefore('inside', 'attr-value', {
  399. 'style-attr': {
  400. pattern: /\s*style=("|').*?\1/i,
  401. inside: {
  402. 'attr-name': {
  403. pattern: /^\s*style/i,
  404. inside: Prism.languages.markup.tag.inside
  405. },
  406. 'punctuation': /^\s*=\s*['"]|['"]\s*$/,
  407. 'attr-value': {
  408. pattern: /.+/i,
  409. inside: Prism.languages.css
  410. }
  411. },
  412. alias: 'language-css'
  413. }
  414. }, Prism.languages.markup.tag);
  415. }
  416. /* **********************************************
  417. Begin prism-clike.js
  418. ********************************************** */
  419. Prism.languages.clike = {
  420. 'comment': [
  421. {
  422. pattern: /(^|[^\\])\/\*[\w\W]*?\*\//,
  423. lookbehind: true
  424. },
  425. {
  426. pattern: /(^|[^\\:])\/\/.*/,
  427. lookbehind: true
  428. }
  429. ],
  430. 'string': /("|')(\\\n|\\?.)*?\1/,
  431. 'class-name': {
  432. pattern: /((?:(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/i,
  433. lookbehind: true,
  434. inside: {
  435. punctuation: /(\.|\\)/
  436. }
  437. },
  438. 'keyword': /\b(if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/,
  439. 'boolean': /\b(true|false)\b/,
  440. 'function': {
  441. pattern: /[a-z0-9_]+\(/i,
  442. inside: {
  443. punctuation: /\(/
  444. }
  445. },
  446. 'number': /\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?)\b/,
  447. 'operator': /[-+]{1,2}|!|<=?|>=?|={1,3}|&{1,2}|\|?\||\?|\*|\/|~|\^|%/,
  448. 'ignore': /&(lt|gt|amp);/i,
  449. 'punctuation': /[{}[\];(),.:]/
  450. };
  451. /* **********************************************
  452. Begin prism-javascript.js
  453. ********************************************** */
  454. Prism.languages.javascript = Prism.languages.extend('clike', {
  455. '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)\b/,
  456. 'number': /\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee][+-]?\d+)?|NaN|-?Infinity)\b/,
  457. 'function': /(?!\d)[a-z0-9_$]+(?=\()/i
  458. });
  459. Prism.languages.insertBefore('javascript', 'keyword', {
  460. 'regex': {
  461. pattern: /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\r\n])+\/[gim]{0,3}(?=\s*($|[\r\n,.;})]))/,
  462. lookbehind: true
  463. }
  464. });
  465. if (Prism.languages.markup) {
  466. Prism.languages.insertBefore('markup', 'tag', {
  467. 'script': {
  468. pattern: /<script[\w\W]*?>[\w\W]*?<\/script>/i,
  469. inside: {
  470. 'tag': {
  471. pattern: /<script[\w\W]*?>|<\/script>/i,
  472. inside: Prism.languages.markup.tag.inside
  473. },
  474. rest: Prism.languages.javascript
  475. },
  476. alias: 'language-javascript'
  477. }
  478. });
  479. }
  480. /* **********************************************
  481. Begin prism-file-highlight.js
  482. ********************************************** */
  483. (function () {
  484. if (!self.Prism || !self.document || !document.querySelector) {
  485. return;
  486. }
  487. self.Prism.fileHighlight = function() {
  488. var Extensions = {
  489. 'js': 'javascript',
  490. 'html': 'markup',
  491. 'svg': 'markup',
  492. 'xml': 'markup',
  493. 'py': 'python',
  494. 'rb': 'ruby',
  495. 'ps1': 'powershell',
  496. 'psm1': 'powershell'
  497. };
  498. Array.prototype.slice.call(document.querySelectorAll('pre[data-src]')).forEach(function(pre) {
  499. var src = pre.getAttribute('data-src');
  500. var extension = (src.match(/\.(\w+)$/) || [,''])[1];
  501. var language = Extensions[extension] || extension;
  502. var code = document.createElement('code');
  503. code.className = 'language-' + language;
  504. pre.textContent = '';
  505. code.textContent = 'Loading…';
  506. pre.appendChild(code);
  507. var xhr = new XMLHttpRequest();
  508. xhr.open('GET', src, true);
  509. xhr.onreadystatechange = function() {
  510. if (xhr.readyState == 4) {
  511. if (xhr.status < 400 && xhr.responseText) {
  512. code.textContent = xhr.responseText;
  513. Prism.highlightElement(code);
  514. }
  515. else if (xhr.status >= 400) {
  516. code.textContent = '✖ Error ' + xhr.status + ' while fetching file: ' + xhr.statusText;
  517. }
  518. else {
  519. code.textContent = '✖ Error: File does not exist or is empty';
  520. }
  521. }
  522. };
  523. xhr.send(null);
  524. });
  525. };
  526. self.Prism.fileHighlight();
  527. })();