Today, after 2 years, I released a new MarkdownEditor components for JavaScript and Blazor. In 2022, I created a Markdown Editor for Blazor based on EasyMDE, a JavaScript code that implements a markdown editor. EasyMDE is a wrap on SimpleMDE another JavaScript code.
Because I found some bugs in the scripts and the projects were not maintained anymore, I decided to continue this great JavaScript code and, at the same time, improve my component for Blazor.
Now, you can find the source code and help me to improve the projects here:
- Easy Markdown Editor for JavaScript: a simple, beautiful, and embeddable JavaScript Markdown editor. Delightful editing for beginners and experts alike. Features built-in autosaving and spell-checking.
- Markdown Editor for Blazor: this is the component for Blazor based on the previous project
- Try now my project
How to use the JavaScript code
First, you have to install the package from npm:
npm install psc-markdowneditor
Another option is to add the required scripts in your HTML using UNPKG
:
<link rel="stylesheet" href="https://unpkg.com/psc-markdowneditor/dist/easymde.min.css">
<script src="https://unpkg.com/psc-markdowneditor/dist/easymde.min.js"></script>
or via jsDelivr
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/erossini/EasyMarkdownEditor@main/dist/easymde.min.css">
<script src="https://cdn.jsdelivr.net/gh/erossini/EasyMarkdownEditor@main/dist/easymde.min.js"></script>
Then, add a textarea
in your HTML code like that:
<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>
Options
- autoDownloadFontAwesome: If set to
true
, force downloads Font Awesome (used for icons). If set tofalse
, prevents downloading. Defaults toundefined
, which will intelligently check whether Font Awesome has already been included, then download accordingly. - autofocus: If set to
true
, focuses the editor automatically. Defaults tofalse
. - 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 tofalse
. - 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
or10000
(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’srefresh()
. - 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 firsttextarea
element on the page. - forceSync: If set to
true
, force text changes made in EasyMDE to be immediately stored in original text area. Defaults tofalse
. - 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 totrue
. - 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 thesrc
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 totrue
. - 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 toundefined
. - 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, orfalse
. - 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 tofalse
. - strikethrough: If set to
false
, will not process GFM strikethrough syntax. Defaults totrue
. - underscoresBreakWords: If set to
true
, let underscores be a delimiter for separating words. Defaults tofalse
. - 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 totrue
. - 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 tofalse
. - 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 tofalse
. - 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
andimageCSRFToken
ineffective.- The function gets a file and
onSuccess
andonError
callback functions as parameters.onSuccess(imageUrl: string)
andonError(errorMessage: string)
- The function gets a file and
- 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 ifimagePathAbsolute
is set to true, relative if otherwise); - otherwise:
{"error": "<errorCode>"}
, where errorCode can benoFileGiven
(HTTP 400 Bad Request),typeNotAllowed
(HTTP 415 Unsupported Media Type),fileTooLarge
(HTTP 413 Payload Too Large) orimportError
(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.
- if the request was successfully processed (HTTP 200 OK):
- imagePathAbsolute: If set to
true
, will treatimageUrl
fromimageUploadFunction
and filePath returned fromimageUploadEndpoint
as an absolute rather than relative path, i.e. not prependwindow.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 tocsrfmiddlewaretoken
. - imageCSRFHeader: If set to
true
, passing CSRF token via header. Defaults tofalse
, 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 totrue
. Defaults toAttach 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 useB,KB,MB
instead if you prefer without whitespaces (218KB
).
- sbInit: Status message displayed initially if
- 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 toThis 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 toImage #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#.
.
- noFileGiven: The server did not receive any file from the user. Defaults to
- 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 tofalse
. To use this feature you must include highlight.js on your page or pass in using thehljs
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 toundefined
. - 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 totrue
. - 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 totrue
. Optionally pass a CodeMirrorSpellChecker-compliant function. - inputStyle:
textarea
orcontenteditable
. Defaults totextarea
for desktop andcontenteditable
for mobile.contenteditable
option is necessary to enable nativeSpellcheck. - nativeSpellcheck: If set to
false
, disable native spell checker. Defaults totrue
. - sideBySideFullscreen: If set to
false
, allows side-by-side editing without going into fullscreen. Defaults totrue
. - 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 theCodeMirror-selectedtext
class from selected lines. Defaults totrue
. - syncSideBySidePreviewScroll: If set to
false
, disable syncing scroll in side by side mode. Defaults totrue
. - 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 totrue
. - 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
orltr
. Changes text direction to support right-to-left languages. Defaults toltr
.
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 |
indent | indent | Indent fa fa-indent |
outdent | outdent | Outdent fa fa-outdent |
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” |