prism-handlebars.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. (function(Prism) {
  2. var handlebars_pattern = /\{\{\{[\w\W]+?\}\}\}|\{\{[\w\W]+?\}\}/g;
  3. Prism.languages.handlebars = Prism.languages.extend('markup', {
  4. 'handlebars': {
  5. pattern: handlebars_pattern,
  6. inside: {
  7. 'delimiter': {
  8. pattern: /^\{\{\{?|\}\}\}?$/i,
  9. alias: 'punctuation'
  10. },
  11. 'string': /(["'])(\\?.)+?\1/,
  12. 'number': /\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?)\b/,
  13. 'boolean': /\b(true|false)\b/,
  14. 'block': {
  15. pattern: /^(\s*~?\s*)[#\/]\w+/i,
  16. lookbehind: true,
  17. alias: 'keyword'
  18. },
  19. 'brackets': {
  20. pattern: /\[[^\]]+\]/,
  21. inside: {
  22. punctuation: /\[|\]/,
  23. variable: /[\w\W]+/
  24. }
  25. },
  26. 'punctuation': /[!"#%&'()*+,.\/;<=>@\[\\\]^`{|}~]/,
  27. 'variable': /[^!"#%&'()*+,.\/;<=>@\[\\\]^`{|}~]+/
  28. }
  29. }
  30. });
  31. // Comments are inserted at top so that they can
  32. // surround markup
  33. Prism.languages.insertBefore('handlebars', 'tag', {
  34. 'handlebars-comment': {
  35. pattern: /\{\{![\w\W]*?\}\}/,
  36. alias: ['handlebars','comment']
  37. }
  38. });
  39. // Tokenize all inline Handlebars expressions that are wrapped in {{ }} or {{{ }}}
  40. // This allows for easy Handlebars + markup highlighting
  41. Prism.hooks.add('before-highlight', function(env) {
  42. if (env.language !== 'handlebars') {
  43. return;
  44. }
  45. env.tokenStack = [];
  46. env.backupCode = env.code;
  47. env.code = env.code.replace(handlebars_pattern, function(match) {
  48. env.tokenStack.push(match);
  49. return '___HANDLEBARS' + env.tokenStack.length + '___';
  50. });
  51. });
  52. // Restore env.code for other plugins (e.g. line-numbers)
  53. Prism.hooks.add('before-insert', function(env) {
  54. if (env.language === 'handlebars') {
  55. env.code = env.backupCode;
  56. delete env.backupCode;
  57. }
  58. });
  59. // Re-insert the tokens after highlighting
  60. // and highlight them with defined grammar
  61. Prism.hooks.add('after-highlight', function(env) {
  62. if (env.language !== 'handlebars') {
  63. return;
  64. }
  65. for (var i = 0, t; t = env.tokenStack[i]; i++) {
  66. env.highlightedCode = env.highlightedCode.replace('___HANDLEBARS' + (i + 1) + '___', Prism.highlight(t, env.grammar, 'handlebars'));
  67. }
  68. env.element.innerHTML = env.highlightedCode;
  69. });
  70. }(Prism));