Docs
Autoformat

Autoformat

Apply formatting automatically using shortcodes.

🏃‍♀️ Autoformat

Empower your writing experience by enabling autoformatting features. Add Markdown-like shortcuts that automatically apply formatting as you type.
While typing, try these mark rules:
Type ** or __ on either side of your text to add **bold* mark.
Type * or _ on either side of your text to add *italic mark.
Type ` on either side of your text to add `inline code mark.
Type ~~ on either side of your text to add ~~strikethrough~ mark.
Note that nothing happens when there is a character before, try on:*bold
We even support smart quotes, try typing "hello" 'world'.
At the beginning of any new block or existing block, try these (block rules):
Type *, - or +followed by space to create a bulleted list.
Type 1. or 1) followed by spaceto create a numbered list.
Type > followed by space to create a block quote.
Type ``` to create a code block.
Type --- to create a horizontal rule.
Type # followed by space to create an H1 heading.
Type ## followed by space to create an H2 sub-heading.
Type ### followed by space to create an H3 sub-heading.
Type #### followed by space to create an H4 sub-heading.
Type ##### followed by space to create an H5 sub-heading.
Type ###### followed by space to create an H6 sub-heading.


Features

  • Enables quick content formatting via shortcodes.
  • Offers markdown-like inline codes for real-time typing.
  • Enhances and simplifies editing by avoiding toolbar buttons and shortcuts for common formatting.
  • Auto conversion feature (e.g., # to H1).
  • Provides predefined formatting rules.

Formatting shortcodes:

  • text* for bold text.
  • _text_ for italicized text.
  • ~~text~~ for strikethrough text.
  • ... and more.

Installation

npm install @udecode/plate-autoformat

Usage

import { createAutoformatPlugin } from '@udecode/plate-autoformat';
 
const plugins = [
  // ...otherPlugins,
  createAutoformatPlugin({
    rules: autoformatRules,
    enableUndoOnDelete: true,
  }),
];

Examples

autoformatRules

import {
  autoformatArrow,
  autoformatLegal,
  autoformatLegalHtml,
  autoformatMath,
  autoformatPunctuation,
  autoformatSmartQuotes,
} from '@udecode/plate-autoformat';
 
import { autoformatBlocks } from '@/lib/plate/autoformatBlocks';
import { autoformatIndentLists } from '@/lib/plate/autoformatIndentLists';
import { autoformatMarks } from '@/lib/plate/autoformatMarks';
import { MyAutoformatRule } from '@/lib/plate/plate-types';
 
export const autoformatRules = [
  ...autoformatBlocks,
  ...autoformatIndentLists,
  ...autoformatMarks,
  ...(autoformatSmartQuotes as MyAutoformatRule[]),
  ...(autoformatPunctuation as MyAutoformatRule[]),
  ...(autoformatLegal as MyAutoformatRule[]),
  ...(autoformatLegalHtml as MyAutoformatRule[]),
  ...(autoformatArrow as MyAutoformatRule[]),
  ...(autoformatMath as MyAutoformatRule[]),
];

autoformatBlocks

import { AutoformatRule } from '@udecode/plate-autoformat';
import { ELEMENT_BLOCKQUOTE } from '@udecode/plate-block-quote';
import {
  ELEMENT_CODE_BLOCK,
  insertEmptyCodeBlock,
} from '@udecode/plate-code-block';
import { ELEMENT_DEFAULT, insertNodes, setNodes } from '@udecode/plate-common';
import {
  ELEMENT_H1,
  ELEMENT_H2,
  ELEMENT_H3,
  ELEMENT_H4,
  ELEMENT_H5,
  ELEMENT_H6,
} from '@udecode/plate-heading';
import { ELEMENT_HR } from '@udecode/plate-horizontal-rule';
 
import { preFormat } from '@/lib/plate/autoformatUtils';
 
export const autoformatBlocks: AutoformatRule[] = [
  {
    mode: 'block',
    type: ELEMENT_H1,
    match: '# ',
    preFormat,
  },
  {
    mode: 'block',
    type: ELEMENT_H2,
    match: '## ',
    preFormat,
  },
  {
    mode: 'block',
    type: ELEMENT_H3,
    match: '### ',
    preFormat,
  },
  {
    mode: 'block',
    type: ELEMENT_H4,
    match: '#### ',
    preFormat,
  },
  {
    mode: 'block',
    type: ELEMENT_H5,
    match: '##### ',
    preFormat,
  },
  {
    mode: 'block',
    type: ELEMENT_H6,
    match: '###### ',
    preFormat,
  },
  {
    mode: 'block',
    type: ELEMENT_BLOCKQUOTE,
    match: '> ',
    preFormat,
  },
  {
    mode: 'block',
    type: ELEMENT_CODE_BLOCK,
    match: '```',
    triggerAtBlockStart: false,
    preFormat,
    format: (editor) => {
      insertEmptyCodeBlock(editor, {
        defaultType: ELEMENT_DEFAULT,
        insertNodesOptions: { select: true },
      });
    },
  },
  {
    mode: 'block',
    type: ELEMENT_HR,
    match: ['---', '—-', '___ '],
    format: (editor) => {
      setNodes(editor, { type: ELEMENT_HR });
      insertNodes(editor, {
        type: ELEMENT_DEFAULT,
        children: [{ text: '' }],
      });
    },
  },
];

autoformatIndentLists

If using the Indent List plugin, you can use the following rules:

import { AutoformatRule } from '@udecode/plate-autoformat';
import { ListStyleType, toggleIndentList } from '@udecode/plate-indent-list';
 
export const autoformatIndentLists: AutoformatRule[] = [
  {
    mode: 'block',
    type: 'list',
    match: ['* ', '- '],
    format: (editor) => {
      toggleIndentList(editor, {
        listStyleType: ListStyleType.Disc,
      });
    },
  },
  {
    mode: 'block',
    type: 'list',
    match: ['1. ', '1) '],
    format: (editor) =>
      toggleIndentList(editor, {
        listStyleType: ListStyleType.Decimal,
      }),
  },
];

autoformatLists

If using the List plugin, you can use the following rules:

import { AutoformatRule } from '@udecode/plate-autoformat';
import { isBlock, setNodes } from '@udecode/plate-common';
import {
  ELEMENT_LI,
  ELEMENT_OL,
  ELEMENT_TODO_LI,
  ELEMENT_UL,
  TTodoListItemElement,
} from '@udecode/plate-list';
 
import { formatList, preFormat } from '@/lib/plate/autoformatUtils';
 
export const autoformatLists: AutoformatRule[] = [
  {
    mode: 'block',
    type: ELEMENT_LI,
    match: ['* ', '- '],
    preFormat,
    format: (editor) => formatList(editor, ELEMENT_UL),
  },
  {
    mode: 'block',
    type: ELEMENT_LI,
    match: ['1. ', '1) '],
    preFormat,
    format: (editor) => formatList(editor, ELEMENT_OL),
  },
  {
    mode: 'block',
    type: ELEMENT_TODO_LI,
    match: '[] ',
  },
  {
    mode: 'block',
    type: ELEMENT_TODO_LI,
    match: '[x] ',
    format: (editor) =>
      setNodes<TTodoListItemElement>(
        editor,
        { type: ELEMENT_TODO_LI, checked: true },
        {
          match: (n) => isBlock(editor, n),
        }
      ),
  },
];

autoformatMarks

import {
  MARK_BOLD,
  MARK_CODE,
  MARK_ITALIC,
  MARK_STRIKETHROUGH,
  MARK_SUBSCRIPT,
  MARK_SUPERSCRIPT,
  MARK_UNDERLINE,
} from '@udecode/plate-basic-marks';
import { MARK_HIGHLIGHT } from '@udecode/plate-highlight';
 
import { MyAutoformatRule } from '@/lib/plate/plate-types';
 
export const autoformatMarks: MyAutoformatRule[] = [
  {
    mode: 'mark',
    type: [MARK_BOLD, MARK_ITALIC],
    match: '***',
  },
  {
    mode: 'mark',
    type: [MARK_UNDERLINE, MARK_ITALIC],
    match: '__*',
  },
  {
    mode: 'mark',
    type: [MARK_UNDERLINE, MARK_BOLD],
    match: '__**',
  },
  {
    mode: 'mark',
    type: [MARK_UNDERLINE, MARK_BOLD, MARK_ITALIC],
    match: '___***',
  },
  {
    mode: 'mark',
    type: MARK_BOLD,
    match: '**',
  },
  {
    mode: 'mark',
    type: MARK_UNDERLINE,
    match: '__',
  },
  {
    mode: 'mark',
    type: MARK_ITALIC,
    match: '*',
  },
  {
    mode: 'mark',
    type: MARK_ITALIC,
    match: '_',
  },
  {
    mode: 'mark',
    type: MARK_STRIKETHROUGH,
    match: '~~',
  },
  {
    mode: 'mark',
    type: MARK_SUPERSCRIPT,
    match: '^',
  },
  {
    mode: 'mark',
    type: MARK_SUBSCRIPT,
    match: '~',
  },
  {
    mode: 'mark',
    type: MARK_HIGHLIGHT,
    match: '==',
  },
  {
    mode: 'mark',
    type: MARK_HIGHLIGHT,
    match: '≡',
  },
  {
    mode: 'mark',
    type: MARK_CODE,
    match: '`',
  },
];

autoformatUtils

import { AutoformatBlockRule } from '@udecode/plate-autoformat';
import {
  ELEMENT_CODE_BLOCK,
  ELEMENT_CODE_LINE,
} from '@udecode/plate-code-block';
import {
  getParentNode,
  isElement,
  isType,
  PlateEditor,
} from '@udecode/plate-common';
import { toggleList, unwrapList } from '@udecode/plate-list';
 
export const preFormat: AutoformatBlockRule['preFormat'] = (editor) =>
  unwrapList(editor);
 
export const format = (editor: PlateEditor, customFormatting: any) => {
  if (editor.selection) {
    const parentEntry = getParentNode(editor, editor.selection);
    if (!parentEntry) return;
    const [node] = parentEntry;
    if (
      isElement(node) &&
      !isType(editor, node, ELEMENT_CODE_BLOCK) &&
      !isType(editor, node, ELEMENT_CODE_LINE)
    ) {
      customFormatting();
    }
  }
};
 
export const formatList = (editor: PlateEditor, elementType: string) => {
  format(editor, () =>
    toggleList(editor, {
      type: elementType,
    })
  );
};
 
export const formatText = (editor: PlateEditor, text: string) => {
  format(editor, () => editor.insertText(text));
};

API

createAutoformatPlugin

Options

Collapse all

    A list of triggering rules.

    • Can be one of the following: AutoformatBlockRule, AutoformatMarkRule, AutoformatTextRule.
    • Extends AutoformatCommonRule.

    Enable undo on delete.

Rules

You can import the following rules:

NameDescription
autoformatSmartQuotesConverts "text" to “text”.
Converts 'text' to ‘text’.
autoformatPunctuationConverts -- to .
Converts ... to .
Converts >> to ».
Converts << to «.
autoformatArrowConverts -> to .
Converts <- to .
Converts => to .
Converts <= and ≤= to .
autoformatLegalConverts (tm) and (TM) to .
Converts (r) and (R) to ®.
Converts (c) and (C) to ©.
autoformatLegalHtmlConverts &trade; to .
Converts &reg; to ®.
Converts &copy; to ©.
Converts &sect; to §.
autoformatComparisonConverts !> to !>.
Converts !< to .
Converts >= to .
Converts <= to .
Converts !>= to .
Converts !<= to .
autoformatEqualityConverts != to .
Converts == to .
Converts !== and ≠= to .
Converts ~= to .
Converts !~= to .
autoformatFractionConverts 1/2 to ½.
Converts 1/3 to .
...
Converts 7/8 to .
autoformatDivisionConverts // to ÷.
autoformatOperationConverts +- to ±.
Converts %% to .
Converts %%% and ‰% to `‱.
autoformatDivision rules.
autoformatSubscriptNumbersConverts ~0 to .
Converts ~1 to .
...
Converts ~9 to .
autoformatSubscriptSymbolsConverts ~+ to .
Converts ~- to .
autoformatSuperscriptNumbersConverts ^0 to .
Converts ^1 to ¹.
...
Converts ^9 to .
autoformatSuperscriptSymbolsConverts ^+ to °.
Converts ^- to .
autoformatMathautoformatComparison rules
autoformatEquality rules
autoformatOperation rules
autoformatFraction rules
autoformatSubscriptNumbers rules
autoformatSubscriptSymbols rules
autoformatSuperscriptNumbers rules
autoformatSuperscriptSymbols rules

AutoformatCommonRule

An interface for the common structure of autoformat rules, regardless of their mode.

Attributes

Collapse all

    The rule applies when the trigger and the text just before the cursor matches.

    • For mode: 'block': lookup for the end match(es) before the cursor.
    • For mode: 'text': lookup for the end match(es) before the cursor. If format is an array, also lookup for the start match(es).
    • For mode: 'mark': lookup for the start and end matches.
    • Note: '_*', ['_*'] and { start: '_*', end: '*_' } are equivalent.
    • MatchRange:

    Triggering character to autoformat.

    If true, insert the triggering character after autoformatting.

    • Default: false

    A query function to allow autoformat.

    • AutoformatQueryOptions extends Omit<AutoformatCommonRule<V, E>, 'query'>:

AutoformatBlockRule

An interface for autoformat rules for block mode.

Attributes

Collapse all

    • Text: insert text.
    • Block: set block type or custom format.
    • Mark: insert mark(s) between matches.

    A pattern to match for the autoformat rule to apply.

    • For mode: 'block': set block type. If format is defined, this field is ignored.
    • For mode: 'mark': Mark(s) to add.

    If true, the trigger should be at block start to allow autoformatting.

    • Default: true

    If true, allow to autoformat even if there is a block of the same type above the selected block.

    • Default: false

    Function called just before format. Generally used to reset the selected block.

    Custom formatting function.

AutoformatMarkRule

An interface for autoformat rules for mark mode.

Attributes

Collapse all

    The mode is 'mark'.

    Mark(s) to add.

    If false, do not format when the string can be trimmed.

AutoformatTextRule

An interface for autoformat rules for text mode.

Parameters

Collapse all

    The mode is 'text'.

    A pattern to match for the autoformat rule to apply.

    The matched text is replaced by that string, the matched texts are replaced by these strings, or a function called when there is a match.