Editor.md

repository·master·Indexed 12 days ago

https://github.com/pandao/editor.md

An open-source, embeddable online Markdown editor component built on CodeMirror, jQuery, and Marked. Version 1.5.0 provides a real-time preview experience with support for GFM, LaTeX (via KaTeX), flowcharts, sequence diagrams, and various Markdown extensions. It includes a comprehensive API for content manipulation, cursor control, and customizable toolbars.

Tokens
6.3K
Snippets
9
Records
17
Agent score
94%

What's inside Editor.md

  1. Create a Markdown editor instance

    master

    To initialize an editor, include the editormd.min.css and editormd.min.js files. You should provide a container element (like a div) and optionally a hidden textarea containing the initial Markdown content. The editormd() function initializes the editor on the specified element.

    Note: The path option is used in 'Autoload modules mode' to tell the editor where its dependent libraries (like CodeMirror and Marked) are located.

    <link rel="stylesheet" href="editor.md/css/editormd.min.css" />
    <div id="editor">
        <!-- Tips: Editor.md can auto append a `<textarea>` tag -->
        <textarea style="display:none;">### Hello Editor.md !</textarea>
    </div>
    <script src="jquery.min.js"></script>
    <script src="editor.md/editormd.min.js"></script>
    <script type="text/javascript">
        $(function() {
            var editor = editormd("editor", {
                // width: "100%",
                // height: "100%",
                // markdown: "xxxx",     // dynamic set Markdown text
                path : "editor.md/lib/"  // Autoload modules mode, codemirror, marked... dependents libs path
            });
        });
    </script>
  2. Markdown Syntax Supported by Editor.md

    master

    Editor.md supports a wide range of Markdown extensions and standard syntax, including:

    • Headings: Standard # syntax, as well as underline-style headings (e.g., === for H1, --- for H2).
    • Text Formatting: Bold (**text**), Italic (*text*), Strikethrough (~~text~~), and HTML tags like <s>.
    • Lists: Unordered lists (-, *, +), Ordered lists (1.), and GFM Task Lists (- [ ], - [x]).
    • Links & Anchors: Standard links [title](url), direct URLs <url>, and reference-style anchor links [text][id].
    • Blockquotes: Standard > syntax, including mixed inline content.
    • Tables: GFM-style tables with alignment support (:---, ---:, :---:) and zebra striping.
    • Images: Standard ![](url) syntax and images wrapped in links [![](img_url)](link_url).
    • Code: Inline code `code`, indented code blocks, and fenced code blocks with language highlighting (e.g., ```javascript).
    • Special Features: Emoji support (:smiley:), HTML entities (&copy;), and GFM @mentions.
  3. Configure Editor.md options

    master

    Editor.md provides a wide range of configuration options. Key categories include:

    • Mode & Content: mode ("gfm" or "markdown"), markdown (source code), value (for non-markdown modes).
    • Appearance: theme, editorTheme, previewTheme, width, height, fontSize.
    • Editor Behavior: readOnly, tabSize, indentUnit, lineNumbers, lineWrapping, autoCloseBrackets, searchReplace.
    • Plugins & Extensions: toc (Table of Contents), emoji, taskList, tex (LaTeX via KaTeX), flowChart, sequenceDiagram.
    • Image Upload: imageUpload (boolean), imageUploadURL, imageFormats, crossDomainUpload.
    • Callbacks: onload, onresize, onchange, onpreviewing, onpreviewed, onfullscreen, etc.
    • Toolbar: toolbar (boolean), toolbarIcons ("full", "simple", "mini"), toolbarCustomIcons.
    {
        mode                 : "gfm",          // gfm or markdown
        name                 : "",             // Form element name for post
        value                : "",             // value for CodeMirror, if mode not gfm/markdown
        theme                : "",             // Editor.md self themes, before v1.5.0 is CodeMirror theme, default empty
        editorTheme          : "default",      // Editor area, this is CodeMirror theme at v1.5.0
        previewTheme         : "",             // Preview area theme, default empty
        markdown             : "",             // Markdown source code
        appendMarkdown       : "",             // if in init textarea value not empty, append markdown to textarea
        width                : "100%",
        height               : "100%",
        path                 : "./lib/",       // Dependents module file directory
        pluginPath           : "",             // If this empty, default use settings.path + "../plugins/"
        delay                : 300,            // Delay parse markdown to html, Uint : ms
        autoLoadModules      : true,           // Automatic load dependent module files
        watch                : true,
        placeholder          : "Enjoy Markdown! coding now...",
        gotoLine             : true,           // Enable / disable goto a line
        codeFold             : false,
        autoHeight           : false,
        autoFocus            : true,           // Enable / disable auto focus editor left input area
        autoCloseTags        : true,
        searchReplace        : true,           // Enable / disable (CodeMirror) search and replace function
        syncScrolling        : true,           // options: true | false | "single", default true
        readOnly             : false,           // Enable / disable readonly mode
        tabSize              : 4,
        indentUnit           : 4,
        lineNumbers          : true,           // Display editor line numbers
        lineWrapping         : true,
        autoCloseBrackets    : true,
        showTrailingSpace    : true,
        matchBrackets        : true,
        indentWithTabs       : true,
        styleSelectedText    : true,
        matchWordHighlight   : true,           // options: true, false, "onselected"
        styleActiveLine      : true,           // Highlight the current line
        dialogLockScreen     : true,
        dialogShowMask       : true,
        dialogDraggable      : true,
        dialogMaskBgColor    : "#fff",
        dialogMaskOpacity    : 0.1,
        fontSize             : "13px",
        saveHTMLToTextarea   : false,          // If enable, Editor will create a <textarea name="{editor-id}-html-code"> tag save HTML code for form post to server-side.
        disabledKeyMaps      : [],
        
        onload               : function() {},
        onresize             : function() {},
        onchange             : function() {},
        onwatch              : null,
        onunwatch            : null,
        onpreviewing         : function() {},
        onpreviewed          : function() {},
        onfullscreen         : function() {},
        onfullscreenExit     : function() {},
        onscroll             : function() {},
        onpreviewscroll      : function() {},
        
        imageUpload          : false,          // Enable/disable upload
        imageFormats         : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
        imageUploadURL       : "",             // Upload url
        crossDomainUpload    : false,          // Enable/disable Cross-domain upload
        uploadCallbackURL    : "",             // Cross-domain upload callback url
    
        toc                  : true,           // Table of contents
        tocm                 : false,          // Using [TOCM], auto create ToC dropdown menu
        tocTitle             : "",             // for ToC dropdown menu button
        tocDropdown          : false,          // Enable/disable Table Of Contents dropdown menu
        tocContainer         : "",             // Custom Table Of Contents Container Selector
        tocStartLevel        : 1,              // Said from H1 to create ToC
        htmlDecode           : false,          // Open the HTML tag identification 
        pageBreak            : true,           // Enable parse page break [========]
        atLink               : true,           // for @link
        emailLink            : true,           // for email address auto link
        taskList             : false,           // Enable Github Flavored Markdown task lists
        emoji                : false,          // :emoji: , Support Github emoji, Twitter Emoji (Twemoji);
                                               // Support FontAwesome icon emoji :fa-xxx: > Using fontAwesome icon web fonts;
                                               // Support Editor.md logo icon emoji :editormd-logo: :editormd-logo-1x: ~1~8x;
        tex                  : false,          // TeX(LaTeX), based on KaTeX
        flowChart            : false,          // flowChart.js only support IE9+
        sequenceDiagram      : false,          // sequenceDiagram.js only support IE9+
        previewCodeHighlight : true,           // Enable / disable code highlight of editor preview area
    
        toolbar              : true,           // show or hide toolbar
        toolbarAutoFixed     : true,           // On window scroll auto fixed position
        toolbarIcons         : "full",         // Toolbar icons mode, options: full, simple, mini, See `editormd.toolbarModes` property.
        toolbarTitles        : {},
        toolbarHandlers      : {
            ucwords : function() {
                return editormd.toolbarHandlers.ucwords;
            },
            lowercase : function() {
                return editormd.toolbarHandlers.lowercase;
            }
        },
        toolbarCustomIcons   : {
            lowercase        : "<a href=\"javascript:;\" title=\"Lowercase\" unselectable=\"on\"><i class=\"fa\" name=\"lowercase\" style=\"font-size:24px;margin-top: -10px;\">a</i></a>",
            "ucwords"        : "<a href=\"javascript:;\" title=\"ucwords\" unselectable=\"on\"><i class=\"fa\" name=\"ucwords\" style=\"font-size:20px;margin-top: -3px;\">Aa</i></a>"
        },
        toolbarIconTexts     : {},
        
        lang : {
            name        : "zh-cn",
            description : "开源在线Markdown编辑器<br/>Open source online Markdown editor.",
            tocTitle    : "目录",
            toolbar     : {},
            button: {},
            dialog : {}
        }
    }
  4. Configure HTML tag parsing and filtering

    master

    Editor.md supports parsing HTML tags to extend Markdown syntax (e.g., for videos).

    • Enable Parsing: Set htmlDecode to true in the settings. Note that this is disabled by default for security.
    • Filtering: You can filter specific tags or attributes by setting htmlDecode to a string of allowed/disallowed tags, such as settings.htmlDecode = "style,script,iframe" to prevent those specific tags from being parsed.
  5. Configure KaTeX for scientific formulas

    master

    Editor.md uses KaTeX for rendering scientific formulas (TeX). To enable this, set the tex configuration option to true. You can also specify the KaTeX resource URL using katexURL.

    Note: The older mathjax configuration, mathjaxURL property, and related methods (setMathJaxConfig(), loadMathJax()) were removed in favor of KaTeX.

    // Example configuration for KaTeX
    editormd.create({
        id: 'your-id',
        tex: true,
        katexURL: 'path/to/katex.min.css'
    });
  6. Configure themes for Editor and Preview

    master

    Starting from v1.5.0, themes are split between the editor and the preview pane.

    • theme: Sets the overall Editor.md theme.
    • editorTheme: Sets the CodeMirror theme for the editing area.
    • previewTheme: Sets the theme for the preview area.

    Use setEditorTheme() (alias for setCodeMirror()) and setPreviewTheme() to change these dynamically.

  7. Configure Table of Contents (ToC) behavior

    master

    Editor.md can generate a Table of Contents.

    • tocStartLevel: Defines the heading level to start from (default is 1 in newer versions).
    • tocm: Set to true (default) to support the [TOCM] Markdown extension which generates a ToC dropdown menu.
    • tocDropdown: Configuration for the dropdown menu.
    • tocTitle: The title of the ToC.
    • tocContainer: A jQuery selector (e.g., '#my-toc') to specify a custom container for the ToC.
    • editormd.tocDropdownMenu(): Method to trigger the ToC dropdown.
  8. Configure synchronization scrolling modes

    master

    Editor.md supports synchronized scrolling between the editor and the preview pane.

    • Two-way Sync: The default behavior.
    • Single-way Sync: Set syncScrolling: "single" to enable scrolling only from the editor to the preview pane (the preview pane does not scroll the editor).
    • Disable Sync: Set syncScrolling: false (default).
    editormd.create({
        id: 'your-id',
        syncScrolling: 'single'
    });
  9. Customize the Editor.md toolbar

    master

    You can customize the toolbar by providing configuration options.

    • toolbarIcons: A function that returns an array of icon button strings (updated from a simple array in v1.1).
    • toolbarIconsTexts: An array used to customize the text for the buttons.
    • toolbarHandlers: An object/function to handle custom button operations.
    • toolbarCustomIcons: Allows inserting custom HTML tags directly for toolbar functionality.

    To use the default operation methods externally, you can call getToolbarHandles().

    editormd.create({
        id: 'your-id',
        toolbarIcons: function() {
            return ['list-ul', 'list-ol', 'link'];
        },
        toolbarIconsTexts: ['Bullet List', 'Numbered List', 'Link'],
        toolbarHandlers: {
            'my-custom-button': function() {
                console.log('Custom button clicked');
            }
        }
    });
  10. Use Math/Scientific Formulas with TeX (KaTeX)

    master

    Editor.md supports scientific formulas using TeX/KaTeX syntax. You can use block math or inline math.

    Block Math: Use $$ for standalone math blocks or specific language identifiers like math, katex, or latex.

    Inline Math: Use $$ within text for inline expressions.

    Example of a block math expression:

    \displaystyle
    \left( \sum\_{k=1}^n a\_k b\_k \right)^2
    \leq
    \left( \sum\_{k=1}^n a\_k^2 \right)
    \left( \sum\_{k=1}^n b\_k^2 \right)