UNPKG

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