or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-ckeditor--ckeditor5-autoformat

Autoformatting feature for CKEditor 5 that enables markdown-like shortcuts for text formatting, lists, headings, and block elements.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@ckeditor/ckeditor5-autoformat@46.0.x

To install, run

npx @tessl/cli install tessl/npm-ckeditor--ckeditor5-autoformat@46.0.0

index.mddocs/

CKEditor 5 Autoformat

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.

Package Information

  • Package Name: @ckeditor/ckeditor5-autoformat
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @ckeditor/ckeditor5-autoformat

Core Imports

import { Autoformat } from "@ckeditor/ckeditor5-autoformat";

For advanced usage:

import { 
  Autoformat, 
  blockAutoformatEditing, 
  inlineAutoformatEditing,
  type AutoformatTestCallback 
} from "@ckeditor/ckeditor5-autoformat";

Basic Usage

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);
});

Architecture

CKEditor 5 Autoformat is built around several key components:

  • Main Plugin Class: Autoformat plugin that coordinates all autoformatting features
  • Inline Engine: inlineAutoformatEditing for pattern-based text formatting (bold, italic, etc.)
  • Block Engine: blockAutoformatEditing for block-level transformations (headings, lists, etc.)
  • Pattern Recognition: RegExp-based pattern matching for detecting formatting triggers
  • Undo Integration: Built-in undo support allowing users to reverse autoformatting with backspace
  • Command Integration: Seamless integration with CKEditor 5's command system for feature availability

Capabilities

Main Plugin

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 list
  • 1. 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 line

Inline Patterns:

  • **text** or __text__ → Bold
  • *text* or _text_ → Italic
  • `text` → Code
  • ~~text~~ → Strikethrough

Block Autoformat Engine

Creates 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');
  }
});

Inline Autoformat Engine

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');
  }
);

Types

/**
 * 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;
}

Integration Requirements

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-styles
  • Heading from @ckeditor/ckeditor5-heading
  • List (with BulletedList, NumberedList, TodoList) from @ckeditor/ckeditor5-list
  • BlockQuote from @ckeditor/ckeditor5-block-quote
  • CodeBlock from @ckeditor/ckeditor5-code-block
  • HorizontalLine from @ckeditor/ckeditor5-horizontal-line

Undo Integration:

  • Automatic undo support via requestUndoOnBackspace() - users can press backspace immediately after autoformatting to revert
  • Uses separate batches to distinguish typing from autoformat changes

Command State Validation:

  • Autoformat automatically checks if commands are enabled before executing
  • Respects editor schema and context (e.g., won't format inside code blocks)
  • Validates ranges against model schema before applying attributes

Error Handling

The autoformat system includes built-in error prevention:

  • Command Availability: Checks if commands exist and are enabled before execution
  • Schema Validation: Validates formatting ranges against the editor's schema
  • Context Awareness: Prevents inappropriate formatting in certain contexts (e.g., code blocks)
  • Graceful Degradation: Missing feature plugins simply disable their corresponding autoformat patterns

Common scenarios where autoformatting is disabled:

  • Inside code blocks (block patterns disabled)
  • Inside list items (only list-related commands allowed)
  • When target commands are disabled by schema or other plugins
  • When selection is not collapsed (not at insertion point)