CKEditor 5 Autoformat provides real-time text formatting capabilities that automatically convert markdown-like patterns into rich text formatting as users type. It supports inline styles (bold, italic, code, strikethrough), block elements (headings, lists, quotes, code blocks), and special elements (horizontal lines), making content creation more efficient by allowing familiar markdown shortcuts while maintaining CKEditor 5's rich editing experience.
npm install @ckeditor/ckeditor5-autoformatimport { Autoformat } from "@ckeditor/ckeditor5-autoformat";For advanced usage:
import {
Autoformat,
blockAutoformatEditing,
inlineAutoformatEditing,
type AutoformatTestCallback
} from "@ckeditor/ckeditor5-autoformat";import { ClassicEditor } from '@ckeditor/ckeditor5-editor-classic';
import { Autoformat } from '@ckeditor/ckeditor5-autoformat';
import { Bold, Italic, Code, Strikethrough } from '@ckeditor/ckeditor5-basic-styles';
import { Heading } from '@ckeditor/ckeditor5-heading';
import { List } from '@ckeditor/ckeditor5-list';
import { BlockQuote } from '@ckeditor/ckeditor5-block-quote';
ClassicEditor.create(document.querySelector('#editor'), {
plugins: [
Autoformat,
Bold, Italic, Code, Strikethrough,
Heading, List, BlockQuote,
// ... other plugins
]
})
.then(editor => {
// Autoformat is now active
// Users can type **bold** or *italic* for formatting
// Users can type # for headings, * for lists, etc.
})
.catch(error => {
console.error(error);
});CKEditor 5 Autoformat is built around several key components:
Autoformat plugin that coordinates all autoformatting featuresinlineAutoformatEditing for pattern-based text formatting (bold, italic, etc.)blockAutoformatEditing for block-level transformations (headings, lists, etc.)The primary autoformat plugin that enables all predefined autoformatting patterns.
/**
* Main autoformat plugin extending CKEditor 5 Plugin class
* Enables predefined autoformatting actions for various text patterns
*/
class Autoformat extends Plugin {
/** Required plugins for autoformat functionality */
static get requires(): readonly [typeof Delete];
/** Plugin name identifier */
static get pluginName(): 'Autoformat';
/** Indicates this is an official CKEditor 5 plugin */
static override get isOfficialPlugin(): true;
/**
* Initializes all autoformat patterns and accessibility information
* Called after plugin initialization
*/
afterInit(): void;
}Supported Autoformat Patterns:
Block Patterns:
* or - → Bulleted list1. or 1) → Numbered list (any digit sequence)[] or [ ] → Todo list[x] or [ x ] → Checked todo list# to ###### → Headings (H1-H6)> → Block quote` ` ` → Code block--- → Horizontal lineInline Patterns:
**text** or __text__ → Bold*text* or _text_ → Italic`text` → Code~~text~~ → StrikethroughCreates block-level autoformatting functionality for patterns like headings, lists, and quotes.
/**
* Creates block-level autoformatting functionality
* @param editor - The editor instance
* @param plugin - The autoformat plugin instance
* @param pattern - Regular expression to match against text from beginning until caret
* @param callbackOrCommand - Command name string or callback function to execute
*/
function blockAutoformatEditing(
editor: Editor,
plugin: Autoformat,
pattern: RegExp,
callbackOrCommand: string | ((context: { match: RegExpExecArray }) => unknown)
): void;Usage Example:
import { blockAutoformatEditing } from '@ckeditor/ckeditor5-autoformat';
// Convert "## " to heading 2
blockAutoformatEditing(editor, plugin, /^##\s$/, 'heading', { value: 'heading2' });
// Custom callback for complex logic
blockAutoformatEditing(editor, plugin, /^>\s$/, (context) => {
if (editor.commands.get('blockQuote').isEnabled) {
editor.execute('blockQuote');
}
});Creates inline autoformatting functionality for text patterns like bold, italic, and code.
/**
* Creates inline autoformatting functionality for text patterns
* @param editor - The editor instance
* @param plugin - The autoformat plugin instance
* @param testRegexpOrCallback - RegExp with 3 capture groups or custom test callback
* @param formatCallback - Callback to apply formatting, should return false if changes should not be applied
*/
function inlineAutoformatEditing(
editor: Editor,
plugin: Autoformat,
testRegexpOrCallback: RegExp | AutoformatTestCallback,
formatCallback: (writer: ModelWriter, rangesToFormat: Array<ModelRange>) => boolean | undefined
): void;
/**
* Type definition for custom autoformat test functions
* @param text - Text to analyze for patterns
* @returns Ranges to remove (delimiters) and format (content)
*/
type AutoformatTestCallback = (text: string) => {
remove: Array<Array<number>>;
format: Array<Array<number>>;
};Usage Example:
import { inlineAutoformatEditing } from '@ckeditor/ckeditor5-autoformat';
// Enable **bold** pattern
inlineAutoformatEditing(
editor,
plugin,
/(\*\*)([^*]+)(\*\*)$/g,
(writer, rangesToFormat) => {
const command = editor.commands.get('bold');
if (!command.isEnabled) {
return false;
}
const validRanges = editor.model.schema.getValidRanges(rangesToFormat, 'bold');
for (const range of validRanges) {
writer.setAttribute('bold', true, range);
}
// Remove selection attribute to prevent continued formatting
writer.removeSelectionAttribute('bold');
}
);/**
* CKEditor 5 core types used by autoformat
*/
interface Editor {
commands: CommandCollection;
model: Model;
execute(commandName: string, ...args: any[]): unknown;
plugins: PluginCollection;
accessibility: AccessibilityHelp;
}
interface Plugin {
editor: Editor;
isEnabled: boolean;
afterInit?(): void;
}
interface ModelWriter {
setAttribute(key: string, value: unknown, range: ModelRange): void;
removeSelectionAttribute(key: string): void;
remove(range: ModelRange): void;
createPositionAt(element: ModelElement, offset: number): ModelPosition;
createRange(start: ModelPosition, end: ModelPosition): ModelRange;
}
interface ModelRange {
start: ModelPosition;
end: ModelPosition;
isCollapsed: boolean;
}
interface ModelPosition {
parent: ModelElement;
offset: number;
getShiftedBy(offset: number): ModelPosition;
}
interface ModelElement {
is(type: string, name?: string): boolean;
getChild(index: number): ModelNode;
isEmpty: boolean;
}
/**
* Autoformat-specific callback context
*/
interface AutoformatCallbackContext {
match: RegExpExecArray;
}The Autoformat plugin requires specific CKEditor 5 plugins to function properly:
Required Dependencies:
Delete plugin from @ckeditor/ckeditor5-typing (automatically included)Optional Feature Dependencies:
Bold, Italic, Code, Strikethrough from @ckeditor/ckeditor5-basic-stylesHeading from @ckeditor/ckeditor5-headingList (with BulletedList, NumberedList, TodoList) from @ckeditor/ckeditor5-listBlockQuote from @ckeditor/ckeditor5-block-quoteCodeBlock from @ckeditor/ckeditor5-code-blockHorizontalLine from @ckeditor/ckeditor5-horizontal-lineUndo Integration:
requestUndoOnBackspace() - users can press backspace immediately after autoformatting to revertCommand State Validation:
The autoformat system includes built-in error prevention:
Common scenarios where autoformatting is disabled: