@tiptap/extension-code-block-lowlight 2.6.2 → 3.0.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/dist/index.cjs +158 -2737
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +16 -0
  4. package/dist/index.d.ts +16 -0
  5. package/dist/index.js +123 -2730
  6. package/dist/index.js.map +1 -1
  7. package/package.json +10 -12
  8. package/dist/index.umd.js +0 -2750
  9. package/dist/index.umd.js.map +0 -1
  10. package/dist/packages/core/src/CommandManager.d.ts +0 -20
  11. package/dist/packages/core/src/Editor.d.ts +0 -163
  12. package/dist/packages/core/src/EventEmitter.d.ts +0 -11
  13. package/dist/packages/core/src/Extension.d.ts +0 -344
  14. package/dist/packages/core/src/ExtensionManager.d.ts +0 -55
  15. package/dist/packages/core/src/InputRule.d.ts +0 -42
  16. package/dist/packages/core/src/Mark.d.ts +0 -452
  17. package/dist/packages/core/src/Node.d.ts +0 -612
  18. package/dist/packages/core/src/NodePos.d.ts +0 -44
  19. package/dist/packages/core/src/NodeView.d.ts +0 -31
  20. package/dist/packages/core/src/PasteRule.d.ts +0 -50
  21. package/dist/packages/core/src/Tracker.d.ts +0 -11
  22. package/dist/packages/core/src/commands/blur.d.ts +0 -13
  23. package/dist/packages/core/src/commands/clearContent.d.ts +0 -14
  24. package/dist/packages/core/src/commands/clearNodes.d.ts +0 -13
  25. package/dist/packages/core/src/commands/command.d.ts +0 -18
  26. package/dist/packages/core/src/commands/createParagraphNear.d.ts +0 -13
  27. package/dist/packages/core/src/commands/cut.d.ts +0 -20
  28. package/dist/packages/core/src/commands/deleteCurrentNode.d.ts +0 -13
  29. package/dist/packages/core/src/commands/deleteNode.d.ts +0 -15
  30. package/dist/packages/core/src/commands/deleteRange.d.ts +0 -14
  31. package/dist/packages/core/src/commands/deleteSelection.d.ts +0 -13
  32. package/dist/packages/core/src/commands/enter.d.ts +0 -13
  33. package/dist/packages/core/src/commands/exitCode.d.ts +0 -13
  34. package/dist/packages/core/src/commands/extendMarkRange.d.ts +0 -25
  35. package/dist/packages/core/src/commands/first.d.ts +0 -14
  36. package/dist/packages/core/src/commands/focus.d.ts +0 -27
  37. package/dist/packages/core/src/commands/forEach.d.ts +0 -14
  38. package/dist/packages/core/src/commands/index.d.ts +0 -55
  39. package/dist/packages/core/src/commands/insertContent.d.ts +0 -34
  40. package/dist/packages/core/src/commands/insertContentAt.d.ts +0 -47
  41. package/dist/packages/core/src/commands/join.d.ts +0 -41
  42. package/dist/packages/core/src/commands/joinItemBackward.d.ts +0 -13
  43. package/dist/packages/core/src/commands/joinItemForward.d.ts +0 -13
  44. package/dist/packages/core/src/commands/joinTextblockBackward.d.ts +0 -12
  45. package/dist/packages/core/src/commands/joinTextblockForward.d.ts +0 -12
  46. package/dist/packages/core/src/commands/keyboardShortcut.d.ts +0 -14
  47. package/dist/packages/core/src/commands/lift.d.ts +0 -17
  48. package/dist/packages/core/src/commands/liftEmptyBlock.d.ts +0 -13
  49. package/dist/packages/core/src/commands/liftListItem.d.ts +0 -15
  50. package/dist/packages/core/src/commands/newlineInCode.d.ts +0 -13
  51. package/dist/packages/core/src/commands/resetAttributes.d.ts +0 -16
  52. package/dist/packages/core/src/commands/scrollIntoView.d.ts +0 -13
  53. package/dist/packages/core/src/commands/selectAll.d.ts +0 -13
  54. package/dist/packages/core/src/commands/selectNodeBackward.d.ts +0 -13
  55. package/dist/packages/core/src/commands/selectNodeForward.d.ts +0 -13
  56. package/dist/packages/core/src/commands/selectParentNode.d.ts +0 -13
  57. package/dist/packages/core/src/commands/selectTextblockEnd.d.ts +0 -13
  58. package/dist/packages/core/src/commands/selectTextblockStart.d.ts +0 -13
  59. package/dist/packages/core/src/commands/setContent.d.ts +0 -40
  60. package/dist/packages/core/src/commands/setMark.d.ts +0 -15
  61. package/dist/packages/core/src/commands/setMeta.d.ts +0 -16
  62. package/dist/packages/core/src/commands/setNode.d.ts +0 -16
  63. package/dist/packages/core/src/commands/setNodeSelection.d.ts +0 -14
  64. package/dist/packages/core/src/commands/setTextSelection.d.ts +0 -14
  65. package/dist/packages/core/src/commands/sinkListItem.d.ts +0 -15
  66. package/dist/packages/core/src/commands/splitBlock.d.ts +0 -17
  67. package/dist/packages/core/src/commands/splitListItem.d.ts +0 -16
  68. package/dist/packages/core/src/commands/toggleList.d.ts +0 -18
  69. package/dist/packages/core/src/commands/toggleMark.d.ts +0 -30
  70. package/dist/packages/core/src/commands/toggleNode.d.ts +0 -17
  71. package/dist/packages/core/src/commands/toggleWrap.d.ts +0 -16
  72. package/dist/packages/core/src/commands/undoInputRule.d.ts +0 -13
  73. package/dist/packages/core/src/commands/unsetAllMarks.d.ts +0 -13
  74. package/dist/packages/core/src/commands/unsetMark.d.ts +0 -25
  75. package/dist/packages/core/src/commands/updateAttributes.d.ts +0 -24
  76. package/dist/packages/core/src/commands/wrapIn.d.ts +0 -16
  77. package/dist/packages/core/src/commands/wrapInList.d.ts +0 -16
  78. package/dist/packages/core/src/extensions/clipboardTextSerializer.d.ts +0 -5
  79. package/dist/packages/core/src/extensions/commands.d.ts +0 -3
  80. package/dist/packages/core/src/extensions/editable.d.ts +0 -2
  81. package/dist/packages/core/src/extensions/focusEvents.d.ts +0 -2
  82. package/dist/packages/core/src/extensions/index.d.ts +0 -6
  83. package/dist/packages/core/src/extensions/keymap.d.ts +0 -2
  84. package/dist/packages/core/src/extensions/tabindex.d.ts +0 -2
  85. package/dist/packages/core/src/helpers/combineTransactionSteps.d.ts +0 -10
  86. package/dist/packages/core/src/helpers/createChainableState.d.ts +0 -10
  87. package/dist/packages/core/src/helpers/createDocument.d.ts +0 -12
  88. package/dist/packages/core/src/helpers/createNodeFromContent.d.ts +0 -15
  89. package/dist/packages/core/src/helpers/defaultBlockAt.d.ts +0 -7
  90. package/dist/packages/core/src/helpers/findChildren.d.ts +0 -9
  91. package/dist/packages/core/src/helpers/findChildrenInRange.d.ts +0 -10
  92. package/dist/packages/core/src/helpers/findParentNode.d.ts +0 -16
  93. package/dist/packages/core/src/helpers/findParentNodeClosestToPos.d.ts +0 -17
  94. package/dist/packages/core/src/helpers/generateHTML.d.ts +0 -8
  95. package/dist/packages/core/src/helpers/generateJSON.d.ts +0 -8
  96. package/dist/packages/core/src/helpers/generateText.d.ts +0 -12
  97. package/dist/packages/core/src/helpers/getAttributes.d.ts +0 -9
  98. package/dist/packages/core/src/helpers/getAttributesFromExtensions.d.ts +0 -6
  99. package/dist/packages/core/src/helpers/getChangedRanges.d.ts +0 -11
  100. package/dist/packages/core/src/helpers/getDebugJSON.d.ts +0 -8
  101. package/dist/packages/core/src/helpers/getExtensionField.d.ts +0 -9
  102. package/dist/packages/core/src/helpers/getHTMLFromFragment.d.ts +0 -2
  103. package/dist/packages/core/src/helpers/getMarkAttributes.d.ts +0 -3
  104. package/dist/packages/core/src/helpers/getMarkRange.d.ts +0 -3
  105. package/dist/packages/core/src/helpers/getMarkType.d.ts +0 -2
  106. package/dist/packages/core/src/helpers/getMarksBetween.d.ts +0 -3
  107. package/dist/packages/core/src/helpers/getNodeAtPosition.d.ts +0 -11
  108. package/dist/packages/core/src/helpers/getNodeAttributes.d.ts +0 -3
  109. package/dist/packages/core/src/helpers/getNodeType.d.ts +0 -2
  110. package/dist/packages/core/src/helpers/getRenderedAttributes.d.ts +0 -3
  111. package/dist/packages/core/src/helpers/getSchema.d.ts +0 -4
  112. package/dist/packages/core/src/helpers/getSchemaByResolvedExtensions.d.ts +0 -10
  113. package/dist/packages/core/src/helpers/getSchemaTypeByName.d.ts +0 -8
  114. package/dist/packages/core/src/helpers/getSchemaTypeNameByName.d.ts +0 -8
  115. package/dist/packages/core/src/helpers/getSplittedAttributes.d.ts +0 -9
  116. package/dist/packages/core/src/helpers/getText.d.ts +0 -15
  117. package/dist/packages/core/src/helpers/getTextBetween.d.ts +0 -14
  118. package/dist/packages/core/src/helpers/getTextContentFromNodes.d.ts +0 -8
  119. package/dist/packages/core/src/helpers/getTextSerializersFromSchema.d.ts +0 -8
  120. package/dist/packages/core/src/helpers/index.d.ts +0 -50
  121. package/dist/packages/core/src/helpers/injectExtensionAttributesToParseRule.d.ts +0 -9
  122. package/dist/packages/core/src/helpers/isActive.d.ts +0 -2
  123. package/dist/packages/core/src/helpers/isAtEndOfNode.d.ts +0 -2
  124. package/dist/packages/core/src/helpers/isAtStartOfNode.d.ts +0 -2
  125. package/dist/packages/core/src/helpers/isExtensionRulesEnabled.d.ts +0 -2
  126. package/dist/packages/core/src/helpers/isList.d.ts +0 -2
  127. package/dist/packages/core/src/helpers/isMarkActive.d.ts +0 -3
  128. package/dist/packages/core/src/helpers/isNodeActive.d.ts +0 -3
  129. package/dist/packages/core/src/helpers/isNodeEmpty.d.ts +0 -14
  130. package/dist/packages/core/src/helpers/isNodeSelection.d.ts +0 -2
  131. package/dist/packages/core/src/helpers/isTextSelection.d.ts +0 -2
  132. package/dist/packages/core/src/helpers/posToDOMRect.d.ts +0 -2
  133. package/dist/packages/core/src/helpers/resolveFocusPosition.d.ts +0 -4
  134. package/dist/packages/core/src/helpers/selectionToInsertionEnd.d.ts +0 -2
  135. package/dist/packages/core/src/helpers/splitExtensions.d.ts +0 -9
  136. package/dist/packages/core/src/index.d.ts +0 -24
  137. package/dist/packages/core/src/inputRules/index.d.ts +0 -5
  138. package/dist/packages/core/src/inputRules/markInputRule.d.ts +0 -13
  139. package/dist/packages/core/src/inputRules/nodeInputRule.d.ts +0 -23
  140. package/dist/packages/core/src/inputRules/textInputRule.d.ts +0 -10
  141. package/dist/packages/core/src/inputRules/textblockTypeInputRule.d.ts +0 -15
  142. package/dist/packages/core/src/inputRules/wrappingInputRule.d.ts +0 -28
  143. package/dist/packages/core/src/pasteRules/index.d.ts +0 -3
  144. package/dist/packages/core/src/pasteRules/markPasteRule.d.ts +0 -13
  145. package/dist/packages/core/src/pasteRules/nodePasteRule.d.ts +0 -14
  146. package/dist/packages/core/src/pasteRules/textPasteRule.d.ts +0 -10
  147. package/dist/packages/core/src/style.d.ts +0 -1
  148. package/dist/packages/core/src/types.d.ts +0 -253
  149. package/dist/packages/core/src/utilities/callOrReturn.d.ts +0 -9
  150. package/dist/packages/core/src/utilities/createStyleTag.d.ts +0 -1
  151. package/dist/packages/core/src/utilities/deleteProps.d.ts +0 -6
  152. package/dist/packages/core/src/utilities/elementFromString.d.ts +0 -1
  153. package/dist/packages/core/src/utilities/escapeForRegEx.d.ts +0 -1
  154. package/dist/packages/core/src/utilities/findDuplicates.d.ts +0 -1
  155. package/dist/packages/core/src/utilities/fromString.d.ts +0 -1
  156. package/dist/packages/core/src/utilities/index.d.ts +0 -20
  157. package/dist/packages/core/src/utilities/isAndroid.d.ts +0 -1
  158. package/dist/packages/core/src/utilities/isEmptyObject.d.ts +0 -1
  159. package/dist/packages/core/src/utilities/isFunction.d.ts +0 -1
  160. package/dist/packages/core/src/utilities/isMacOS.d.ts +0 -1
  161. package/dist/packages/core/src/utilities/isNumber.d.ts +0 -1
  162. package/dist/packages/core/src/utilities/isPlainObject.d.ts +0 -1
  163. package/dist/packages/core/src/utilities/isRegExp.d.ts +0 -1
  164. package/dist/packages/core/src/utilities/isString.d.ts +0 -1
  165. package/dist/packages/core/src/utilities/isiOS.d.ts +0 -1
  166. package/dist/packages/core/src/utilities/mergeAttributes.d.ts +0 -1
  167. package/dist/packages/core/src/utilities/mergeDeep.d.ts +0 -1
  168. package/dist/packages/core/src/utilities/minMax.d.ts +0 -1
  169. package/dist/packages/core/src/utilities/objectIncludes.d.ts +0 -8
  170. package/dist/packages/core/src/utilities/removeDuplicates.d.ts +0 -8
  171. package/dist/packages/extension-code-block/src/code-block.d.ts +0 -65
  172. package/dist/packages/extension-code-block/src/index.d.ts +0 -3
  173. package/dist/packages/extension-code-block-lowlight/src/code-block-lowlight.d.ts +0 -12
  174. package/dist/packages/extension-code-block-lowlight/src/index.d.ts +0 -3
  175. package/dist/packages/extension-code-block-lowlight/src/lowlight-plugin.d.ts +0 -6
package/dist/index.cjs CHANGED
@@ -1,2753 +1,174 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var CodeBlock = require('@tiptap/extension-code-block');
6
- var core$1 = require('@tiptap/core');
7
- var state = require('@tiptap/pm/state');
8
- var view = require('@tiptap/pm/view');
9
-
10
- function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
11
-
12
- var CodeBlock__default = /*#__PURE__*/_interopDefaultCompat(CodeBlock);
13
-
14
- function getDefaultExportFromCjs (x) {
15
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
16
- }
17
-
18
- /* eslint-disable no-multi-assign */
19
-
20
- function deepFreeze(obj) {
21
- if (obj instanceof Map) {
22
- obj.clear =
23
- obj.delete =
24
- obj.set =
25
- function () {
26
- throw new Error('map is read-only');
27
- };
28
- } else if (obj instanceof Set) {
29
- obj.add =
30
- obj.clear =
31
- obj.delete =
32
- function () {
33
- throw new Error('set is read-only');
34
- };
35
- }
36
-
37
- // Freeze self
38
- Object.freeze(obj);
39
-
40
- Object.getOwnPropertyNames(obj).forEach((name) => {
41
- const prop = obj[name];
42
- const type = typeof prop;
43
-
44
- // Freeze prop if it is an object or function and also not already frozen
45
- if ((type === 'object' || type === 'function') && !Object.isFrozen(prop)) {
46
- deepFreeze(prop);
47
- }
48
- });
49
-
50
- return obj;
51
- }
52
-
53
- /** @typedef {import('highlight.js').CallbackResponse} CallbackResponse */
54
- /** @typedef {import('highlight.js').CompiledMode} CompiledMode */
55
- /** @implements CallbackResponse */
56
-
57
- class Response {
58
- /**
59
- * @param {CompiledMode} mode
60
- */
61
- constructor(mode) {
62
- // eslint-disable-next-line no-undefined
63
- if (mode.data === undefined) mode.data = {};
64
-
65
- this.data = mode.data;
66
- this.isMatchIgnored = false;
67
- }
68
-
69
- ignoreMatch() {
70
- this.isMatchIgnored = true;
71
- }
72
- }
73
-
74
- /**
75
- * @param {string} value
76
- * @returns {string}
77
- */
78
- function escapeHTML(value) {
79
- return value
80
- .replace(/&/g, '&')
81
- .replace(/</g, '&lt;')
82
- .replace(/>/g, '&gt;')
83
- .replace(/"/g, '&quot;')
84
- .replace(/'/g, '&#x27;');
85
- }
86
-
87
- /**
88
- * performs a shallow merge of multiple objects into one
89
- *
90
- * @template T
91
- * @param {T} original
92
- * @param {Record<string,any>[]} objects
93
- * @returns {T} a single new object
94
- */
95
- function inherit$1(original, ...objects) {
96
- /** @type Record<string,any> */
97
- const result = Object.create(null);
98
-
99
- for (const key in original) {
100
- result[key] = original[key];
101
- }
102
- objects.forEach(function(obj) {
103
- for (const key in obj) {
104
- result[key] = obj[key];
105
- }
106
- });
107
- return /** @type {T} */ (result);
108
- }
109
-
110
- /**
111
- * @typedef {object} Renderer
112
- * @property {(text: string) => void} addText
113
- * @property {(node: Node) => void} openNode
114
- * @property {(node: Node) => void} closeNode
115
- * @property {() => string} value
116
- */
117
-
118
- /** @typedef {{scope?: string, language?: string, sublanguage?: boolean}} Node */
119
- /** @typedef {{walk: (r: Renderer) => void}} Tree */
120
- /** */
121
-
122
- const SPAN_CLOSE = '</span>';
123
-
124
- /**
125
- * Determines if a node needs to be wrapped in <span>
126
- *
127
- * @param {Node} node */
128
- const emitsWrappingTags = (node) => {
129
- // rarely we can have a sublanguage where language is undefined
130
- // TODO: track down why
131
- return !!node.scope;
132
- };
133
-
134
- /**
135
- *
136
- * @param {string} name
137
- * @param {{prefix:string}} options
138
- */
139
- const scopeToCSSClass = (name, { prefix }) => {
140
- // sub-language
141
- if (name.startsWith("language:")) {
142
- return name.replace("language:", "language-");
143
- }
144
- // tiered scope: comment.line
145
- if (name.includes(".")) {
146
- const pieces = name.split(".");
147
- return [
148
- `${prefix}${pieces.shift()}`,
149
- ...(pieces.map((x, i) => `${x}${"_".repeat(i + 1)}`))
150
- ].join(" ");
151
- }
152
- // simple scope
153
- return `${prefix}${name}`;
154
- };
155
-
156
- /** @type {Renderer} */
157
- class HTMLRenderer {
158
- /**
159
- * Creates a new HTMLRenderer
160
- *
161
- * @param {Tree} parseTree - the parse tree (must support `walk` API)
162
- * @param {{classPrefix: string}} options
163
- */
164
- constructor(parseTree, options) {
165
- this.buffer = "";
166
- this.classPrefix = options.classPrefix;
167
- parseTree.walk(this);
168
- }
169
-
170
- /**
171
- * Adds texts to the output stream
172
- *
173
- * @param {string} text */
174
- addText(text) {
175
- this.buffer += escapeHTML(text);
176
- }
177
-
178
- /**
179
- * Adds a node open to the output stream (if needed)
180
- *
181
- * @param {Node} node */
182
- openNode(node) {
183
- if (!emitsWrappingTags(node)) return;
184
-
185
- const className = scopeToCSSClass(node.scope,
186
- { prefix: this.classPrefix });
187
- this.span(className);
188
- }
189
-
190
- /**
191
- * Adds a node close to the output stream (if needed)
192
- *
193
- * @param {Node} node */
194
- closeNode(node) {
195
- if (!emitsWrappingTags(node)) return;
196
-
197
- this.buffer += SPAN_CLOSE;
198
- }
199
-
200
- /**
201
- * returns the accumulated buffer
202
- */
203
- value() {
204
- return this.buffer;
205
- }
206
-
207
- // helpers
208
-
209
- /**
210
- * Builds a span element
211
- *
212
- * @param {string} className */
213
- span(className) {
214
- this.buffer += `<span class="${className}">`;
215
- }
216
- }
217
-
218
- /** @typedef {{scope?: string, language?: string, children: Node[]} | string} Node */
219
- /** @typedef {{scope?: string, language?: string, children: Node[]} } DataNode */
220
- /** @typedef {import('highlight.js').Emitter} Emitter */
221
- /** */
222
-
223
- /** @returns {DataNode} */
224
- const newNode = (opts = {}) => {
225
- /** @type DataNode */
226
- const result = { children: [] };
227
- Object.assign(result, opts);
228
- return result;
229
- };
230
-
231
- class TokenTree {
232
- constructor() {
233
- /** @type DataNode */
234
- this.rootNode = newNode();
235
- this.stack = [this.rootNode];
236
- }
237
-
238
- get top() {
239
- return this.stack[this.stack.length - 1];
240
- }
241
-
242
- get root() { return this.rootNode; }
243
-
244
- /** @param {Node} node */
245
- add(node) {
246
- this.top.children.push(node);
247
- }
248
-
249
- /** @param {string} scope */
250
- openNode(scope) {
251
- /** @type Node */
252
- const node = newNode({ scope });
253
- this.add(node);
254
- this.stack.push(node);
255
- }
256
-
257
- closeNode() {
258
- if (this.stack.length > 1) {
259
- return this.stack.pop();
260
- }
261
- // eslint-disable-next-line no-undefined
262
- return undefined;
263
- }
264
-
265
- closeAllNodes() {
266
- while (this.closeNode());
267
- }
268
-
269
- toJSON() {
270
- return JSON.stringify(this.rootNode, null, 4);
271
- }
272
-
273
- /**
274
- * @typedef { import("./html_renderer").Renderer } Renderer
275
- * @param {Renderer} builder
276
- */
277
- walk(builder) {
278
- // this does not
279
- return this.constructor._walk(builder, this.rootNode);
280
- // this works
281
- // return TokenTree._walk(builder, this.rootNode);
282
- }
283
-
284
- /**
285
- * @param {Renderer} builder
286
- * @param {Node} node
287
- */
288
- static _walk(builder, node) {
289
- if (typeof node === "string") {
290
- builder.addText(node);
291
- } else if (node.children) {
292
- builder.openNode(node);
293
- node.children.forEach((child) => this._walk(builder, child));
294
- builder.closeNode(node);
295
- }
296
- return builder;
297
- }
298
-
299
- /**
300
- * @param {Node} node
301
- */
302
- static _collapse(node) {
303
- if (typeof node === "string") return;
304
- if (!node.children) return;
305
-
306
- if (node.children.every(el => typeof el === "string")) {
307
- // node.text = node.children.join("");
308
- // delete node.children;
309
- node.children = [node.children.join("")];
310
- } else {
311
- node.children.forEach((child) => {
312
- TokenTree._collapse(child);
313
- });
314
- }
315
- }
316
- }
317
-
318
- /**
319
- Currently this is all private API, but this is the minimal API necessary
320
- that an Emitter must implement to fully support the parser.
321
-
322
- Minimal interface:
323
-
324
- - addText(text)
325
- - __addSublanguage(emitter, subLanguageName)
326
- - startScope(scope)
327
- - endScope()
328
- - finalize()
329
- - toHTML()
330
-
331
- */
332
-
333
- /**
334
- * @implements {Emitter}
335
- */
336
- class TokenTreeEmitter extends TokenTree {
337
- /**
338
- * @param {*} options
339
- */
340
- constructor(options) {
341
- super();
342
- this.options = options;
343
- }
344
-
345
- /**
346
- * @param {string} text
347
- */
348
- addText(text) {
349
- if (text === "") { return; }
350
-
351
- this.add(text);
352
- }
353
-
354
- /** @param {string} scope */
355
- startScope(scope) {
356
- this.openNode(scope);
357
- }
358
-
359
- endScope() {
360
- this.closeNode();
361
- }
362
-
363
- /**
364
- * @param {Emitter & {root: DataNode}} emitter
365
- * @param {string} name
366
- */
367
- __addSublanguage(emitter, name) {
368
- /** @type DataNode */
369
- const node = emitter.root;
370
- if (name) node.scope = `language:${name}`;
371
-
372
- this.add(node);
373
- }
374
-
375
- toHTML() {
376
- const renderer = new HTMLRenderer(this, this.options);
377
- return renderer.value();
378
- }
379
-
380
- finalize() {
381
- this.closeAllNodes();
382
- return true;
383
- }
384
- }
385
-
386
- /**
387
- * @param {string} value
388
- * @returns {RegExp}
389
- * */
390
-
391
- /**
392
- * @param {RegExp | string } re
393
- * @returns {string}
394
- */
395
- function source(re) {
396
- if (!re) return null;
397
- if (typeof re === "string") return re;
398
-
399
- return re.source;
400
- }
401
-
402
- /**
403
- * @param {RegExp | string } re
404
- * @returns {string}
405
- */
406
- function lookahead(re) {
407
- return concat('(?=', re, ')');
408
- }
409
-
410
- /**
411
- * @param {RegExp | string } re
412
- * @returns {string}
413
- */
414
- function anyNumberOfTimes(re) {
415
- return concat('(?:', re, ')*');
416
- }
417
-
418
- /**
419
- * @param {RegExp | string } re
420
- * @returns {string}
421
- */
422
- function optional(re) {
423
- return concat('(?:', re, ')?');
424
- }
425
-
426
- /**
427
- * @param {...(RegExp | string) } args
428
- * @returns {string}
429
- */
430
- function concat(...args) {
431
- const joined = args.map((x) => source(x)).join("");
432
- return joined;
433
- }
434
-
435
- /**
436
- * @param { Array<string | RegExp | Object> } args
437
- * @returns {object}
438
- */
439
- function stripOptionsFromArgs(args) {
440
- const opts = args[args.length - 1];
441
-
442
- if (typeof opts === 'object' && opts.constructor === Object) {
443
- args.splice(args.length - 1, 1);
444
- return opts;
445
- } else {
446
- return {};
447
- }
448
- }
449
-
450
- /** @typedef { {capture?: boolean} } RegexEitherOptions */
451
-
452
- /**
453
- * Any of the passed expresssions may match
454
- *
455
- * Creates a huge this | this | that | that match
456
- * @param {(RegExp | string)[] | [...(RegExp | string)[], RegexEitherOptions]} args
457
- * @returns {string}
458
- */
459
- function either(...args) {
460
- /** @type { object & {capture?: boolean} } */
461
- const opts = stripOptionsFromArgs(args);
462
- const joined = '('
463
- + (opts.capture ? "" : "?:")
464
- + args.map((x) => source(x)).join("|") + ")";
465
- return joined;
466
- }
467
-
468
- /**
469
- * @param {RegExp | string} re
470
- * @returns {number}
471
- */
472
- function countMatchGroups(re) {
473
- return (new RegExp(re.toString() + '|')).exec('').length - 1;
474
- }
475
-
476
- /**
477
- * Does lexeme start with a regular expression match at the beginning
478
- * @param {RegExp} re
479
- * @param {string} lexeme
480
- */
481
- function startsWith(re, lexeme) {
482
- const match = re && re.exec(lexeme);
483
- return match && match.index === 0;
484
- }
485
-
486
- // BACKREF_RE matches an open parenthesis or backreference. To avoid
487
- // an incorrect parse, it additionally matches the following:
488
- // - [...] elements, where the meaning of parentheses and escapes change
489
- // - other escape sequences, so we do not misparse escape sequences as
490
- // interesting elements
491
- // - non-matching or lookahead parentheses, which do not capture. These
492
- // follow the '(' with a '?'.
493
- const BACKREF_RE = /\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;
494
-
495
- // **INTERNAL** Not intended for outside usage
496
- // join logically computes regexps.join(separator), but fixes the
497
- // backreferences so they continue to match.
498
- // it also places each individual regular expression into it's own
499
- // match group, keeping track of the sequencing of those match groups
500
- // is currently an exercise for the caller. :-)
501
- /**
502
- * @param {(string | RegExp)[]} regexps
503
- * @param {{joinWith: string}} opts
504
- * @returns {string}
505
- */
506
- function _rewriteBackreferences(regexps, { joinWith }) {
507
- let numCaptures = 0;
508
-
509
- return regexps.map((regex) => {
510
- numCaptures += 1;
511
- const offset = numCaptures;
512
- let re = source(regex);
513
- let out = '';
514
-
515
- while (re.length > 0) {
516
- const match = BACKREF_RE.exec(re);
517
- if (!match) {
518
- out += re;
519
- break;
520
- }
521
- out += re.substring(0, match.index);
522
- re = re.substring(match.index + match[0].length);
523
- if (match[0][0] === '\\' && match[1]) {
524
- // Adjust the backreference.
525
- out += '\\' + String(Number(match[1]) + offset);
526
- } else {
527
- out += match[0];
528
- if (match[0] === '(') {
529
- numCaptures++;
530
- }
531
- }
532
- }
533
- return out;
534
- }).map(re => `(${re})`).join(joinWith);
535
- }
536
-
537
- /** @typedef {import('highlight.js').Mode} Mode */
538
- /** @typedef {import('highlight.js').ModeCallback} ModeCallback */
539
-
540
- // Common regexps
541
- const MATCH_NOTHING_RE = /\b\B/;
542
- const IDENT_RE = '[a-zA-Z]\\w*';
543
- const UNDERSCORE_IDENT_RE = '[a-zA-Z_]\\w*';
544
- const NUMBER_RE = '\\b\\d+(\\.\\d+)?';
545
- const C_NUMBER_RE = '(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)'; // 0x..., 0..., decimal, float
546
- const BINARY_NUMBER_RE = '\\b(0b[01]+)'; // 0b...
547
- const RE_STARTERS_RE = '!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~';
548
-
549
- /**
550
- * @param { Partial<Mode> & {binary?: string | RegExp} } opts
551
- */
552
- const SHEBANG = (opts = {}) => {
553
- const beginShebang = /^#![ ]*\//;
554
- if (opts.binary) {
555
- opts.begin = concat(
556
- beginShebang,
557
- /.*\b/,
558
- opts.binary,
559
- /\b.*/);
560
- }
561
- return inherit$1({
562
- scope: 'meta',
563
- begin: beginShebang,
564
- end: /$/,
565
- relevance: 0,
566
- /** @type {ModeCallback} */
567
- "on:begin": (m, resp) => {
568
- if (m.index !== 0) resp.ignoreMatch();
569
- }
570
- }, opts);
571
- };
572
-
573
- // Common modes
574
- const BACKSLASH_ESCAPE = {
575
- begin: '\\\\[\\s\\S]', relevance: 0
576
- };
577
- const APOS_STRING_MODE = {
578
- scope: 'string',
579
- begin: '\'',
580
- end: '\'',
581
- illegal: '\\n',
582
- contains: [BACKSLASH_ESCAPE]
583
- };
584
- const QUOTE_STRING_MODE = {
585
- scope: 'string',
586
- begin: '"',
587
- end: '"',
588
- illegal: '\\n',
589
- contains: [BACKSLASH_ESCAPE]
590
- };
591
- const PHRASAL_WORDS_MODE = {
592
- begin: /\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/
593
- };
594
- /**
595
- * Creates a comment mode
596
- *
597
- * @param {string | RegExp} begin
598
- * @param {string | RegExp} end
599
- * @param {Mode | {}} [modeOptions]
600
- * @returns {Partial<Mode>}
601
- */
602
- const COMMENT = function(begin, end, modeOptions = {}) {
603
- const mode = inherit$1(
604
- {
605
- scope: 'comment',
606
- begin,
607
- end,
608
- contains: []
609
- },
610
- modeOptions
611
- );
612
- mode.contains.push({
613
- scope: 'doctag',
614
- // hack to avoid the space from being included. the space is necessary to
615
- // match here to prevent the plain text rule below from gobbling up doctags
616
- begin: '[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)',
617
- end: /(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,
618
- excludeBegin: true,
619
- relevance: 0
620
- });
621
- const ENGLISH_WORD = either(
622
- // list of common 1 and 2 letter words in English
623
- "I",
624
- "a",
625
- "is",
626
- "so",
627
- "us",
628
- "to",
629
- "at",
630
- "if",
631
- "in",
632
- "it",
633
- "on",
634
- // note: this is not an exhaustive list of contractions, just popular ones
635
- /[A-Za-z]+['](d|ve|re|ll|t|s|n)/, // contractions - can't we'd they're let's, etc
636
- /[A-Za-z]+[-][a-z]+/, // `no-way`, etc.
637
- /[A-Za-z][a-z]{2,}/ // allow capitalized words at beginning of sentences
638
- );
639
- // looking like plain text, more likely to be a comment
640
- mode.contains.push(
641
- {
642
- // TODO: how to include ", (, ) without breaking grammars that use these for
643
- // comment delimiters?
644
- // begin: /[ ]+([()"]?([A-Za-z'-]{3,}|is|a|I|so|us|[tT][oO]|at|if|in|it|on)[.]?[()":]?([.][ ]|[ ]|\))){3}/
645
- // ---
646
-
647
- // this tries to find sequences of 3 english words in a row (without any
648
- // "programming" type syntax) this gives us a strong signal that we've
649
- // TRULY found a comment - vs perhaps scanning with the wrong language.
650
- // It's possible to find something that LOOKS like the start of the
651
- // comment - but then if there is no readable text - good chance it is a
652
- // false match and not a comment.
653
- //
654
- // for a visual example please see:
655
- // https://github.com/highlightjs/highlight.js/issues/2827
656
-
657
- begin: concat(
658
- /[ ]+/, // necessary to prevent us gobbling up doctags like /* @author Bob Mcgill */
659
- '(',
660
- ENGLISH_WORD,
661
- /[.]?[:]?([.][ ]|[ ])/,
662
- '){3}') // look for 3 words in a row
663
- }
664
- );
665
- return mode;
666
- };
667
- const C_LINE_COMMENT_MODE = COMMENT('//', '$');
668
- const C_BLOCK_COMMENT_MODE = COMMENT('/\\*', '\\*/');
669
- const HASH_COMMENT_MODE = COMMENT('#', '$');
670
- const NUMBER_MODE = {
671
- scope: 'number',
672
- begin: NUMBER_RE,
673
- relevance: 0
674
- };
675
- const C_NUMBER_MODE = {
676
- scope: 'number',
677
- begin: C_NUMBER_RE,
678
- relevance: 0
679
- };
680
- const BINARY_NUMBER_MODE = {
681
- scope: 'number',
682
- begin: BINARY_NUMBER_RE,
683
- relevance: 0
684
- };
685
- const REGEXP_MODE = {
686
- scope: "regexp",
687
- begin: /\/(?=[^/\n]*\/)/,
688
- end: /\/[gimuy]*/,
689
- contains: [
690
- BACKSLASH_ESCAPE,
691
- {
692
- begin: /\[/,
693
- end: /\]/,
694
- relevance: 0,
695
- contains: [BACKSLASH_ESCAPE]
696
- }
697
- ]
698
- };
699
- const TITLE_MODE = {
700
- scope: 'title',
701
- begin: IDENT_RE,
702
- relevance: 0
703
- };
704
- const UNDERSCORE_TITLE_MODE = {
705
- scope: 'title',
706
- begin: UNDERSCORE_IDENT_RE,
707
- relevance: 0
708
- };
709
- const METHOD_GUARD = {
710
- // excludes method names from keyword processing
711
- begin: '\\.\\s*' + UNDERSCORE_IDENT_RE,
712
- relevance: 0
713
- };
714
-
715
- /**
716
- * Adds end same as begin mechanics to a mode
717
- *
718
- * Your mode must include at least a single () match group as that first match
719
- * group is what is used for comparison
720
- * @param {Partial<Mode>} mode
721
- */
722
- const END_SAME_AS_BEGIN = function(mode) {
723
- return Object.assign(mode,
724
- {
725
- /** @type {ModeCallback} */
726
- 'on:begin': (m, resp) => { resp.data._beginMatch = m[1]; },
727
- /** @type {ModeCallback} */
728
- 'on:end': (m, resp) => { if (resp.data._beginMatch !== m[1]) resp.ignoreMatch(); }
729
- });
730
- };
731
-
732
- var MODES = /*#__PURE__*/Object.freeze({
733
- __proto__: null,
734
- APOS_STRING_MODE: APOS_STRING_MODE,
735
- BACKSLASH_ESCAPE: BACKSLASH_ESCAPE,
736
- BINARY_NUMBER_MODE: BINARY_NUMBER_MODE,
737
- BINARY_NUMBER_RE: BINARY_NUMBER_RE,
738
- COMMENT: COMMENT,
739
- C_BLOCK_COMMENT_MODE: C_BLOCK_COMMENT_MODE,
740
- C_LINE_COMMENT_MODE: C_LINE_COMMENT_MODE,
741
- C_NUMBER_MODE: C_NUMBER_MODE,
742
- C_NUMBER_RE: C_NUMBER_RE,
743
- END_SAME_AS_BEGIN: END_SAME_AS_BEGIN,
744
- HASH_COMMENT_MODE: HASH_COMMENT_MODE,
745
- IDENT_RE: IDENT_RE,
746
- MATCH_NOTHING_RE: MATCH_NOTHING_RE,
747
- METHOD_GUARD: METHOD_GUARD,
748
- NUMBER_MODE: NUMBER_MODE,
749
- NUMBER_RE: NUMBER_RE,
750
- PHRASAL_WORDS_MODE: PHRASAL_WORDS_MODE,
751
- QUOTE_STRING_MODE: QUOTE_STRING_MODE,
752
- REGEXP_MODE: REGEXP_MODE,
753
- RE_STARTERS_RE: RE_STARTERS_RE,
754
- SHEBANG: SHEBANG,
755
- TITLE_MODE: TITLE_MODE,
756
- UNDERSCORE_IDENT_RE: UNDERSCORE_IDENT_RE,
757
- UNDERSCORE_TITLE_MODE: UNDERSCORE_TITLE_MODE
758
- });
759
-
760
- /**
761
- @typedef {import('highlight.js').CallbackResponse} CallbackResponse
762
- @typedef {import('highlight.js').CompilerExt} CompilerExt
763
- */
764
-
765
- // Grammar extensions / plugins
766
- // See: https://github.com/highlightjs/highlight.js/issues/2833
767
-
768
- // Grammar extensions allow "syntactic sugar" to be added to the grammar modes
769
- // without requiring any underlying changes to the compiler internals.
770
-
771
- // `compileMatch` being the perfect small example of now allowing a grammar
772
- // author to write `match` when they desire to match a single expression rather
773
- // than being forced to use `begin`. The extension then just moves `match` into
774
- // `begin` when it runs. Ie, no features have been added, but we've just made
775
- // the experience of writing (and reading grammars) a little bit nicer.
776
-
777
- // ------
778
-
779
- // TODO: We need negative look-behind support to do this properly
780
- /**
781
- * Skip a match if it has a preceding dot
782
- *
783
- * This is used for `beginKeywords` to prevent matching expressions such as
784
- * `bob.keyword.do()`. The mode compiler automatically wires this up as a
785
- * special _internal_ 'on:begin' callback for modes with `beginKeywords`
786
- * @param {RegExpMatchArray} match
787
- * @param {CallbackResponse} response
788
- */
789
- function skipIfHasPrecedingDot(match, response) {
790
- const before = match.input[match.index - 1];
791
- if (before === ".") {
792
- response.ignoreMatch();
793
- }
794
- }
795
-
796
- /**
797
- *
798
- * @type {CompilerExt}
799
- */
800
- function scopeClassName(mode, _parent) {
801
- // eslint-disable-next-line no-undefined
802
- if (mode.className !== undefined) {
803
- mode.scope = mode.className;
804
- delete mode.className;
805
- }
806
- }
807
-
808
- /**
809
- * `beginKeywords` syntactic sugar
810
- * @type {CompilerExt}
811
- */
812
- function beginKeywords(mode, parent) {
813
- if (!parent) return;
814
- if (!mode.beginKeywords) return;
815
-
816
- // for languages with keywords that include non-word characters checking for
817
- // a word boundary is not sufficient, so instead we check for a word boundary
818
- // or whitespace - this does no harm in any case since our keyword engine
819
- // doesn't allow spaces in keywords anyways and we still check for the boundary
820
- // first
821
- mode.begin = '\\b(' + mode.beginKeywords.split(' ').join('|') + ')(?!\\.)(?=\\b|\\s)';
822
- mode.__beforeBegin = skipIfHasPrecedingDot;
823
- mode.keywords = mode.keywords || mode.beginKeywords;
824
- delete mode.beginKeywords;
825
-
826
- // prevents double relevance, the keywords themselves provide
827
- // relevance, the mode doesn't need to double it
828
- // eslint-disable-next-line no-undefined
829
- if (mode.relevance === undefined) mode.relevance = 0;
830
- }
831
-
832
- /**
833
- * Allow `illegal` to contain an array of illegal values
834
- * @type {CompilerExt}
835
- */
836
- function compileIllegal(mode, _parent) {
837
- if (!Array.isArray(mode.illegal)) return;
838
-
839
- mode.illegal = either(...mode.illegal);
840
- }
841
-
842
- /**
843
- * `match` to match a single expression for readability
844
- * @type {CompilerExt}
845
- */
846
- function compileMatch(mode, _parent) {
847
- if (!mode.match) return;
848
- if (mode.begin || mode.end) throw new Error("begin & end are not supported with match");
849
-
850
- mode.begin = mode.match;
851
- delete mode.match;
852
- }
853
-
854
- /**
855
- * provides the default 1 relevance to all modes
856
- * @type {CompilerExt}
857
- */
858
- function compileRelevance(mode, _parent) {
859
- // eslint-disable-next-line no-undefined
860
- if (mode.relevance === undefined) mode.relevance = 1;
861
- }
862
-
863
- // allow beforeMatch to act as a "qualifier" for the match
864
- // the full match begin must be [beforeMatch][begin]
865
- const beforeMatchExt = (mode, parent) => {
866
- if (!mode.beforeMatch) return;
867
- // starts conflicts with endsParent which we need to make sure the child
868
- // rule is not matched multiple times
869
- if (mode.starts) throw new Error("beforeMatch cannot be used with starts");
870
-
871
- const originalMode = Object.assign({}, mode);
872
- Object.keys(mode).forEach((key) => { delete mode[key]; });
873
-
874
- mode.keywords = originalMode.keywords;
875
- mode.begin = concat(originalMode.beforeMatch, lookahead(originalMode.begin));
876
- mode.starts = {
877
- relevance: 0,
878
- contains: [
879
- Object.assign(originalMode, { endsParent: true })
880
- ]
881
- };
882
- mode.relevance = 0;
883
-
884
- delete originalMode.beforeMatch;
885
- };
886
-
887
- // keywords that should have no default relevance value
888
- const COMMON_KEYWORDS = [
889
- 'of',
890
- 'and',
891
- 'for',
892
- 'in',
893
- 'not',
894
- 'or',
895
- 'if',
896
- 'then',
897
- 'parent', // common variable name
898
- 'list', // common variable name
899
- 'value' // common variable name
900
- ];
901
-
902
- const DEFAULT_KEYWORD_SCOPE = "keyword";
903
-
904
- /**
905
- * Given raw keywords from a language definition, compile them.
906
- *
907
- * @param {string | Record<string,string|string[]> | Array<string>} rawKeywords
908
- * @param {boolean} caseInsensitive
909
- */
910
- function compileKeywords(rawKeywords, caseInsensitive, scopeName = DEFAULT_KEYWORD_SCOPE) {
911
- /** @type {import("highlight.js/private").KeywordDict} */
912
- const compiledKeywords = Object.create(null);
913
-
914
- // input can be a string of keywords, an array of keywords, or a object with
915
- // named keys representing scopeName (which can then point to a string or array)
916
- if (typeof rawKeywords === 'string') {
917
- compileList(scopeName, rawKeywords.split(" "));
918
- } else if (Array.isArray(rawKeywords)) {
919
- compileList(scopeName, rawKeywords);
920
- } else {
921
- Object.keys(rawKeywords).forEach(function(scopeName) {
922
- // collapse all our objects back into the parent object
923
- Object.assign(
924
- compiledKeywords,
925
- compileKeywords(rawKeywords[scopeName], caseInsensitive, scopeName)
926
- );
927
- });
928
- }
929
- return compiledKeywords;
930
-
931
- // ---
932
-
933
- /**
934
- * Compiles an individual list of keywords
935
- *
936
- * Ex: "for if when while|5"
937
- *
938
- * @param {string} scopeName
939
- * @param {Array<string>} keywordList
940
- */
941
- function compileList(scopeName, keywordList) {
942
- if (caseInsensitive) {
943
- keywordList = keywordList.map(x => x.toLowerCase());
944
- }
945
- keywordList.forEach(function(keyword) {
946
- const pair = keyword.split('|');
947
- compiledKeywords[pair[0]] = [scopeName, scoreForKeyword(pair[0], pair[1])];
948
- });
949
- }
950
- }
951
-
952
- /**
953
- * Returns the proper score for a given keyword
954
- *
955
- * Also takes into account comment keywords, which will be scored 0 UNLESS
956
- * another score has been manually assigned.
957
- * @param {string} keyword
958
- * @param {string} [providedScore]
959
- */
960
- function scoreForKeyword(keyword, providedScore) {
961
- // manual scores always win over common keywords
962
- // so you can force a score of 1 if you really insist
963
- if (providedScore) {
964
- return Number(providedScore);
965
- }
966
-
967
- return commonKeyword(keyword) ? 0 : 1;
968
- }
969
-
970
- /**
971
- * Determines if a given keyword is common or not
972
- *
973
- * @param {string} keyword */
974
- function commonKeyword(keyword) {
975
- return COMMON_KEYWORDS.includes(keyword.toLowerCase());
976
- }
977
-
978
- /*
979
-
980
- For the reasoning behind this please see:
981
- https://github.com/highlightjs/highlight.js/issues/2880#issuecomment-747275419
982
-
983
- */
984
-
985
- /**
986
- * @type {Record<string, boolean>}
987
- */
988
- const seenDeprecations = {};
989
-
990
- /**
991
- * @param {string} message
992
- */
993
- const error = (message) => {
994
- console.error(message);
995
- };
996
-
997
- /**
998
- * @param {string} message
999
- * @param {any} args
1000
- */
1001
- const warn = (message, ...args) => {
1002
- console.log(`WARN: ${message}`, ...args);
1003
- };
1004
-
1005
- /**
1006
- * @param {string} version
1007
- * @param {string} message
1008
- */
1009
- const deprecated = (version, message) => {
1010
- if (seenDeprecations[`${version}/${message}`]) return;
1011
-
1012
- console.log(`Deprecated as of ${version}. ${message}`);
1013
- seenDeprecations[`${version}/${message}`] = true;
1014
- };
1015
-
1016
- /* eslint-disable no-throw-literal */
1017
-
1018
- /**
1019
- @typedef {import('highlight.js').CompiledMode} CompiledMode
1020
- */
1021
-
1022
- const MultiClassError = new Error();
1023
-
1024
- /**
1025
- * Renumbers labeled scope names to account for additional inner match
1026
- * groups that otherwise would break everything.
1027
- *
1028
- * Lets say we 3 match scopes:
1029
- *
1030
- * { 1 => ..., 2 => ..., 3 => ... }
1031
- *
1032
- * So what we need is a clean match like this:
1033
- *
1034
- * (a)(b)(c) => [ "a", "b", "c" ]
1035
- *
1036
- * But this falls apart with inner match groups:
1037
- *
1038
- * (a)(((b)))(c) => ["a", "b", "b", "b", "c" ]
1039
- *
1040
- * Our scopes are now "out of alignment" and we're repeating `b` 3 times.
1041
- * What needs to happen is the numbers are remapped:
1042
- *
1043
- * { 1 => ..., 2 => ..., 5 => ... }
1044
- *
1045
- * We also need to know that the ONLY groups that should be output
1046
- * are 1, 2, and 5. This function handles this behavior.
1047
- *
1048
- * @param {CompiledMode} mode
1049
- * @param {Array<RegExp | string>} regexes
1050
- * @param {{key: "beginScope"|"endScope"}} opts
1051
- */
1052
- function remapScopeNames(mode, regexes, { key }) {
1053
- let offset = 0;
1054
- const scopeNames = mode[key];
1055
- /** @type Record<number,boolean> */
1056
- const emit = {};
1057
- /** @type Record<number,string> */
1058
- const positions = {};
1059
-
1060
- for (let i = 1; i <= regexes.length; i++) {
1061
- positions[i + offset] = scopeNames[i];
1062
- emit[i + offset] = true;
1063
- offset += countMatchGroups(regexes[i - 1]);
1064
- }
1065
- // we use _emit to keep track of which match groups are "top-level" to avoid double
1066
- // output from inside match groups
1067
- mode[key] = positions;
1068
- mode[key]._emit = emit;
1069
- mode[key]._multi = true;
1070
- }
1071
-
1072
- /**
1073
- * @param {CompiledMode} mode
1074
- */
1075
- function beginMultiClass(mode) {
1076
- if (!Array.isArray(mode.begin)) return;
1077
-
1078
- if (mode.skip || mode.excludeBegin || mode.returnBegin) {
1079
- error("skip, excludeBegin, returnBegin not compatible with beginScope: {}");
1080
- throw MultiClassError;
1081
- }
1082
-
1083
- if (typeof mode.beginScope !== "object" || mode.beginScope === null) {
1084
- error("beginScope must be object");
1085
- throw MultiClassError;
1086
- }
1087
-
1088
- remapScopeNames(mode, mode.begin, { key: "beginScope" });
1089
- mode.begin = _rewriteBackreferences(mode.begin, { joinWith: "" });
1090
- }
1091
-
1092
- /**
1093
- * @param {CompiledMode} mode
1094
- */
1095
- function endMultiClass(mode) {
1096
- if (!Array.isArray(mode.end)) return;
1097
-
1098
- if (mode.skip || mode.excludeEnd || mode.returnEnd) {
1099
- error("skip, excludeEnd, returnEnd not compatible with endScope: {}");
1100
- throw MultiClassError;
1101
- }
1102
-
1103
- if (typeof mode.endScope !== "object" || mode.endScope === null) {
1104
- error("endScope must be object");
1105
- throw MultiClassError;
1106
- }
1107
-
1108
- remapScopeNames(mode, mode.end, { key: "endScope" });
1109
- mode.end = _rewriteBackreferences(mode.end, { joinWith: "" });
1110
- }
1111
-
1112
- /**
1113
- * this exists only to allow `scope: {}` to be used beside `match:`
1114
- * Otherwise `beginScope` would necessary and that would look weird
1115
-
1116
- {
1117
- match: [ /def/, /\w+/ ]
1118
- scope: { 1: "keyword" , 2: "title" }
1119
- }
1120
-
1121
- * @param {CompiledMode} mode
1122
- */
1123
- function scopeSugar(mode) {
1124
- if (mode.scope && typeof mode.scope === "object" && mode.scope !== null) {
1125
- mode.beginScope = mode.scope;
1126
- delete mode.scope;
1127
- }
1128
- }
1129
-
1130
- /**
1131
- * @param {CompiledMode} mode
1132
- */
1133
- function MultiClass(mode) {
1134
- scopeSugar(mode);
1135
-
1136
- if (typeof mode.beginScope === "string") {
1137
- mode.beginScope = { _wrap: mode.beginScope };
1138
- }
1139
- if (typeof mode.endScope === "string") {
1140
- mode.endScope = { _wrap: mode.endScope };
1141
- }
1142
-
1143
- beginMultiClass(mode);
1144
- endMultiClass(mode);
1145
- }
1146
-
1147
- /**
1148
- @typedef {import('highlight.js').Mode} Mode
1149
- @typedef {import('highlight.js').CompiledMode} CompiledMode
1150
- @typedef {import('highlight.js').Language} Language
1151
- @typedef {import('highlight.js').HLJSPlugin} HLJSPlugin
1152
- @typedef {import('highlight.js').CompiledLanguage} CompiledLanguage
1153
- */
1154
-
1155
- // compilation
1156
-
1157
- /**
1158
- * Compiles a language definition result
1159
- *
1160
- * Given the raw result of a language definition (Language), compiles this so
1161
- * that it is ready for highlighting code.
1162
- * @param {Language} language
1163
- * @returns {CompiledLanguage}
1164
- */
1165
- function compileLanguage(language) {
1166
- /**
1167
- * Builds a regex with the case sensitivity of the current language
1168
- *
1169
- * @param {RegExp | string} value
1170
- * @param {boolean} [global]
1171
- */
1172
- function langRe(value, global) {
1173
- return new RegExp(
1174
- source(value),
1175
- 'm'
1176
- + (language.case_insensitive ? 'i' : '')
1177
- + (language.unicodeRegex ? 'u' : '')
1178
- + (global ? 'g' : '')
1179
- );
1180
- }
1181
-
1182
- /**
1183
- Stores multiple regular expressions and allows you to quickly search for
1184
- them all in a string simultaneously - returning the first match. It does
1185
- this by creating a huge (a|b|c) regex - each individual item wrapped with ()
1186
- and joined by `|` - using match groups to track position. When a match is
1187
- found checking which position in the array has content allows us to figure
1188
- out which of the original regexes / match groups triggered the match.
1189
-
1190
- The match object itself (the result of `Regex.exec`) is returned but also
1191
- enhanced by merging in any meta-data that was registered with the regex.
1192
- This is how we keep track of which mode matched, and what type of rule
1193
- (`illegal`, `begin`, end, etc).
1194
- */
1195
- class MultiRegex {
1196
- constructor() {
1197
- this.matchIndexes = {};
1198
- // @ts-ignore
1199
- this.regexes = [];
1200
- this.matchAt = 1;
1201
- this.position = 0;
1202
- }
1203
-
1204
- // @ts-ignore
1205
- addRule(re, opts) {
1206
- opts.position = this.position++;
1207
- // @ts-ignore
1208
- this.matchIndexes[this.matchAt] = opts;
1209
- this.regexes.push([opts, re]);
1210
- this.matchAt += countMatchGroups(re) + 1;
1211
- }
1212
-
1213
- compile() {
1214
- if (this.regexes.length === 0) {
1215
- // avoids the need to check length every time exec is called
1216
- // @ts-ignore
1217
- this.exec = () => null;
1218
- }
1219
- const terminators = this.regexes.map(el => el[1]);
1220
- this.matcherRe = langRe(_rewriteBackreferences(terminators, { joinWith: '|' }), true);
1221
- this.lastIndex = 0;
1222
- }
1223
-
1224
- /** @param {string} s */
1225
- exec(s) {
1226
- this.matcherRe.lastIndex = this.lastIndex;
1227
- const match = this.matcherRe.exec(s);
1228
- if (!match) { return null; }
1229
-
1230
- // eslint-disable-next-line no-undefined
1231
- const i = match.findIndex((el, i) => i > 0 && el !== undefined);
1232
- // @ts-ignore
1233
- const matchData = this.matchIndexes[i];
1234
- // trim off any earlier non-relevant match groups (ie, the other regex
1235
- // match groups that make up the multi-matcher)
1236
- match.splice(0, i);
1237
-
1238
- return Object.assign(match, matchData);
1239
- }
1240
- }
1241
-
1242
- /*
1243
- Created to solve the key deficiently with MultiRegex - there is no way to
1244
- test for multiple matches at a single location. Why would we need to do
1245
- that? In the future a more dynamic engine will allow certain matches to be
1246
- ignored. An example: if we matched say the 3rd regex in a large group but
1247
- decided to ignore it - we'd need to started testing again at the 4th
1248
- regex... but MultiRegex itself gives us no real way to do that.
1249
-
1250
- So what this class creates MultiRegexs on the fly for whatever search
1251
- position they are needed.
1252
-
1253
- NOTE: These additional MultiRegex objects are created dynamically. For most
1254
- grammars most of the time we will never actually need anything more than the
1255
- first MultiRegex - so this shouldn't have too much overhead.
1256
-
1257
- Say this is our search group, and we match regex3, but wish to ignore it.
1258
-
1259
- regex1 | regex2 | regex3 | regex4 | regex5 ' ie, startAt = 0
1260
-
1261
- What we need is a new MultiRegex that only includes the remaining
1262
- possibilities:
1263
-
1264
- regex4 | regex5 ' ie, startAt = 3
1265
-
1266
- This class wraps all that complexity up in a simple API... `startAt` decides
1267
- where in the array of expressions to start doing the matching. It
1268
- auto-increments, so if a match is found at position 2, then startAt will be
1269
- set to 3. If the end is reached startAt will return to 0.
1270
-
1271
- MOST of the time the parser will be setting startAt manually to 0.
1272
- */
1273
- class ResumableMultiRegex {
1274
- constructor() {
1275
- // @ts-ignore
1276
- this.rules = [];
1277
- // @ts-ignore
1278
- this.multiRegexes = [];
1279
- this.count = 0;
1280
-
1281
- this.lastIndex = 0;
1282
- this.regexIndex = 0;
1283
- }
1284
-
1285
- // @ts-ignore
1286
- getMatcher(index) {
1287
- if (this.multiRegexes[index]) return this.multiRegexes[index];
1288
-
1289
- const matcher = new MultiRegex();
1290
- this.rules.slice(index).forEach(([re, opts]) => matcher.addRule(re, opts));
1291
- matcher.compile();
1292
- this.multiRegexes[index] = matcher;
1293
- return matcher;
1294
- }
1295
-
1296
- resumingScanAtSamePosition() {
1297
- return this.regexIndex !== 0;
1298
- }
1299
-
1300
- considerAll() {
1301
- this.regexIndex = 0;
1302
- }
1303
-
1304
- // @ts-ignore
1305
- addRule(re, opts) {
1306
- this.rules.push([re, opts]);
1307
- if (opts.type === "begin") this.count++;
1308
- }
1309
-
1310
- /** @param {string} s */
1311
- exec(s) {
1312
- const m = this.getMatcher(this.regexIndex);
1313
- m.lastIndex = this.lastIndex;
1314
- let result = m.exec(s);
1315
-
1316
- // The following is because we have no easy way to say "resume scanning at the
1317
- // existing position but also skip the current rule ONLY". What happens is
1318
- // all prior rules are also skipped which can result in matching the wrong
1319
- // thing. Example of matching "booger":
1320
-
1321
- // our matcher is [string, "booger", number]
1322
- //
1323
- // ....booger....
1324
-
1325
- // if "booger" is ignored then we'd really need a regex to scan from the
1326
- // SAME position for only: [string, number] but ignoring "booger" (if it
1327
- // was the first match), a simple resume would scan ahead who knows how
1328
- // far looking only for "number", ignoring potential string matches (or
1329
- // future "booger" matches that might be valid.)
1330
-
1331
- // So what we do: We execute two matchers, one resuming at the same
1332
- // position, but the second full matcher starting at the position after:
1333
-
1334
- // /--- resume first regex match here (for [number])
1335
- // |/---- full match here for [string, "booger", number]
1336
- // vv
1337
- // ....booger....
1338
-
1339
- // Which ever results in a match first is then used. So this 3-4 step
1340
- // process essentially allows us to say "match at this position, excluding
1341
- // a prior rule that was ignored".
1342
- //
1343
- // 1. Match "booger" first, ignore. Also proves that [string] does non match.
1344
- // 2. Resume matching for [number]
1345
- // 3. Match at index + 1 for [string, "booger", number]
1346
- // 4. If #2 and #3 result in matches, which came first?
1347
- if (this.resumingScanAtSamePosition()) {
1348
- if (result && result.index === this.lastIndex) ; else { // use the second matcher result
1349
- const m2 = this.getMatcher(0);
1350
- m2.lastIndex = this.lastIndex + 1;
1351
- result = m2.exec(s);
1352
- }
1353
- }
1354
-
1355
- if (result) {
1356
- this.regexIndex += result.position + 1;
1357
- if (this.regexIndex === this.count) {
1358
- // wrap-around to considering all matches again
1359
- this.considerAll();
1360
- }
1361
- }
1362
-
1363
- return result;
1364
- }
1365
- }
1366
-
1367
- /**
1368
- * Given a mode, builds a huge ResumableMultiRegex that can be used to walk
1369
- * the content and find matches.
1370
- *
1371
- * @param {CompiledMode} mode
1372
- * @returns {ResumableMultiRegex}
1373
- */
1374
- function buildModeRegex(mode) {
1375
- const mm = new ResumableMultiRegex();
1376
-
1377
- mode.contains.forEach(term => mm.addRule(term.begin, { rule: term, type: "begin" }));
1378
-
1379
- if (mode.terminatorEnd) {
1380
- mm.addRule(mode.terminatorEnd, { type: "end" });
1381
- }
1382
- if (mode.illegal) {
1383
- mm.addRule(mode.illegal, { type: "illegal" });
1384
- }
1385
-
1386
- return mm;
1387
- }
1388
-
1389
- /** skip vs abort vs ignore
1390
- *
1391
- * @skip - The mode is still entered and exited normally (and contains rules apply),
1392
- * but all content is held and added to the parent buffer rather than being
1393
- * output when the mode ends. Mostly used with `sublanguage` to build up
1394
- * a single large buffer than can be parsed by sublanguage.
1395
- *
1396
- * - The mode begin ands ends normally.
1397
- * - Content matched is added to the parent mode buffer.
1398
- * - The parser cursor is moved forward normally.
1399
- *
1400
- * @abort - A hack placeholder until we have ignore. Aborts the mode (as if it
1401
- * never matched) but DOES NOT continue to match subsequent `contains`
1402
- * modes. Abort is bad/suboptimal because it can result in modes
1403
- * farther down not getting applied because an earlier rule eats the
1404
- * content but then aborts.
1405
- *
1406
- * - The mode does not begin.
1407
- * - Content matched by `begin` is added to the mode buffer.
1408
- * - The parser cursor is moved forward accordingly.
1409
- *
1410
- * @ignore - Ignores the mode (as if it never matched) and continues to match any
1411
- * subsequent `contains` modes. Ignore isn't technically possible with
1412
- * the current parser implementation.
1413
- *
1414
- * - The mode does not begin.
1415
- * - Content matched by `begin` is ignored.
1416
- * - The parser cursor is not moved forward.
1417
- */
1418
-
1419
- /**
1420
- * Compiles an individual mode
1421
- *
1422
- * This can raise an error if the mode contains certain detectable known logic
1423
- * issues.
1424
- * @param {Mode} mode
1425
- * @param {CompiledMode | null} [parent]
1426
- * @returns {CompiledMode | never}
1427
- */
1428
- function compileMode(mode, parent) {
1429
- const cmode = /** @type CompiledMode */ (mode);
1430
- if (mode.isCompiled) return cmode;
1431
-
1432
- [
1433
- scopeClassName,
1434
- // do this early so compiler extensions generally don't have to worry about
1435
- // the distinction between match/begin
1436
- compileMatch,
1437
- MultiClass,
1438
- beforeMatchExt
1439
- ].forEach(ext => ext(mode, parent));
1440
-
1441
- language.compilerExtensions.forEach(ext => ext(mode, parent));
1442
-
1443
- // __beforeBegin is considered private API, internal use only
1444
- mode.__beforeBegin = null;
1445
-
1446
- [
1447
- beginKeywords,
1448
- // do this later so compiler extensions that come earlier have access to the
1449
- // raw array if they wanted to perhaps manipulate it, etc.
1450
- compileIllegal,
1451
- // default to 1 relevance if not specified
1452
- compileRelevance
1453
- ].forEach(ext => ext(mode, parent));
1454
-
1455
- mode.isCompiled = true;
1456
-
1457
- let keywordPattern = null;
1458
- if (typeof mode.keywords === "object" && mode.keywords.$pattern) {
1459
- // we need a copy because keywords might be compiled multiple times
1460
- // so we can't go deleting $pattern from the original on the first
1461
- // pass
1462
- mode.keywords = Object.assign({}, mode.keywords);
1463
- keywordPattern = mode.keywords.$pattern;
1464
- delete mode.keywords.$pattern;
1465
- }
1466
- keywordPattern = keywordPattern || /\w+/;
1467
-
1468
- if (mode.keywords) {
1469
- mode.keywords = compileKeywords(mode.keywords, language.case_insensitive);
1470
- }
1471
-
1472
- cmode.keywordPatternRe = langRe(keywordPattern, true);
1473
-
1474
- if (parent) {
1475
- if (!mode.begin) mode.begin = /\B|\b/;
1476
- cmode.beginRe = langRe(cmode.begin);
1477
- if (!mode.end && !mode.endsWithParent) mode.end = /\B|\b/;
1478
- if (mode.end) cmode.endRe = langRe(cmode.end);
1479
- cmode.terminatorEnd = source(cmode.end) || '';
1480
- if (mode.endsWithParent && parent.terminatorEnd) {
1481
- cmode.terminatorEnd += (mode.end ? '|' : '') + parent.terminatorEnd;
1482
- }
1483
- }
1484
- if (mode.illegal) cmode.illegalRe = langRe(/** @type {RegExp | string} */ (mode.illegal));
1485
- if (!mode.contains) mode.contains = [];
1486
-
1487
- mode.contains = [].concat(...mode.contains.map(function(c) {
1488
- return expandOrCloneMode(c === 'self' ? mode : c);
1489
- }));
1490
- mode.contains.forEach(function(c) { compileMode(/** @type Mode */ (c), cmode); });
1491
-
1492
- if (mode.starts) {
1493
- compileMode(mode.starts, parent);
1494
- }
1495
-
1496
- cmode.matcher = buildModeRegex(cmode);
1497
- return cmode;
1498
- }
1499
-
1500
- if (!language.compilerExtensions) language.compilerExtensions = [];
1501
-
1502
- // self is not valid at the top-level
1503
- if (language.contains && language.contains.includes('self')) {
1504
- throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");
1505
- }
1506
-
1507
- // we need a null object, which inherit will guarantee
1508
- language.classNameAliases = inherit$1(language.classNameAliases || {});
1509
-
1510
- return compileMode(/** @type Mode */ (language));
1511
- }
1512
-
1513
- /**
1514
- * Determines if a mode has a dependency on it's parent or not
1515
- *
1516
- * If a mode does have a parent dependency then often we need to clone it if
1517
- * it's used in multiple places so that each copy points to the correct parent,
1518
- * where-as modes without a parent can often safely be re-used at the bottom of
1519
- * a mode chain.
1520
- *
1521
- * @param {Mode | null} mode
1522
- * @returns {boolean} - is there a dependency on the parent?
1523
- * */
1524
- function dependencyOnParent(mode) {
1525
- if (!mode) return false;
1526
-
1527
- return mode.endsWithParent || dependencyOnParent(mode.starts);
1528
- }
1529
-
1530
- /**
1531
- * Expands a mode or clones it if necessary
1532
- *
1533
- * This is necessary for modes with parental dependenceis (see notes on
1534
- * `dependencyOnParent`) and for nodes that have `variants` - which must then be
1535
- * exploded into their own individual modes at compile time.
1536
- *
1537
- * @param {Mode} mode
1538
- * @returns {Mode | Mode[]}
1539
- * */
1540
- function expandOrCloneMode(mode) {
1541
- if (mode.variants && !mode.cachedVariants) {
1542
- mode.cachedVariants = mode.variants.map(function(variant) {
1543
- return inherit$1(mode, { variants: null }, variant);
1544
- });
1545
- }
1546
-
1547
- // EXPAND
1548
- // if we have variants then essentially "replace" the mode with the variants
1549
- // this happens in compileMode, where this function is called from
1550
- if (mode.cachedVariants) {
1551
- return mode.cachedVariants;
1552
- }
1553
-
1554
- // CLONE
1555
- // if we have dependencies on parents then we need a unique
1556
- // instance of ourselves, so we can be reused with many
1557
- // different parents without issue
1558
- if (dependencyOnParent(mode)) {
1559
- return inherit$1(mode, { starts: mode.starts ? inherit$1(mode.starts) : null });
1560
- }
1561
-
1562
- if (Object.isFrozen(mode)) {
1563
- return inherit$1(mode);
1564
- }
1565
-
1566
- // no special dependency issues, just return ourselves
1567
- return mode;
1568
- }
1569
-
1570
- var version = "11.10.0";
1571
-
1572
- class HTMLInjectionError extends Error {
1573
- constructor(reason, html) {
1574
- super(reason);
1575
- this.name = "HTMLInjectionError";
1576
- this.html = html;
1577
- }
1578
- }
1579
-
1580
- /*
1581
- Syntax highlighting with language autodetection.
1582
- https://highlightjs.org/
1583
- */
1584
-
1585
-
1586
-
1587
- /**
1588
- @typedef {import('highlight.js').Mode} Mode
1589
- @typedef {import('highlight.js').CompiledMode} CompiledMode
1590
- @typedef {import('highlight.js').CompiledScope} CompiledScope
1591
- @typedef {import('highlight.js').Language} Language
1592
- @typedef {import('highlight.js').HLJSApi} HLJSApi
1593
- @typedef {import('highlight.js').HLJSPlugin} HLJSPlugin
1594
- @typedef {import('highlight.js').PluginEvent} PluginEvent
1595
- @typedef {import('highlight.js').HLJSOptions} HLJSOptions
1596
- @typedef {import('highlight.js').LanguageFn} LanguageFn
1597
- @typedef {import('highlight.js').HighlightedHTMLElement} HighlightedHTMLElement
1598
- @typedef {import('highlight.js').BeforeHighlightContext} BeforeHighlightContext
1599
- @typedef {import('highlight.js/private').MatchType} MatchType
1600
- @typedef {import('highlight.js/private').KeywordData} KeywordData
1601
- @typedef {import('highlight.js/private').EnhancedMatch} EnhancedMatch
1602
- @typedef {import('highlight.js/private').AnnotatedError} AnnotatedError
1603
- @typedef {import('highlight.js').AutoHighlightResult} AutoHighlightResult
1604
- @typedef {import('highlight.js').HighlightOptions} HighlightOptions
1605
- @typedef {import('highlight.js').HighlightResult} HighlightResult
1606
- */
1607
-
1608
-
1609
- const escape = escapeHTML;
1610
- const inherit = inherit$1;
1611
- const NO_MATCH = Symbol("nomatch");
1612
- const MAX_KEYWORD_HITS = 7;
1613
-
1614
- /**
1615
- * @param {any} hljs - object that is extended (legacy)
1616
- * @returns {HLJSApi}
1617
- */
1618
- const HLJS = function(hljs) {
1619
- // Global internal variables used within the highlight.js library.
1620
- /** @type {Record<string, Language>} */
1621
- const languages = Object.create(null);
1622
- /** @type {Record<string, string>} */
1623
- const aliases = Object.create(null);
1624
- /** @type {HLJSPlugin[]} */
1625
- const plugins = [];
1626
-
1627
- // safe/production mode - swallows more errors, tries to keep running
1628
- // even if a single syntax or parse hits a fatal error
1629
- let SAFE_MODE = true;
1630
- const LANGUAGE_NOT_FOUND = "Could not find the language '{}', did you forget to load/include a language module?";
1631
- /** @type {Language} */
1632
- const PLAINTEXT_LANGUAGE = { disableAutodetect: true, name: 'Plain text', contains: [] };
1633
-
1634
- // Global options used when within external APIs. This is modified when
1635
- // calling the `hljs.configure` function.
1636
- /** @type HLJSOptions */
1637
- let options = {
1638
- ignoreUnescapedHTML: false,
1639
- throwUnescapedHTML: false,
1640
- noHighlightRe: /^(no-?highlight)$/i,
1641
- languageDetectRe: /\blang(?:uage)?-([\w-]+)\b/i,
1642
- classPrefix: 'hljs-',
1643
- cssSelector: 'pre code',
1644
- languages: null,
1645
- // beta configuration options, subject to change, welcome to discuss
1646
- // https://github.com/highlightjs/highlight.js/issues/1086
1647
- __emitter: TokenTreeEmitter
1648
- };
1649
-
1650
- /* Utility functions */
1651
-
1652
- /**
1653
- * Tests a language name to see if highlighting should be skipped
1654
- * @param {string} languageName
1655
- */
1656
- function shouldNotHighlight(languageName) {
1657
- return options.noHighlightRe.test(languageName);
1658
- }
1659
-
1660
- /**
1661
- * @param {HighlightedHTMLElement} block - the HTML element to determine language for
1662
- */
1663
- function blockLanguage(block) {
1664
- let classes = block.className + ' ';
1665
-
1666
- classes += block.parentNode ? block.parentNode.className : '';
1667
-
1668
- // language-* takes precedence over non-prefixed class names.
1669
- const match = options.languageDetectRe.exec(classes);
1670
- if (match) {
1671
- const language = getLanguage(match[1]);
1672
- if (!language) {
1673
- warn(LANGUAGE_NOT_FOUND.replace("{}", match[1]));
1674
- warn("Falling back to no-highlight mode for this block.", block);
1675
- }
1676
- return language ? match[1] : 'no-highlight';
1677
- }
1678
-
1679
- return classes
1680
- .split(/\s+/)
1681
- .find((_class) => shouldNotHighlight(_class) || getLanguage(_class));
1682
- }
1683
-
1684
- /**
1685
- * Core highlighting function.
1686
- *
1687
- * OLD API
1688
- * highlight(lang, code, ignoreIllegals, continuation)
1689
- *
1690
- * NEW API
1691
- * highlight(code, {lang, ignoreIllegals})
1692
- *
1693
- * @param {string} codeOrLanguageName - the language to use for highlighting
1694
- * @param {string | HighlightOptions} optionsOrCode - the code to highlight
1695
- * @param {boolean} [ignoreIllegals] - whether to ignore illegal matches, default is to bail
1696
- *
1697
- * @returns {HighlightResult} Result - an object that represents the result
1698
- * @property {string} language - the language name
1699
- * @property {number} relevance - the relevance score
1700
- * @property {string} value - the highlighted HTML code
1701
- * @property {string} code - the original raw code
1702
- * @property {CompiledMode} top - top of the current mode stack
1703
- * @property {boolean} illegal - indicates whether any illegal matches were found
1704
- */
1705
- function highlight(codeOrLanguageName, optionsOrCode, ignoreIllegals) {
1706
- let code = "";
1707
- let languageName = "";
1708
- if (typeof optionsOrCode === "object") {
1709
- code = codeOrLanguageName;
1710
- ignoreIllegals = optionsOrCode.ignoreIllegals;
1711
- languageName = optionsOrCode.language;
1712
- } else {
1713
- // old API
1714
- deprecated("10.7.0", "highlight(lang, code, ...args) has been deprecated.");
1715
- deprecated("10.7.0", "Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277");
1716
- languageName = codeOrLanguageName;
1717
- code = optionsOrCode;
1718
- }
1719
-
1720
- // https://github.com/highlightjs/highlight.js/issues/3149
1721
- // eslint-disable-next-line no-undefined
1722
- if (ignoreIllegals === undefined) { ignoreIllegals = true; }
1723
-
1724
- /** @type {BeforeHighlightContext} */
1725
- const context = {
1726
- code,
1727
- language: languageName
1728
- };
1729
- // the plugin can change the desired language or the code to be highlighted
1730
- // just be changing the object it was passed
1731
- fire("before:highlight", context);
1732
-
1733
- // a before plugin can usurp the result completely by providing it's own
1734
- // in which case we don't even need to call highlight
1735
- const result = context.result
1736
- ? context.result
1737
- : _highlight(context.language, context.code, ignoreIllegals);
1738
-
1739
- result.code = context.code;
1740
- // the plugin can change anything in result to suite it
1741
- fire("after:highlight", result);
1742
-
1743
- return result;
1744
- }
1745
-
1746
- /**
1747
- * private highlight that's used internally and does not fire callbacks
1748
- *
1749
- * @param {string} languageName - the language to use for highlighting
1750
- * @param {string} codeToHighlight - the code to highlight
1751
- * @param {boolean?} [ignoreIllegals] - whether to ignore illegal matches, default is to bail
1752
- * @param {CompiledMode?} [continuation] - current continuation mode, if any
1753
- * @returns {HighlightResult} - result of the highlight operation
1754
- */
1755
- function _highlight(languageName, codeToHighlight, ignoreIllegals, continuation) {
1756
- const keywordHits = Object.create(null);
1757
-
1758
- /**
1759
- * Return keyword data if a match is a keyword
1760
- * @param {CompiledMode} mode - current mode
1761
- * @param {string} matchText - the textual match
1762
- * @returns {KeywordData | false}
1763
- */
1764
- function keywordData(mode, matchText) {
1765
- return mode.keywords[matchText];
1766
- }
1767
-
1768
- function processKeywords() {
1769
- if (!top.keywords) {
1770
- emitter.addText(modeBuffer);
1771
- return;
1772
- }
1773
-
1774
- let lastIndex = 0;
1775
- top.keywordPatternRe.lastIndex = 0;
1776
- let match = top.keywordPatternRe.exec(modeBuffer);
1777
- let buf = "";
1778
-
1779
- while (match) {
1780
- buf += modeBuffer.substring(lastIndex, match.index);
1781
- const word = language.case_insensitive ? match[0].toLowerCase() : match[0];
1782
- const data = keywordData(top, word);
1783
- if (data) {
1784
- const [kind, keywordRelevance] = data;
1785
- emitter.addText(buf);
1786
- buf = "";
1787
-
1788
- keywordHits[word] = (keywordHits[word] || 0) + 1;
1789
- if (keywordHits[word] <= MAX_KEYWORD_HITS) relevance += keywordRelevance;
1790
- if (kind.startsWith("_")) {
1791
- // _ implied for relevance only, do not highlight
1792
- // by applying a class name
1793
- buf += match[0];
1794
- } else {
1795
- const cssClass = language.classNameAliases[kind] || kind;
1796
- emitKeyword(match[0], cssClass);
1797
- }
1798
- } else {
1799
- buf += match[0];
1800
- }
1801
- lastIndex = top.keywordPatternRe.lastIndex;
1802
- match = top.keywordPatternRe.exec(modeBuffer);
1803
- }
1804
- buf += modeBuffer.substring(lastIndex);
1805
- emitter.addText(buf);
1806
- }
1807
-
1808
- function processSubLanguage() {
1809
- if (modeBuffer === "") return;
1810
- /** @type HighlightResult */
1811
- let result = null;
1812
-
1813
- if (typeof top.subLanguage === 'string') {
1814
- if (!languages[top.subLanguage]) {
1815
- emitter.addText(modeBuffer);
1816
- return;
1817
- }
1818
- result = _highlight(top.subLanguage, modeBuffer, true, continuations[top.subLanguage]);
1819
- continuations[top.subLanguage] = /** @type {CompiledMode} */ (result._top);
1820
- } else {
1821
- result = highlightAuto(modeBuffer, top.subLanguage.length ? top.subLanguage : null);
1822
- }
1823
-
1824
- // Counting embedded language score towards the host language may be disabled
1825
- // with zeroing the containing mode relevance. Use case in point is Markdown that
1826
- // allows XML everywhere and makes every XML snippet to have a much larger Markdown
1827
- // score.
1828
- if (top.relevance > 0) {
1829
- relevance += result.relevance;
1830
- }
1831
- emitter.__addSublanguage(result._emitter, result.language);
1832
- }
1833
-
1834
- function processBuffer() {
1835
- if (top.subLanguage != null) {
1836
- processSubLanguage();
1837
- } else {
1838
- processKeywords();
1839
- }
1840
- modeBuffer = '';
1841
- }
1842
-
1843
- /**
1844
- * @param {string} text
1845
- * @param {string} scope
1846
- */
1847
- function emitKeyword(keyword, scope) {
1848
- if (keyword === "") return;
1849
-
1850
- emitter.startScope(scope);
1851
- emitter.addText(keyword);
1852
- emitter.endScope();
1853
- }
1854
-
1855
- /**
1856
- * @param {CompiledScope} scope
1857
- * @param {RegExpMatchArray} match
1858
- */
1859
- function emitMultiClass(scope, match) {
1860
- let i = 1;
1861
- const max = match.length - 1;
1862
- while (i <= max) {
1863
- if (!scope._emit[i]) { i++; continue; }
1864
- const klass = language.classNameAliases[scope[i]] || scope[i];
1865
- const text = match[i];
1866
- if (klass) {
1867
- emitKeyword(text, klass);
1868
- } else {
1869
- modeBuffer = text;
1870
- processKeywords();
1871
- modeBuffer = "";
1872
- }
1873
- i++;
1874
- }
1875
- }
1876
-
1877
- /**
1878
- * @param {CompiledMode} mode - new mode to start
1879
- * @param {RegExpMatchArray} match
1880
- */
1881
- function startNewMode(mode, match) {
1882
- if (mode.scope && typeof mode.scope === "string") {
1883
- emitter.openNode(language.classNameAliases[mode.scope] || mode.scope);
1884
- }
1885
- if (mode.beginScope) {
1886
- // beginScope just wraps the begin match itself in a scope
1887
- if (mode.beginScope._wrap) {
1888
- emitKeyword(modeBuffer, language.classNameAliases[mode.beginScope._wrap] || mode.beginScope._wrap);
1889
- modeBuffer = "";
1890
- } else if (mode.beginScope._multi) {
1891
- // at this point modeBuffer should just be the match
1892
- emitMultiClass(mode.beginScope, match);
1893
- modeBuffer = "";
1894
- }
1895
- }
1896
-
1897
- top = Object.create(mode, { parent: { value: top } });
1898
- return top;
1899
- }
1900
-
1901
- /**
1902
- * @param {CompiledMode } mode - the mode to potentially end
1903
- * @param {RegExpMatchArray} match - the latest match
1904
- * @param {string} matchPlusRemainder - match plus remainder of content
1905
- * @returns {CompiledMode | void} - the next mode, or if void continue on in current mode
1906
- */
1907
- function endOfMode(mode, match, matchPlusRemainder) {
1908
- let matched = startsWith(mode.endRe, matchPlusRemainder);
1909
-
1910
- if (matched) {
1911
- if (mode["on:end"]) {
1912
- const resp = new Response(mode);
1913
- mode["on:end"](match, resp);
1914
- if (resp.isMatchIgnored) matched = false;
1915
- }
1916
-
1917
- if (matched) {
1918
- while (mode.endsParent && mode.parent) {
1919
- mode = mode.parent;
1920
- }
1921
- return mode;
1922
- }
1923
- }
1924
- // even if on:end fires an `ignore` it's still possible
1925
- // that we might trigger the end node because of a parent mode
1926
- if (mode.endsWithParent) {
1927
- return endOfMode(mode.parent, match, matchPlusRemainder);
1928
- }
1929
- }
1930
-
1931
- /**
1932
- * Handle matching but then ignoring a sequence of text
1933
- *
1934
- * @param {string} lexeme - string containing full match text
1935
- */
1936
- function doIgnore(lexeme) {
1937
- if (top.matcher.regexIndex === 0) {
1938
- // no more regexes to potentially match here, so we move the cursor forward one
1939
- // space
1940
- modeBuffer += lexeme[0];
1941
- return 1;
1942
- } else {
1943
- // no need to move the cursor, we still have additional regexes to try and
1944
- // match at this very spot
1945
- resumeScanAtSamePosition = true;
1946
- return 0;
1947
- }
1948
- }
1949
-
1950
- /**
1951
- * Handle the start of a new potential mode match
1952
- *
1953
- * @param {EnhancedMatch} match - the current match
1954
- * @returns {number} how far to advance the parse cursor
1955
- */
1956
- function doBeginMatch(match) {
1957
- const lexeme = match[0];
1958
- const newMode = match.rule;
1959
-
1960
- const resp = new Response(newMode);
1961
- // first internal before callbacks, then the public ones
1962
- const beforeCallbacks = [newMode.__beforeBegin, newMode["on:begin"]];
1963
- for (const cb of beforeCallbacks) {
1964
- if (!cb) continue;
1965
- cb(match, resp);
1966
- if (resp.isMatchIgnored) return doIgnore(lexeme);
1967
- }
1968
-
1969
- if (newMode.skip) {
1970
- modeBuffer += lexeme;
1971
- } else {
1972
- if (newMode.excludeBegin) {
1973
- modeBuffer += lexeme;
1974
- }
1975
- processBuffer();
1976
- if (!newMode.returnBegin && !newMode.excludeBegin) {
1977
- modeBuffer = lexeme;
1978
- }
1979
- }
1980
- startNewMode(newMode, match);
1981
- return newMode.returnBegin ? 0 : lexeme.length;
1982
- }
1983
-
1984
- /**
1985
- * Handle the potential end of mode
1986
- *
1987
- * @param {RegExpMatchArray} match - the current match
1988
- */
1989
- function doEndMatch(match) {
1990
- const lexeme = match[0];
1991
- const matchPlusRemainder = codeToHighlight.substring(match.index);
1992
-
1993
- const endMode = endOfMode(top, match, matchPlusRemainder);
1994
- if (!endMode) { return NO_MATCH; }
1995
-
1996
- const origin = top;
1997
- if (top.endScope && top.endScope._wrap) {
1998
- processBuffer();
1999
- emitKeyword(lexeme, top.endScope._wrap);
2000
- } else if (top.endScope && top.endScope._multi) {
2001
- processBuffer();
2002
- emitMultiClass(top.endScope, match);
2003
- } else if (origin.skip) {
2004
- modeBuffer += lexeme;
2005
- } else {
2006
- if (!(origin.returnEnd || origin.excludeEnd)) {
2007
- modeBuffer += lexeme;
2008
- }
2009
- processBuffer();
2010
- if (origin.excludeEnd) {
2011
- modeBuffer = lexeme;
2012
- }
2013
- }
2014
- do {
2015
- if (top.scope) {
2016
- emitter.closeNode();
2017
- }
2018
- if (!top.skip && !top.subLanguage) {
2019
- relevance += top.relevance;
2020
- }
2021
- top = top.parent;
2022
- } while (top !== endMode.parent);
2023
- if (endMode.starts) {
2024
- startNewMode(endMode.starts, match);
2025
- }
2026
- return origin.returnEnd ? 0 : lexeme.length;
2027
- }
2028
-
2029
- function processContinuations() {
2030
- const list = [];
2031
- for (let current = top; current !== language; current = current.parent) {
2032
- if (current.scope) {
2033
- list.unshift(current.scope);
2034
- }
2035
- }
2036
- list.forEach(item => emitter.openNode(item));
2037
- }
2038
-
2039
- /** @type {{type?: MatchType, index?: number, rule?: Mode}}} */
2040
- let lastMatch = {};
2041
-
2042
- /**
2043
- * Process an individual match
2044
- *
2045
- * @param {string} textBeforeMatch - text preceding the match (since the last match)
2046
- * @param {EnhancedMatch} [match] - the match itself
2047
- */
2048
- function processLexeme(textBeforeMatch, match) {
2049
- const lexeme = match && match[0];
2050
-
2051
- // add non-matched text to the current mode buffer
2052
- modeBuffer += textBeforeMatch;
2053
-
2054
- if (lexeme == null) {
2055
- processBuffer();
2056
- return 0;
2057
- }
2058
-
2059
- // we've found a 0 width match and we're stuck, so we need to advance
2060
- // this happens when we have badly behaved rules that have optional matchers to the degree that
2061
- // sometimes they can end up matching nothing at all
2062
- // Ref: https://github.com/highlightjs/highlight.js/issues/2140
2063
- if (lastMatch.type === "begin" && match.type === "end" && lastMatch.index === match.index && lexeme === "") {
2064
- // spit the "skipped" character that our regex choked on back into the output sequence
2065
- modeBuffer += codeToHighlight.slice(match.index, match.index + 1);
2066
- if (!SAFE_MODE) {
2067
- /** @type {AnnotatedError} */
2068
- const err = new Error(`0 width match regex (${languageName})`);
2069
- err.languageName = languageName;
2070
- err.badRule = lastMatch.rule;
2071
- throw err;
2072
- }
2073
- return 1;
2074
- }
2075
- lastMatch = match;
2076
-
2077
- if (match.type === "begin") {
2078
- return doBeginMatch(match);
2079
- } else if (match.type === "illegal" && !ignoreIllegals) {
2080
- // illegal match, we do not continue processing
2081
- /** @type {AnnotatedError} */
2082
- const err = new Error('Illegal lexeme "' + lexeme + '" for mode "' + (top.scope || '<unnamed>') + '"');
2083
- err.mode = top;
2084
- throw err;
2085
- } else if (match.type === "end") {
2086
- const processed = doEndMatch(match);
2087
- if (processed !== NO_MATCH) {
2088
- return processed;
2089
- }
2090
- }
2091
-
2092
- // edge case for when illegal matches $ (end of line) which is technically
2093
- // a 0 width match but not a begin/end match so it's not caught by the
2094
- // first handler (when ignoreIllegals is true)
2095
- if (match.type === "illegal" && lexeme === "") {
2096
- // advance so we aren't stuck in an infinite loop
2097
- return 1;
2098
- }
2099
-
2100
- // infinite loops are BAD, this is a last ditch catch all. if we have a
2101
- // decent number of iterations yet our index (cursor position in our
2102
- // parsing) still 3x behind our index then something is very wrong
2103
- // so we bail
2104
- if (iterations > 100000 && iterations > match.index * 3) {
2105
- const err = new Error('potential infinite loop, way more iterations than matches');
2106
- throw err;
2107
- }
2108
-
2109
- /*
2110
- Why might be find ourselves here? An potential end match that was
2111
- triggered but could not be completed. IE, `doEndMatch` returned NO_MATCH.
2112
- (this could be because a callback requests the match be ignored, etc)
2113
-
2114
- This causes no real harm other than stopping a few times too many.
2115
- */
2116
-
2117
- modeBuffer += lexeme;
2118
- return lexeme.length;
2119
- }
2120
-
2121
- const language = getLanguage(languageName);
2122
- if (!language) {
2123
- error(LANGUAGE_NOT_FOUND.replace("{}", languageName));
2124
- throw new Error('Unknown language: "' + languageName + '"');
2125
- }
2126
-
2127
- const md = compileLanguage(language);
2128
- let result = '';
2129
- /** @type {CompiledMode} */
2130
- let top = continuation || md;
2131
- /** @type Record<string,CompiledMode> */
2132
- const continuations = {}; // keep continuations for sub-languages
2133
- const emitter = new options.__emitter(options);
2134
- processContinuations();
2135
- let modeBuffer = '';
2136
- let relevance = 0;
2137
- let index = 0;
2138
- let iterations = 0;
2139
- let resumeScanAtSamePosition = false;
2140
-
2141
- try {
2142
- if (!language.__emitTokens) {
2143
- top.matcher.considerAll();
2144
-
2145
- for (;;) {
2146
- iterations++;
2147
- if (resumeScanAtSamePosition) {
2148
- // only regexes not matched previously will now be
2149
- // considered for a potential match
2150
- resumeScanAtSamePosition = false;
2151
- } else {
2152
- top.matcher.considerAll();
2153
- }
2154
- top.matcher.lastIndex = index;
2155
-
2156
- const match = top.matcher.exec(codeToHighlight);
2157
- // console.log("match", match[0], match.rule && match.rule.begin)
2158
-
2159
- if (!match) break;
2160
-
2161
- const beforeMatch = codeToHighlight.substring(index, match.index);
2162
- const processedCount = processLexeme(beforeMatch, match);
2163
- index = match.index + processedCount;
2164
- }
2165
- processLexeme(codeToHighlight.substring(index));
2166
- } else {
2167
- language.__emitTokens(codeToHighlight, emitter);
2168
- }
2169
-
2170
- emitter.finalize();
2171
- result = emitter.toHTML();
2172
-
2173
- return {
2174
- language: languageName,
2175
- value: result,
2176
- relevance,
2177
- illegal: false,
2178
- _emitter: emitter,
2179
- _top: top
2180
- };
2181
- } catch (err) {
2182
- if (err.message && err.message.includes('Illegal')) {
2183
- return {
2184
- language: languageName,
2185
- value: escape(codeToHighlight),
2186
- illegal: true,
2187
- relevance: 0,
2188
- _illegalBy: {
2189
- message: err.message,
2190
- index,
2191
- context: codeToHighlight.slice(index - 100, index + 100),
2192
- mode: err.mode,
2193
- resultSoFar: result
2194
- },
2195
- _emitter: emitter
2196
- };
2197
- } else if (SAFE_MODE) {
2198
- return {
2199
- language: languageName,
2200
- value: escape(codeToHighlight),
2201
- illegal: false,
2202
- relevance: 0,
2203
- errorRaised: err,
2204
- _emitter: emitter,
2205
- _top: top
2206
- };
2207
- } else {
2208
- throw err;
2209
- }
2210
- }
2211
- }
2212
-
2213
- /**
2214
- * returns a valid highlight result, without actually doing any actual work,
2215
- * auto highlight starts with this and it's possible for small snippets that
2216
- * auto-detection may not find a better match
2217
- * @param {string} code
2218
- * @returns {HighlightResult}
2219
- */
2220
- function justTextHighlightResult(code) {
2221
- const result = {
2222
- value: escape(code),
2223
- illegal: false,
2224
- relevance: 0,
2225
- _top: PLAINTEXT_LANGUAGE,
2226
- _emitter: new options.__emitter(options)
2227
- };
2228
- result._emitter.addText(code);
2229
- return result;
2230
- }
2231
-
2232
- /**
2233
- Highlighting with language detection. Accepts a string with the code to
2234
- highlight. Returns an object with the following properties:
2235
-
2236
- - language (detected language)
2237
- - relevance (int)
2238
- - value (an HTML string with highlighting markup)
2239
- - secondBest (object with the same structure for second-best heuristically
2240
- detected language, may be absent)
2241
-
2242
- @param {string} code
2243
- @param {Array<string>} [languageSubset]
2244
- @returns {AutoHighlightResult}
2245
- */
2246
- function highlightAuto(code, languageSubset) {
2247
- languageSubset = languageSubset || options.languages || Object.keys(languages);
2248
- const plaintext = justTextHighlightResult(code);
2249
-
2250
- const results = languageSubset.filter(getLanguage).filter(autoDetection).map(name =>
2251
- _highlight(name, code, false)
2252
- );
2253
- results.unshift(plaintext); // plaintext is always an option
2254
-
2255
- const sorted = results.sort((a, b) => {
2256
- // sort base on relevance
2257
- if (a.relevance !== b.relevance) return b.relevance - a.relevance;
2258
-
2259
- // always award the tie to the base language
2260
- // ie if C++ and Arduino are tied, it's more likely to be C++
2261
- if (a.language && b.language) {
2262
- if (getLanguage(a.language).supersetOf === b.language) {
2263
- return 1;
2264
- } else if (getLanguage(b.language).supersetOf === a.language) {
2265
- return -1;
2266
- }
2267
- }
2268
-
2269
- // otherwise say they are equal, which has the effect of sorting on
2270
- // relevance while preserving the original ordering - which is how ties
2271
- // have historically been settled, ie the language that comes first always
2272
- // wins in the case of a tie
2273
- return 0;
2274
- });
2275
-
2276
- const [best, secondBest] = sorted;
2277
-
2278
- /** @type {AutoHighlightResult} */
2279
- const result = best;
2280
- result.secondBest = secondBest;
2281
-
2282
- return result;
2283
- }
2284
-
2285
- /**
2286
- * Builds new class name for block given the language name
2287
- *
2288
- * @param {HTMLElement} element
2289
- * @param {string} [currentLang]
2290
- * @param {string} [resultLang]
2291
- */
2292
- function updateClassName(element, currentLang, resultLang) {
2293
- const language = (currentLang && aliases[currentLang]) || resultLang;
2294
-
2295
- element.classList.add("hljs");
2296
- element.classList.add(`language-${language}`);
2297
- }
2298
-
2299
- /**
2300
- * Applies highlighting to a DOM node containing code.
2301
- *
2302
- * @param {HighlightedHTMLElement} element - the HTML element to highlight
2303
- */
2304
- function highlightElement(element) {
2305
- /** @type HTMLElement */
2306
- let node = null;
2307
- const language = blockLanguage(element);
2308
-
2309
- if (shouldNotHighlight(language)) return;
2310
-
2311
- fire("before:highlightElement",
2312
- { el: element, language });
2313
-
2314
- if (element.dataset.highlighted) {
2315
- console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.", element);
2316
- return;
2317
- }
2318
-
2319
- // we should be all text, no child nodes (unescaped HTML) - this is possibly
2320
- // an HTML injection attack - it's likely too late if this is already in
2321
- // production (the code has likely already done its damage by the time
2322
- // we're seeing it)... but we yell loudly about this so that hopefully it's
2323
- // more likely to be caught in development before making it to production
2324
- if (element.children.length > 0) {
2325
- if (!options.ignoreUnescapedHTML) {
2326
- console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk.");
2327
- console.warn("https://github.com/highlightjs/highlight.js/wiki/security");
2328
- console.warn("The element with unescaped HTML:");
2329
- console.warn(element);
2330
- }
2331
- if (options.throwUnescapedHTML) {
2332
- const err = new HTMLInjectionError(
2333
- "One of your code blocks includes unescaped HTML.",
2334
- element.innerHTML
2335
- );
2336
- throw err;
2337
- }
2338
- }
2339
-
2340
- node = element;
2341
- const text = node.textContent;
2342
- const result = language ? highlight(text, { language, ignoreIllegals: true }) : highlightAuto(text);
2343
-
2344
- element.innerHTML = result.value;
2345
- element.dataset.highlighted = "yes";
2346
- updateClassName(element, language, result.language);
2347
- element.result = {
2348
- language: result.language,
2349
- // TODO: remove with version 11.0
2350
- re: result.relevance,
2351
- relevance: result.relevance
2352
- };
2353
- if (result.secondBest) {
2354
- element.secondBest = {
2355
- language: result.secondBest.language,
2356
- relevance: result.secondBest.relevance
2357
- };
2358
- }
2359
-
2360
- fire("after:highlightElement", { el: element, result, text });
2361
- }
2362
-
2363
- /**
2364
- * Updates highlight.js global options with the passed options
2365
- *
2366
- * @param {Partial<HLJSOptions>} userOptions
2367
- */
2368
- function configure(userOptions) {
2369
- options = inherit(options, userOptions);
2370
- }
2371
-
2372
- // TODO: remove v12, deprecated
2373
- const initHighlighting = () => {
2374
- highlightAll();
2375
- deprecated("10.6.0", "initHighlighting() deprecated. Use highlightAll() now.");
2376
- };
2377
-
2378
- // TODO: remove v12, deprecated
2379
- function initHighlightingOnLoad() {
2380
- highlightAll();
2381
- deprecated("10.6.0", "initHighlightingOnLoad() deprecated. Use highlightAll() now.");
2382
- }
2383
-
2384
- let wantsHighlight = false;
2385
-
2386
- /**
2387
- * auto-highlights all pre>code elements on the page
2388
- */
2389
- function highlightAll() {
2390
- // if we are called too early in the loading process
2391
- if (document.readyState === "loading") {
2392
- wantsHighlight = true;
2393
- return;
2394
- }
2395
-
2396
- const blocks = document.querySelectorAll(options.cssSelector);
2397
- blocks.forEach(highlightElement);
2398
- }
2399
-
2400
- function boot() {
2401
- // if a highlight was requested before DOM was loaded, do now
2402
- if (wantsHighlight) highlightAll();
2403
- }
2404
-
2405
- // make sure we are in the browser environment
2406
- if (typeof window !== 'undefined' && window.addEventListener) {
2407
- window.addEventListener('DOMContentLoaded', boot, false);
2408
- }
2409
-
2410
- /**
2411
- * Register a language grammar module
2412
- *
2413
- * @param {string} languageName
2414
- * @param {LanguageFn} languageDefinition
2415
- */
2416
- function registerLanguage(languageName, languageDefinition) {
2417
- let lang = null;
2418
- try {
2419
- lang = languageDefinition(hljs);
2420
- } catch (error$1) {
2421
- error("Language definition for '{}' could not be registered.".replace("{}", languageName));
2422
- // hard or soft error
2423
- if (!SAFE_MODE) { throw error$1; } else { error(error$1); }
2424
- // languages that have serious errors are replaced with essentially a
2425
- // "plaintext" stand-in so that the code blocks will still get normal
2426
- // css classes applied to them - and one bad language won't break the
2427
- // entire highlighter
2428
- lang = PLAINTEXT_LANGUAGE;
2429
- }
2430
- // give it a temporary name if it doesn't have one in the meta-data
2431
- if (!lang.name) lang.name = languageName;
2432
- languages[languageName] = lang;
2433
- lang.rawDefinition = languageDefinition.bind(null, hljs);
2434
-
2435
- if (lang.aliases) {
2436
- registerAliases(lang.aliases, { languageName });
2437
- }
2438
- }
2439
-
2440
- /**
2441
- * Remove a language grammar module
2442
- *
2443
- * @param {string} languageName
2444
- */
2445
- function unregisterLanguage(languageName) {
2446
- delete languages[languageName];
2447
- for (const alias of Object.keys(aliases)) {
2448
- if (aliases[alias] === languageName) {
2449
- delete aliases[alias];
2450
- }
2451
- }
2452
- }
2453
-
2454
- /**
2455
- * @returns {string[]} List of language internal names
2456
- */
2457
- function listLanguages() {
2458
- return Object.keys(languages);
2459
- }
2460
-
2461
- /**
2462
- * @param {string} name - name of the language to retrieve
2463
- * @returns {Language | undefined}
2464
- */
2465
- function getLanguage(name) {
2466
- name = (name || '').toLowerCase();
2467
- return languages[name] || languages[aliases[name]];
2468
- }
2469
-
2470
- /**
2471
- *
2472
- * @param {string|string[]} aliasList - single alias or list of aliases
2473
- * @param {{languageName: string}} opts
2474
- */
2475
- function registerAliases(aliasList, { languageName }) {
2476
- if (typeof aliasList === 'string') {
2477
- aliasList = [aliasList];
2478
- }
2479
- aliasList.forEach(alias => { aliases[alias.toLowerCase()] = languageName; });
2480
- }
2481
-
2482
- /**
2483
- * Determines if a given language has auto-detection enabled
2484
- * @param {string} name - name of the language
2485
- */
2486
- function autoDetection(name) {
2487
- const lang = getLanguage(name);
2488
- return lang && !lang.disableAutodetect;
2489
- }
2490
-
2491
- /**
2492
- * Upgrades the old highlightBlock plugins to the new
2493
- * highlightElement API
2494
- * @param {HLJSPlugin} plugin
2495
- */
2496
- function upgradePluginAPI(plugin) {
2497
- // TODO: remove with v12
2498
- if (plugin["before:highlightBlock"] && !plugin["before:highlightElement"]) {
2499
- plugin["before:highlightElement"] = (data) => {
2500
- plugin["before:highlightBlock"](
2501
- Object.assign({ block: data.el }, data)
2502
- );
2503
- };
2504
- }
2505
- if (plugin["after:highlightBlock"] && !plugin["after:highlightElement"]) {
2506
- plugin["after:highlightElement"] = (data) => {
2507
- plugin["after:highlightBlock"](
2508
- Object.assign({ block: data.el }, data)
2509
- );
2510
- };
2511
- }
2512
- }
2513
-
2514
- /**
2515
- * @param {HLJSPlugin} plugin
2516
- */
2517
- function addPlugin(plugin) {
2518
- upgradePluginAPI(plugin);
2519
- plugins.push(plugin);
2520
- }
2521
-
2522
- /**
2523
- * @param {HLJSPlugin} plugin
2524
- */
2525
- function removePlugin(plugin) {
2526
- const index = plugins.indexOf(plugin);
2527
- if (index !== -1) {
2528
- plugins.splice(index, 1);
2529
- }
2530
- }
2531
-
2532
- /**
2533
- *
2534
- * @param {PluginEvent} event
2535
- * @param {any} args
2536
- */
2537
- function fire(event, args) {
2538
- const cb = event;
2539
- plugins.forEach(function(plugin) {
2540
- if (plugin[cb]) {
2541
- plugin[cb](args);
2542
- }
2543
- });
2544
- }
2545
-
2546
- /**
2547
- * DEPRECATED
2548
- * @param {HighlightedHTMLElement} el
2549
- */
2550
- function deprecateHighlightBlock(el) {
2551
- deprecated("10.7.0", "highlightBlock will be removed entirely in v12.0");
2552
- deprecated("10.7.0", "Please use highlightElement now.");
2553
-
2554
- return highlightElement(el);
2555
- }
2556
-
2557
- /* Interface definition */
2558
- Object.assign(hljs, {
2559
- highlight,
2560
- highlightAuto,
2561
- highlightAll,
2562
- highlightElement,
2563
- // TODO: Remove with v12 API
2564
- highlightBlock: deprecateHighlightBlock,
2565
- configure,
2566
- initHighlighting,
2567
- initHighlightingOnLoad,
2568
- registerLanguage,
2569
- unregisterLanguage,
2570
- listLanguages,
2571
- getLanguage,
2572
- registerAliases,
2573
- autoDetection,
2574
- inherit,
2575
- addPlugin,
2576
- removePlugin
2577
- });
2578
-
2579
- hljs.debugMode = function() { SAFE_MODE = false; };
2580
- hljs.safeMode = function() { SAFE_MODE = true; };
2581
- hljs.versionString = version;
2582
-
2583
- hljs.regex = {
2584
- concat: concat,
2585
- lookahead: lookahead,
2586
- either: either,
2587
- optional: optional,
2588
- anyNumberOfTimes: anyNumberOfTimes
2589
- };
2590
-
2591
- for (const key in MODES) {
2592
- // @ts-ignore
2593
- if (typeof MODES[key] === "object") {
2594
- // @ts-ignore
2595
- deepFreeze(MODES[key]);
2596
- }
2597
- }
2598
-
2599
- // merge all the modes/regexes into our main object
2600
- Object.assign(hljs, MODES);
2601
-
2602
- return hljs;
2603
- };
2604
-
2605
- // Other names for the variable may break build script
2606
- const highlight = HLJS({});
2607
-
2608
- // returns a new instance of the highlighter to be used for extensions
2609
- // check https://github.com/wooorm/lowlight/issues/47
2610
- highlight.newInstance = () => HLJS({});
2611
-
2612
- var core = highlight;
2613
- highlight.HighlightJS = highlight;
2614
- highlight.default = highlight;
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ CodeBlockLowlight: () => CodeBlockLowlight,
34
+ default: () => src_default
35
+ });
36
+ module.exports = __toCommonJS(src_exports);
2615
37
 
2616
- var HighlightJS = /*@__PURE__*/getDefaultExportFromCjs(core);
38
+ // src/code-block-lowlight.ts
39
+ var import_extension_code_block = __toESM(require("@tiptap/extension-code-block"), 1);
2617
40
 
41
+ // src/lowlight-plugin.ts
42
+ var import_core = require("@tiptap/core");
43
+ var import_state = require("@tiptap/pm/state");
44
+ var import_view = require("@tiptap/pm/view");
45
+ var import_core2 = __toESM(require("highlight.js/lib/core"), 1);
2618
46
  function parseNodes(nodes, className = []) {
2619
- return nodes
2620
- .map(node => {
2621
- const classes = [...className, ...(node.properties ? node.properties.className : [])];
2622
- if (node.children) {
2623
- return parseNodes(node.children, classes);
2624
- }
2625
- return {
2626
- text: node.value,
2627
- classes,
2628
- };
2629
- })
2630
- .flat();
47
+ return nodes.map((node) => {
48
+ const classes = [...className, ...node.properties ? node.properties.className : []];
49
+ if (node.children) {
50
+ return parseNodes(node.children, classes);
51
+ }
52
+ return {
53
+ text: node.value,
54
+ classes
55
+ };
56
+ }).flat();
2631
57
  }
2632
58
  function getHighlightNodes(result) {
2633
- // `.value` for lowlight v1, `.children` for lowlight v2
2634
- return result.value || result.children || [];
59
+ return result.value || result.children || [];
2635
60
  }
2636
61
  function registered(aliasOrLanguage) {
2637
- return Boolean(HighlightJS.getLanguage(aliasOrLanguage));
2638
- }
2639
- function getDecorations({ doc, name, lowlight, defaultLanguage, }) {
2640
- const decorations = [];
2641
- core$1.findChildren(doc, node => node.type.name === name).forEach(block => {
2642
- let from = block.pos + 1;
2643
- const language = block.node.attrs.language || defaultLanguage;
2644
- const languages = lowlight.listLanguages();
2645
- const nodes = language && (languages.includes(language) || registered(language))
2646
- ? getHighlightNodes(lowlight.highlight(language, block.node.textContent))
2647
- : getHighlightNodes(lowlight.highlightAuto(block.node.textContent));
2648
- parseNodes(nodes).forEach(node => {
2649
- const to = from + node.text.length;
2650
- if (node.classes.length) {
2651
- const decoration = view.Decoration.inline(from, to, {
2652
- class: node.classes.join(' '),
2653
- });
2654
- decorations.push(decoration);
2655
- }
2656
- from = to;
62
+ return Boolean(import_core2.default.getLanguage(aliasOrLanguage));
63
+ }
64
+ function getDecorations({
65
+ doc,
66
+ name,
67
+ lowlight,
68
+ defaultLanguage
69
+ }) {
70
+ const decorations = [];
71
+ (0, import_core.findChildren)(doc, (node) => node.type.name === name).forEach((block) => {
72
+ let from = block.pos + 1;
73
+ const language = block.node.attrs.language || defaultLanguage;
74
+ const languages = lowlight.listLanguages();
75
+ const nodes = language && (languages.includes(language) || registered(language)) ? getHighlightNodes(lowlight.highlight(language, block.node.textContent)) : getHighlightNodes(lowlight.highlightAuto(block.node.textContent));
76
+ parseNodes(nodes).forEach((node) => {
77
+ const to = from + node.text.length;
78
+ if (node.classes.length) {
79
+ const decoration = import_view.Decoration.inline(from, to, {
80
+ class: node.classes.join(" ")
2657
81
  });
82
+ decorations.push(decoration);
83
+ }
84
+ from = to;
2658
85
  });
2659
- return view.DecorationSet.create(doc, decorations);
86
+ });
87
+ return import_view.DecorationSet.create(doc, decorations);
2660
88
  }
2661
89
  function isFunction(param) {
2662
- return typeof param === 'function';
2663
- }
2664
- function LowlightPlugin({ name, lowlight, defaultLanguage, }) {
2665
- if (!['highlight', 'highlightAuto', 'listLanguages'].every(api => isFunction(lowlight[api]))) {
2666
- throw Error('You should provide an instance of lowlight to use the code-block-lowlight extension');
90
+ return typeof param === "function";
91
+ }
92
+ function LowlightPlugin({
93
+ name,
94
+ lowlight,
95
+ defaultLanguage
96
+ }) {
97
+ if (!["highlight", "highlightAuto", "listLanguages"].every((api) => isFunction(lowlight[api]))) {
98
+ throw Error(
99
+ "You should provide an instance of lowlight to use the code-block-lowlight extension"
100
+ );
101
+ }
102
+ const lowlightPlugin = new import_state.Plugin({
103
+ key: new import_state.PluginKey("lowlight"),
104
+ state: {
105
+ init: (_, { doc }) => getDecorations({
106
+ doc,
107
+ name,
108
+ lowlight,
109
+ defaultLanguage
110
+ }),
111
+ apply: (transaction, decorationSet, oldState, newState) => {
112
+ const oldNodeName = oldState.selection.$head.parent.type.name;
113
+ const newNodeName = newState.selection.$head.parent.type.name;
114
+ const oldNodes = (0, import_core.findChildren)(oldState.doc, (node) => node.type.name === name);
115
+ const newNodes = (0, import_core.findChildren)(newState.doc, (node) => node.type.name === name);
116
+ if (transaction.docChanged && ([oldNodeName, newNodeName].includes(name) || newNodes.length !== oldNodes.length || transaction.steps.some((step) => {
117
+ return (
118
+ // @ts-ignore
119
+ step.from !== void 0 && step.to !== void 0 && oldNodes.some((node) => {
120
+ return (
121
+ // @ts-ignore
122
+ node.pos >= step.from && node.pos + node.node.nodeSize <= step.to
123
+ );
124
+ })
125
+ );
126
+ }))) {
127
+ return getDecorations({
128
+ doc: transaction.doc,
129
+ name,
130
+ lowlight,
131
+ defaultLanguage
132
+ });
133
+ }
134
+ return decorationSet.map(transaction.mapping, transaction.doc);
135
+ }
136
+ },
137
+ props: {
138
+ decorations(state) {
139
+ return lowlightPlugin.getState(state);
140
+ }
2667
141
  }
2668
- const lowlightPlugin = new state.Plugin({
2669
- key: new state.PluginKey('lowlight'),
2670
- state: {
2671
- init: (_, { doc }) => getDecorations({
2672
- doc,
2673
- name,
2674
- lowlight,
2675
- defaultLanguage,
2676
- }),
2677
- apply: (transaction, decorationSet, oldState, newState) => {
2678
- const oldNodeName = oldState.selection.$head.parent.type.name;
2679
- const newNodeName = newState.selection.$head.parent.type.name;
2680
- const oldNodes = core$1.findChildren(oldState.doc, node => node.type.name === name);
2681
- const newNodes = core$1.findChildren(newState.doc, node => node.type.name === name);
2682
- if (transaction.docChanged
2683
- // Apply decorations if:
2684
- // selection includes named node,
2685
- && ([oldNodeName, newNodeName].includes(name)
2686
- // OR transaction adds/removes named node,
2687
- || newNodes.length !== oldNodes.length
2688
- // OR transaction has changes that completely encapsulte a node
2689
- // (for example, a transaction that affects the entire document).
2690
- // Such transactions can happen during collab syncing via y-prosemirror, for example.
2691
- || transaction.steps.some(step => {
2692
- // @ts-ignore
2693
- return (
2694
- // @ts-ignore
2695
- step.from !== undefined
2696
- // @ts-ignore
2697
- && step.to !== undefined
2698
- && oldNodes.some(node => {
2699
- // @ts-ignore
2700
- return (
2701
- // @ts-ignore
2702
- node.pos >= step.from
2703
- // @ts-ignore
2704
- && node.pos + node.node.nodeSize <= step.to);
2705
- }));
2706
- }))) {
2707
- return getDecorations({
2708
- doc: transaction.doc,
2709
- name,
2710
- lowlight,
2711
- defaultLanguage,
2712
- });
2713
- }
2714
- return decorationSet.map(transaction.mapping, transaction.doc);
2715
- },
2716
- },
2717
- props: {
2718
- decorations(state) {
2719
- return lowlightPlugin.getState(state);
2720
- },
2721
- },
2722
- });
2723
- return lowlightPlugin;
142
+ });
143
+ return lowlightPlugin;
2724
144
  }
2725
145
 
2726
- /**
2727
- * This extension allows you to highlight code blocks with lowlight.
2728
- * @see https://tiptap.dev/api/nodes/code-block-lowlight
2729
- */
2730
- const CodeBlockLowlight = CodeBlock__default.default.extend({
2731
- addOptions() {
2732
- var _a;
2733
- return {
2734
- ...(_a = this.parent) === null || _a === void 0 ? void 0 : _a.call(this),
2735
- lowlight: {},
2736
- };
2737
- },
2738
- addProseMirrorPlugins() {
2739
- var _a;
2740
- return [
2741
- ...((_a = this.parent) === null || _a === void 0 ? void 0 : _a.call(this)) || [],
2742
- LowlightPlugin({
2743
- name: this.name,
2744
- lowlight: this.options.lowlight,
2745
- defaultLanguage: this.options.defaultLanguage,
2746
- }),
2747
- ];
2748
- },
146
+ // src/code-block-lowlight.ts
147
+ var CodeBlockLowlight = import_extension_code_block.default.extend({
148
+ addOptions() {
149
+ var _a;
150
+ return {
151
+ ...(_a = this.parent) == null ? void 0 : _a.call(this),
152
+ lowlight: {}
153
+ };
154
+ },
155
+ addProseMirrorPlugins() {
156
+ var _a;
157
+ return [
158
+ ...((_a = this.parent) == null ? void 0 : _a.call(this)) || [],
159
+ LowlightPlugin({
160
+ name: this.name,
161
+ lowlight: this.options.lowlight,
162
+ defaultLanguage: this.options.defaultLanguage
163
+ })
164
+ ];
165
+ }
2749
166
  });
2750
167
 
2751
- exports.CodeBlockLowlight = CodeBlockLowlight;
2752
- exports.default = CodeBlockLowlight;
2753
- //# sourceMappingURL=index.cjs.map
168
+ // src/index.ts
169
+ var src_default = CodeBlockLowlight;
170
+ // Annotate the CommonJS export names for ESM import in node:
171
+ 0 && (module.exports = {
172
+ CodeBlockLowlight
173
+ });
174
+ //# sourceMappingURL=index.cjs.map