@ckeditor/ckeditor5-autoformat 41.3.1 → 41.4.0

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 (134) hide show
  1. package/dist/index-content.css +4 -0
  2. package/dist/index-editor.css +4 -0
  3. package/dist/index.css +4 -0
  4. package/dist/index.js +497 -0
  5. package/dist/index.js.map +1 -0
  6. package/dist/translations/ar.d.ts +8 -0
  7. package/dist/translations/ar.js +5 -0
  8. package/dist/translations/ar.umd.js +11 -0
  9. package/dist/translations/bg.d.ts +8 -0
  10. package/dist/translations/bg.js +5 -0
  11. package/dist/translations/bg.umd.js +11 -0
  12. package/dist/translations/bn.d.ts +8 -0
  13. package/dist/translations/bn.js +5 -0
  14. package/dist/translations/bn.umd.js +11 -0
  15. package/dist/translations/ca.d.ts +8 -0
  16. package/dist/translations/ca.js +5 -0
  17. package/dist/translations/ca.umd.js +11 -0
  18. package/dist/translations/cs.d.ts +8 -0
  19. package/dist/translations/cs.js +5 -0
  20. package/dist/translations/cs.umd.js +11 -0
  21. package/dist/translations/da.d.ts +8 -0
  22. package/dist/translations/da.js +5 -0
  23. package/dist/translations/da.umd.js +11 -0
  24. package/dist/translations/de.d.ts +8 -0
  25. package/dist/translations/de.js +5 -0
  26. package/dist/translations/de.umd.js +11 -0
  27. package/dist/translations/el.d.ts +8 -0
  28. package/dist/translations/el.js +5 -0
  29. package/dist/translations/el.umd.js +11 -0
  30. package/dist/translations/en.d.ts +8 -0
  31. package/dist/translations/en.js +5 -0
  32. package/dist/translations/en.umd.js +11 -0
  33. package/dist/translations/es-co.d.ts +8 -0
  34. package/dist/translations/es-co.js +5 -0
  35. package/dist/translations/es-co.umd.js +11 -0
  36. package/dist/translations/es.d.ts +8 -0
  37. package/dist/translations/es.js +5 -0
  38. package/dist/translations/es.umd.js +11 -0
  39. package/dist/translations/et.d.ts +8 -0
  40. package/dist/translations/et.js +5 -0
  41. package/dist/translations/et.umd.js +11 -0
  42. package/dist/translations/fi.d.ts +8 -0
  43. package/dist/translations/fi.js +5 -0
  44. package/dist/translations/fi.umd.js +11 -0
  45. package/dist/translations/fr.d.ts +8 -0
  46. package/dist/translations/fr.js +5 -0
  47. package/dist/translations/fr.umd.js +11 -0
  48. package/dist/translations/he.d.ts +8 -0
  49. package/dist/translations/he.js +5 -0
  50. package/dist/translations/he.umd.js +11 -0
  51. package/dist/translations/hi.d.ts +8 -0
  52. package/dist/translations/hi.js +5 -0
  53. package/dist/translations/hi.umd.js +11 -0
  54. package/dist/translations/hr.d.ts +8 -0
  55. package/dist/translations/hr.js +5 -0
  56. package/dist/translations/hr.umd.js +11 -0
  57. package/dist/translations/hu.d.ts +8 -0
  58. package/dist/translations/hu.js +5 -0
  59. package/dist/translations/hu.umd.js +11 -0
  60. package/dist/translations/id.d.ts +8 -0
  61. package/dist/translations/id.js +5 -0
  62. package/dist/translations/id.umd.js +11 -0
  63. package/dist/translations/it.d.ts +8 -0
  64. package/dist/translations/it.js +5 -0
  65. package/dist/translations/it.umd.js +11 -0
  66. package/dist/translations/ja.d.ts +8 -0
  67. package/dist/translations/ja.js +5 -0
  68. package/dist/translations/ja.umd.js +11 -0
  69. package/dist/translations/ko.d.ts +8 -0
  70. package/dist/translations/ko.js +5 -0
  71. package/dist/translations/ko.umd.js +11 -0
  72. package/dist/translations/lt.d.ts +8 -0
  73. package/dist/translations/lt.js +5 -0
  74. package/dist/translations/lt.umd.js +11 -0
  75. package/dist/translations/lv.d.ts +8 -0
  76. package/dist/translations/lv.js +5 -0
  77. package/dist/translations/lv.umd.js +11 -0
  78. package/dist/translations/ms.d.ts +8 -0
  79. package/dist/translations/ms.js +5 -0
  80. package/dist/translations/ms.umd.js +11 -0
  81. package/dist/translations/nl.d.ts +8 -0
  82. package/dist/translations/nl.js +5 -0
  83. package/dist/translations/nl.umd.js +11 -0
  84. package/dist/translations/no.d.ts +8 -0
  85. package/dist/translations/no.js +5 -0
  86. package/dist/translations/no.umd.js +11 -0
  87. package/dist/translations/pl.d.ts +8 -0
  88. package/dist/translations/pl.js +5 -0
  89. package/dist/translations/pl.umd.js +11 -0
  90. package/dist/translations/pt-br.d.ts +8 -0
  91. package/dist/translations/pt-br.js +5 -0
  92. package/dist/translations/pt-br.umd.js +11 -0
  93. package/dist/translations/pt.d.ts +8 -0
  94. package/dist/translations/pt.js +5 -0
  95. package/dist/translations/pt.umd.js +11 -0
  96. package/dist/translations/ro.d.ts +8 -0
  97. package/dist/translations/ro.js +5 -0
  98. package/dist/translations/ro.umd.js +11 -0
  99. package/dist/translations/ru.d.ts +8 -0
  100. package/dist/translations/ru.js +5 -0
  101. package/dist/translations/ru.umd.js +11 -0
  102. package/dist/translations/sk.d.ts +8 -0
  103. package/dist/translations/sk.js +5 -0
  104. package/dist/translations/sk.umd.js +11 -0
  105. package/dist/translations/sr.d.ts +8 -0
  106. package/dist/translations/sr.js +5 -0
  107. package/dist/translations/sr.umd.js +11 -0
  108. package/dist/translations/sv.d.ts +8 -0
  109. package/dist/translations/sv.js +5 -0
  110. package/dist/translations/sv.umd.js +11 -0
  111. package/dist/translations/th.d.ts +8 -0
  112. package/dist/translations/th.js +5 -0
  113. package/dist/translations/th.umd.js +11 -0
  114. package/dist/translations/tr.d.ts +8 -0
  115. package/dist/translations/tr.js +5 -0
  116. package/dist/translations/tr.umd.js +11 -0
  117. package/dist/translations/uk.d.ts +8 -0
  118. package/dist/translations/uk.js +5 -0
  119. package/dist/translations/uk.umd.js +11 -0
  120. package/dist/translations/vi.d.ts +8 -0
  121. package/dist/translations/vi.js +5 -0
  122. package/dist/translations/vi.umd.js +11 -0
  123. package/dist/translations/zh-cn.d.ts +8 -0
  124. package/dist/translations/zh-cn.js +5 -0
  125. package/dist/translations/zh-cn.umd.js +11 -0
  126. package/dist/translations/zh.d.ts +8 -0
  127. package/dist/translations/zh.js +5 -0
  128. package/dist/translations/zh.umd.js +11 -0
  129. package/dist/types/augmentation.d.ts +14 -0
  130. package/dist/types/autoformat.d.ts +85 -0
  131. package/dist/types/blockautoformatediting.d.ts +61 -0
  132. package/dist/types/index.d.ts +13 -0
  133. package/dist/types/inlineautoformatediting.d.ts +87 -0
  134. package/package.json +3 -2
@@ -0,0 +1,4 @@
1
+ /**
2
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
3
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
+ */
@@ -0,0 +1,4 @@
1
+ /**
2
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
3
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
+ */
package/dist/index.css ADDED
@@ -0,0 +1,4 @@
1
+ /**
2
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
3
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
+ */
package/dist/index.js ADDED
@@ -0,0 +1,497 @@
1
+ /**
2
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
3
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
+ */
5
+ import { Plugin } from '@ckeditor/ckeditor5-core/dist/index.js';
6
+ import { Delete } from '@ckeditor/ckeditor5-typing/dist/index.js';
7
+ import { LiveRange } from '@ckeditor/ckeditor5-engine/dist/index.js';
8
+ import { first } from '@ckeditor/ckeditor5-utils/dist/index.js';
9
+
10
+ /**
11
+ * The block autoformatting engine. It allows to format various block patterns. For example,
12
+ * it can be configured to turn a paragraph starting with `*` and followed by a space into a list item.
13
+ *
14
+ * The autoformatting operation is integrated with the undo manager,
15
+ * so the autoformatting step can be undone if the user's intention was not to format the text.
16
+ *
17
+ * See the {@link module:autoformat/blockautoformatediting~blockAutoformatEditing `blockAutoformatEditing`} documentation
18
+ * to learn how to create custom block autoformatters. You can also use
19
+ * the {@link module:autoformat/autoformat~Autoformat} feature which enables a set of default autoformatters
20
+ * (lists, headings, bold and italic).
21
+ *
22
+ * @module autoformat/blockautoformatediting
23
+ */ /**
24
+ * Creates a listener triggered on {@link module:engine/model/document~Document#event:change:data `change:data`} event in the document.
25
+ * Calls the callback when inserted text matches the regular expression or the command name
26
+ * if provided instead of the callback.
27
+ *
28
+ * Examples of usage:
29
+ *
30
+ * To convert a paragraph into heading 1 when `- ` is typed, using just the command name:
31
+ *
32
+ * ```ts
33
+ * blockAutoformatEditing( editor, plugin, /^\- $/, 'heading1' );
34
+ * ```
35
+ *
36
+ * To convert a paragraph into heading 1 when `- ` is typed, using just the callback:
37
+ *
38
+ * ```ts
39
+ * blockAutoformatEditing( editor, plugin, /^\- $/, ( context ) => {
40
+ * const { match } = context;
41
+ * const headingLevel = match[ 1 ].length;
42
+ *
43
+ * editor.execute( 'heading', {
44
+ * formatId: `heading${ headingLevel }`
45
+ * } );
46
+ * } );
47
+ * ```
48
+ *
49
+ * @param editor The editor instance.
50
+ * @param plugin The autoformat plugin instance.
51
+ * @param pattern The regular expression to execute on just inserted text. The regular expression is tested against the text
52
+ * from the beginning until the caret position.
53
+ * @param callbackOrCommand The callback to execute or the command to run when the text is matched.
54
+ * In case of providing the callback, it receives the following parameter:
55
+ * * match RegExp.exec() result of matching the pattern to inserted text.
56
+ */ function blockAutoformatEditing(editor, plugin, pattern, callbackOrCommand) {
57
+ let callback;
58
+ let command = null;
59
+ if (typeof callbackOrCommand == 'function') {
60
+ callback = callbackOrCommand;
61
+ } else {
62
+ // We assume that the actual command name was provided.
63
+ command = editor.commands.get(callbackOrCommand);
64
+ callback = ()=>{
65
+ editor.execute(callbackOrCommand);
66
+ };
67
+ }
68
+ editor.model.document.on('change:data', (evt, batch)=>{
69
+ if (command && !command.isEnabled || !plugin.isEnabled) {
70
+ return;
71
+ }
72
+ const range = first(editor.model.document.selection.getRanges());
73
+ if (!range.isCollapsed) {
74
+ return;
75
+ }
76
+ if (batch.isUndo || !batch.isLocal) {
77
+ return;
78
+ }
79
+ const changes = Array.from(editor.model.document.differ.getChanges());
80
+ const entry = changes[0];
81
+ // Typing is represented by only a single change.
82
+ if (changes.length != 1 || entry.type !== 'insert' || entry.name != '$text' || entry.length != 1) {
83
+ return;
84
+ }
85
+ const blockToFormat = entry.position.parent;
86
+ // Block formatting should be disabled in codeBlocks (#5800).
87
+ if (blockToFormat.is('element', 'codeBlock')) {
88
+ return;
89
+ }
90
+ // Only list commands and custom callbacks can be applied inside a list.
91
+ if (blockToFormat.is('element', 'listItem') && typeof callbackOrCommand !== 'function' && ![
92
+ 'numberedList',
93
+ 'bulletedList',
94
+ 'todoList'
95
+ ].includes(callbackOrCommand)) {
96
+ return;
97
+ }
98
+ // In case a command is bound, do not re-execute it over an existing block style which would result in a style removal.
99
+ // Instead, just drop processing so that autoformat trigger text is not lost. E.g. writing "# " in a level 1 heading.
100
+ if (command && command.value === true) {
101
+ return;
102
+ }
103
+ const firstNode = blockToFormat.getChild(0);
104
+ const firstNodeRange = editor.model.createRangeOn(firstNode);
105
+ // Range is only expected to be within or at the very end of the first text node.
106
+ if (!firstNodeRange.containsRange(range) && !range.end.isEqual(firstNodeRange.end)) {
107
+ return;
108
+ }
109
+ const match = pattern.exec(firstNode.data.substr(0, range.end.offset));
110
+ // ...and this text node's data match the pattern.
111
+ if (!match) {
112
+ return;
113
+ }
114
+ // Use enqueueChange to create new batch to separate typing batch from the auto-format changes.
115
+ editor.model.enqueueChange((writer)=>{
116
+ // Matched range.
117
+ const start = writer.createPositionAt(blockToFormat, 0);
118
+ const end = writer.createPositionAt(blockToFormat, match[0].length);
119
+ const range = new LiveRange(start, end);
120
+ const wasChanged = callback({
121
+ match
122
+ });
123
+ // Remove matched text.
124
+ if (wasChanged !== false) {
125
+ writer.remove(range);
126
+ const selectionRange = editor.model.document.selection.getFirstRange();
127
+ const blockRange = writer.createRangeIn(blockToFormat);
128
+ // If the block is empty and the document selection has been moved when
129
+ // applying formatting (e.g. is now in newly created block).
130
+ if (blockToFormat.isEmpty && !blockRange.isEqual(selectionRange) && !blockRange.containsRange(selectionRange, true)) {
131
+ writer.remove(blockToFormat);
132
+ }
133
+ }
134
+ range.detach();
135
+ editor.model.enqueueChange(()=>{
136
+ const deletePlugin = editor.plugins.get('Delete');
137
+ deletePlugin.requestUndoOnBackspace();
138
+ });
139
+ });
140
+ });
141
+ }
142
+
143
+ /**
144
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
145
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
146
+ */ /**
147
+ * Enables autoformatting mechanism for a given {@link module:core/editor/editor~Editor}.
148
+ *
149
+ * It formats the matched text by applying the given model attribute or by running the provided formatting callback.
150
+ * On every {@link module:engine/model/document~Document#event:change:data data change} in the model document
151
+ * the autoformatting engine checks the text on the left of the selection
152
+ * and executes the provided action if the text matches given criteria (regular expression or callback).
153
+ *
154
+ * @param editor The editor instance.
155
+ * @param plugin The autoformat plugin instance.
156
+ * @param testRegexpOrCallback The regular expression or callback to execute on text.
157
+ * Provided regular expression *must* have three capture groups. The first and the third capture group
158
+ * should match opening and closing delimiters. The second capture group should match the text to format.
159
+ *
160
+ * ```ts
161
+ * // Matches the `**bold text**` pattern.
162
+ * // There are three capturing groups:
163
+ * // - The first to match the starting `**` delimiter.
164
+ * // - The second to match the text to format.
165
+ * // - The third to match the ending `**` delimiter.
166
+ * inlineAutoformatEditing( editor, plugin, /(\*\*)([^\*]+?)(\*\*)$/g, formatCallback );
167
+ * ```
168
+ *
169
+ * When a function is provided instead of the regular expression, it will be executed with the text to match as a parameter.
170
+ * The function should return proper "ranges" to delete and format.
171
+ *
172
+ * ```ts
173
+ * {
174
+ * remove: [
175
+ * [ 0, 1 ], // Remove the first letter from the given text.
176
+ * [ 5, 6 ] // Remove the 6th letter from the given text.
177
+ * ],
178
+ * format: [
179
+ * [ 1, 5 ] // Format all letters from 2nd to 5th.
180
+ * ]
181
+ * }
182
+ * ```
183
+ *
184
+ * @param formatCallback A callback to apply actual formatting.
185
+ * It should return `false` if changes should not be applied (e.g. if a command is disabled).
186
+ *
187
+ * ```ts
188
+ * inlineAutoformatEditing( editor, plugin, /(\*\*)([^\*]+?)(\*\*)$/g, ( writer, rangesToFormat ) => {
189
+ * const command = editor.commands.get( 'bold' );
190
+ *
191
+ * if ( !command.isEnabled ) {
192
+ * return false;
193
+ * }
194
+ *
195
+ * const validRanges = editor.model.schema.getValidRanges( rangesToFormat, 'bold' );
196
+ *
197
+ * for ( let range of validRanges ) {
198
+ * writer.setAttribute( 'bold', true, range );
199
+ * }
200
+ * } );
201
+ * ```
202
+ */ function inlineAutoformatEditing(editor, plugin, testRegexpOrCallback, formatCallback) {
203
+ let regExp;
204
+ let testCallback;
205
+ if (testRegexpOrCallback instanceof RegExp) {
206
+ regExp = testRegexpOrCallback;
207
+ } else {
208
+ testCallback = testRegexpOrCallback;
209
+ }
210
+ // A test callback run on changed text.
211
+ testCallback = testCallback || ((text)=>{
212
+ let result;
213
+ const remove = [];
214
+ const format = [];
215
+ while((result = regExp.exec(text)) !== null){
216
+ // There should be full match and 3 capture groups.
217
+ if (result && result.length < 4) {
218
+ break;
219
+ }
220
+ let { index, '1': leftDel, '2': content, '3': rightDel } = result;
221
+ // Real matched string - there might be some non-capturing groups so we need to recalculate starting index.
222
+ const found = leftDel + content + rightDel;
223
+ index += result[0].length - found.length;
224
+ // Start and End offsets of delimiters to remove.
225
+ const delStart = [
226
+ index,
227
+ index + leftDel.length
228
+ ];
229
+ const delEnd = [
230
+ index + leftDel.length + content.length,
231
+ index + leftDel.length + content.length + rightDel.length
232
+ ];
233
+ remove.push(delStart);
234
+ remove.push(delEnd);
235
+ format.push([
236
+ index + leftDel.length,
237
+ index + leftDel.length + content.length
238
+ ]);
239
+ }
240
+ return {
241
+ remove,
242
+ format
243
+ };
244
+ });
245
+ editor.model.document.on('change:data', (evt, batch)=>{
246
+ if (batch.isUndo || !batch.isLocal || !plugin.isEnabled) {
247
+ return;
248
+ }
249
+ const model = editor.model;
250
+ const selection = model.document.selection;
251
+ // Do nothing if selection is not collapsed.
252
+ if (!selection.isCollapsed) {
253
+ return;
254
+ }
255
+ const changes = Array.from(model.document.differ.getChanges());
256
+ const entry = changes[0];
257
+ // Typing is represented by only a single change.
258
+ if (changes.length != 1 || entry.type !== 'insert' || entry.name != '$text' || entry.length != 1) {
259
+ return;
260
+ }
261
+ const focus = selection.focus;
262
+ const block = focus.parent;
263
+ const { text, range } = getTextAfterCode(model.createRange(model.createPositionAt(block, 0), focus), model);
264
+ const testOutput = testCallback(text);
265
+ const rangesToFormat = testOutputToRanges(range.start, testOutput.format, model);
266
+ const rangesToRemove = testOutputToRanges(range.start, testOutput.remove, model);
267
+ if (!(rangesToFormat.length && rangesToRemove.length)) {
268
+ return;
269
+ }
270
+ // Use enqueueChange to create new batch to separate typing batch from the auto-format changes.
271
+ model.enqueueChange((writer)=>{
272
+ // Apply format.
273
+ const hasChanged = formatCallback(writer, rangesToFormat);
274
+ // Strict check on `false` to have backward compatibility (when callbacks were returning `undefined`).
275
+ if (hasChanged === false) {
276
+ return;
277
+ }
278
+ // Remove delimiters - use reversed order to not mix the offsets while removing.
279
+ for (const range of rangesToRemove.reverse()){
280
+ writer.remove(range);
281
+ }
282
+ model.enqueueChange(()=>{
283
+ const deletePlugin = editor.plugins.get('Delete');
284
+ deletePlugin.requestUndoOnBackspace();
285
+ });
286
+ });
287
+ });
288
+ }
289
+ /**
290
+ * Converts output of the test function provided to the inlineAutoformatEditing and converts it to the model ranges
291
+ * inside provided block.
292
+ */ function testOutputToRanges(start, arrays, model) {
293
+ return arrays.filter((array)=>array[0] !== undefined && array[1] !== undefined).map((array)=>{
294
+ return model.createRange(start.getShiftedBy(array[0]), start.getShiftedBy(array[1]));
295
+ });
296
+ }
297
+ /**
298
+ * Returns the last text line after the last code element from the given range.
299
+ * It is similar to {@link module:typing/utils/getlasttextline.getLastTextLine `getLastTextLine()`},
300
+ * but it ignores any text before the last `code`.
301
+ */ function getTextAfterCode(range, model) {
302
+ let start = range.start;
303
+ const text = Array.from(range.getItems()).reduce((rangeText, node)=>{
304
+ // Trim text to a last occurrence of an inline element and update range start.
305
+ if (!(node.is('$text') || node.is('$textProxy')) || node.getAttribute('code')) {
306
+ start = model.createPositionAfter(node);
307
+ return '';
308
+ }
309
+ return rangeText + node.data;
310
+ }, '');
311
+ return {
312
+ text,
313
+ range: model.createRange(start, range.end)
314
+ };
315
+ }
316
+
317
+ class Autoformat extends Plugin {
318
+ /**
319
+ * @inheritDoc
320
+ */ static get requires() {
321
+ return [
322
+ Delete
323
+ ];
324
+ }
325
+ /**
326
+ * @inheritDoc
327
+ */ static get pluginName() {
328
+ return 'Autoformat';
329
+ }
330
+ /**
331
+ * @inheritDoc
332
+ */ afterInit() {
333
+ const editor = this.editor;
334
+ const t = this.editor.t;
335
+ this._addListAutoformats();
336
+ this._addBasicStylesAutoformats();
337
+ this._addHeadingAutoformats();
338
+ this._addBlockQuoteAutoformats();
339
+ this._addCodeBlockAutoformats();
340
+ this._addHorizontalLineAutoformats();
341
+ // Add the information about the keystroke to the accessibility database.
342
+ editor.accessibility.addKeystrokeInfos({
343
+ keystrokes: [
344
+ {
345
+ label: t('Revert autoformatting action'),
346
+ keystroke: 'Backspace'
347
+ }
348
+ ]
349
+ });
350
+ }
351
+ /**
352
+ * Adds autoformatting related to the {@link module:list/list~List}.
353
+ *
354
+ * When typed:
355
+ * - `* ` or `- ` &ndash; A paragraph will be changed into a bulleted list.
356
+ * - `1. ` or `1) ` &ndash; A paragraph will be changed into a numbered list ("1" can be any digit or a list of digits).
357
+ * - `[] ` or `[ ] ` &ndash; A paragraph will be changed into a to-do list.
358
+ * - `[x] ` or `[ x ] ` &ndash; A paragraph will be changed into a checked to-do list.
359
+ */ _addListAutoformats() {
360
+ const commands = this.editor.commands;
361
+ if (commands.get('bulletedList')) {
362
+ blockAutoformatEditing(this.editor, this, /^[*-]\s$/, 'bulletedList');
363
+ }
364
+ if (commands.get('numberedList')) {
365
+ blockAutoformatEditing(this.editor, this, /^1[.|)]\s$/, 'numberedList');
366
+ }
367
+ if (commands.get('todoList')) {
368
+ blockAutoformatEditing(this.editor, this, /^\[\s?\]\s$/, 'todoList');
369
+ }
370
+ if (commands.get('checkTodoList')) {
371
+ blockAutoformatEditing(this.editor, this, /^\[\s?x\s?\]\s$/, ()=>{
372
+ this.editor.execute('todoList');
373
+ this.editor.execute('checkTodoList');
374
+ });
375
+ }
376
+ }
377
+ /**
378
+ * Adds autoformatting related to the {@link module:basic-styles/bold~Bold},
379
+ * {@link module:basic-styles/italic~Italic}, {@link module:basic-styles/code~Code}
380
+ * and {@link module:basic-styles/strikethrough~Strikethrough}
381
+ *
382
+ * When typed:
383
+ * - `**foobar**` &ndash; `**` characters are removed and `foobar` is set to bold,
384
+ * - `__foobar__` &ndash; `__` characters are removed and `foobar` is set to bold,
385
+ * - `*foobar*` &ndash; `*` characters are removed and `foobar` is set to italic,
386
+ * - `_foobar_` &ndash; `_` characters are removed and `foobar` is set to italic,
387
+ * - ``` `foobar` &ndash; ``` ` ``` characters are removed and `foobar` is set to code,
388
+ * - `~~foobar~~` &ndash; `~~` characters are removed and `foobar` is set to strikethrough.
389
+ */ _addBasicStylesAutoformats() {
390
+ const commands = this.editor.commands;
391
+ if (commands.get('bold')) {
392
+ const boldCallback = getCallbackFunctionForInlineAutoformat(this.editor, 'bold');
393
+ inlineAutoformatEditing(this.editor, this, /(?:^|\s)(\*\*)([^*]+)(\*\*)$/g, boldCallback);
394
+ inlineAutoformatEditing(this.editor, this, /(?:^|\s)(__)([^_]+)(__)$/g, boldCallback);
395
+ }
396
+ if (commands.get('italic')) {
397
+ const italicCallback = getCallbackFunctionForInlineAutoformat(this.editor, 'italic');
398
+ // The italic autoformatter cannot be triggered by the bold markers, so we need to check the
399
+ // text before the pattern (e.g. `(?:^|[^\*])`).
400
+ inlineAutoformatEditing(this.editor, this, /(?:^|\s)(\*)([^*_]+)(\*)$/g, italicCallback);
401
+ inlineAutoformatEditing(this.editor, this, /(?:^|\s)(_)([^_]+)(_)$/g, italicCallback);
402
+ }
403
+ if (commands.get('code')) {
404
+ const codeCallback = getCallbackFunctionForInlineAutoformat(this.editor, 'code');
405
+ inlineAutoformatEditing(this.editor, this, /(`)([^`]+)(`)$/g, codeCallback);
406
+ }
407
+ if (commands.get('strikethrough')) {
408
+ const strikethroughCallback = getCallbackFunctionForInlineAutoformat(this.editor, 'strikethrough');
409
+ inlineAutoformatEditing(this.editor, this, /(~~)([^~]+)(~~)$/g, strikethroughCallback);
410
+ }
411
+ }
412
+ /**
413
+ * Adds autoformatting related to {@link module:heading/heading~Heading}.
414
+ *
415
+ * It is using a number at the end of the command name to associate it with the proper trigger:
416
+ *
417
+ * * `heading` with a `heading1` value will be executed when typing `#`,
418
+ * * `heading` with a `heading2` value will be executed when typing `##`,
419
+ * * ... up to `heading6` for `######`.
420
+ */ _addHeadingAutoformats() {
421
+ const command = this.editor.commands.get('heading');
422
+ if (command) {
423
+ command.modelElements.filter((name)=>name.match(/^heading[1-6]$/)).forEach((modelName)=>{
424
+ const level = modelName[7];
425
+ const pattern = new RegExp(`^(#{${level}})\\s$`);
426
+ blockAutoformatEditing(this.editor, this, pattern, ()=>{
427
+ // Should only be active if command is enabled and heading style associated with pattern is inactive.
428
+ if (!command.isEnabled || command.value === modelName) {
429
+ return false;
430
+ }
431
+ this.editor.execute('heading', {
432
+ value: modelName
433
+ });
434
+ });
435
+ });
436
+ }
437
+ }
438
+ /**
439
+ * Adds autoformatting related to {@link module:block-quote/blockquote~BlockQuote}.
440
+ *
441
+ * When typed:
442
+ * * `> ` &ndash; A paragraph will be changed to a block quote.
443
+ */ _addBlockQuoteAutoformats() {
444
+ if (this.editor.commands.get('blockQuote')) {
445
+ blockAutoformatEditing(this.editor, this, /^>\s$/, 'blockQuote');
446
+ }
447
+ }
448
+ /**
449
+ * Adds autoformatting related to {@link module:code-block/codeblock~CodeBlock}.
450
+ *
451
+ * When typed:
452
+ * - `` ``` `` &ndash; A paragraph will be changed to a code block.
453
+ */ _addCodeBlockAutoformats() {
454
+ const editor = this.editor;
455
+ const selection = editor.model.document.selection;
456
+ if (editor.commands.get('codeBlock')) {
457
+ blockAutoformatEditing(editor, this, /^```$/, ()=>{
458
+ if (selection.getFirstPosition().parent.is('element', 'listItem')) {
459
+ return false;
460
+ }
461
+ this.editor.execute('codeBlock', {
462
+ usePreviousLanguageChoice: true
463
+ });
464
+ });
465
+ }
466
+ }
467
+ /**
468
+ * Adds autoformatting related to {@link module:horizontal-line/horizontalline~HorizontalLine}.
469
+ *
470
+ * When typed:
471
+ * - `` --- `` &ndash; Will be replaced with a horizontal line.
472
+ */ _addHorizontalLineAutoformats() {
473
+ if (this.editor.commands.get('horizontalLine')) {
474
+ blockAutoformatEditing(this.editor, this, /^---$/, 'horizontalLine');
475
+ }
476
+ }
477
+ }
478
+ /**
479
+ * Helper function for getting `inlineAutoformatEditing` callbacks that checks if command is enabled.
480
+ */ function getCallbackFunctionForInlineAutoformat(editor, attributeKey) {
481
+ return (writer, rangesToFormat)=>{
482
+ const command = editor.commands.get(attributeKey);
483
+ if (!command.isEnabled) {
484
+ return false;
485
+ }
486
+ const validRanges = editor.model.schema.getValidRanges(rangesToFormat, attributeKey);
487
+ for (const range of validRanges){
488
+ writer.setAttribute(attributeKey, true, range);
489
+ }
490
+ // After applying attribute to the text, remove given attribute from the selection.
491
+ // This way user is able to type a text without attribute used by auto formatter.
492
+ writer.removeSelectionAttribute(attributeKey);
493
+ };
494
+ }
495
+
496
+ export { Autoformat };
497
+ //# sourceMappingURL=index.js.map