Git Product home page Git Product logo

ionaru / easy-markdown-editor Goto Github PK

View Code? Open in Web Editor NEW
2.3K 25.0 308.0 12.75 MB

EasyMDE: A simple, beautiful, and embeddable JavaScript Markdown editor. Delightful editing for beginners and experts alike. Features built-in autosaving and spell checking.

Home Page: https://stackblitz.com/edit/easymde

License: MIT License

CSS 6.15% JavaScript 86.82% TypeScript 4.67% HTML 2.35%
markdown-editor markdown markdown-to-html markdown-converter markdown-viewer markdown-parser

easy-markdown-editor's Introduction

EasyMDE - Markdown Editor

npm version npm version Build Status

This repository is a fork of SimpleMDE, made by Sparksuite. Go to the dedicated section for more information.

A drop-in JavaScript text area replacement for writing beautiful and understandable Markdown. EasyMDE allows users who may be less experienced with Markdown to use familiar toolbar buttons and shortcuts.

In addition, the syntax is rendered while editing to clearly show the expected result. Headings are larger, emphasized words are italicized, links are underlined, etc.

EasyMDE also features both built-in auto saving and spell checking. The editor is entirely customizable, from theming to toolbar buttons and javascript hooks.

Try the demo

Preview

Quick access

Install EasyMDE

Via npm:

npm install easymde

Via the UNPKG CDN:

<link rel="stylesheet" href="https://unpkg.com/easymde/dist/easymde.min.css">
<script src="https://unpkg.com/easymde/dist/easymde.min.js"></script>

Or jsDelivr:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/easymde/dist/easymde.min.css">
<script src="https://cdn.jsdelivr.net/npm/easymde/dist/easymde.min.js"></script>

How to use

Loading the editor

After installing and/or importing the module, you can load EasyMDE onto the first textarea element on the web page:

<textarea></textarea>
<script>
const easyMDE = new EasyMDE();
</script>

Alternatively you can select a specific textarea, via JavaScript:

<textarea id="my-text-area"></textarea>
<script>
const easyMDE = new EasyMDE({element: document.getElementById('my-text-area')});
</script>

Editor functions

Use easyMDE.value() to get the content of the editor:

<script>
easyMDE.value();
</script>

Use easyMDE.value(val) to set the content of the editor:

<script>
easyMDE.value('New input for **EasyMDE**');
</script>

Configuration

Options list

  • autoDownloadFontAwesome: If set to true, force downloads Font Awesome (used for icons). If set to false, prevents downloading. Defaults to undefined, which will intelligently check whether Font Awesome has already been included, then download accordingly.
  • autofocus: If set to true, focuses the editor automatically. Defaults to false.
  • autosave: Saves the text that's being written and will load it back in the future. It will forget the text when the form it's contained in is submitted.
    • enabled: If set to true, saves the text automatically. Defaults to false.
    • delay: Delay between saves, in milliseconds. Defaults to 10000 (10 seconds).
    • submit_delay: Delay before assuming that submit of the form failed and saving the text, in milliseconds. Defaults to autosave.delay or 10000 (10 seconds).
    • uniqueId: You must set a unique string identifier so that EasyMDE can autosave. Something that separates this from other instances of EasyMDE elsewhere on your website.
    • timeFormat: Set DateTimeFormat. More information see DateTimeFormat instances. Default locale: en-US, format: hour:minute.
    • text: Set text for autosave.
  • autoRefresh: Useful, when initializing the editor in a hidden DOM node. If set to { delay: 300 }, it will check every 300 ms if the editor is visible and if positive, call CodeMirror's refresh().
  • blockStyles: Customize how certain buttons that style blocks of text behave.
    • bold: Can be set to ** or __. Defaults to **.
    • code: Can be set to ``` or ~~~. Defaults to ```.
    • italic: Can be set to * or _. Defaults to *.
  • unorderedListStyle: can be *, - or +. Defaults to *.
  • scrollbarStyle: Chooses a scrollbar implementation. The default is "native", showing native scrollbars. The core library also provides the "null" style, which completely hides the scrollbars. Addons can implement additional scrollbar models.
  • element: The DOM element for the textarea element to use. Defaults to the first textarea element on the page.
  • forceSync: If set to true, force text changes made in EasyMDE to be immediately stored in original text area. Defaults to false.
  • hideIcons: An array of icon names to hide. Can be used to hide specific icons shown by default without completely customizing the toolbar.
  • indentWithTabs: If set to false, indent using spaces instead of tabs. Defaults to true.
  • initialValue: If set, will customize the initial value of the editor.
  • previewImagesInEditor: - EasyMDE will show preview of images, false by default, preview for images will appear only for images on separate lines.
  • imagesPreviewHandler: - A custom function for handling the preview of images. Takes the parsed string between the parantheses of the image markdown ![]( ) as argument and returns a string that serves as the src attribute of the <img> tag in the preview. Enables dynamic previewing of images in the frontend without having to upload them to a server, allows copy-pasting of images to the editor with preview.
  • insertTexts: Customize how certain buttons that insert text behave. Takes an array with two elements. The first element will be the text inserted before the cursor or highlight, and the second element will be inserted after. For example, this is the default link value: ["[", "](http://)"].
    • horizontalRule
    • image
    • link
    • table
  • lineNumbers: If set to true, enables line numbers in the editor.
  • lineWrapping: If set to false, disable line wrapping. Defaults to true.
  • minHeight: Sets the minimum height for the composition area, before it starts auto-growing. Should be a string containing a valid CSS value like "500px". Defaults to "300px".
  • maxHeight: Sets fixed height for the composition area. minHeight option will be ignored. Should be a string containing a valid CSS value like "500px". Defaults to undefined.
  • onToggleFullScreen: A function that gets called when the editor's full screen mode is toggled. The function will be passed a boolean as parameter, true when the editor is currently going into full screen mode, or false.
  • parsingConfig: Adjust settings for parsing the Markdown during editing (not previewing).
    • allowAtxHeaderWithoutSpace: If set to true, will render headers without a space after the #. Defaults to false.
    • strikethrough: If set to false, will not process GFM strikethrough syntax. Defaults to true.
    • underscoresBreakWords: If set to true, let underscores be a delimiter for separating words. Defaults to false.
  • overlayMode: Pass a custom codemirror overlay mode to parse and style the Markdown during editing.
    • mode: A codemirror mode object.
    • combine: If set to false, will replace CSS classes returned by the default Markdown mode. Otherwise the classes returned by the custom mode will be combined with the classes returned by the default mode. Defaults to true.
  • placeholder: If set, displays a custom placeholder message.
  • previewClass: A string or array of strings that will be applied to the preview screen when activated. Defaults to "editor-preview".
  • previewRender: Custom function for parsing the plaintext Markdown and returning HTML. Used when user previews.
  • promptURLs: If set to true, a JS alert window appears asking for the link or image URL. Defaults to false.
  • promptTexts: Customize the text used to prompt for URLs.
    • image: The text to use when prompting for an image's URL. Defaults to URL of the image:.
    • link: The text to use when prompting for a link's URL. Defaults to URL for the link:.
  • iconClassMap: Used to specify the icon class names for the various toolbar buttons.
  • uploadImage: If set to true, enables the image upload functionality, which can be triggered by drag and drop, copy-paste and through the browse-file window (opened when the user click on the upload-image icon). Defaults to false.
  • imageMaxSize: Maximum image size in bytes, checked before upload (note: never trust client, always check the image size at server-side). Defaults to 1024 * 1024 * 2 (2 MB).
  • imageAccept: A comma-separated list of mime-types used to check image type before upload (note: never trust client, always check file types at server-side). Defaults to image/png, image/jpeg.
  • imageUploadFunction: A custom function for handling the image upload. Using this function will render the options imageMaxSize, imageAccept, imageUploadEndpoint and imageCSRFToken ineffective.
    • The function gets a file and onSuccess and onError callback functions as parameters. onSuccess(imageUrl: string) and onError(errorMessage: string)
  • imageUploadEndpoint: The endpoint where the images data will be sent, via an asynchronous POST request. The server is supposed to save this image, and return a JSON response.
    • if the request was successfully processed (HTTP 200 OK): {"data": {"filePath": "<filePath>"}} where filePath is the path of the image (absolute if imagePathAbsolute is set to true, relative if otherwise);
    • otherwise: {"error": "<errorCode>"}, where errorCode can be noFileGiven (HTTP 400 Bad Request), typeNotAllowed (HTTP 415 Unsupported Media Type), fileTooLarge (HTTP 413 Payload Too Large) or importError (see errorMessages below). If errorCode is not one of the errorMessages, it is alerted unchanged to the user. This allows for server-side error messages. No default value.
  • imagePathAbsolute: If set to true, will treat imageUrl from imageUploadFunction and filePath returned from imageUploadEndpoint as an absolute rather than relative path, i.e. not prepend window.location.origin to it.
  • imageCSRFToken: CSRF token to include with AJAX call to upload image. For various instances like Django, Spring and Laravel.
  • imageCSRFName: CSRF token filed name to include with AJAX call to upload image, applied when imageCSRFToken has value, defaults to csrfmiddlewaretoken.
  • imageCSRFHeader: If set to true, passing CSRF token via header. Defaults to false, which pass CSRF through request body.
  • imageTexts: Texts displayed to the user (mainly on the status bar) for the import image feature, where #image_name#, #image_size# and #image_max_size# will replaced by their respective values, that can be used for customization or internationalization:
    • sbInit: Status message displayed initially if uploadImage is set to true. Defaults to Attach files by drag and dropping or pasting from clipboard..
    • sbOnDragEnter: Status message displayed when the user drags a file to the text area. Defaults to Drop image to upload it..
    • sbOnDrop: Status message displayed when the user drops a file in the text area. Defaults to Uploading images #images_names#.
    • sbProgress: Status message displayed to show uploading progress. Defaults to Uploading #file_name#: #progress#%.
    • sbOnUploaded: Status message displayed when the image has been uploaded. Defaults to Uploaded #image_name#.
    • sizeUnits: A comma-separated list of units used to display messages with human-readable file sizes. Defaults to B, KB, MB (example: 218 KB). You can use B,KB,MB instead if you prefer without whitespaces (218KB).
  • errorMessages: Errors displayed to the user, using the errorCallback option, where #image_name#, #image_size# and #image_max_size# will replaced by their respective values, that can be used for customization or internationalization:
    • noFileGiven: The server did not receive any file from the user. Defaults to You must select a file..
    • typeNotAllowed: The user send a file type which doesn't match the imageAccept list, or the server returned this error code. Defaults to This image type is not allowed..
    • fileTooLarge: The size of the image being imported is bigger than the imageMaxSize, or if the server returned this error code. Defaults to Image #image_name# is too big (#image_size#).\nMaximum file size is #image_max_size#..
    • importError: An unexpected error occurred when uploading the image. Defaults to Something went wrong when uploading the image #image_name#..
  • errorCallback: A callback function used to define how to display an error message. Defaults to (errorMessage) => alert(errorMessage).
  • renderingConfig: Adjust settings for parsing the Markdown during previewing (not editing).
    • codeSyntaxHighlighting: If set to true, will highlight using highlight.js. Defaults to false. To use this feature you must include highlight.js on your page or pass in using the hljs option. For example, include the script and the CSS files like:
      <script src="https://cdn.jsdelivr.net/highlight.js/latest/highlight.min.js"></script>
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/highlight.js/latest/styles/github.min.css">
    • hljs: An injectible instance of highlight.js. If you don't want to rely on the global namespace (window.hljs), you can provide an instance here. Defaults to undefined.
    • markedOptions: Set the internal Markdown renderer's options. Other renderingConfig options will take precedence.
    • singleLineBreaks: If set to false, disable parsing GitHub Flavored Markdown (GFM) single line breaks. Defaults to true.
    • sanitizerFunction: Custom function for sanitizing the HTML output of Markdown renderer.
  • shortcuts: Keyboard shortcuts associated with this instance. Defaults to the array of shortcuts.
  • showIcons: An array of icon names to show. Can be used to show specific icons hidden by default without completely customizing the toolbar.
  • spellChecker: If set to false, disable the spell checker. Defaults to true. Optionally pass a CodeMirrorSpellChecker-compliant function.
  • inputStyle: textarea or contenteditable. Defaults to textarea for desktop and contenteditable for mobile. contenteditable option is necessary to enable nativeSpellcheck.
  • nativeSpellcheck: If set to false, disable native spell checker. Defaults to true.
  • sideBySideFullscreen: If set to false, allows side-by-side editing without going into fullscreen. Defaults to true.
  • status: If set to false, hide the status bar. Defaults to the array of built-in status bar items.
    • Optionally, you can set an array of status bar items to include, and in what order. You can even define your own custom status bar items.
  • styleSelectedText: If set to false, remove the CodeMirror-selectedtext class from selected lines. Defaults to true.
  • syncSideBySidePreviewScroll: If set to false, disable syncing scroll in side by side mode. Defaults to true.
  • tabSize: If set, customize the tab size. Defaults to 2.
  • theme: Override the theme. Defaults to easymde.
  • toolbar: If set to false, hide the toolbar. Defaults to the array of icons.
  • toolbarTips: If set to false, disable toolbar button tips. Defaults to true.
  • toolbarButtonClassPrefix: Adds a prefix to the toolbar button classes when set. For example, a value of "mde" results in "mde-bold" for the Bold button.
  • direction: rtl or ltr. Changes text direction to support right-to-left languages. Defaults to ltr.

Options example

Most options demonstrate the non-default behavior:

const editor = new EasyMDE({
    autofocus: true,
    autosave: {
        enabled: true,
        uniqueId: "MyUniqueID",
        delay: 1000,
        submit_delay: 5000,
        timeFormat: {
            locale: 'en-US',
            format: {
                year: 'numeric',
                month: 'long',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
            },
        },
        text: "Autosaved: "
    },
    blockStyles: {
        bold: "__",
        italic: "_",
    },
    unorderedListStyle: "-",
    element: document.getElementById("MyID"),
    forceSync: true,
    hideIcons: ["guide", "heading"],
    indentWithTabs: false,
    initialValue: "Hello world!",
    insertTexts: {
        horizontalRule: ["", "\n\n-----\n\n"],
        image: ["![](http://", ")"],
        link: ["[", "](https://)"],
        table: ["", "\n\n| Column 1 | Column 2 | Column 3 |\n| -------- | -------- | -------- |\n| Text     | Text      | Text     |\n\n"],
    },
    lineWrapping: false,
    minHeight: "500px",
    parsingConfig: {
        allowAtxHeaderWithoutSpace: true,
        strikethrough: false,
        underscoresBreakWords: true,
    },
    placeholder: "Type here...",

    previewClass: "my-custom-styling",
    previewClass: ["my-custom-styling", "more-custom-styling"],

    previewRender: (plainText) => customMarkdownParser(plainText), // Returns HTML from a custom parser
    previewRender: (plainText, preview) => { // Async method
        setTimeout(() => {
            preview.innerHTML = customMarkdownParser(plainText);
        }, 250);

        // If you return null, the innerHTML of the preview will not
        // be overwritten. Useful if you control the preview node's content via
        // vdom diffing.
        // return null;

        return "Loading...";
    },
    promptURLs: true,
    promptTexts: {
        image: "Custom prompt for URL:",
        link: "Custom prompt for URL:",
    },
    renderingConfig: {
        singleLineBreaks: false,
        codeSyntaxHighlighting: true,
        sanitizerFunction: (renderedHTML) => {
            // Using DOMPurify and only allowing <b> tags
            return DOMPurify.sanitize(renderedHTML, {ALLOWED_TAGS: ['b']})
        },
    },
    shortcuts: {
        drawTable: "Cmd-Alt-T"
    },
    showIcons: ["code", "table"],
    spellChecker: false,
    status: false,
    status: ["autosave", "lines", "words", "cursor"], // Optional usage
    status: ["autosave", "lines", "words", "cursor", {
        className: "keystrokes",
        defaultValue: (el) => {
            el.setAttribute('data-keystrokes', 0);
        },
        onUpdate: (el) => {
            const keystrokes = Number(el.getAttribute('data-keystrokes')) + 1;
            el.innerHTML = `${keystrokes} Keystrokes`;
            el.setAttribute('data-keystrokes', keystrokes);
        },
    }], // Another optional usage, with a custom status bar item that counts keystrokes
    styleSelectedText: false,
    sideBySideFullscreen: false,
    syncSideBySidePreviewScroll: false,
    tabSize: 4,
    toolbar: false,
    toolbarTips: false,
    toolbarButtonClassPrefix: "mde",
});

Toolbar icons

Below are the built-in toolbar icons (only some of which are enabled by default), which can be reorganized however you like. "Name" is the name of the icon, referenced in the JavaScript. "Action" is either a function or a URL to open. "Class" is the class given to the icon. "Tooltip" is the small tooltip that appears via the title="" attribute. Note that shortcut hints are added automatically and reflect the specified action if it has a key bind assigned to it (i.e. with the value of action set to bold and that of tooltip set to Bold, the final text the user will see would be "Bold (Ctrl-B)").

Additionally, you can add a separator between any icons by adding "|" to the toolbar array.

Name Action Tooltip
Class
bold toggleBold Bold
fa fa-bold
italic toggleItalic Italic
fa fa-italic
strikethrough toggleStrikethrough Strikethrough
fa fa-strikethrough
heading toggleHeadingSmaller Heading
fa fa-header
heading-smaller toggleHeadingSmaller Smaller Heading
fa fa-header
heading-bigger toggleHeadingBigger Bigger Heading
fa fa-lg fa-header
heading-1 toggleHeading1 Big Heading
fa fa-header header-1
heading-2 toggleHeading2 Medium Heading
fa fa-header header-2
heading-3 toggleHeading3 Small Heading
fa fa-header header-3
code toggleCodeBlock Code
fa fa-code
quote toggleBlockquote Quote
fa fa-quote-left
unordered-list toggleUnorderedList Generic List
fa fa-list-ul
ordered-list toggleOrderedList Numbered List
fa fa-list-ol
clean-block cleanBlock Clean block
fa fa-eraser
link drawLink Create Link
fa fa-link
image drawImage Insert Image
fa fa-picture-o
upload-image drawUploadedImage Raise browse-file window
fa fa-image
table drawTable Insert Table
fa fa-table
horizontal-rule drawHorizontalRule Insert Horizontal Line
fa fa-minus
preview togglePreview Toggle Preview
fa fa-eye no-disable
side-by-side toggleSideBySide Toggle Side by Side
fa fa-columns no-disable no-mobile
fullscreen toggleFullScreen Toggle Fullscreen
fa fa-arrows-alt no-disable no-mobile
guide This link Markdown Guide
fa fa-question-circle
undo undo Undo
fa fa-undo
redo redo Redo
fa fa-redo

Toolbar customization

Customize the toolbar using the toolbar option.

Only the order of existing buttons:

const easyMDE = new EasyMDE({
    toolbar: ["bold", "italic", "heading", "|", "quote"]
});

All information and/or add your own icons or text

const easyMDE = new EasyMDE({
    toolbar: [
        {
            name: "bold",
            action: EasyMDE.toggleBold,
            className: "fa fa-bold",
            title: "Bold",
        },
        "italic", // shortcut to pre-made button
        {
            name: "custom",
            action: (editor) => {
                // Add your own code
            },
            className: "fa fa-star",
            text: "Starred",
            title: "Custom Button",
            attributes: { // for custom attributes
                id: "custom-id",
                "data-value": "custom value" // HTML5 data-* attributes need to be enclosed in quotation marks ("") because of the dash (-) in its name.
            }
        },
        "|" // Separator
        // [, ...]
    ]
});

Put some buttons on dropdown menu

const easyMDE = new EasyMDE({
    toolbar: [{
                name: "heading",
                action: EasyMDE.toggleHeadingSmaller,
                className: "fa fa-header",
                title: "Headers",
            },
            "|",
            {
                name: "others",
                className: "fa fa-blind",
                title: "others buttons",
                children: [
                    {
                        name: "image",
                        action: EasyMDE.drawImage,
                        className: "fa fa-picture-o",
                        title: "Image",
                    },
                    {
                        name: "quote",
                        action: EasyMDE.toggleBlockquote,
                        className: "fa fa-percent",
                        title: "Quote",
                    },
                    {
                        name: "link",
                        action: EasyMDE.drawLink,
                        className: "fa fa-link",
                        title: "Link",
                    }
                ]
            },
        // [, ...]
    ]
});

Keyboard shortcuts

EasyMDE comes with an array of predefined keyboard shortcuts, but they can be altered with a configuration option. The list of default ones is as follows:

Shortcut (Windows / Linux) Shortcut (macOS) Action
Ctrl-' Cmd-' "toggleBlockquote"
Ctrl-B Cmd-B "toggleBold"
Ctrl-E Cmd-E "cleanBlock"
Ctrl-H Cmd-H "toggleHeadingSmaller"
Ctrl-I Cmd-I "toggleItalic"
Ctrl-K Cmd-K "drawLink"
Ctrl-L Cmd-L "toggleUnorderedList"
Ctrl-P Cmd-P "togglePreview"
Ctrl-Alt-C Cmd-Alt-C "toggleCodeBlock"
Ctrl-Alt-I Cmd-Alt-I "drawImage"
Ctrl-Alt-L Cmd-Alt-L "toggleOrderedList"
Shift-Ctrl-H Shift-Cmd-H "toggleHeadingBigger"
F9 F9 "toggleSideBySide"
F11 F11 "toggleFullScreen"
Ctrl-Alt-1 Cmd-Alt-1 "toggleHeading1"
Ctrl-Alt-2 Cmd-Alt-2 "toggleHeading2"
Ctrl-Alt-3 Cmd-Alt-3 "toggleHeading3"
Ctrl-Alt-4 Cmd-Alt-4 "toggleHeading4"
Ctrl-Alt-5 Cmd-Alt-5 "toggleHeading5"
Ctrl-Alt-6 Cmd-Alt-6 "toggleHeading6"

Here is how you can change a few, while leaving others untouched:

const editor = new EasyMDE({
    shortcuts: {
        "toggleOrderedList": "Ctrl-Alt-K", // alter the shortcut for toggleOrderedList
        "toggleCodeBlock": null, // unbind Ctrl-Alt-C
        "drawTable": "Cmd-Alt-T", // bind Cmd-Alt-T to drawTable action, which doesn't come with a default shortcut
    }
});

Shortcuts are automatically converted between platforms. If you define a shortcut as "Cmd-B", on PC that shortcut will be changed to "Ctrl-B". Conversely, a shortcut defined as "Ctrl-B" will become "Cmd-B" for Mac users.

The list of actions that can be bound is the same as the list of built-in actions available for toolbar buttons.

Advanced use

Event handling

You can catch the following list of events: https://codemirror.net/doc/manual.html#events

const easyMDE = new EasyMDE();
easyMDE.codemirror.on("change", () => {
    console.log(easyMDE.value());
});

Removing EasyMDE from text area

You can revert to the initial text area by calling the toTextArea method. Note that this clears up the autosave (if enabled) associated with it. The text area will retain any text from the destroyed EasyMDE instance.

const easyMDE = new EasyMDE();
// ...
easyMDE.toTextArea();
easyMDE = null;

If you need to remove registered event listeners (when the editor is not needed anymore), call easyMDE.cleanup().

Useful methods

The following self-explanatory methods may be of use while developing with EasyMDE.

const easyMDE = new EasyMDE();
easyMDE.isPreviewActive(); // returns boolean
easyMDE.isSideBySideActive(); // returns boolean
easyMDE.isFullscreenActive(); // returns boolean
easyMDE.clearAutosavedValue(); // no returned value

How it works

EasyMDE is a continuation of SimpleMDE.

SimpleMDE began as an improvement of lepture's Editor project, but has now taken on an identity of its own. It is bundled with CodeMirror and depends on Font Awesome.

CodeMirror is the backbone of the project and parses much of the Markdown syntax as it's being written. This allows us to add styles to the Markdown that's being written. Additionally, a toolbar and status bar have been added to the top and bottom, respectively. Previews are rendered by Marked using GitHub Flavored Markdown (GFM).

SimpleMDE fork

I originally made this fork to implement FontAwesome 5 compatibility into SimpleMDE. When that was done I submitted a pull request, which has not been accepted yet. This, and the project being inactive since May 2017, triggered me to make more changes and try to put new life into the project.

Changes include:

  • FontAwesome 5 compatibility
  • Guide button works when editor is in preview mode
  • Links are now https:// by default
  • Small styling changes
  • Support for Node 8 and beyond
  • Lots of refactored code
  • Links in preview will open in a new tab by default
  • TypeScript support

My intention is to continue development on this project, improving it and keeping it alive.

Hacking EasyMDE

You may want to edit this library to adapt its behavior to your needs. This can be done in some quick steps:

  1. Follow the prerequisites and installation instructions in the contribution guide;
  2. Do your changes;
  3. Run gulp command, which will generate files: dist/easymde.min.css and dist/easymde.min.js;
  4. Copy-paste those files to your code base, and you are done.

Contributing

Want to contribute to EasyMDE? Thank you! We have a contribution guide just for you!

License

This project is released under the MIT License.

  • Copyright (c) 2015 Sparksuite, Inc.
  • Copyright (c) 2017 Jeroen Akkerman.

easy-markdown-editor's People

Contributors

7upcat avatar a-312 avatar adam187 avatar adamb70 avatar brondsem avatar cbadke avatar danice avatar dependabot[bot] avatar dima-bzz avatar fabiankoestring avatar firm1 avatar frm avatar ggtmtmgg avatar ionaru avatar ivictbor avatar jecsham avatar kolaente avatar lukasz89 avatar nick-denry avatar nofxx avatar roipoussiere avatar roryok avatar situphen avatar smundro avatar trwired avatar vanillajonathan avatar wescossick avatar whiterm avatar zignature avatar zsgsdesign avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

easy-markdown-editor's Issues

Custom autosave handler

I'm submitting a...

  • Bug report
  • Feature request

The current autosave feature periodically stores contents to the local storage. It would be great if a function for autosave can be passed to option so that the autosave handler may be overridden for feature like server-side autosave,

heading-smaller, heading-bigger, heading-1, 2, 3 - using wrong css class?

Seems all these icons are using fa-header which doesn't exist in FontAwesome.
Should they also have fa-heading?

Displaying those buttons by default will result in the FontAwesome 'missing icon question mark' displaying instead.

On a similar note, the "H1, H2, H3" is currently added using css :after, but FontAwesome 5 has inbuilt support for fa-h1, etc, which looks cleaner.

CodeMirror.commands undefined when importing package

I'm submitting a...

  • Bug report
  • Feature request

Reproduction steps

  1. Install package npm install --save easymde
  2. Use webpack to bundle your js and point it to an entrypoint javascript file.
  3. Import it in your JS file import "easymde" or import { EasyMDE } from "easymde" or import * as EasyMDE from "easymde"
  4. Visit page that JS is loaded, it will say CodeMirror.commands is undefined in browser console.

If I import the minified js file (see below) it works fine, so I guess the issue is related to the bundling, perhaps some dependency or something that have to be set in the webpack config file that is not specified?

const EasyMDE = require('easymde/dist/easymde.min.js');

Version information

Browser type and version: Chrome/Firefox
EasyMDE version: 2.4.2

Don't commit dist folder?

I don't find how is that useful to commit the dist folder, since it's generated with gulp.

Some drawbacks:

  • redundancy;
  • always creates conflicts, so many pull-requests can not be merged automatically and it makes the update more difficult, so it's annoying both for maintainers and developers;
  • we are never really sure that the files in the dist folder are consistent with the sources before to run gulp;
  • this make the git history huge.

Set sanitize marked option to true by default?

Many issues on simple-mde was about an XSS vulnerability, allowing the user to execute JS code in the preview.

While the never trust the user is a common practice in web development, I think that we should avoid this and set the marked sanitize option to true by default.

I don't really find use-cases where injecting JS in a markdown viewer is useful.

Note that of course we can easily set this option with renderingConfig like below, this issue is just about choosing the default behavior.

new EasyMDE({
    element: ...,
    renderingConfig: {
        markedOptions: {
            sanitize: true
        }
    }
});

I'm submitting a...

  • Bug report
  • Feature request

(well, not sure here...)

Reproduction steps

Just type this in the text area:

<div onclick="alert('oops!')">Click here, please</div>

Then activate the preview and click on the text.

Version information

Any browser, any version

iOS Text Input Issue

I'm submitting a...

  • Bug report
  • Feature request

Reproduction steps

  1. Get an iOS device (I am personally using an iPhone X)
  2. Open a browser of your choice (I used Safari and Chrome)
  3. Navigate to this JSFiddle
  4. Select the text input box
  5. Type

You will notice that the keyboard does not dynamically or automatically change. Ever. When you first tap on the text input box it should automatically be in Caps mode, and after typing a single character it should automatically become uncapitalised. This does not happen. Another issue double-tapping space does not produce a full-stop. If you need any reminder of how the keyboard should be behaving, just open the notes app and type for a bit.

I believe that it must be because the keyboard isn't able to find any information on the contents of the text input box, though I'm speaking with no knowledge in the area.

Note: If you remove show from the URL of the JSFiddle, it will take you to the code.

Version information

Browser type and version: Safari (latest version), Chrome (latest version)
EasyMDE version: 2.4.0

New line after list

I'm submitting a... Bug report..

Reproduction steps

I am using it as a replacement for simplemde.

  1. There is a difference in markdown rendering in preview mode when using list. The very next line (dont have to leave any blank space), in preview mode is rendered differently. The content of next line shows up on last line of list (ignoring \n)
  2. Also markdown is also a bit different. (On Simplemde, we had markdown \r\n on new line but on this version, its only \n

Version information

Browser type and version: Chrome
EasyMDE version: v2.1.0

Editing without viewing the markdown ?

It would be great to have a mode, like preview - but with editing.

Some of my users are non-technical, so I could show them a version of the editor that doesn't have the markdown available.

Include CSS directly from JavaScript

I'm submitting a...

  • [] Bug report
  • Feature request

Reproduction steps

  1. ...
  2. ...

Version information

Browser type and version: Chrome 65
SimpleMDE version: Latest

Description

Currently developers are forced to include the css file as an external link through HTML. In my opinion this is bad practice and should be rather packed with the module itself, so that whenever I require or import this module I don't need the extra link. In the meantime, it would be pretty useful to explicitly say so, cause as per docs you only need this when you include the module via CDNs.

Relation to InscrybMDE

Hi, I've been looking for a (maintained) replacement to SimpleMDE and found this and InscrybMDE - what is the relation between the forks? I would really like to have my cake and eat it all :D

Bold, italic toggle at end of word causing issues.

I'm submitting a...

  • Bug report

Reproduction steps

  1. Place cursor at end of word and click bold multiple times like toggling. It adds multiple ** and activating italic instead of removing the initial bold **
    image

image

Version information

Browser type and version: Chrome Version 70.0.3538.77
EasyMDE version: 2.5.1

Fix word count for words with German Umlauts and ß

I'm submitting a...

  • Bug report
  • Feature request

Reproduction steps

  1. Set the editor's text input to this fictive German example text: "Öffentliche Apfelbäume wären schön für die Bürger, denn selbst mit ein wenig Übung würden die höchstgelegenen Äpfel außerordentlich schnell gepflückt werden."
  2. EasyMDE counts 30 words.
  3. It's actually 21 words.

or

  1. Change the text to: "Öffentliche Äußerungen werden manchmal ohne große Überlegung übernommen und ähnlich öffentlich wiedergegeben."
  2. EasyMDE counts 14 words.
  3. It's actually 12 words.

or

  1. Change the text to: "Üa Öa Üa aü aä aö aß ßß ßa"
  2. EasyMDE counts 8 words.
  3. It's actually 9 "words", "ßß" is not counted.

Version information

EasyMDE version: 2.5.1

Unicode sequences

Ä = \u00c4
Ö = \u00d6
Ü = \u00dc
ä = u00e4
ö = \u00f6
ü = \u00fc
ß = \u00df

Feature: Pass own marked renderer

I'm submitting a...

  • Bug report
  • Feature request

Feature Request

I found this fork after going through the network on the original project and as stated in #1 you said that you planned to continue the development of the original project since it seems that the original has stopped.

As noted in the title I would like to pass my own markedjs renderer to simplemde for rendering the previews since marked is what does it in the first place. I think that this should be done with a config property like such:

// Init the default renderer
var renderer = new marked.Renderer();
// Custom table rendering (in this case bootstrap table)
renderer.table = function (header, body) {
     return `<table class="table">${header} ${body}</table>`
};
new SimpleMDE({
    element: document.getElementById('simplemde-box'),
    // Pass the custom renderer
    renderer: renderer
});

Would be great to get some information about this fork

Hi there, looks like you've been adding some good stuff to simplemde, while the main simplemde project hasn't been updated for 2 years (unless I'm reading it wrong). Any chance you could post some information about this fork? Thanks

Breaking change with SimpleMDE in toolbar icons

I'm submitting a...

  • Bug report
  • Feature request

Reproduction steps

When passing custom toolbar icons, the no-disable class previously used in SimpleMDE is not respected.
Check this JSFiddle: https://jsfiddle.net/myv5wgh0/.

Due to a change in early v2 (7b147b3#diff-510834ebe67771ad1adc3336cb7fd314R16116), element.classList is now used instead of the element.className previously in use which results in a loss of classnames.

Also, the changes in v2 resulted in changes in the shape of the toolbar objects, which makes it a breaking change with SimpleMDE (need to add the noDisableproperty in EasyMDE).

So, no big bad breaking change, but I think it's worth mentioning it.

I found this "bug" because in a project of ours we use a different set of toolbar icons (material) and we needed to customize the actions.

Version information

EasyMDE version: >2.0.0

Hyperlink text getting doubled each time click on link

I'm submitting a...

  • Bug report
  • Feature request

Reproduction steps

  1. Navigate to editor and enter some link
  2. Select the link and click on link icon in header (multiple times)

Version information

Browser type and version: Chrome (Desktop) - Latest version
EasyMDE version: NA
2018-09-03_19-37-42

Apply custom class to string

I'm submitting a...

  • Question

Reproduction steps

I'm looking the way to highlight some text in the editor, for example when I write ???category I want to apply some CSS style to that part of the text, it's possible ?
Thank you!

EDIT:
Here some code for what I want to do, for example if I write &Hello the text parsed and styled to

<span class="cm-formatting cm-my-style1">&</span>
<span class="cm-my-style2">Hello</span>

IE11 - mouse slection not working

I'm submitting a...

  • Bug report
  • Feature request

Reproduction steps

  1. Open browser.
  2. Type several paragraphs.
  3. Try selecting one of the paragraphs in IE11.
  4. Kick yourself in the nutsack.
  5. Load up https://simplemde.com/ in the same browser
  6. Successfully select any paragraph you want.
  7. Kick yourself in the nutsack.
  8. Ponder what may have introduced this odd bug.

https://jsfiddle.net/vo1g3kue/

Version information

Browser type and version: IE 11.471.17134.0
EasyMDE version: any?

Android Mobile Text Input

I'm submitting a...

  • Bug report
  • Feature request

Reproduction steps

User a Android device and start typing. Each character is on a new line

Version information

Browser type and version: Chrome, Firefox on Android
EasyMDE version: 2.1.0

Blockquote double enter not removing stay >

I'm submitting a...

  • Bug report
  • Feature request

Reproduction steps

When doing a block quote, i hit enter twice, I expect the last one to disappear i.e.

> fubar
>
qqeqweqw

You end up with a stray >

Lists work fine, just blockquote

Font Awesome 5 Needs 'far' or 'fas' classes, not 'fa'

I'm submitting a...

  • Bug report
  • Feature request

Reproduction steps

  1. install EasyMDE on a site that already uses FontAwesome, and thus doesn't pull the loaded one
  2. Look at toolbar's missing icons

Version information

Browser type and version:
EasyMDE version: 2.4.1

Font Awesome 5 has changed the way they do their classing from Font Awesome 4. No longer can you simply use fa, rather you need to use fas, far, etc... It appears that your autoloaded version actually uses FA 4.7.0, does not behave this way, so when using EasyMDE on a site that already uses FontAwesome 5, the icons do not show.

It seems to me that the solution is to simply add far or fas to the corresponding icon classes, as it won't affect people who still use FA4, and the extra fa won't affect people using FA5.

Unordered and ordered lists are combined

I'm submitting a...

  • Bug report
  • Feature request

Reproduction steps

The minimal markdown input required to reproduce the bug is the following:

 - unordered
 1. ordered

It displays the following:

  • unordered
  • ordered

Github displays it correctly:

  • unordered
  1. ordered

Two newlines still counts as one list and displays the buggy behaviour:

 - unordered

 1. ordered

When there are three newlines, it stops exhibiting the behaviour:

 - unordered


 1. ordered

Version information

Browser type and version: Chrome, Version 72.0.3626.96 (Official Build) (64-bit)
EasyMDE version: Unsure, it is present on https://easymde.tk/

Add ability to pass `spellcheck` and `inputType` options to CodeMirror

I'm submitting a...

  • Feature request

After adding

inputStyle: "contenteditable",
spellcheck: true

to the CodeMirror initialisation at https://github.com/Ionaru/easy-markdown-editor/blob/master/src/js/easymde.js#L1584, I was able to get spellchecking within the browser (at least Google Chrome) functional without any apparent issues. If we could pass these options (or arbitrary options that just had defaults) to the CodeMirror initialisation, that would be awesome.

PS. Thanks so much for this fork of simplemde. It powers our internal CMS and our staff love using it.

API hooks for image/file uploading

I'm submitting a...

  • Feature request

We would like to give our users the ability to upload images and files, and I think that GitHub has solved this really nice. In order to implement this, I would love it if there was some way to register hooks for when a file is dropped onto the editor.

To be clear, I would not like the editor to do anything regarding the actual uploading of the files. Just a hook that calls my own function when a file has been dropped.

My own code could then upload the file, and insert the correct markdown syntax for it to be displayed ☺️

I'd be happy to help contribute code for this, please let me know what you think!

Add type="button" to toolbar buttons

I'm submitting a...

  • Bug report
  • Feature request

Reproduction steps

Please add role="button" to toolbar buttons. Otherwise they are by default treated as submit buttons which causes weird behaviour when SimpleMDE is inside a form with other inputs. Instead of submitting the form when I press <enter>, first button (SimpleMDE's bold button) is pressed.

See this fiddle: https://jsfiddle.net/ge9hfkaL/2/

Version information

Browser type and version: all?
EasyMDE version: all?

Newlines not being displayed when setting value

When setting the value to a markdown string that includes newline characters the entire string is displaying as one line when using myEditor.value('myMarkdownString').

Either I'm doing it wrong or it's not parsing the newlines correctly. Any help appreciated

EasyMDE version: 2.5.1

Easy way to redefine an action?

I'm submitting a...

  • Bug report
  • Feature request

I would like to redefine some actions. The only way I found to do this is to use the toolbar option, but this one overwrite all default items, so I need to set all default icons and create a new icon with the same values instead the custom action, like this:

toolbar: [
    'bold', 'italic', 'heading', '|', 'quote', 'unordered-list', 'ordered-list', '|', 'link',
    {
        name: 'image',
        action: function customFunction(editor){
            alert('Hey!')
        },
        className: 'fa fa-image',
        title: 'Insert image'
    },
    '|', 'preview', 'side-by-side', 'fullscreen', 'guide'
]

Is there an easier way to do this?

If not, I would suggest a toolbarAction option, which could work like this:

new EasyMDE({
    toolbarAction: {
        image: function customFunction(editor){
            alert('Hey!')
        },
    }
});

Add Ability to preview without full screen

I'm submitting a...

  • Bug report
  • Feature request

Reproduction steps

The editor currently forces the user to go full screen with codemirror when the side by side mode is enabled. It would be nice to be able to disable this functionality as it's fairly opinionated by the original devs.

A quick option and if check here would resolve this.

Disable EasyMDE inside form

I'm submitting a...

  • [] Bug report
  • Feature request

Version information

Browser type and version: latest Chrome
EasyMDE version: 2.5.1

Hi, thank you for the awesome plugin and big thanks for the regular updates.

I'm here to ask you about "disabling" feature. I've used your plugin in Formik (Reactjs) and in some cases, I should disable all fields in the form and EasyMDE too.

My feature request is: Can we have "disable" option or not.

Thank you.

Programatically set preview

I'm submitting a...

  • [] Bug report
  • Feature request

Version information

Browser type and version:
EasyMDE version: 4

Im curios how i can set the editor to render in preview mode? I only want the editor to be editable when the admin is using it, other users should only see the preview

Before- and afterRender functions

I'm submitting a...

  • [] Bug report
  • [x ] Feature request

Reproduction steps

It would be nice if there was a possibility to have functions that are called before and after the rendering of the preview render function. It creates a possibility to render custom text within the preview without me having to also to the markdown rendering, i.e. think of having mentions inside the text.

Add checklist toolbar button

I'm submitting a...

  • Feature request

It would be great to have another type of list (in addition to generic and numbered) that starts each line with - [ ] for easy building of to-do lists and other such things.

Include typings

I'm submitting a...

  • Bug report
  • Feature request

The typings from here should be adapted for EasyMDE and included in this repo.

Can not select text on mobile

I'm submitting a...

  • Bug report
  • Feature request

Reproduction steps

  1. Double tap on a word to select it
  2. It selects it and deselects it, making it impossible to select text

Version information

Browser type and version: Latest Android Chrome
EasyMDE version: Latest from unpkg

This also happens on the demo version of EasyMDE.

Bug With unordered lists

When creating an unordered list like so:

- One
- Two

entering a newline at the end of line - One (i.e., inserting a new item between One and Two) results in the following:

- One
- 
NaNundefinedTwo

Note: This does not occur with ordered list. Also, the old SimpleMDE 1.11.2 doesn't have this problem.

Split up toolbar button and icon classes

I'm submitting a...

  • Bug report
  • Feature request

While working on #41 I noticed it is necessary define button classes and icon classes in the same field, this is a result of changes made to have FontAwesome 5 compatibility.

This behaviour is confusing for developers working with the editor and error prone because the editor has to figure out which classes to add to the icon and which ones to add to the button.

I want to mark className as deprecated and introduce iconClass and buttonClass, those fields combined will facilitate the same functionality.

Impossible to navigate cursor on Mobile

Impossible to navigate cursor on Mobile

Hey Guys,

I'm having issue with easy-markdown implementation for responsive version of the editor on mobile, So after adding some text if you move around the the texts it starts blinking on a word and make it impossible to move around any further.

Steps:

  • Open text editor on mobile
  • Add some long text
  • Try to navigate around through cursor
  • Repeat it for a while until a word gets highlighted and starts blinking
  • After that you wont be able to navigate around the text properly

Please if anyone can guide me on this.

RFE: allow a callback for link generation

I'm submitting a...

  • Bug report
  • Feature request

Reproduction steps

N/A

Version information

EasyMDE version: hopefully the next one ;)

i would like to have a callback (as part of the config options) which gets called when the editor/previewer wants to render a link. The callback should get the link URI and the label as arguments and should return the "rendered" form of the link as an HTML string (or, if the internal API supports it, as a DOM element - that would give us more flexibility). If the callback is not set, or returns the undefined value, the previewer should use its current default behaviour.

Concrete use case: i'd like to replace an old custom blog/wiki of mine which uses the Google Code Wiki format. It runs as a one-page app and loads new wiki pages (in the same app session) when a user clicks on a link to a wiki page (yet treats external links "as usual"). That is only possible because the Google Code Wiki parser allows me to replace (via a callback) its default link generator with one which i use to check "is this a link to a wiki page, and if so, create a custom link". Such a callback also makes it possible to replace anchor tags with, e.g., spans with on-click handlers, which might conceivably be useful as an anti-bot/spider method.

As an example:

https://fossil.wanderinghorse.net/wikis/cson

The "TableOfContents" link on the first page is a link to another wiki page, which the Google Code Wiki parser has allowed me to customize the link for. Tapping the link loads the requested page via ajax and feeds it into the app.

spell checker

is codemirror-spell-checker really necessary?
it brings in lots of other dependencies i don't want/need (it seems to only be english wish my website don't use).

I think it should be an optional dependency. Also, isn't possible to use the native spell checker somehow?

(related: cfinke/Typo.js#68, cross-js#dont-use-buffer)

Cannot bundle code with webpack that imports EasyMDE

I'm submitting a...

  • Bug report
  • Feature request

Reproduction steps

  1. npm install easymde --save
  2. Added import EasyMDE from 'easymde'
  3. Compiled the component that imports it using webpack

Version information

Node: 8.9.4
NPM: 5.6.0
EasyMDE version: 2.0.1

Issue:
I currently have webpack set up as my app's bundler, and I've had no problems so far with any other modules, but after installing and trying to use easymde, babel-loader freaks out and says it cannot find the module, even though I confirmed it's present in node_modules. I tested with another module and it worked fine. Could it be because your package.json main field points to the dev build of the module?

Change role="button" to type="button" on toolbar buttons

I am sorry, a created issue #38, to fix weird behaviour when submitting form via ENTER key. After testing with new release bug mentioned in #38 still occurring, so after futher googling and this time also testing I found you have to set type="button" not role="button"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.