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