@benrbray/prosemirror-math

中文文档
1.0.0发布于 2024/04/14MITTypeScriptES Module零依赖近 30 天下载 13.8万

Schema and plugins for first-class math support in ProseMirror.

原始使用文档
文档目录9 节
  1. Overview
  2. Basic Usage ( try it yourself! )
  3. Installation & Setup
  4. CSS
  5. Schema
  6. Input Rules
  7. Plugins
  8. Development
  9. Release

prosemirror-math

license types

Please don't hesitate to report issues or make feature requests! Contributions welcome!

Overview

The prosemirror-math package provides schema and plugins for comfortably writing mathematics with ProseMirror. Written in TypeScript, with math rendering handled by KaTeX. You can install the npm package or use this repository as a starting point for your own plugin. The important files in this project are:

  • lib/math-schema.ts: A minimal ProseMirror schema supporting inline and display math nodes.
  • lib/math-nodeview.ts: A NodeView responsible for rendering and editing math nodes.
  • public/prosemirror-math.css: Contains all necessary styling for math nodes to display correctly. This file can easily be modified to achieve your desired appearance.

Basic Usage (try it yourself!)

Unlike other editors, this plugin treats math as part of the text itself, rather than as an "atom" that can only be edited through a dialog box. For example, inline math nodes can be edited directly by bringing the cursor inside of them:

edit inline math

Display math supports multiline editing, as shown below:

edit display math

To create a new math expression, simply enclose LaTeX math notation in dollar signs, like $x+y=5$. When you finish typing, a new math node will be automatically created:

create inline math

To start a display math block, create a blank line and type $$ followed by a space. A multiline editor will appear. To exit the block, press Ctrl-Enter or navigate away the mouse or arrow keys.

create display math

Math nodes behave like regular text when using the arrow keys or Backspace. You can select, copy, and paste math nodes just like regular text! From within a math node, press Ctrl-Backspace to delete the entire node.

TIP: You can define your own commands with \providecommand{\cmd}{...}!

See the KaTeX documentation for a list of supported LaTeX commands. In the future, prosemirror-math will also accept a custom callback that can be used to invoke alternative renderers like MathJax.

Installation & Setup

Note that prosemirror-math is built on top of ProseMirror, which itself has a steep learning curve. At the very least, you will need to understand Schema and Plugins to integrate prosemirror-math into your project. Start by installing the npm package:

npm install @benrbray/prosemirror-math

CSS

First, make sure you include the CSS files for prosemirror-math and katex on any pages that will need them. They can be found at the following paths:

node_modules/katex/dist/katex.min.css
node_modules/@benrbray/prosemirror-math/dist/prosemirror-math.css

If you are using a bundler like vite or webpack, you may be able to include the CSS files like this:

import "@benrbray/prosemirror-math/dist/prosemirror-math.css";
import "katex/dist/katex.min.css";

Schema

Add math_inline and math_display nodes to your prosemirror document schema. The names are important! If you modify the schema, be careful not to change any of the values marked important! below, or you might run into unexpected behavior!

import { Schema } from "prosemirror-model";

let schema = new Schema({
    nodes: {
        doc: {
            content: "block+"
        },
        paragraph: {
            content: "inline*",
            group: "block",
            parseDOM: [{ tag: "p" }],
            toDOM() { return ["p", 0]; }
        },
        math_inline: {               // important!
            group: "inline math",
            content: "text*",        // important!
            inline: true,            // important!
            atom: true,              // important!
            toDOM: () => ["math-inline", { class: "math-node" }, 0],
            parseDOM: [{
                tag: "math-inline"   // important!
            }]
        },
        math_display: {              // important!
            group: "block math",
            content: "text*",        // important!
            atom: true,              // important!
            code: true,              // important!
            toDOM: () => ["math-display", { class: "math-node" }, 0],
            parseDOM: [{
                tag: "math-display"  // important!
            }]
        },
        text: {
            group: "inline"
        }
    }
});

Input Rules

If you want the user to be able to easily add new math nodes by typing $...$ for inline math or $$ followed by a space for block math, you need to create InputRule instances. You can write your own, or use the helper functions provided by prosemirror-math.

CAUTION: Make sure the NodeTypes you provide to each input rule belong to the same schema instance that you pass to your ProseMirror EditorView instance. Otherwise, you'll see strange errors in the console!

import {
    makeBlockMathInputRule, makeInlineMathInputRule,
    REGEX_INLINE_MATH_DOLLARS, REGEX_BLOCK_MATH_DOLLARS
} from "@benrbray/prosemirror-math";

// create input rules (using default regex)
let inlineMathInputRule = makeInlineMathInputRule(REGEX_INLINE_MATH_DOLLARS, editorSchema.nodes.math_inline);
let blockMathInputRule = makeBlockMathInputRule(REGEX_BLOCK_MATH_DOLLARS, editorSchema.nodes.math_display);

Plugins

Choose which plugins you need from the following list, and pass them to your EditorState instance, along with the input rules you created.

  • mathPlugin (required) Provides the core functionality of prosemirror-math.
  • mathBackspaceCmd (recommended) When included in your keymap for the "Backspace" key, pressing backspace on the right boundary of a math node will place the cursor inside the math node, rather than deleting it.
  • insertMathCmd(nodeType: NodeType) (optional) Helper function for creating a command which can be used to insert a math node at the current document position.
  • mathSerializer (recommended) Attach to the clipboardTextSerializer prop of your EditorView. When pasting a selection from a prosemirror-math editor to a plain text editor, ensures that the pasted math expressions will be properly delimited by $...$ and $$...$$.

Here is the recommended setup:

import { mathPlugin, mathBackspaceCmd, insertMathCmd, mathSerializer } from "@benrbray/prosemirror-math";

// prosemirror imports
import { EditorView } from "prosemirror-view";
import { EditorState, Plugin } from "prosemirror-state";
import { chainCommands, deleteSelection, selectNodeBackward, joinBackward, Command } from "prosemirror-commands";
import { keymap } from "prosemirror-keymap";
import { inputRules } from "prosemirror-inputrules";

// plugins (order matters)
let plugins:Plugin[] = [
    mathPlugin,
    keymap({
        "Mod-Space" : insertMathCmd(schema.nodes.math_inline),
        // modify the default keymap chain for backspace
        "Backspace": chainCommands(deleteSelection, mathBackspaceCmd, joinBackward, selectNodeBackward),
    }),
    inputRules({ rules: [ inlineMathInputRule, blockMathInputRule ] })
];

// create prosemirror state
let state = EditorState.create({
    schema: editorSchema,
    plugins: plugins,
    doc: /* ... */
})

// create prosemirror view
let view = new EditorView(editorElt, {
    state,
    clipboardTextSerializer: (slice) => { return mathSerializer.serializeSlice(slice) },
})

Development

Clone this repository and install the necessary dependencies:

git clone [email protected]:benrbray/prosemirror-math.git
cd prosemirror-math
npm install

From the root directory, you can run the scripts in package.json.

  • Use npm run build to build the prosemirror-math package
  • Use npm run build:site to generate the static demo website
  • Use npm run dev to start a local development server

Release

(this section is to help me remember the steps required to publish a new release)

To make a prerelease version for testing:

# begin a prerelease
npm version premajor --preid=rc # from 1.0.0 to 2.0.0-rc.0
npm version preminor --preid=rc # from 1.0.0 to 1.1.0-rc.0
npm version prepatch --preid=rc # from 1.0.0 to 1.0.1-rc.0

# increment the prerelease version number
npm version prerelease # from 2.0.0-rc.0 to 2.0.0-rc.1

# promote the prerelease version
npm version major # from 2.0.0-rc.1 to 2.0.0
npm version minor # from 1.1.0-beta.0 to 1.1.0
npm version patch # from 1.0.1-alpha.0 to 1.0.1

版本与发布记录

@benrbray/prosemirror-math 共发布 13 个版本,首次发布于 2021/03/28;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.0.0latest2024/04/142 年前
1.0.0-rc.32024/04/132 年前
1.0.0-rc.22024/04/132 年前
1.0.0-rc.12024/04/132 年前
1.0.0-rc.02024/04/132 年前
0.2.22021/06/235 年前

关于 @benrbray/prosemirror-math 的常见问题

@benrbray/prosemirror-math 是什么?

Schema and plugins for first-class math support in ProseMirror.

如何安装 @benrbray/prosemirror-math?

在项目目录运行 npm install @benrbray/prosemirror-math,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:katex(^0.16.10)、prosemirror-commands(^1.5.2)、prosemirror-history(^1.4.0)、prosemirror-inputrules(^1.4.0)、prosemirror-keymap(^1.2.2)、prosemirror-model(^1.20.0)、prosemirror-state(^1.4.3)、prosemirror-transform(^1.8.0)、prosemirror-view(^1.33.4)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@benrbray/prosemirror-math 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@benrbray/prosemirror-math 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@benrbray/prosemirror-math 可以商用吗?

@benrbray/prosemirror-math 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@benrbray/prosemirror-math 的下载量有多少?

根据 npm 官方下载统计,@benrbray/prosemirror-math 在 2026/10/08 – 2026/11/06 这 30 天内被下载 138,240 次,日均约 4,608 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@benrbray/prosemirror-math 还在维护吗?

最新版本 1.0.0 发布于 2024/04/14(2 年前);至今共发布 13 个版本,其中过去 12 个月发布了 0 个;首次发布于 2021/03/28。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。