玛氪宕·梦魔(Markdown Memo),使用Markdown的云端备忘录,百度IFE的RIA启航班的不合格的作业,才……才没有什么阴谋呢! 源gitee链接https://gitee.com/arathi/MarkdownMemo?_from=gitee_search
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4331 lines
150 KiB

10 years ago
/*
* Editor.md
10 years ago
*
* @file editormd.amd.js
10 years ago
* @version v1.4.0
* @description Open source online markdown editor.
10 years ago
* @license MIT License
* @author Pandao
* {@link https://github.com/pandao/editor.md}
10 years ago
* @updateTime 2015-03-23
10 years ago
*/
10 years ago
;(function(factory) {
"use strict";
// CommonJS/Node.js
if (typeof require === "function" && typeof exports === "object" && typeof module === "object")
{
10 years ago
module.exports = factory;
10 years ago
}
else if (typeof define === "function") // AMD/CMD/Sea.js
{
10 years ago
if (define.amd) // for Require.js
{
var cmModePath = "codemirror/mode/";
var cmAddonPath = "codemirror/addon/";
var codeMirrorModules = [
"jquery", "marked", "prettify",
"katex", "raphael", "underscore", "flowchart", "jqueryflowchart", "sequenceDiagram",
"codemirror/lib/codemirror",
cmModePath + "css/css",
cmModePath + "sass/sass",
cmModePath + "shell/shell",
cmModePath + "sql/sql",
cmModePath + "clike/clike",
cmModePath + "php/php",
cmModePath + "xml/xml",
cmModePath + "markdown/markdown",
cmModePath + "javascript/javascript",
cmModePath + "htmlmixed/htmlmixed",
cmModePath + "gfm/gfm",
cmModePath + "http/http",
cmModePath + "go/go",
cmModePath + "dart/dart",
cmModePath + "coffeescript/coffeescript",
cmModePath + "nginx/nginx",
cmModePath + "python/python",
cmModePath + "perl/perl",
cmModePath + "lua/lua",
cmModePath + "r/r",
cmModePath + "ruby/ruby",
cmModePath + "rst/rst",
cmModePath + "smartymixed/smartymixed",
cmModePath + "vb/vb",
cmModePath + "vbscript/vbscript",
cmModePath + "velocity/velocity",
cmModePath + "xquery/xquery",
cmModePath + "yaml/yaml",
cmModePath + "erlang/erlang",
cmModePath + "jade/jade",
cmAddonPath + "edit/trailingspace",
cmAddonPath + "dialog/dialog",
cmAddonPath + "search/searchcursor",
cmAddonPath + "search/search",
cmAddonPath + "scroll/annotatescrollbar",
cmAddonPath + "search/matchesonscrollbar",
cmAddonPath + "display/placeholder",
cmAddonPath + "edit/closetag",
cmAddonPath + "fold/foldcode",
cmAddonPath + "fold/foldgutter",
cmAddonPath + "fold/indent-fold",
cmAddonPath + "fold/brace-fold",
cmAddonPath + "fold/xml-fold",
cmAddonPath + "fold/markdown-fold",
cmAddonPath + "fold/comment-fold",
cmAddonPath + "mode/overlay",
cmAddonPath + "selection/active-line",
cmAddonPath + "edit/closebrackets",
cmAddonPath + "display/fullscreen",
cmAddonPath + "search/match-highlighter"
];
define(codeMirrorModules, factory);
}
else
{
define(["jquery"], factory); // for Sea.js
}
10 years ago
}
else
{
window.editormd = factory();
}
10 years ago
}(function() {
if (typeof define == "function" && define.amd) {
$ = arguments[0];
marked = arguments[1];
prettify = arguments[2];
katex = arguments[3];
Raphael = arguments[4];
_ = arguments[5];
flowchart = arguments[6];
CodeMirror = arguments[9];
}
10 years ago
"use strict";
10 years ago
var $ = (typeof (jQuery) !== "undefined") ? jQuery : Zepto;
if (typeof ($) === "undefined") {
return ;
}
10 years ago
10 years ago
/**
* editormd
*
* @param {String} id 编辑器的ID
* @param {Object} options 配置选项 Key/Value
* @returns {Object} editormd 返回editormd对象
*/
10 years ago
var editormd = function (id, options) {
return new editormd.fn.init(id, options);
};
10 years ago
editormd.title = editormd.$name = "Editor.md";
10 years ago
editormd.version = "1.4.0";
10 years ago
editormd.homePage = "https://pandao.github.io/editor.md/";
editormd.classPrefix = "editormd-";
10 years ago
10 years ago
editormd.toolbarModes = {
full : [
"undo", "redo", "|",
10 years ago
"bold", "del", "italic", "quote", "ucwords", "uppercase", "lowercase", "|",
10 years ago
"h1", "h2", "h3", "h4", "h5", "h6", "|",
"list-ul", "list-ol", "hr", "|",
10 years ago
"link", "reference-link", "image", "code", "preformatted-text", "code-block", "table", "datetime", "emoji", "html-entities", "pagebreak", "|",
"goto-line", "watch", "preview", "fullscreen", "clear", "search", "|",
10 years ago
"help", "info"
],
simple : [
"undo", "redo", "|",
10 years ago
"bold", "del", "italic", "quote", "uppercase", "lowercase", "|",
10 years ago
"h1", "h2", "h3", "h4", "h5", "h6", "|",
"list-ul", "list-ol", "hr", "|",
"watch", "preview", "fullscreen", "|",
"help", "info"
],
mini : [
"undo", "redo", "|",
"watch", "preview", "|",
"help", "info"
]
};
editormd.defaults = {
10 years ago
mode : "gfm", //gfm or markdown
10 years ago
theme : "default",
value : "", // value for CodeMirror, if mode not gfm/markdown
10 years ago
markdown : "",
10 years ago
appendMarkdown : "", // if in init textarea value not empty, append markdown to textarea
10 years ago
width : "100%",
height : "100%",
10 years ago
path : "./lib/", // Dependents module file directory
10 years ago
pluginPath : "", // If this empty, default use settings.path + "../plugins/"
delay : 300,
autoLoadModules : true, // Automatic load dependent module files
10 years ago
watch : true,
10 years ago
placeholder : "Enjoy Markdown! coding now...",
gotoLine : true,
10 years ago
codeFold : false,
10 years ago
autoHeight : false,
10 years ago
autoCloseTags : true,
10 years ago
searchReplace : true,
10 years ago
readOnly : false,
lineNumbers : true,
10 years ago
matchWordHighlight : true, // options: true, false, "onselected"
styleActiveLine : true, // Highlight the current line
10 years ago
dialogLockScreen : true,
dialogShowMask : true,
dialogDraggable : true,
dialogMaskBgColor : "#fff",
dialogMaskOpacity : 0.1,
10 years ago
fontSize : "13px",
saveHTMLToTextarea : false,
10 years ago
disabledKeyMaps : [],
10 years ago
10 years ago
onload : function() {},
10 years ago
onresize : function() {},
onchange : function() {},
10 years ago
onwatch : null,
onunwatch : null,
onpreviewing : function() {},
onpreviewed : function() {},
onfullscreen : function() {},
onfullscreenExit : function() {},
10 years ago
onscroll : function() {},
onpreviewscroll : function() {},
10 years ago
imageUpload : false,
imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
imageUploadURL : "",
10 years ago
crossDomainUpload : false,
uploadCallbackURL : "",
10 years ago
toc : true, // Table of contents
10 years ago
tocm : false, // Using [TOCM], auto create ToC dropdown menu
tocTitle : "", // for ToC dropdown menu btn
tocDropdown : false,
tocContainer : "",
10 years ago
tocStartLevel : 1, // Said from H1 to create ToC
10 years ago
htmlDecode : false, // Open the HTML tag identification
pageBreak : true, // Enable parse page break [========]
10 years ago
atLink : true, // for @link
emailLink : true, // for email address auto link
10 years ago
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
10 years ago
flowChart : false, // flowChart.js only support IE9+
sequenceDiagram : false, // sequenceDiagram.js only support IE9+
previewCodeHighlight : true,
10 years ago
10 years ago
toolbar : true, // show/hide toolbar
10 years ago
toolbarAutoFixed : true, // on window scroll auto fixed position
10 years ago
toolbarIcons : "full",
10 years ago
toolbarTitles : {},
10 years ago
toolbarHandlers : {
ucwords : function() {
return editormd.toolbarHandlers.ucwords;
},
lowercase : function() {
return editormd.toolbarHandlers.lowercase;
}
},
toolbarCustomIcons : { // using html tag create toolbar icon, unused default <a> tag.
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>"
},
10 years ago
toolbarIconsClass : {
undo : "fa-undo",
redo : "fa-repeat",
bold : "fa-bold",
del : "fa-strikethrough",
italic : "fa-italic",
quote : "fa-quote-left",
10 years ago
uppercase : "fa-font",
10 years ago
h1 : editormd.classPrefix + "bold",
h2 : editormd.classPrefix + "bold",
h3 : editormd.classPrefix + "bold",
h4 : editormd.classPrefix + "bold",
h5 : editormd.classPrefix + "bold",
h6 : editormd.classPrefix + "bold",
"list-ul" : "fa-list-ul",
"list-ol" : "fa-list-ol",
hr : "fa-minus",
link : "fa-link",
10 years ago
"reference-link" : "fa-anchor",
10 years ago
image : "fa-picture-o",
10 years ago
code : "fa-code",
10 years ago
"preformatted-text" : "fa-file-code-o",
10 years ago
"code-block" : "fa-file-code-o",
10 years ago
table : "fa-table",
10 years ago
datetime : "fa-clock-o",
10 years ago
emoji : "fa-smile-o",
10 years ago
"html-entities" : "fa-copyright",
pagebreak : "fa-newspaper-o",
"goto-line" : "fa-terminal", // fa-crosshairs
10 years ago
watch : "fa-eye-slash",
unwatch : "fa-eye",
10 years ago
preview : "fa-desktop",
search : "fa-search",
10 years ago
fullscreen : "fa-arrows-alt",
10 years ago
clear : "fa-eraser",
10 years ago
help : "fa-question-circle",
10 years ago
info : "fa-info-circle"
10 years ago
},
10 years ago
toolbarIconTexts : {},
10 years ago
10 years ago
lang : {
10 years ago
name : "zh-cn",
10 years ago
description : "开源在线Markdown编辑器<br/>Open source online Markdown editor.",
tocTitle : "目录",
10 years ago
toolbar : {
undo : "撤销(Ctrl+Z)",
redo : "重做(Ctrl+Y)",
10 years ago
bold : "粗体",
del : "删除线",
italic : "斜体",
quote : "引用",
10 years ago
ucwords : "将每个单词首字母转成大写",
uppercase : "将所选转换成大写",
lowercase : "将所选转换成小写",
10 years ago
h1 : "标题1",
h2 : "标题2",
h3 : "标题3",
h4 : "标题4",
h5 : "标题5",
h6 : "标题6",
"list-ul" : "无序列表",
"list-ol" : "有序列表",
hr : "横线",
link : "链接",
10 years ago
"reference-link" : "引用链接",
10 years ago
image : "添加图片",
10 years ago
code : "行内代码",
10 years ago
"preformatted-text" : "预格式文本 / 代码块(缩进风格)",
10 years ago
"code-block" : "代码块(多语言风格)",
10 years ago
table : "添加表格",
10 years ago
datetime : "日期时间",
10 years ago
emoji : "Emoji表情",
10 years ago
"html-entities" : "HTML实体字符",
pagebreak : "插入分页符",
"goto-line" : "跳转到行",
10 years ago
watch : "关闭实时预览",
unwatch : "开启实时预览",
10 years ago
preview : "全窗口预览HTML(按 Shift + ESC还原)",
10 years ago
fullscreen : "全屏(按ESC还原)",
clear : "清空",
10 years ago
search : "搜索",
10 years ago
help : "使用帮助",
10 years ago
info : "关于" + editormd.title
10 years ago
},
buttons : {
enter : "确定",
10 years ago
cancel : "取消",
close : "关闭"
10 years ago
},
dialog : {
link : {
title : "添加链接",
url : "链接地址",
urlTitle : "链接标题",
10 years ago
urlEmpty : "错误:请填写链接地址。"
10 years ago
},
10 years ago
referenceLink : {
title : "添加引用链接",
name : "引用名称",
10 years ago
url : "链接地址",
10 years ago
urlId : "链接ID",
10 years ago
urlTitle : "链接标题",
10 years ago
nameEmpty: "错误:引用链接的名称不能为空。",
idEmpty : "错误:请填写引用链接的ID。",
urlEmpty : "错误:请填写引用链接的URL地址。"
10 years ago
},
image : {
title : "添加图片",
url : "图片地址",
link : "图片链接",
alt : "图片描述",
uploadButton : "本地上传",
imageURLEmpty : "错误:图片地址不能为空。",
uploadFileEmpty : "错误:上传的图片不能为空。",
formatNotAllowed : "错误:只允许上传图片文件,允许上传的图片文件格式有:"
},
10 years ago
preformattedText : {
10 years ago
title : "添加预格式文本或代码块",
10 years ago
emptyAlert : "错误:请填写预格式文本或代码的内容。"
10 years ago
},
codeBlock : {
title : "添加代码块",
selectLabel : "代码语言:",
selectDefaultText : "请选择代码语言",
otherLanguage : "其他语言",
unselectedLanguageAlert : "错误:请选择代码所属的语言类型。",
codeEmptyAlert : "错误:请填写代码内容。"
10 years ago
},
htmlEntities : {
title : "HTML 实体字符"
},
help : {
title : "使用帮助"
10 years ago
}
10 years ago
}
}
};
editormd.classNames = {
10 years ago
tex : editormd.classPrefix + "tex"
};
10 years ago
10 years ago
editormd.dialogZindex = 99999;
editormd.$katex = null;
10 years ago
editormd.$marked = null;
editormd.$CodeMirror = null;
editormd.$prettyPrint = null;
10 years ago
var timer, flowchartTimer;
10 years ago
editormd.prototype = editormd.fn = {
state : {
10 years ago
watching : false,
loaded : false,
10 years ago
preview : false,
fullscreen : false
},
/**
* 构造函数/实例初始化
10 years ago
* Constructor / instance initialization
*
10 years ago
* @param {String} id 编辑器的ID
* @param {Object} [options={}] 配置选项 Key/Value
* @returns {editormd} 返回editormd的实例对象
*/
init : function (id, options) {
10 years ago
options = options || {};
10 years ago
10 years ago
if (typeof id === "object")
{
options = id;
}
10 years ago
var _this = this;
10 years ago
var classPrefix = this.classPrefix = editormd.classPrefix;
10 years ago
var settings = this.settings = $.extend(true, editormd.defaults, options);
10 years ago
10 years ago
id = (typeof id === "object") ? settings.id : id;
var editor = this.editor = $("#" + id);
10 years ago
this.id = id;
this.lang = settings.lang;
var classNames = this.classNames = {
10 years ago
textarea : {
10 years ago
html : classPrefix + "html-textarea",
markdown : classPrefix + "markdown-textarea"
10 years ago
}
};
10 years ago
settings.pluginPath = (settings.pluginPath === "") ? settings.path + "../plugins/" : settings.pluginPath;
10 years ago
10 years ago
this.state.watching = (settings.watch) ? true : false;
10 years ago
if (!editor.hasClass("editormd")) {
editor.addClass("editormd");
}
10 years ago
editor.css({
width : (typeof settings.width === "number") ? settings.width + "px" : settings.width,
height : (typeof settings.height === "number") ? settings.height + "px" : settings.height
});
10 years ago
if (settings.autoHeight)
{
editor.css("height", "auto");
}
10 years ago
var markdownTextarea = this.markdownTextarea = editor.children("textarea");
10 years ago
10 years ago
if (markdownTextarea.length < 1)
{
editor.append("<textarea></textarea>");
markdownTextarea = this.markdownTextarea = editor.children("textarea");
}
10 years ago
10 years ago
markdownTextarea.addClass(classNames.textarea.markdown).attr("name", id + "-markdown-doc").attr("placeholder", settings.placeholder);
10 years ago
var appendElements = [
10 years ago
(!settings.readOnly) ? "<a href=\"javascript:;\" class=\"fa fa-close " + classPrefix + "preview-close-btn\"></a>" : "",
( (settings.saveHTMLToTextarea) ? "<textarea class=\"" + classNames.textarea.html + "\" name=\"" + id + "-html-code\"></textarea>" : "" ),
"<div class=\"" + classPrefix + "preview\"><div class=\"markdown-body " + classPrefix + "preview-container\"></div></div>",
10 years ago
"<div class=\"" + classPrefix + "container-mask\" style=\"display:block;\"></div>",
10 years ago
"<div class=\"" + classPrefix + "mask\"></div>"
10 years ago
].join("\n");
10 years ago
editor.append(appendElements).addClass(classPrefix + "vertical");
10 years ago
this.mask = editor.children("." + classPrefix + "mask");
this.containerMask = editor.children("." + classPrefix + "container-mask");
10 years ago
if (settings.markdown !== "")
{
10 years ago
markdownTextarea.val(settings.markdown);
}
10 years ago
if (settings.appendMarkdown !== "")
{
markdownTextarea.val(markdownTextarea.val() + settings.appendMarkdown);
}
this.htmlTextarea = editor.children("." + classNames.textarea.html);
this.preview = editor.children("." + classPrefix + "preview");
this.previewContainer = this.preview.children("." + classPrefix + "preview-container");
10 years ago
10 years ago
if (typeof define === "function" && define.amd)
10 years ago
{
10 years ago
if (typeof katex !== "undefined")
{
editormd.$katex = katex;
}
10 years ago
if (settings.searchReplace && !settings.readOnly)
10 years ago
{
editormd.loadCSS(settings.path + "codemirror/addon/dialog/dialog");
editormd.loadCSS(settings.path + "codemirror/addon/search/matchesonscrollbar");
}
}
10 years ago
if ((typeof define === "function" && define.amd) || !settings.autoLoadModules)
10 years ago
{
10 years ago
if (typeof CodeMirror !== "undefined") {
editormd.$CodeMirror = CodeMirror;
}
10 years ago
10 years ago
if (typeof marked !== "undefined") {
editormd.$marked = marked;
}
this.setCodeMirror().setToolbar().loadedDisplay();
10 years ago
}
else
10 years ago
{
10 years ago
this.loadQueues();
10 years ago
}
return this;
},
/**
* 所需组件加载队列
10 years ago
* Required components loading queue
*
10 years ago
* @returns {editormd} 返回editormd的实例对象
*/
loadQueues : function() {
var _this = this;
var settings = this.settings;
var loadPath = settings.path;
var loadFlowChartOrSequenceDiagram = function() {
10 years ago
if (editormd.isIE8)
{
10 years ago
_this.loadedDisplay();
10 years ago
return ;
}
10 years ago
if (settings.flowChart || settings.sequenceDiagram)
{
editormd.loadScript(loadPath + "raphael.min", function() {
editormd.loadScript(loadPath + "underscore.min", function() {
if (!settings.flowChart && settings.sequenceDiagram)
{
editormd.loadScript(loadPath + "sequence-diagram.min", function() {
10 years ago
_this.loadedDisplay();
10 years ago
});
}
else if (settings.flowChart && !settings.sequenceDiagram)
{
editormd.loadScript(loadPath + "flowchart.min", function() {
editormd.loadScript(loadPath + "jquery.flowchart.min", function() {
10 years ago
_this.loadedDisplay();
10 years ago
});
});
}
else if (settings.flowChart && settings.sequenceDiagram)
{
editormd.loadScript(loadPath + "flowchart.min", function() {
editormd.loadScript(loadPath + "jquery.flowchart.min", function() {
editormd.loadScript(loadPath + "sequence-diagram.min", function() {
10 years ago
_this.loadedDisplay();
10 years ago
});
});
});
}
});
});
}
else
{
10 years ago
_this.loadedDisplay();
10 years ago
}
};
10 years ago
editormd.loadCSS(loadPath + "codemirror/codemirror.min");
10 years ago
if (settings.searchReplace && !settings.readOnly)
10 years ago
{
editormd.loadCSS(loadPath + "codemirror/addon/dialog/dialog");
editormd.loadCSS(loadPath + "codemirror/addon/search/matchesonscrollbar");
}
if (settings.codeFold)
{
editormd.loadCSS(loadPath + "codemirror/addon/fold/foldgutter");
}
10 years ago
editormd.loadScript(loadPath + "codemirror/codemirror.min", function() {
editormd.$CodeMirror = CodeMirror;
editormd.loadScript(loadPath + "codemirror/modes.min", function() {
editormd.loadScript(loadPath + "codemirror/addons.min", function() {
10 years ago
_this.setCodeMirror();
if (settings.mode !== "gfm" && settings.mode !== "markdown")
{
_this.loadedDisplay();
return false;
}
10 years ago
_this.setToolbar();
10 years ago
editormd.loadScript(loadPath + "marked.min", function() {
editormd.$marked = marked;
10 years ago
if (settings.previewCodeHighlight)
{
editormd.loadScript(loadPath + "prettify.min", function() {
loadFlowChartOrSequenceDiagram();
});
}
else
10 years ago
{
10 years ago
loadFlowChartOrSequenceDiagram();
}
});
});
10 years ago
});
10 years ago
});
return this;
},
10 years ago
/**
* 设置CodeMirror的主题
* Setting CodeMirror theme
*
* @returns {editormd} 返回editormd的实例对象
*/
setTheme : function(theme) {
var settings = this.settings;
settings.theme = theme;
if (theme !== "default")
{
editormd.loadCSS(settings.path + "codemirror/theme/" + settings.theme);
}
this.cm.setOption("theme", theme);
return this;
},
10 years ago
/**
* 配置和初始化CodeMirror组件
10 years ago
* CodeMirror initialization
*
10 years ago
* @returns {editormd} 返回editormd的实例对象
*/
setCodeMirror : function() {
var settings = this.settings;
var editor = this.editor;
10 years ago
if (settings.theme !== "default")
{
editormd.loadCSS(settings.path + "codemirror/theme/" + settings.theme);
}
10 years ago
var codeMirrorConfig = {
10 years ago
mode : settings.mode,
10 years ago
theme : settings.theme,
10 years ago
tabSize : 4,
dragDrop : false,
autofocus : true,
10 years ago
autoCloseTags : settings.autoCloseTags,
10 years ago
readOnly : (settings.readOnly) ? "nocursor" : false,
indentUnit : 4,
lineNumbers : settings.lineNumbers,
lineWrapping : true,
10 years ago
extraKeys : {
"Ctrl-Q": function(cm) {
cm.foldCode(cm.getCursor());
}
},
10 years ago
foldGutter : settings.codeFold,
gutters : ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
10 years ago
matchBrackets : true,
indentWithTabs : true,
styleActiveLine : settings.styleActiveLine,
styleSelectedText : true,
autoCloseBrackets : true,
showTrailingSpace : true,
10 years ago
highlightSelectionMatches : ( (!settings.matchWordHighlight) ? false : { showToken: (settings.matchWordHighlight === "onselected") ? false : /\w/ } )
10 years ago
};
10 years ago
this.codeEditor = this.cm = editormd.$CodeMirror.fromTextArea(this.markdownTextarea[0], codeMirrorConfig);
this.codeMirror = this.cmElement = editor.children(".CodeMirror");
10 years ago
10 years ago
if (settings.value !== "")
{
this.cm.setValue(settings.value);
}
10 years ago
this.codeMirror.css({
fontSize : settings.fontSize,
10 years ago
width : (!settings.watch) ? "100%" : "50%"
});
10 years ago
if (settings.autoHeight)
{
this.codeMirror.css("height", "auto");
this.cm.setOption("viewportMargin", Infinity);
}
10 years ago
return this;
},
10 years ago
/**
* 获取CodeMirror的配置选项
* Get CodeMirror setting options
*
* @returns {Mixed} return CodeMirror setting option value
*/
getCodeMirrorOption : function(key) {
return this.cm.getOption(key);
},
/**
* 配置和重配置CodeMirror的选项
* CodeMirror setting options / resettings
*
* @returns {editormd} 返回editormd的实例对象
*/
setCodeMirrorOption : function(key, value) {
this.cm.setOption(key, value);
return this;
},
10 years ago
/**
* 添加 CodeMirror 键盘快捷键
* Add CodeMirror keyboard shortcuts key map
*
* @returns {editormd} 返回editormd的实例对象
*/
10 years ago
addKeyMap : function(map, bottom) {
this.cm.addKeyMap(map, bottom);
return this;
},
10 years ago
/**
* 移除 CodeMirror 键盘快捷键
* Remove CodeMirror keyboard shortcuts key map
*
* @returns {editormd} 返回editormd的实例对象
*/
10 years ago
removeKeyMap : function(map) {
this.cm.removeKeyMap(map);
return this;
},
10 years ago
/**
* 跳转到指定的行
* Goto CodeMirror line
*
* @param {String|Intiger} line line number or "first"|"last"
* @returns {editormd} 返回editormd的实例对象
*/
gotoLine : function (line) {
var settings = this.settings;
if (!settings.gotoLine)
{
return this;
}
var cm = this.cm;
var editor = this.editor;
var count = cm.lineCount();
var preview = this.preview;
if (typeof line === "string")
{
if(line === "last")
{
line = count;
}
if (line === "first")
{
line = 1;
}
}
if (typeof line !== "number")
{
alert("Error: The line number must be an integer.");
return this;
}
line = parseInt(line) - 1;
if (line > count)
{
alert("Error: The line number range 1-" + count);
return this;
}
cm.setCursor( {line : line, ch : 0} );
var scrollInfo = cm.getScrollInfo();
var clientHeight = scrollInfo.clientHeight;
var coords = cm.charCoords({line : line, ch : 0}, "local");
cm.scrollTo(null, (coords.top + coords.bottom - clientHeight) / 2);
if (settings.watch)
{
var cmScroll = this.codeMirror.find(".CodeMirror-scroll")[0];
var height = $(cmScroll).height();
var scrollTop = cmScroll.scrollTop;
var percent = (scrollTop / cmScroll.scrollHeight);
if (scrollTop === 0)
{
preview.scrollTop(0);
}
10 years ago
else if (scrollTop + height >= cmScroll.scrollHeight - 16)
10 years ago
{
preview.scrollTop(preview[0].scrollHeight);
}
else
{
preview.scrollTop(preview[0].scrollHeight * percent);
}
}
cm.focus();
return this;
},
10 years ago
/**
* 扩展当前实例对象可同时设置多个或者只设置一个
* Extend editormd instance object, can mutil setting.
*
* @returns {editormd} this(editormd instance object.)
*/
10 years ago
extends : function() {
10 years ago
if (typeof arguments[1] !== "undefined")
{
10 years ago
if (typeof arguments[1] === "function")
10 years ago
{
arguments[1] = $.proxy(arguments[1], this);
}
this[arguments[0]] = arguments[1];
}
if (typeof arguments[0] === "object" && typeof arguments[0].length === "undefined")
{
$.extend(true, this, arguments[0]);
}
return this;
},
/**
* 设置或扩展当前实例对象单个设置
* Extend editormd instance object, one by one
*
* @param {String|Object} key option key
* @param {String|Object} value option value
* @returns {editormd} this(editormd instance object.)
*/
set : function (key, value) {
10 years ago
if (typeof value !== "undefined" && typeof value === "function")
10 years ago
{
value = $.proxy(value, this);
}
this[key] = value;
return this;
},
/**
* 重新配置
* Resetting editor options
*
* @param {String|Object} key option key
* @param {String|Object} value option value
* @returns {editormd} this(editormd instance object.)
*/
config : function(key, value) {
var settings = this.settings;
10 years ago
if (typeof key === "object")
10 years ago
{
settings = $.extend(true, settings, key);
}
10 years ago
if (typeof key === "string")
10 years ago
{
settings[key] = value;
}
this.settings = settings;
this.recreate();
return this;
},
/**
* 注册事件处理方法
* Bind editor event handle
*
* @param {String} eventType event type
* @param {Function} callback 回调函数
* @returns {editormd} this(editormd instance object.)
*/
on : function(eventType, callback) {
var settings = this.settings;
if (typeof settings["on" + eventType] !== "undefined")
{
settings["on" + eventType] = $.proxy(callback, this);
}
return this;
},
/**
* 解除事件处理方法
* Unbind editor event handle
*
* @param {String} eventType event type
* @returns {editormd} this(editormd instance object.)
*/
off : function(eventType) {
var settings = this.settings;
if (typeof settings["on" + eventType] !== "undefined")
{
settings["on" + eventType] = function(){};
}
return this;
},
10 years ago
/**
* 显示工具栏
10 years ago
* Display toolbar
*
* @param {Function} [callback=function(){}] 回调函数
10 years ago
* @returns {editormd} 返回editormd的实例对象
*/
10 years ago
showToolbar : function(callback) {
10 years ago
var settings = this.settings;
10 years ago
10 years ago
if(settings.readOnly) {
return this;
}
10 years ago
10 years ago
if (settings.toolbar && (this.toolbar.length < 1 || this.toolbar.find("." + this.classPrefix + "menu").html() === "") )
{
this.setToolbar();
}
10 years ago
settings.toolbar = true;
10 years ago
10 years ago
this.toolbar.show();
this.resize();
10 years ago
$.proxy(callback || function(){}, this)();
10 years ago
return this;
},
/**
* 隐藏工具栏
10 years ago
* Hide toolbar
*
* @param {Function} [callback=function(){}] 回调函数
* @returns {editormd} this(editormd instance object.)
10 years ago
*/
10 years ago
hideToolbar : function(callback) {
var settings = this.settings;
10 years ago
10 years ago
settings.toolbar = false;
10 years ago
this.toolbar.hide();
this.resize();
10 years ago
$.proxy(callback || function(){}, this)();
10 years ago
return this;
},
10 years ago
/**
* 页面滚动时工具栏的固定定位
* Set toolbar in window scroll auto fixed position
*
* @returns {editormd} 返回editormd的实例对象
*/
setToolbarAutoFixed : function(fixed) {
var state = this.state;
var editor = this.editor;
var toolbar = this.toolbar;
var settings = this.settings;
if (typeof fixed !== "undefined")
{
settings.toolbarAutoFixed = fixed;
}
var autoFixedHandle = function(){
10 years ago
var $window = $(window);
var top = $window.scrollTop();
10 years ago
if (!settings.toolbarAutoFixed)
{
return false;
}
if (top - editor.offset().top > 10 && top < editor.height())
10 years ago
{
toolbar.css({
position : "fixed",
width : editor.width() + "px",
10 years ago
left : ($window.width() - editor.width()) / 2 + "px"
10 years ago
});
}
else
{
toolbar.css({
position : "absolute",
width : "100%",
left : 0
});
}
};
if (!state.fullscreen && !state.preview && settings.toolbar && settings.toolbarAutoFixed)
{
$(window).bind("scroll", autoFixedHandle);
}
return this;
},
10 years ago
/**
* 配置和初始化工具栏
10 years ago
* Set toolbar and Initialization
*
10 years ago
* @returns {editormd} 返回editormd的实例对象
*/
setToolbar : function() {
10 years ago
var settings = this.settings;
10 years ago
if(settings.readOnly) {
return this;
}
10 years ago
var editor = this.editor;
var preview = this.preview;
var classPrefix = this.classPrefix;
10 years ago
var toolbar = this.toolbar = editor.children("." + classPrefix + "toolbar");
10 years ago
10 years ago
if (settings.toolbar && toolbar.length < 1)
{
10 years ago
var toolbarHTML = "<div class=\"" + classPrefix + "toolbar\"><div class=\"" + classPrefix + "toolbar-container\"><ul class=\"" + classPrefix + "menu\"></ul></div></div>";
editor.append(toolbarHTML);
toolbar = this.toolbar = editor.children("." + classPrefix + "toolbar");
10 years ago
}
10 years ago
if (!settings.toolbar)
{
10 years ago
toolbar.hide();
10 years ago
10 years ago
return this;
10 years ago
}
10 years ago
10 years ago
toolbar.show();
var icons = (typeof settings.toolbarIcons === "function") ? settings.toolbarIcons()
: ((typeof settings.toolbarIcons === "string") ? editormd.toolbarModes[settings.toolbarIcons] : settings.toolbarIcons);
10 years ago
10 years ago
var toolbarMenu = toolbar.find("." + this.classPrefix + "menu"), menu = "";
10 years ago
10 years ago
for (var i = 0, len = icons.length; i < len; i++)
10 years ago
{
10 years ago
var name = icons[i];
10 years ago
if (name !== "|")
{
var isHeader = (/h(\d)/.test(name));
10 years ago
var index = name;
if (name === "watch" && !settings.watch) {
index = "unwatch";
}
10 years ago
10 years ago
var title = settings.lang.toolbar[index];
var iconTexts = settings.toolbarIconTexts[index];
var iconClass = settings.toolbarIconsClass[index];
title = (typeof title === "undefined") ? "" : title;
iconTexts = (typeof iconTexts === "undefined") ? "" : iconTexts;
iconClass = (typeof iconClass === "undefined") ? "" : iconClass;
10 years ago
menu += "<li>";
10 years ago
if (typeof settings.toolbarCustomIcons[name] !== "undefined" && typeof settings.toolbarCustomIcons[name] !== "function")
10 years ago
{
menu += settings.toolbarCustomIcons[name];
}
else
{
menu += "<a href=\"javascript:;\" title=\"" + title + "\" unselectable=\"on\">" +
10 years ago
"<i class=\"fa " + iconClass + "\" name=\""+name+"\" unselectable=\"on\">"+((isHeader) ? name.toUpperCase() : ( (iconClass === "") ? iconTexts : "") ) + "</i>" +
10 years ago
"</a>";
}
menu += "</li>";
10 years ago
}
else
{
10 years ago
menu += "<li class=\"divider\" unselectable=\"on\">|</li>";
10 years ago
}
}
10 years ago
toolbarMenu.html(menu);
10 years ago
toolbarMenu.find("[title=\"Lowercase\"]").attr("title", settings.lang.toolbar.lowercase);
toolbarMenu.find("[title=\"ucwords\"]").attr("title", settings.lang.toolbar.ucwords);
10 years ago
this.setToolbarHandler();
10 years ago
this.setToolbarAutoFixed();
10 years ago
return this;
10 years ago
},
/**
* 工具栏图标事件处理对象序列
10 years ago
* Get toolbar icons event handlers
*
10 years ago
* @param {Object} cm CodeMirror的实例对象
10 years ago
* @param {String} name 要获取的事件处理器名称
* @returns {Object} 返回处理对象序列
*/
10 years ago
dialogLockScreen : function() {
$.proxy(editormd.dialogLockScreen, this)();
return this;
},
dialogShowMask : function(dialog) {
$.proxy(editormd.dialogShowMask, this)(dialog);
return this;
},
getToolbarHandles : function(name) {
var toolbarHandlers = this.toolbarHandlers = editormd.toolbarHandlers;
return (name && typeof toolbarIconHandlers[name] !== "undefined") ? toolbarHandlers[name] : toolbarHandlers;
},
/**
* 工具栏图标事件处理器
* Bind toolbar icons event handle
*
* @returns {editormd} 返回editormd的实例对象
*/
10 years ago
10 years ago
setToolbarHandler : function() {
var _this = this;
var settings = this.settings;
10 years ago
10 years ago
if (!settings.toolbar || settings.readOnly) {
10 years ago
return this;
10 years ago
}
10 years ago
10 years ago
var toolbar = this.toolbar;
10 years ago
var cm = this.cm;
var classPrefix = this.classPrefix;
10 years ago
var toolbarIcons = this.toolbarIcons = toolbar.find("." + classPrefix + "menu > li > a");
10 years ago
var toolbarIconHandlers = this.getToolbarHandles();
10 years ago
10 years ago
toolbarIcons.bind(editormd.mouseOrTouch("click", "touchend"), function(event) {
10 years ago
10 years ago
var icon = $(this).children(".fa");
var name = icon.attr("name");
10 years ago
var cursor = cm.getCursor();
var selection = cm.getSelection();
10 years ago
10 years ago
if (name === "") {
return ;
}
_this.activeIcon = icon;
10 years ago
10 years ago
if (typeof toolbarIconHandlers[name] !== "undefined")
{
10 years ago
$.proxy(toolbarIconHandlers[name], _this)(cm);
10 years ago
}
else
{
if (typeof settings.toolbarHandlers[name] !== "undefined")
{
10 years ago
$.proxy(settings.toolbarHandlers[name], _this)(cm, icon, cursor, selection);
10 years ago
}
10 years ago
}
10 years ago
if (name !== "link" && name !== "reference-link" && name !== "image" && name !== "code-block" &&
name !== "preformatted-text" && name !== "watch" && name !== "preview" && name !== "search" && name !== "fullscreen" && name !== "info")
10 years ago
{
10 years ago
cm.focus();
10 years ago
}
10 years ago
10 years ago
return false;
10 years ago
10 years ago
});
10 years ago
10 years ago
return this;
},
/**
* 动态创建对话框
* Creating custom dialogs
*
* @param {Object} options 配置项键值对 Key/Value
* @returns {dialog} 返回创建的dialog的jQuery实例对象
*/
createDialog : function(options) {
return $.proxy(editormd.createDialog, this)(options);
10 years ago
},
/**
* 创建关于Editor.md的对话框
10 years ago
* Create about Editor.md dialog
*
10 years ago
* @returns {editormd} 返回editormd的实例对象
*/
createInfoDialog : function() {
var _this = this;
var editor = this.editor;
var classPrefix = this.classPrefix;
var infoDialogHTML = [
10 years ago
"<div class=\"" + classPrefix + "dialog " + classPrefix + "dialog-info\" style=\"\">",
10 years ago
"<div class=\"" + classPrefix + "dialog-container\">",
"<h1><i class=\"editormd-logo editormd-logo-lg editormd-logo-color\"></i> " + editormd.title + "<small>v" + editormd.version + "</small></h1>",
"<p>" + this.lang.description + "</p>",
10 years ago
"<p style=\"margin: 10px 0 20px 0;\"><a href=\"" + editormd.homePage + "\" target=\"_blank\">" + editormd.homePage + " <i class=\"fa fa-external-link\"></i></a></p>",
"<p style=\"font-size: 0.85em;\">Copyright &copy; 2015 <a href=\"https://github.com/pandao\" target=\"_blank\" class=\"hover-link\">Pandao</a>, The <a href=\"https://github.com/pandao/editor.md/blob/master/LICENSE\" target=\"_blank\" class=\"hover-link\">MIT</a> License.</p>",
10 years ago
"</div>",
"<a href=\"javascript:;\" class=\"fa fa-close " + classPrefix + "dialog-close\"></a>",
"</div>"
].join("\n");
10 years ago
10 years ago
editor.append(infoDialogHTML);
10 years ago
var infoDialog = this.infoDialog = editor.children("." + classPrefix + "dialog-info");
10 years ago
infoDialog.find("." + classPrefix + "dialog-close").bind(editormd.mouseOrTouch("click", "touchend"), function() {
_this.hideInfoDialog();
10 years ago
});
10 years ago
10 years ago
infoDialog.css("border", (editormd.isIE8) ? "1px solid #ddd" : "").css("z-index", editormd.dialogZindex).show();
10 years ago
this.infoDialogPosition();
return this;
},
/**
* 关于Editor.md对话居中定位
10 years ago
* Editor.md dialog position handle
*
10 years ago
* @returns {editormd} 返回editormd的实例对象
*/
infoDialogPosition : function() {
var infoDialog = this.infoDialog;
var _infoDialogPosition = function() {
infoDialog.css({
top : ($(window).height() - infoDialog.height()) / 2 + "px",
left : ($(window).width() - infoDialog.width()) / 2 + "px"
});
};
10 years ago
10 years ago
_infoDialogPosition();
$(window).resize(_infoDialogPosition);
10 years ago
return this;
},
/**
* 显示关于Editor.md
10 years ago
* Display about Editor.md dialog
*
10 years ago
* @returns {editormd} 返回editormd的实例对象
*/
showInfoDialog : function() {
$("html,body").css("overflow-x", "hidden");
10 years ago
var _this = this;
var editor = this.editor;
10 years ago
var settings = this.settings;
var infoDialog = this.infoDialog = editor.children("." + this.classPrefix + "dialog-info");
10 years ago
if (infoDialog.length < 1)
{
this.createInfoDialog();
}
10 years ago
this.lockScreen(true);
this.mask.css({
opacity : settings.dialogMaskOpacity,
backgroundColor : settings.dialogMaskBgColor
}).show();
10 years ago
10 years ago
infoDialog.css("z-index", editormd.dialogZindex).show();
10 years ago
10 years ago
this.infoDialogPosition();
10 years ago
return this;
},
/**
* 隐藏关于Editor.md
10 years ago
* Hide about Editor.md dialog
*
10 years ago
* @returns {editormd} 返回editormd的实例对象
*/
10 years ago
hideInfoDialog : function() {
$("html,body").css("overflow-x", "");
10 years ago
this.infoDialog.hide();
10 years ago
this.mask.hide();
this.lockScreen(false);
10 years ago
return this;
},
/**
10 years ago
* 锁屏
* lock screen
*
* @param {Boolean} lock Boolean 布尔值是否锁屏
* @returns {editormd} 返回editormd的实例对象
10 years ago
*/
10 years ago
lockScreen : function(lock) {
editormd.lockScreen(lock);
10 years ago
return this;
},
10 years ago
/**
* 编辑器界面重建用于动态语言包或模块加载等
10 years ago
* Recreate editor
*
10 years ago
* @returns {editormd} 返回editormd的实例对象
*/
10 years ago
recreate : function() {
10 years ago
var _this = this;
var editor = this.editor;
var settings = this.settings;
10 years ago
this.codeMirror.remove();
this.setCodeMirror();
10 years ago
if (!settings.readOnly)
10 years ago
{
if (editor.find(".editormd-dialog").length > 0) {
editor.find(".editormd-dialog").remove();
}
10 years ago
if (settings.toolbar)
{
this.getToolbarHandles();
this.setToolbar();
}
10 years ago
}
10 years ago
this.loadedDisplay(true);
10 years ago
return this;
},
/**
* 高亮预览HTML的pre代码部分
10 years ago
* highlight of preview codes
*
* @returns {editormd} 返回editormd的实例对象
*/
previewCodeHighlight : function() {
var settings = this.settings;
var previewContainer = this.previewContainer;
if (settings.previewCodeHighlight)
{
previewContainer.find("pre").addClass("prettyprint linenums");
10 years ago
if (typeof prettyPrint !== "undefined")
{
prettyPrint();
}
}
return this;
},
/**
* 解析TeX(KaTeX)科学公式
10 years ago
* TeX(KaTeX) Renderer
*
* @returns {editormd} 返回editormd的实例对象
*/
katexRender : function() {
10 years ago
if (timer === null)
{
return this;
}
10 years ago
this.previewContainer.find("." + editormd.classNames.tex).each(function(){
var tex = $(this);
editormd.$katex.render(tex.html(), tex[0]);
});
return this;
},
/**
* 解析和渲染流程图及时序图
10 years ago
* FlowChart and SequenceDiagram Renderer
*
* @returns {editormd} 返回editormd的实例对象
*/
flowChartAndSequenceDiagramRender : function() {
var settings = this.settings;
var previewContainer = this.previewContainer;
10 years ago
if (editormd.isIE8) {
return this;
}
if (settings.flowChart) {
10 years ago
if (flowchartTimer === null) {
return this;
}
previewContainer.find(".flowchart").flowChart();
}
if (settings.sequenceDiagram) {
previewContainer.find(".sequence-diagram").sequenceDiagram({theme: "simple"});
}
return this;
},
10 years ago
/**
* 注册键盘快捷键处理
* Register CodeMirror keyMaps (keyboard shortcuts).
*
* @param {Object} keyMap KeyMap key/value {"(Ctrl/Shift/Alt)-Key" : function(){}}
* @returns {editormd} return this
*/
registerKeyMaps : function(keyMap) {
10 years ago
var _this = this;
var cm = this.cm;
var settings = this.settings;
var toolbarHandlers = editormd.toolbarHandlers;
var disabledKeyMaps = settings.disabledKeyMaps;
keyMap = keyMap || null;
10 years ago
if (keyMap)
{
for (var i in keyMap)
{
10 years ago
if ($.inArray(i, disabledKeyMaps) < 0)
10 years ago
{
var map = {};
map[i] = keyMap[i];
cm.addKeyMap(keyMap);
}
}
}
else
{
10 years ago
for (var k in editormd.keyMaps)
10 years ago
{
10 years ago
var _keyMap = editormd.keyMaps[k];
var handle = (typeof _keyMap === "string") ? $.proxy(toolbarHandlers[_keyMap], _this) : $.proxy(_keyMap, _this);
10 years ago
10 years ago
if ($.inArray(k, ["F9", "F10", "F11"]) < 0 && $.inArray(k, disabledKeyMaps) < 0)
10 years ago
{
10 years ago
var _map = {};
_map[k] = handle;
10 years ago
10 years ago
cm.addKeyMap(_map);
10 years ago
}
}
$(window).keydown(function(event) {
var keymaps = {
"120" : "F9",
"121" : "F10",
"122" : "F11"
};
10 years ago
if ( $.inArray(keymaps[event.keyCode], disabledKeyMaps) < 0 )
10 years ago
{
switch (event.keyCode)
{
case 120:
10 years ago
$.proxy(toolbarHandlers["watch"], _this)();
10 years ago
return false;
break;
case 121:
10 years ago
$.proxy(toolbarHandlers["preview"], _this)();
10 years ago
return false;
break;
case 122:
10 years ago
$.proxy(toolbarHandlers["fullscreen"], _this)();
return false;
10 years ago
break;
default:
break;
}
}
});
}
return this;
},
10 years ago
bindScrollEvent : function() {
10 years ago
var _this = this;
var preview = this.preview;
var settings = this.settings;
var codeMirror = this.codeMirror;
var mouseOrTouch = editormd.mouseOrTouch;
10 years ago
var cmBindScroll = function() {
10 years ago
codeMirror.find(".CodeMirror-scroll").bind(mouseOrTouch("scroll", "touchmove"), function(event) {
10 years ago
var height = $(this).height();
10 years ago
var scrollTop = $(this).scrollTop();
var percent = (scrollTop / $(this)[0].scrollHeight);
if (scrollTop === 0)
{
preview.scrollTop(0);
}
10 years ago
else if (scrollTop + height >= $(this)[0].scrollHeight - 16)
10 years ago
{
preview.scrollTop(preview[0].scrollHeight);
}
else
{
preview.scrollTop(preview[0].scrollHeight * percent);
}
10 years ago
10 years ago
$.proxy(settings.onscroll, _this)(event);
10 years ago
});
};
10 years ago
var cmUnbindScroll = function() {
10 years ago
codeMirror.find(".CodeMirror-scroll").unbind(mouseOrTouch("scroll", "touchmove"));
};
var previewBindScroll = function() {
10 years ago
preview.bind(mouseOrTouch("scroll", "touchmove"), function(event) {
10 years ago
var height = $(this).height();
10 years ago
var scrollTop = $(this).scrollTop();
10 years ago
var percent = (scrollTop / $(this)[0].scrollHeight);
var codeView = codeMirror.find(".CodeMirror-scroll");
if(scrollTop === 0)
{
codeView.scrollTop(0);
10 years ago
}
10 years ago
else if (scrollTop + height >= $(this)[0].scrollHeight)
10 years ago
{
10 years ago
codeView.scrollTop(codeView[0].scrollHeight);
10 years ago
}
10 years ago
else
10 years ago
{
10 years ago
codeView.scrollTop(codeView[0].scrollHeight * percent);
}
10 years ago
10 years ago
$.proxy(settings.onpreviewscroll, _this)(event);
10 years ago
});
10 years ago
10 years ago
};
var previewUnbindScroll = function() {
preview.unbind(mouseOrTouch("scroll", "touchmove"));
};
10 years ago
codeMirror.bind({
10 years ago
mouseover : cmBindScroll,
mouseout : cmUnbindScroll,
touchstart : cmBindScroll,
touchend : cmUnbindScroll
10 years ago
});
10 years ago
10 years ago
preview.bind({
mouseover : previewBindScroll,
mouseout : previewUnbindScroll,
touchstart : previewBindScroll,
touchend : previewUnbindScroll
});
10 years ago
10 years ago
return this;
},
bindChangeEvent : function() {
var _this = this;
var cm = this.cm;
var settings = this.settings;
cm.on("change", function(_cm, changeObj) {
if (settings.watch)
{
_this.previewContainer.css("padding", settings.autoHeight ? "20px 20px 50px 40px" : "20px");
}
timer = setTimeout(function() {
clearTimeout(timer);
_this.save();
timer = null;
}, settings.delay);
10 years ago
});
10 years ago
return this;
},
/**
* 加载队列完成之后的显示处理
* Display handle of the module queues loaded after.
*
* @param {Boolean} recreate 是否为重建编辑器
* @returns {editormd} 返回editormd的实例对象
*/
loadedDisplay : function(recreate) {
recreate = recreate || false;
var _this = this;
var editor = this.editor;
var preview = this.preview;
var settings = this.settings;
10 years ago
10 years ago
this.containerMask.hide();
this.save();
if (settings.watch) {
preview.show();
}
editor.data("oldWidth", editor.width()).data("oldHeight", editor.height()); // 为了兼容Zepto
this.resize();
this.registerKeyMaps();
$(window).resize(function(){
_this.resize();
});
this.bindScrollEvent().bindChangeEvent();
if (!recreate)
{
$.proxy(settings.onload, this)();
}
10 years ago
this.state.loaded = true;
10 years ago
return this;
},
/**
* 设置编辑器的宽度
10 years ago
* Set editor width
*
10 years ago
* @param {Number|String} width 编辑器宽度值
* @returns {editormd} 返回editormd的实例对象
*/
width : function(width) {
10 years ago
this.editor.css("width", (typeof width === "number") ? width + "px" : width);
10 years ago
this.resize();
return this;
},
/**
* 设置编辑器的高度
10 years ago
* Set editor height
*
10 years ago
* @param {Number|String} height 编辑器高度值
* @returns {editormd} 返回editormd的实例对象
*/
height : function(height) {
10 years ago
this.editor.css("height", (typeof height === "number") ? height + "px" : height);
10 years ago
this.resize();
return this;
},
/**
* 调整编辑器的尺寸和布局
10 years ago
* Resize editor layout
*
10 years ago
* @param {Number|String} [width=null] 编辑器宽度值
* @param {Number|String} [height=null] 编辑器高度值
* @returns {editormd} 返回editormd的实例对象
*/
resize : function(width, height) {
width = width || null;
height = height || null;
10 years ago
var state = this.state;
var editor = this.editor;
var preview = this.preview;
var toolbar = this.toolbar;
var settings = this.settings;
var codeMirror = this.codeMirror;
10 years ago
if (width)
{
editor.css("width", (typeof width === "number") ? width + "px" : width);
10 years ago
}
10 years ago
if (settings.autoHeight && !state.fullscreen && !state.preview)
{
editor.css("height", "auto");
codeMirror.css("height", "auto");
}
else
10 years ago
{
if (height)
{
editor.css("height", (typeof height === "number") ? height + "px" : height);
10 years ago
}
if (state.fullscreen)
{
editor.height($(window).height());
}
10 years ago
if (settings.toolbar && !settings.readOnly)
{
10 years ago
codeMirror.css("margin-top", toolbar.height() + 1).height(editor.height() - toolbar.height());
10 years ago
}
else
{
10 years ago
codeMirror.css("margin-top", 0).height(editor.height());
}
10 years ago
}
10 years ago
if(settings.watch)
10 years ago
{
10 years ago
codeMirror.width(editor.width() / 2);
10 years ago
preview.width((!state.preview) ? editor.width() / 2 : editor.width());
10 years ago
10 years ago
this.previewContainer.css("padding", settings.autoHeight ? "20px 20px 50px 40px" : "20px");
10 years ago
if (settings.toolbar && !settings.readOnly)
{
preview.css("top", toolbar.height());
}
else
{
preview.css("top", 0);
}
if (settings.autoHeight && !state.fullscreen && !state.preview)
{
10 years ago
preview.height("");
10 years ago
}
else
{
10 years ago
preview.height((settings.toolbar && !settings.readOnly) ? editor.height() - toolbar.height() : editor.height());
10 years ago
}
}
else
{
10 years ago
codeMirror.width(editor.width());
10 years ago
preview.hide();
}
10 years ago
10 years ago
if (state.loaded)
10 years ago
{
$.proxy(settings.onresize, this)();
}
10 years ago
return this;
},
/**
10 years ago
* 解析和保存Markdown代码
* Parse & Saving Markdown source code
10 years ago
*
10 years ago
* @returns {editormd} 返回editormd的实例对象
10 years ago
*/
10 years ago
save : function() {
if (timer === null)
{
return this;
}
var _this = this;
10 years ago
var state = this.state;
10 years ago
var settings = this.settings;
10 years ago
var cm = this.cm;
var cmValue = cm.getValue();
10 years ago
var previewContainer = this.previewContainer;
10 years ago
if (settings.mode !== "gfm" && settings.mode !== "markdown")
{
10 years ago
this.markdownTextarea.val(cmValue);
10 years ago
return this;
}
var marked = editormd.$marked;
var markdownToC = this.markdownToC = [];
var rendererOptions = this.markedRendererOptions = {
toc : settings.toc,
10 years ago
tocm : settings.tocm,
10 years ago
tocStartLevel : settings.tocStartLevel,
10 years ago
pageBreak : settings.pageBreak,
10 years ago
taskList : settings.taskList,
emoji : settings.emoji,
tex : settings.tex,
10 years ago
atLink : settings.atLink, // for @link
emailLink : settings.emailLink, // for mail address auto link
10 years ago
flowChart : settings.flowChart,
sequenceDiagram : settings.sequenceDiagram,
previewCodeHighlight : settings.previewCodeHighlight,
};
var markedOptions = this.markedOptions = {
renderer : editormd.markedRenderer(markdownToC, rendererOptions),
gfm : true,
tables : true,
breaks : true,
pedantic : false,
sanitize : (settings.htmlDecode) ? false : true, // 关闭忽略HTML标签,即开启识别HTML标签,默认为false
smartLists : true,
smartypants : true
};
marked.setOptions(markedOptions);
10 years ago
cmValue = editormd.filterHTMLTags(cmValue, settings.htmlDecode);
10 years ago
10 years ago
var newMarkdownDoc = editormd.$marked(cmValue, markedOptions);
10 years ago
10 years ago
this.markdownTextarea.val(cmValue);
10 years ago
cm.save();
10 years ago
if (settings.saveHTMLToTextarea)
{
10 years ago
this.htmlTextarea.html(newMarkdownDoc);
}
10 years ago
if(settings.watch || (!settings.watch && state.preview))
10 years ago
{
previewContainer.html(newMarkdownDoc);
this.previewCodeHighlight();
10 years ago
if (settings.toc)
{
var tocContainer = (settings.tocContainer === "") ? previewContainer : $(settings.tocContainer);
var tocMenu = tocContainer.find("." + this.classPrefix + "toc-menu");
tocContainer.attr("previewContainer", (settings.tocContainer === "") ? "true" : "false");
if (settings.tocContainer !== "" && tocMenu.length > 0)
{
tocMenu.remove();
}
editormd.markdownToCRenderer(markdownToC, tocContainer, settings.tocDropdown, settings.tocStartLevel);
if (settings.tocDropdown || tocContainer.find("." + this.classPrefix + "toc-menu").length > 0)
{
editormd.tocDropdownMenu(tocContainer, (settings.tocTitle !== "") ? settings.tocTitle : this.lang.tocTitle);
}
10 years ago
10 years ago
if (settings.tocContainer !== "")
{
previewContainer.find(".markdown-toc").css("border", "none");
}
10 years ago
}
10 years ago
if (settings.tex)
{
10 years ago
if (!editormd.kaTeXLoaded && settings.autoLoadModules)
{
editormd.loadKaTeX(function() {
10 years ago
editormd.$katex = katex;
editormd.kaTeXLoaded = true;
_this.katexRender();
});
10 years ago
}
else
{
editormd.$katex = katex;
10 years ago
this.katexRender();
}
}
if (settings.flowChart || settings.sequenceDiagram)
{
10 years ago
flowchartTimer = setTimeout(function(){
clearTimeout(flowchartTimer);
10 years ago
_this.flowChartAndSequenceDiagramRender();
10 years ago
flowchartTimer = null;
10 years ago
}, 10);
}
10 years ago
if (state.loaded)
{
$.proxy(settings.onchange, this)();
}
10 years ago
}
10 years ago
return this;
},
10 years ago
/**
* 聚焦光标位置
10 years ago
* Focusing the cursor position
*
10 years ago
* @returns {editormd} 返回editormd的实例对象
*/
focus : function() {
10 years ago
this.cm.focus();
10 years ago
return this;
},
/**
* 设置光标的位置
10 years ago
* Set cursor position
*
10 years ago
* @param {Object} cursor 要设置的光标位置键值对象{line:1, ch:0}
* @returns {editormd} 返回editormd的实例对象
*/
setCursor : function(cursor) {
10 years ago
this.cm.setCursor(cursor);
10 years ago
return this;
},
/**
* 获取当前光标的位置
10 years ago
* Get the current position of the cursor
*
10 years ago
* @returns {Cursor} 返回一个光标Cursor对象
*/
getCursor : function() {
10 years ago
return this.cm.getCursor();
10 years ago
},
/**
* 设置光标选中的范围
10 years ago
* Set cursor selected ranges
*
10 years ago
* @param {Object} from 开始位置的光标键值对象{line:1, ch:0}
* @param {Object} to 结束位置的光标键值对象{line:1, ch:0}
* @returns {editormd} 返回editormd的实例对象
*/
setSelection : function(from, to) {
10 years ago
this.cm.setSelection(from, to);
10 years ago
return this;
},
/**
* 获取光标选中的文本
10 years ago
* Get the texts from cursor selected
*
10 years ago
* @returns {String} 返回选中文本的字符串形式
*/
getSelection : function() {
10 years ago
return this.cm.getSelection();
10 years ago
},
10 years ago
/**
* 设置光标选中的文本范围
* Set the cursor selection ranges
*
* @param {Array} ranges cursor selection ranges array
* @returns {Array} return this
*/
setSelections : function(ranges) {
this.cm.setSelections(ranges);
return this;
},
/**
* 获取光标选中的文本范围
* Get the cursor selection ranges
*
* @returns {Array} return selection ranges array
*/
getSelections : function() {
return this.cm.getSelections();
},
10 years ago
/**
* 替换当前光标选中的文本或在当前光标处插入新字符
10 years ago
* Replace the text at the current cursor selected or insert a new character at the current cursor position
*
10 years ago
* @param {String} value 要插入的字符值
* @returns {editormd} 返回editormd的实例对象
*/
replaceSelection : function(value) {
10 years ago
this.cm.replaceSelection(value);
10 years ago
return this;
},
/**
* 在当前光标处插入新字符
10 years ago
* Insert a new character at the current cursor position
10 years ago
*
* 同replaceSelection()方法
10 years ago
* With the replaceSelection() method
*
10 years ago
* @param {String} value 要插入的字符值
* @returns {editormd} 返回editormd的实例对象
*/
insertValue : function(value) {
this.replaceSelection(value);
return this;
},
10 years ago
/**
* 追加markdown
* append Markdown to editor
*
* @param {String} md 要追加的markdown源文档
* @returns {editormd} 返回editormd的实例对象
*/
appendMarkdown : function(md) {
var settings = this.settings;
var cm = this.cm;
cm.setValue(cm.getValue() + md);
return this;
},
10 years ago
/**
* 设置和传入编辑器的markdown源文档
10 years ago
* Set Markdown source document
*
10 years ago
* @param {String} md 要传入的markdown源文档
* @returns {editormd} 返回editormd的实例对象
*/
10 years ago
setMarkdown : function(md) {
this.cm.setValue(md || this.settings.markdown);
10 years ago
return this;
},
/**
* 获取编辑器的markdown源文档
10 years ago
* Set Editor.md markdown/CodeMirror value
*
10 years ago
* @returns {editormd} 返回editormd的实例对象
*/
getMarkdown : function() {
10 years ago
return this.cm.getValue();
10 years ago
},
10 years ago
/**
* 获取编辑器的源文档
* Get CodeMirror value
*
* @returns {editormd} 返回editormd的实例对象
*/
getValue : function() {
10 years ago
return this.cm.getValue();
10 years ago
},
/**
* 设置编辑器的源文档
* Set CodeMirror value
*
* @param {String} value set code/value/string/text
* @returns {editormd} 返回editormd的实例对象
*/
setValue : function(value) {
10 years ago
this.cm.setValue(value);
10 years ago
return this;
},
10 years ago
/**
10 years ago
* 清空编辑器
10 years ago
* Empty CodeMirror editor container
*
10 years ago
* @returns {editormd} 返回editormd的实例对象
*/
10 years ago
clear : function() {
10 years ago
this.cm.setValue("");
10 years ago
10 years ago
return this;
10 years ago
},
/**
* 获取解析后存放在Textarea的HTML源码
10 years ago
* Get parsed html code from Textarea
*
10 years ago
* @returns {String} 返回HTML源码
*/
10 years ago
getHTML : function() {
10 years ago
if (!this.settings.saveHTMLToTextarea)
10 years ago
{
alert("Error: settings.saveHTMLToTextarea == false");
return false;
}
return this.htmlTextarea.html();
},
/**
* getHTML()的别名
10 years ago
* getHTML (alias)
*
* @returns {String} Return html code 返回HTML源码
10 years ago
*/
getTextareaSavedHTML : function() {
return this.getHTML();
},
/**
* 获取预览窗口的HTML源码
10 years ago
* Get html from preview container
*
10 years ago
* @returns {editormd} 返回editormd的实例对象
*/
getPreviewedHTML : function() {
10 years ago
if (!this.settings.watch)
10 years ago
{
alert("Error: settings.watch == false");
return false;
}
10 years ago
return this.previewContainer.html();
10 years ago
},
/**
* 开启实时预览
10 years ago
* Enable real-time watching
*
10 years ago
* @returns {editormd} 返回editormd的实例对象
*/
10 years ago
watch : function(callback) {
10 years ago
var settings = this.settings;
if ($.inArray(settings.mode, ["gfm", "markdown"]) < 0)
{
return this;
}
10 years ago
this.state.watching = settings.watch = true;
10 years ago
this.preview.show();
10 years ago
if (this.toolbar)
{
var watchIcon = settings.toolbarIconsClass.watch;
var unWatchIcon = settings.toolbarIconsClass.unwatch;
var icon = this.toolbar.find(".fa[name=watch]");
icon.parent().attr("title", settings.lang.toolbar.watch);
icon.removeClass(unWatchIcon).addClass(watchIcon);
}
10 years ago
10 years ago
this.codeMirror.css("border-right", "1px solid #ddd").width(this.editor.width() / 2);
10 years ago
10 years ago
timer = 0;
this.save().resize();
10 years ago
10 years ago
if (!settings.onwatch)
{
settings.onwatch = callback || function() {};
}
$.proxy(settings.onwatch, this)();
10 years ago
return this;
},
/**
* 关闭实时预览
10 years ago
* Disable real-time watching
*
10 years ago
* @returns {editormd} 返回editormd的实例对象
*/
unwatch : function(callback) {
10 years ago
var settings = this.settings;
this.state.watching = settings.watch = false;
10 years ago
this.preview.hide();
10 years ago
if (this.toolbar)
{
10 years ago
var watchIcon = settings.toolbarIconsClass.watch;
var unWatchIcon = settings.toolbarIconsClass.unwatch;
10 years ago
var icon = this.toolbar.find(".fa[name=watch]");
icon.parent().attr("title", settings.lang.toolbar.unwatch);
icon.removeClass(watchIcon).addClass(unWatchIcon);
}
10 years ago
10 years ago
this.codeMirror.css("border-right", "none").width(this.editor.width());
10 years ago
this.resize();
10 years ago
if (!settings.onunwatch)
{
settings.onunwatch = callback || function() {};
}
$.proxy(settings.onunwatch, this)();
10 years ago
return this;
},
/**
* 显示编辑器
10 years ago
* Show editor
*
* @param {Function} [callback=function()] 回调函数
* @returns {editormd} 返回editormd的实例对象
10 years ago
*/
10 years ago
show : function(callback) {
callback = callback || function() {};
var _this = this;
10 years ago
this.editor.show(0, function() {
$.proxy(callback, _this)();
});
10 years ago
return this;
},
/**
* 隐藏编辑器
10 years ago
* Hide editor
*
* @param {Function} [callback=function()] 回调函数
* @returns {editormd} 返回editormd的实例对象
10 years ago
*/
hide : function(callback) {
callback = callback || function() {};
var _this = this;
10 years ago
this.editor.hide(0, function() {
$.proxy(callback, _this)();
});
10 years ago
return this;
},
/**
* 隐藏编辑器部分只预览HTML
10 years ago
* Enter preview html state
*
10 years ago
* @returns {editormd} 返回editormd的实例对象
*/
previewing : function() {
var _this = this;
var editor = this.editor;
var preview = this.preview;
var toolbar = this.toolbar;
var settings = this.settings;
var codeMirror = this.codeMirror;
10 years ago
if ($.inArray(settings.mode, ["gfm", "markdown"]) < 0) {
return this;
}
if (settings.toolbar && toolbar) {
10 years ago
toolbar.toggle();
10 years ago
toolbar.find(".fa[name=preview]").toggleClass("active");
10 years ago
}
10 years ago
10 years ago
codeMirror.toggle();
10 years ago
var escHandle = function(event) {
if (event.shiftKey && event.keyCode === 27) {
_this.previewed();
}
};
10 years ago
10 years ago
if (codeMirror.css("display") === "none") // 为了兼容Zepto,而不使用codeMirror.is(":hidden")
10 years ago
{
this.state.preview = true;
10 years ago
if (this.state.fullscreen) {
10 years ago
preview.css("background", "#fff");
}
10 years ago
editor.find("." + this.classPrefix + "preview-close-btn").show().bind(editormd.mouseOrTouch("click", "touchend"), function(){
_this.previewed();
});
10 years ago
10 years ago
if (!settings.watch)
10 years ago
{
10 years ago
this.save();
10 years ago
}
10 years ago
preview.show().css({
10 years ago
position : "static",
10 years ago
top : 0,
width : editor.width(),
10 years ago
height : (settings.autoHeight && !this.state.fullscreen) ? "auto" : editor.height()
10 years ago
});
10 years ago
if (this.state.loaded)
{
$.proxy(settings.onpreviewing, this)();
}
10 years ago
$(window).bind("keyup", escHandle);
10 years ago
}
else
{
10 years ago
$(window).unbind("keyup", escHandle);
10 years ago
this.previewed();
}
},
/**
* 显示编辑器部分退出只预览HTML
10 years ago
* Exit preview html state
*
10 years ago
* @returns {editormd} 返回editormd的实例对象
*/
previewed : function() {
var editor = this.editor;
var preview = this.preview;
var toolbar = this.toolbar;
var settings = this.settings;
10 years ago
var previewCloseBtn = editor.find("." + this.classPrefix + "preview-close-btn");
10 years ago
10 years ago
this.state.preview = false;
10 years ago
10 years ago
this.codeMirror.show();
10 years ago
if (settings.toolbar) {
toolbar.show();
}
10 years ago
preview[(settings.watch) ? "show" : "hide"]();
10 years ago
10 years ago
previewCloseBtn.hide().unbind(editormd.mouseOrTouch("click", "touchend"));
10 years ago
10 years ago
preview.css({
background : null,
10 years ago
position : "absolute",
10 years ago
width : editor.width() / 2,
10 years ago
height : (settings.autoHeight && !this.state.fullscreen) ? "auto" : editor.height() - toolbar.height(),
top : (settings.toolbar) ? toolbar.height() : 0
10 years ago
});
10 years ago
if (this.state.loaded)
{
$.proxy(settings.onpreviewed, this)();
}
10 years ago
return this;
},
/**
* 编辑器全屏显示
10 years ago
* Fullscreen show
*
10 years ago
* @returns {editormd} 返回editormd的实例对象
*/
fullscreen : function() {
var _this = this;
10 years ago
var state = this.state;
10 years ago
var editor = this.editor;
var preview = this.preview;
var toolbar = this.toolbar;
10 years ago
var settings = this.settings;
10 years ago
var fullscreenClass = this.classPrefix + "fullscreen";
10 years ago
if (toolbar) {
toolbar.find(".fa[name=fullscreen]").parent().toggleClass("active");
}
10 years ago
var escHandle = function(event) {
if (!event.shiftKey && event.keyCode === 27)
{
10 years ago
if (state.fullscreen)
10 years ago
{
_this.fullscreenExit();
}
}
};
10 years ago
if (!editor.hasClass(fullscreenClass))
10 years ago
{
10 years ago
state.fullscreen = true;
10 years ago
$("html,body").css("overflow", "hidden");
editor.css({
position : "fixed",
top : 0,
left : 0,
margin : 0,
border : "none",
width : $(window).width(),
height : $(window).height()
10 years ago
}).addClass(fullscreenClass);
this.resize();
10 years ago
10 years ago
$.proxy(settings.onfullscreen, this)();
10 years ago
$(window).bind("keyup", escHandle);
10 years ago
}
else
10 years ago
{
$(window).unbind("keyup", escHandle);
this.fullscreenExit();
}
10 years ago
return this;
},
/**
* 编辑器退出全屏显示
10 years ago
* Exit fullscreen state
*
10 years ago
* @returns {editormd} 返回editormd的实例对象
*/
fullscreenExit : function() {
var editor = this.editor;
10 years ago
var settings = this.settings;
10 years ago
var toolbar = this.toolbar;
10 years ago
var fullscreenClass = this.classPrefix + "fullscreen";
this.state.fullscreen = false;
10 years ago
10 years ago
if (toolbar) {
toolbar.find(".fa[name=fullscreen]").parent().removeClass("active");
}
10 years ago
$("html,body").css("overflow", "");
10 years ago
editor.css({
position : "",
top : "",
left : "",
10 years ago
margin : "0 auto 15px",
10 years ago
width : editor.data("oldWidth"),
height : editor.data("oldHeight"),
border : "1px solid #ddd"
}).removeClass(fullscreenClass);
10 years ago
this.resize();
10 years ago
$.proxy(settings.onfullscreenExit, this)();
10 years ago
return this;
},
10 years ago
/**
* 加载并执行插件
* Load and execute the plugin
*
* @param {String} name plugin name / function name
* @param {String} path plugin load path
* @returns {editormd} 返回editormd的实例对象
*/
10 years ago
executePlugin : function(name, path) {
10 years ago
var _this = this;
var cm = this.cm;
var settings = this.settings;
10 years ago
10 years ago
path = settings.pluginPath + path;
if (typeof define === "function")
{
if (typeof this[name] === "undefined")
{
alert("Error: " + name + " plugin is not found, you are not load this plugin.");
return this;
}
10 years ago
this[name](cm);
10 years ago
return this;
10 years ago
}
if ($.inArray(path, editormd.loadFiles.plugin) < 0)
{
editormd.loadPlugin(path, function() {
editormd.loadPlugins[name] = _this[name];
_this[name](cm);
});
}
else
{
$.proxy(editormd.loadPlugins[name], this)(cm);
}
10 years ago
return this;
},
/**
* 搜索替换
* Search & replace
*
* @param {String} command CodeMirror serach commands, "find, fintNext, fintPrev, clearSearch, replace, replaceAll"
* @returns {editormd} return this
*/
search : function(command) {
var settings = this.settings;
if (!settings.searchReplace)
{
alert("Error: settings.searchReplace == false");
return this;
}
if (!settings.readOnly)
{
this.cm.execCommand(command || "find");
}
return this;
},
searchReplace : function() {
this.search("replace");
return this;
},
searchReplaceAll : function() {
this.search("replaceAll");
return this;
10 years ago
}
};
editormd.fn.init.prototype = editormd.fn;
10 years ago
/**
* 锁屏
* lock screen when dialog opening
*
* @returns {void}
*/
10 years ago
editormd.dialogLockScreen = function() {
10 years ago
var settings = this.settings || {dialogLockScreen : true};
10 years ago
if (settings.dialogLockScreen)
{
$("html,body").css("overflow", "hidden");
}
};
10 years ago
/**
* 显示透明背景层
* Display mask layer when dialog opening
*
* @param {Object} dialog dialog jQuery object
* @returns {void}
*/
10 years ago
editormd.dialogShowMask = function(dialog) {
var editor = this.editor;
10 years ago
var settings = this.settings || {dialogShowMask : true};
10 years ago
dialog.css({
top : ($(window).height() - dialog.height()) / 2 + "px",
left : ($(window).width() - dialog.width()) / 2 + "px"
});
if (settings.dialogShowMask) {
editor.children("." + this.classPrefix + "mask").css("z-index", parseInt(dialog.css("z-index")) - 1).show();
}
};
10 years ago
10 years ago
editormd.toolbarHandlers = {
undo : function() {
this.cm.undo();
},
redo : function() {
this.cm.redo();
},
bold : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
cm.replaceSelection("**" + selection + "**");
if(selection === "") {
cm.setCursor(cursor.line, cursor.ch + 2);
10 years ago
}
10 years ago
},
del : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
cm.replaceSelection("~~" + selection + "~~");
if(selection === "") {
cm.setCursor(cursor.line, cursor.ch + 2);
}
},
italic : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
cm.replaceSelection("*" + selection + "*");
if(selection === "") {
cm.setCursor(cursor.line, cursor.ch + 1);
}
},
quote : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
cm.replaceSelection("> " + selection);
cm.setCursor(cursor.line, (selection === "") ? cursor.ch + 2 : cursor.ch + selection.length + 2);
},
10 years ago
ucfirst : function() {
var cm = this.cm;
var selection = cm.getSelection();
var selections = cm.listSelections();
cm.replaceSelection(editormd.firstUpperCase(selection));
cm.setSelections(selections);
},
ucwords : function() {
var cm = this.cm;
var selection = cm.getSelection();
var selections = cm.listSelections();
cm.replaceSelection(editormd.wordsFirstUpperCase(selection));
cm.setSelections(selections);
},
uppercase : function() {
var cm = this.cm;
var selection = cm.getSelection();
var selections = cm.listSelections();
cm.replaceSelection(selection.toUpperCase());
cm.setSelections(selections);
},
lowercase : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
var selections = cm.listSelections();
cm.replaceSelection(selection.toLowerCase());
cm.setSelections(selections);
},
10 years ago
h1 : function() {
var cm = this.cm;
var selection = cm.getSelection();
cm.replaceSelection("# " + selection);
},
h2 : function() {
var cm = this.cm;
var selection = cm.getSelection();
cm.replaceSelection("## " + selection);
},
h3 : function() {
var cm = this.cm;
var selection = cm.getSelection();
cm.replaceSelection("### " + selection);
},
h4 : function() {
var cm = this.cm;
var selection = cm.getSelection();
cm.replaceSelection("#### " + selection);
},
h5 : function() {
var cm = this.cm;
var selection = cm.getSelection();
cm.replaceSelection("##### " + selection);
},
h6 : function() {
var cm = this.cm;
var selection = cm.getSelection();
cm.replaceSelection("###### " + selection);
},
"list-ul" : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
if (selection === "")
{
cm.replaceSelection("- " + selection);
}
else
{
var selectionText = selection.split("\n");
for (var i = 0, len = selectionText.length; i < len; i++)
{
selectionText[i] = (selectionText[i] === "") ? "" : "- " + selectionText[i];
}
cm.replaceSelection(selectionText.join("\n"));
}
},
"list-ol" : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
if(selection === "")
{
cm.replaceSelection("1. " + selection);
}
else
{
var selectionText = selection.split("\n");
for (var i = 0, len = selectionText.length; i < len; i++)
{
selectionText[i] = (selectionText[i] === "") ? "" : (i+1) + ". " + selectionText[i];
}
cm.replaceSelection(selectionText.join("\n"));
}
},
hr : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
cm.replaceSelection("------------");
},
10 years ago
tex : function() {
if (!this.settings.tex)
{
alert("settings.tex === false");
return this;
}
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
cm.replaceSelection("$$" + selection + "$$");
if(selection === "") {
cm.setCursor(cursor.line, cursor.ch + 2);
}
},
10 years ago
link : function() {
this.executePlugin("linkDialog", "link-dialog/link-dialog");
},
10 years ago
"reference-link" : function() {
this.executePlugin("referenceLinkDialog", "reference-link-dialog/reference-link-dialog");
},
pagebreak : function() {
if (!this.settings.pageBreak)
{
alert("settings.pageBreak === false");
return this;
}
var cm = this.cm;
var selection = cm.getSelection();
cm.replaceSelection("\r\n[========]\r\n");
10 years ago
},
image : function() {
this.executePlugin("imageDialog", "image-dialog/image-dialog");
},
code : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
cm.replaceSelection("`" + selection + "`");
if (selection === "") {
cm.setCursor(cursor.line, cursor.ch + 1);
}
},
"code-block" : function() {
this.executePlugin("codeBlockDialog", "code-block-dialog/code-block-dialog");
},
"preformatted-text" : function() {
this.executePlugin("preformattedTextDialog", "preformatted-text-dialog/preformatted-text-dialog");
},
table : function() {
this.executePlugin("tableDialog", "table-dialog/table-dialog");
},
datetime : function() {
var cm = this.cm;
var selection = cm.getSelection();
var date = new Date();
var langName = this.settings.lang.name;
var datefmt = editormd.dateFormat() + " " + editormd.dateFormat((langName === "zh-cn" || langName === "zh-tw") ? "cn-week-day" : "week-day");
cm.replaceSelection(datefmt);
},
emoji : function() {
this.executePlugin("emojiDialog", "emoji-dialog/emoji-dialog");
},
10 years ago
"html-entities" : function() {
10 years ago
this.executePlugin("htmlEntitiesDialog", "html-entities-dialog/html-entities-dialog");
},
10 years ago
"goto-line" : function() {
this.executePlugin("gotoLineDialog", "goto-line-dialog/goto-line-dialog");
},
10 years ago
watch : function() {
this[this.settings.watch ? "unwatch" : "watch"]();
},
preview : function() {
this.previewing();
},
10 years ago
10 years ago
fullscreen : function() {
this.fullscreen();
},
10 years ago
10 years ago
clear : function() {
this.clear();
},
10 years ago
search : function() {
this.search();
},
10 years ago
help : function() {
this.executePlugin("helpDialog", "help-dialog/help-dialog");
},
info : function() {
this.showInfoDialog();
10 years ago
}
};
10 years ago
editormd.keyMaps = {
"Ctrl-1" : "h1",
"Ctrl-2" : "h2",
"Ctrl-3" : "h3",
"Ctrl-4" : "h4",
"Ctrl-5" : "h5",
"Ctrl-6" : "h6",
10 years ago
"Ctrl-B" : "bold", // if this is string == editormd.toolbarHandlers.xxxx
10 years ago
"Ctrl-D" : "datetime",
"Ctrl-E" : function() { // emoji
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
10 years ago
if (!this.settings.emoji)
{
alert("Error: settings.emoji == false");
return ;
}
10 years ago
cm.replaceSelection(":" + selection + ":");
if (selection === "") {
cm.setCursor(cursor.line, cursor.ch + 1);
}
},
10 years ago
"Ctrl-Alt-G" : "goto-line",
"Ctrl-H" : "hr",
"Ctrl-I" : "italic",
"Ctrl-K" : "code",
10 years ago
"Ctrl-L" : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
var title = (selection === "") ? "" : " \""+selection+"\"";
cm.replaceSelection("[" + selection + "]("+title+")");
if (selection === "") {
cm.setCursor(cursor.line, cursor.ch + 1);
}
},
"Ctrl-U" : "list-ul",
"Shift-Ctrl-A" : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
10 years ago
if (!this.settings.atLink)
{
alert("Error: settings.atLink == false");
return ;
}
10 years ago
cm.replaceSelection("@" + selection);
if (selection === "") {
cm.setCursor(cursor.line, cursor.ch + 1);
}
},
10 years ago
"Shift-Ctrl-C" : "code",
"Shift-Ctrl-Q" : "quote",
"Shift-Ctrl-S" : "del",
"Shift-Ctrl-K" : "tex", // KaTeX
10 years ago
"Shift-Alt-C" : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
cm.replaceSelection(["```", selection, "```"].join("\n"));
if (selection === "") {
cm.setCursor(cursor.line, cursor.ch + 3);
}
},
"Shift-Ctrl-Alt-C" : "code-block",
10 years ago
"Shift-Ctrl-H" : "html-entities",
10 years ago
"Shift-Alt-H" : "help",
"Shift-Ctrl-E" : "emoji",
"Shift-Ctrl-U" : "uppercase",
"Shift-Alt-U" : "ucwords",
"Shift-Ctrl-Alt-U" : "ucfirst",
"Shift-Alt-L" : "lowercase",
"Shift-Ctrl-I" : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
var title = (selection === "") ? "" : " \""+selection+"\"";
cm.replaceSelection("![" + selection + "]("+title+")");
if (selection === "") {
cm.setCursor(cursor.line, cursor.ch + 4);
}
},
"Shift-Ctrl-Alt-I" : "image",
"Shift-Ctrl-L" : "link",
"Shift-Ctrl-O" : "list-ol",
"Shift-Ctrl-P" : "preformatted-text",
"Shift-Ctrl-T" : "table",
10 years ago
"Shift-Alt-P" : "pagebreak",
10 years ago
"F9" : "watch",
"F10" : "preview",
"F11" : "fullscreen",
};
10 years ago
/**
* 清除字符串两边的空格
10 years ago
* Clear the space of strings both sides.
*
10 years ago
* @param {String} str string
10 years ago
* @returns {String} trimed string
10 years ago
*/
10 years ago
var trim = function(str) {
10 years ago
return (!String.prototype.trim) ? str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "") : str.trim();
10 years ago
};
10 years ago
editormd.trim = trim;
/**
* 所有单词首字母大写
* Words first to uppercase
*
* @param {String} str string
* @returns {String} string
*/
var ucwords = function (str) {
return str.toLowerCase().replace(/\b(\w)|\s(\w)/g, function($1) {
return $1.toUpperCase();
});
};
editormd.ucwords = editormd.wordsFirstUpperCase = ucwords;
/**
* 字符串首字母大写
* Only string first char to uppercase
*
* @param {String} str string
* @returns {String} string
*/
var firstUpperCase = function(str) {
return str.toLowerCase().replace(/\b(\w)/, function($1){
return $1.toUpperCase();
});
};
var ucfirst = firstUpperCase;
editormd.firstUpperCase = editormd.ucfirst = firstUpperCase;
10 years ago
10 years ago
editormd.urls = {
atLinkBase : "https://github.com/"
};
10 years ago
editormd.regexs = {
10 years ago
atLink : /@(\w+)/g,
email : /(\w+)@(\w+)\.(\w+)\.?(\w+)?/g,
emailLink : /(mailto:)?([\w\.\_]+)@(\w+)\.(\w+)\.?(\w+)?/g,
emoji : /:([\-\w]+):/g,
emojiDatetime : /(\d{2}:\d{2}:\d{2})/g,
twemoji : /:(tw-([\w]+)-?(\w+)?):/g,
fontAwesome : /:(fa-([\w]+)(-(\w+)){0,}):/g,
10 years ago
editormdLogo : /:(editormd-logo-?(\w+)?):/g,
pageBreak : /^\[[=]{8,}\]$/
10 years ago
};
// Emoji graphics files url path
editormd.emoji = {
path : "http://www.emoji-cheat-sheet.com/graphics/emojis/",
ext : ".png"
};
// Twitter Emoji (Twemoji) graphics files url path
editormd.twemoji = {
path : "http://twemoji.maxcdn.com/36x36/",
ext : ".png"
};
10 years ago
/**
* 自定义marked的解析器
10 years ago
* Custom Marked renderer rules
*
10 years ago
* @param {Array} markdownToC 传入用于接收TOC的数组
10 years ago
* @returns {Renderer} markedRenderer 返回marked的Renderer自定义对象
10 years ago
*/
10 years ago
editormd.markedRenderer = function(markdownToC, options) {
var defaults = {
toc : true, // Table of contents
10 years ago
tocm : false,
10 years ago
tocStartLevel : 1, // Said from H1 to create ToC
10 years ago
pageBreak : true,
10 years ago
atLink : true, // for @link
emailLink : true, // for mail address auto link
10 years ago
taskList : false, // Enable Github Flavored Markdown task lists
emoji : false, // :emoji: , Support Twemoji, fontAwesome, Editor.md logo emojis.
tex : false, // TeX(LaTeX), based on KaTeX
flowChart : false, // flowChart.js only support IE9+
sequenceDiagram : false, // sequenceDiagram.js only support IE9+
};
var settings = $.extend(defaults, options || {});
var marked = editormd.$marked;
var markedRenderer = new marked.Renderer();
10 years ago
markdownToC = markdownToC || [];
10 years ago
var regexs = editormd.regexs;
var atLinkReg = regexs.atLink;
var emojiReg = regexs.emoji;
var emailReg = regexs.email;
var emailLinkReg = regexs.emailLink;
var twemojiReg = regexs.twemoji;
var faIconReg = regexs.fontAwesome;
var editormdLogoReg = regexs.editormdLogo;
var pageBreakReg = regexs.pageBreak;
10 years ago
markedRenderer.emoji = function(text) {
10 years ago
text = text.replace(editormd.regexs.emojiDatetime, function($1) {
return $1.replace(/:/g, "&#58;");
});
10 years ago
var matchs = text.match(emojiReg);
if (!matchs || !settings.emoji) {
return text;
}
for (var i = 0, len = matchs.length; i < len; i++)
{
text = text.replace(new RegExp(matchs[i]), function($1, $2){
var faMatchs = $1.match(faIconReg);
var name = $1.replace(/:/g, "");
if (faMatchs)
{
for (var fa = 0, len1 = faMatchs.length; fa < len1; fa++)
{
var faName = faMatchs[fa].replace(/:/g, "");
return "<i class=\"fa " + faName + " fa-emoji\" title=\"" + faName.replace("fa-", "") + "\"></i>";
}
}
else
{
var emdlogoMathcs = $1.match(editormdLogoReg);
var twemojiMatchs = $1.match(twemojiReg);
if (emdlogoMathcs)
{
for (var x = 0, len2 = emdlogoMathcs.length; x < len2; x++)
{
var logoName = emdlogoMathcs[x].replace(/:/g, "");
return "<i class=\"" + logoName + "\" title=\"Editor.md logo (" + logoName + ")\"></i>";
}
}
else if (twemojiMatchs)
{
for (var t = 0, len3 = twemojiMatchs.length; t < len3; t++)
{
var twe = twemojiMatchs[t].replace(/:/g, "").replace("tw-", "");
return "<img src=\"" + editormd.twemoji.path + twe + editormd.twemoji.ext + "\" title=\"twemoji-" + twe + "\" alt=\"twemoji-" + twe + "\" class=\"emoji twemoji\" />";
}
}
else
{
return "<img src=\"" + editormd.emoji.path + name + editormd.emoji.ext + "\" class=\"emoji\" title=\"&#58;" + name + "&#58;\" alt=\"&#58;" + name + "&#58;\" />";
}
}
});
}
return text;
};
markedRenderer.atLink = function(text) {
if (atLinkReg.test(text))
10 years ago
{
if (settings.atLink)
{
text = text.replace(emailReg, function($1, $2, $3, $4) {
return $1.replace(/@/g, "_#_&#64;_#_");
});
text = text.replace(atLinkReg, function($1, $2) {
return "<a href=\"" + editormd.urls.atLinkBase + "" + $2 + "\" title=\"&#64;" + $2 + "\" class=\"at-link\">" + $1 + "</a>";
}).replace(/_#_&#64;_#_/g, "@");
}
if (settings.emailLink)
{
10 years ago
text = text.replace(emailLinkReg, function($1, $2, $3, $4, $5) {
return (!$2 && $.inArray($5, "jpg|jpeg|png|gif|webp|ico|icon|pdf".split("|")) < 0) ? "<a href=\"mailto:" + $1 + "\">"+$1+"</a>" : $1;
10 years ago
});
}
return text;
10 years ago
}
return text;
};
markedRenderer.link = function (href, title, text) {
if (this.options.sanitize) {
try {
var prot = decodeURIComponent(unescape(href)).replace(/[^\w:]/g,"").toLowerCase();
} catch(e) {
return "";
}
if (prot.indexOf("javascript:") === 0) {
return "";
}
}
var out = "<a href=\"" + href + "\"";
if (atLinkReg.test(title) || atLinkReg.test(text))
{
if (title)
{
out += " title=\"" + title.replace(/@/g, "&#64;");
}
return out + "\">" + text.replace(/@/g, "&#64;") + "</a>";
}
if (title) {
out += " title=\"" + title + "\"";
}
out += ">" + text + "</a>";
return out;
10 years ago
};
10 years ago
markedRenderer.heading = function(text, level, raw) {
10 years ago
var linkText = text;
var hasLinkReg = /\s*\<a\s*href\=\"(.*)\"\s*([^\>]*)\>(.*)\<\/a\>\s*/;
var getLinkTextReg = /\s*\<a\s*([^\>]+)\>([^\>]*)\<\/a\>\s*/g;
if (hasLinkReg.test(text))
{
var tempText = [];
text = text.split(/\<a\s*([^\>]+)\>([^\>]*)\<\/a\>/);
for (var i = 0, len = text.length; i < len; i++)
{
tempText.push(text[i].replace(/\s*href\=\"(.*)\"\s*/g, ""));
}
text = tempText.join(" ");
}
text = trim(text);
10 years ago
var escapedText = text.toLowerCase().replace(/[^\w]+/g, "-");
10 years ago
var toc = {
10 years ago
text : text,
10 years ago
level : level,
10 years ago
slug : escapedText
};
var isChinese = /^[\u4e00-\u9fa5]+$/.test(text);
10 years ago
var id = (isChinese) ? escape(text).replace(/\%/g, "") : text.toLowerCase().replace(/[^\w]+/g, "-");
10 years ago
markdownToC.push(toc);
10 years ago
var headingHTML = "<h" + level + " id=\"h"+ level + "-" + this.options.headerPrefix + id +"\">";
10 years ago
headingHTML += "<a name=\"" + text + "\" class=\"reference-link\"></a>";
10 years ago
headingHTML += "<span class=\"header-link octicon octicon-link\"></span>";
10 years ago
headingHTML += (hasLinkReg) ? this.atLink(this.emoji(linkText)) : this.atLink(this.emoji(text));
10 years ago
headingHTML += "</h" + level + ">";
10 years ago
10 years ago
return headingHTML;
};
10 years ago
markedRenderer.pageBreak = function(text) {
if (pageBreakReg.test(text) && settings.pageBreak)
{
text = "<hr style=\"page-break-after:always;\" class=\"page-break editormd-page-break\" />";
}
return text;
};
10 years ago
markedRenderer.paragraph = function(text) {
var isTeXInline = /\$\$(.*)\$\$/g.test(text);
var isTeXLine = /^\$\$(.*)\$\$$/.test(text);
10 years ago
var isTeXAddClass = (isTeXLine) ? " class=\"" + editormd.classNames.tex + "\"" : "";
var isToC = (settings.tocm) ? /^(\[TOC\]|\[TOCM\])$/.test(text) : /^\[TOC\]$/.test(text);
var isToCMenu = /^\[TOCM\]$/.test(text);
if (!isTeXLine && isTeXInline)
{
text = text.replace(/(\$\$([^\$]*)\$\$)+/g, function($1, $2) {
return "<span class=\"" + editormd.classNames.tex + "\">" + $2.replace(/\$/g, "") + "</span>";
});
}
else
{
text = (isTeXLine) ? text.replace(/\$/g, "") : text;
10 years ago
}
10 years ago
var tocHTML = "<div class=\"markdown-toc editormd-markdown-toc\">" + text + "</div>";
return (isToC) ? ( (isToCMenu) ? "<div class=\"editormd-toc-menu\">" + tocHTML + "</div><br/>" : tocHTML )
: ( (pageBreakReg.test(text)) ? this.pageBreak(text) : "<p" + isTeXAddClass + ">" + this.atLink(this.emoji(text)) + "</p>\n" );
10 years ago
};
markedRenderer.code = function (code, lang, escaped) {
if (lang === "seq" || lang === "sequence")
10 years ago
{
return "<div class=\"sequence-diagram\">" + code + "</div>";
}
else if ( lang === "flow")
{
return "<div class=\"flowchart\">" + code + "</div>";
}
else
{
return marked.Renderer.prototype.code.apply(this, arguments);
}
};
10 years ago
markedRenderer.tablecell = function(content, flags) {
var type = (flags.header) ? "th" : "td";
var tag = (flags.align) ? "<" + type +" style=\"text-align:" + flags.align + "\">" : "<" + type + ">";
return tag + this.atLink(this.emoji(content)) + "</" + type + ">\n";
};
markedRenderer.listitem = function(text) {
if (settings.taskList && /^\s*\[[x\s]\]\s*/.test(text))
{
text = text.replace(/^\s*\[\s\]\s*/, "<input type=\"checkbox\" class=\"task-list-item-checkbox\" /> ")
.replace(/^\s*\[x\]\s*/, "<input type=\"checkbox\" class=\"task-list-item-checkbox\" checked disabled /> ");
return "<li style=\"list-style: none;\">" + this.atLink(this.emoji(text)) + "</li>";
}
else
{
return "<li>" + this.atLink(this.emoji(text)) + "</li>";
}
};
10 years ago
return markedRenderer;
};
10 years ago
/**
10 years ago
*
10 years ago
* 生成TOC(Table of Contents)
10 years ago
* Creating ToC (Table of Contents)
*
10 years ago
* @param {Array} toc 从marked获取的TOC数组列表
* @param {Element} container 插入TOC的容器元素
* @param {Integer} startLevel Hx 起始层级
* @returns {Object} tocContainer 返回ToC列表容器层的jQuery对象元素
10 years ago
*/
10 years ago
editormd.markdownToCRenderer = function(toc, container, tocDropdown, startLevel) {
var html = "";
var lastLevel = 0;
var classPrefix = this.classPrefix;
10 years ago
10 years ago
startLevel = startLevel || 1;
10 years ago
for (var i = 0, len = toc.length; i < len; i++)
{
var text = toc[i].text;
var level = toc[i].level;
10 years ago
if (level < startLevel) {
continue;
}
10 years ago
10 years ago
if (level > lastLevel)
{
10 years ago
html += "";
10 years ago
}
10 years ago
else if (level < lastLevel)
{
10 years ago
html += (new Array(lastLevel - level + 2)).join("</ul></li>");
10 years ago
}
else
{
10 years ago
html += "</ul></li>";
}
10 years ago
html += "<li><a class=\"toc-level-" + level + "\" href=\"#" + text + "\" level=\"" + level + "\">" + text + "</a><ul>";
10 years ago
lastLevel = level;
}
10 years ago
var tocContainer = container.find(".markdown-toc");
10 years ago
10 years ago
if (tocContainer.length < 1 && container.attr("previewContainer") === "false")
{
var tocHTML = "<div class=\"markdown-toc " + classPrefix + "markdown-toc\"></div>";
tocHTML = (tocDropdown) ? "<div class=\"" + classPrefix + "toc-menu\">" + tocHTML + "</div>" : tocHTML;
container.html(tocHTML);
tocContainer = container.find(".markdown-toc");
}
if (tocDropdown)
{
tocContainer.wrap("<div class=\"" + classPrefix + "toc-menu\"></div><br/>");
}
tocContainer.html("<ul class=\"markdown-toc-list\"></ul>").children(".markdown-toc-list").html(html.replace(/\r?\n?\<ul\>\<\/ul\>/g, ""));
10 years ago
return tocContainer;
10 years ago
};
10 years ago
/**
*
* 生成TOC下拉菜单
* Creating ToC dropdown menu
*
* @param {Object} container 插入TOC的容器jQuery对象元素
* @param {String} tocTitle ToC title
* @returns {Object} return toc-menu object
*/
editormd.tocDropdownMenu = function(container, tocTitle) {
tocTitle = tocTitle || "Table of Contents";
var zindex = 400;
var tocMenus = container.find("." + this.classPrefix + "toc-menu");
tocMenus.each(function() {
var $this = $(this);
var toc = $this.children(".markdown-toc");
var icon = "<i class=\"fa fa-angle-down\"></i>";
var btn = "<a href=\"javascript:;\" class=\"toc-menu-btn\">" + icon + tocTitle + "</a>";
var menu = toc.children("ul");
var list = menu.find("li");
toc.append(btn);
list.first().before("<li><h1>" + tocTitle + " " + icon + "</h1></li>");
$this.mouseover(function(){
menu.show();
list.each(function(){
var li = $(this);
var ul = li.children("ul");
if (ul.html() === "")
{
ul.remove();
}
if (ul.length > 0 && ul.html() !== "")
{
var firstA = li.children("a").first();
if (firstA.children(".fa").length < 1)
{
firstA.append( $(icon).css({ float:"right", paddingTop:"4px" }) );
}
}
li.mouseover(function(){
ul.css("z-index", zindex).show();
zindex += 1;
}).mouseleave(function(){
ul.hide();
});
});
}).mouseleave(function(){
menu.hide();
});
});
return tocMenus;
};
10 years ago
/**
* 简单地过滤指定的HTML标签
* Filter custom html tags
*
* @param {String} html 要过滤HTML
* @param {String} filters 要过滤的标签
* @returns {String} html 返回过滤的HTML
*/
editormd.filterHTMLTags = function(html, filters) {
if (typeof filters === "string")
{
var filterTags = filters.split(",");
for (var i = 0, len = filterTags.length; i < len; i++)
{
var tag = filterTags[i];
html = html.replace(new RegExp("\<\s*"+tag+"\s*([^\>]*)\>", "igm"), "").replace(new RegExp("\<\s*\/"+tag+"\s*\>", "igm"), "");
}
}
return html;
};
10 years ago
/**
* 将Markdown文档解析为HTML用于前台显示
10 years ago
* Parse Markdown to HTML for Font-end preview.
*
10 years ago
* @param {String} id 用于显示HTML的对象ID
* @param {Object} [options={}] 配置选项可选
* @returns {Object} div 返回jQuery对象元素
10 years ago
*/
10 years ago
editormd.markdownToHTML = function(id, options) {
10 years ago
var defaults = {
10 years ago
gfm : true,
10 years ago
toc : true,
10 years ago
tocm : false,
10 years ago
tocStartLevel : 1,
10 years ago
tocTitle : "目录",
tocDropdown : false,
10 years ago
markdown : "",
10 years ago
htmlDecode : false,
10 years ago
autoLoadKaTeX : true,
10 years ago
pageBreak : true,
10 years ago
atLink : true, // for @link
emailLink : true, // for mail address auto link
tex : false,
10 years ago
taskList : false, // Github Flavored Markdown task lists
emoji : false,
10 years ago
flowChart : false,
sequenceDiagram : false,
previewCodeHighlight : true
10 years ago
};
10 years ago
editormd.$marked = marked;
10 years ago
10 years ago
var div = $("#" + id);
10 years ago
var settings = div.settings = $.extend(true, defaults, options || {});
10 years ago
var saveTo = div.find("textarea");
10 years ago
if (saveTo.length < 1)
{
div.append("<textarea></textarea>");
saveTo = div.find("textarea");
}
10 years ago
var markdownDoc = (settings.markdown === "") ? saveTo.val() : settings.markdown;
10 years ago
var markdownToC = [];
10 years ago
10 years ago
var rendererOptions = {
toc : settings.toc,
10 years ago
tocm : settings.tocm,
10 years ago
tocStartLevel : settings.tocStartLevel,
taskList : settings.taskList,
emoji : settings.emoji,
tex : settings.tex,
10 years ago
pageBreak : settings.pageBreak,
10 years ago
atLink : settings.atLink, // for @link
emailLink : settings.emailLink, // for mail address auto link
10 years ago
flowChart : settings.flowChart,
sequenceDiagram : settings.sequenceDiagram,
previewCodeHighlight : settings.previewCodeHighlight,
};
10 years ago
var markedOptions = {
10 years ago
renderer : editormd.markedRenderer(markdownToC, rendererOptions),
gfm : settings.gfm,
10 years ago
tables : true,
10 years ago
breaks : true,
10 years ago
pedantic : false,
10 years ago
sanitize : (settings.htmlDecode) ? false : true, // 是否忽略HTML标签,即是否开启HTML标签解析,为了安全性,默认不开启
10 years ago
smartLists : true,
smartypants : true
10 years ago
};
10 years ago
10 years ago
markdownDoc = editormd.filterHTMLTags(markdownDoc, settings.htmlDecode);
10 years ago
var markdownParsed = marked(markdownDoc, markedOptions);
10 years ago
10 years ago
saveTo.val(markdownDoc);
10 years ago
div.addClass("markdown-body " + this.classPrefix + "html-preview").append(markdownParsed);
10 years ago
if (settings.toc)
{
div.tocContainer = this.markdownToCRenderer(markdownToC, div, settings.tocDropdown, settings.tocStartLevel);
if (settings.tocDropdown || div.find("." + this.classPrefix + "toc-menu").length > 0)
{
this.tocDropdownMenu(div, settings.tocTitle);
}
10 years ago
}
10 years ago
if (settings.previewCodeHighlight)
{
div.find("pre").addClass("prettyprint linenums");
prettyPrint();
}
10 years ago
if (!editormd.isIE8)
{
if (settings.flowChart) {
div.find(".flowchart").flowChart();
}
10 years ago
10 years ago
if (settings.sequenceDiagram) {
div.find(".sequence-diagram").sequenceDiagram({theme: "simple"});
}
10 years ago
}
if (settings.tex)
10 years ago
{
var katexHandle = function() {
div.find("." + editormd.classNames.tex).each(function(){
var tex = $(this);
10 years ago
katex.render(tex.html(), tex[0]);
});
};
10 years ago
if (settings.autoLoadKaTeX && !editormd.$katex && !editormd.kaTeXLoaded)
{
this.loadKaTeX(function() {
editormd.$katex = katex;
editormd.kaTeXLoaded = true;
katexHandle();
});
10 years ago
}
else
{
katexHandle();
}
10 years ago
}
10 years ago
10 years ago
div.getMarkdown = function() {
return saveTo.val();
10 years ago
};
return div;
};
10 years ago
editormd.themes = [
10 years ago
"default", "3024-day", "3024-night",
10 years ago
"ambiance", "ambiance-mobile",
"base16-dark", "base16-light", "blackboard",
"cobalt",
"eclipse", "elegant", "erlang-dark",
"lesser-dark",
"mbo", "mdn-like", "midnight", "monokai",
"neat", "neo", "night",
"paraiso-dark", "paraiso-light", "pastel-on-dark",
"rubyblue",
"solarized",
"the-matrix", "tomorrow-night-eighties", "twilight",
"vibrant-ink",
"xq-dark", "xq-light"
];
editormd.loadPlugins = {};
10 years ago
10 years ago
editormd.loadFiles = {
js : [],
css : [],
plugin : []
10 years ago
};
/**
10 years ago
* 动态加载Editor.md插件但不立即执行
* Load editor.md plugins
*
* @param {String} fileName 插件文件路径
* @param {Function} [callback=function()] 加载成功后执行的回调函数
* @param {String} [into="head"] 嵌入页面的位置
10 years ago
*/
10 years ago
editormd.loadPlugin = function(fileName, callback, into) {
callback = callback || function() {};
10 years ago
this.loadScript(fileName, function() {
editormd.loadFiles.plugin.push(fileName);
callback();
}, into);
10 years ago
};
/**
* 动态加载CSS文件的方法
10 years ago
* Load css file method
*
10 years ago
* @param {String} fileName CSS文件名
* @param {Function} [callback=function()] 加载成功后执行的回调函数
* @param {String} [into="head"] 嵌入页面的位置
*/
editormd.loadCSS = function(fileName, callback, into) {
into = into || "head";
callback = callback || function() {};
var css = document.createElement("link");
css.type = "text/css";
css.rel = "stylesheet";
css.onload = css.onreadystatechange = function() {
10 years ago
editormd.loadFiles.css.push(fileName);
10 years ago
callback();
};
css.href = fileName + ".css";
if(into === "head") {
document.getElementsByTagName("head")[0].appendChild(css);
} else {
document.body.appendChild(css);
}
};
10 years ago
editormd.isIE = (navigator.appName == "Microsoft Internet Explorer");
editormd.isIE8 = (editormd.isIE && navigator.appVersion.match(/8./i) == "8.");
10 years ago
/**
* 动态加载JS文件的方法
10 years ago
* Load javascript file method
*
10 years ago
* @param {String} fileName JS文件名
* @param {Function} [callback=function()] 加载成功后执行的回调函数
* @param {String} [into="head"] 嵌入页面的位置
*/
10 years ago
10 years ago
editormd.loadScript = function(fileName, callback, into) {
into = into || "head";
callback = callback || function() {};
10 years ago
var script = null;
script = document.createElement("script");
script.id = fileName.replace(/[\./]+/g, "-");
script.type = "text/javascript";
script.src = fileName + ".js";
10 years ago
10 years ago
if (editormd.isIE8)
{
10 years ago
script.onreadystatechange = function() {
if(script.readyState)
10 years ago
{
10 years ago
if (script.readyState === "loaded" || script.readyState === "complete")
{
script.onreadystatechange = null;
10 years ago
editormd.loadFiles.js.push(fileName);
10 years ago
callback();
}
}
};
}
else
{
script.onload = function() {
10 years ago
editormd.loadFiles.js.push(fileName);
10 years ago
callback();
10 years ago
};
}
10 years ago
if (into === "head") {
document.getElementsByTagName("head")[0].appendChild(script);
} else {
document.body.appendChild(script);
}
};
// 使用国外的CDN,加载速度有时会很慢,或者自定义URL
10 years ago
// You can custom KaTeX load url.
editormd.katexURL = {
10 years ago
css : "//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.1.1/katex.min",
js : "//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.1.1/katex.min"
10 years ago
};
editormd.kaTeXLoaded = false;
10 years ago
/**
10 years ago
* 加载KaTeX文件
* load KaTeX files
*
10 years ago
* @param {Function} [callback=function()] 加载成功后执行的回调函数
*/
editormd.loadKaTeX = function (callback) {
editormd.loadCSS(editormd.katexURL.css, function(){
editormd.loadScript(editormd.katexURL.js, callback || function(){});
});
10 years ago
};
10 years ago
/**
* 锁屏
* lock screen
*
* @param {Boolean} lock Boolean 布尔值是否锁屏
* @returns {void}
*/
editormd.lockScreen = function(lock) {
$("html,body").css("overflow", (lock) ? "hidden" : "");
};
/**
* 动态创建对话框
* Creating custom dialogs
*
* @param {Object} options 配置项键值对 Key/Value
* @returns {dialog} 返回创建的dialog的jQuery实例对象
*/
editormd.createDialog = function(options) {
var defaults = {
name : "",
width : 420,
height: 240,
title : "",
drag : true,
closed : true,
content : "",
mask : true,
maskStyle : {
backgroundColor : "#fff",
opacity : 0.1
},
lockScreen : true,
footer : true,
buttons : false
};
options = $.extend(true, defaults, options);
var editor = this.editor;
var classPrefix = editormd.classPrefix;
10 years ago
var guid = (new Date()).getTime();
10 years ago
var dialogName = ( (options.name === "") ? classPrefix + "dialog-" + guid : options.name);
var mouseOrTouch = editormd.mouseOrTouch;
var html = "<div class=\"" + classPrefix + "dialog " + dialogName + "\">";
if (options.title !== "")
{
html += "<div class=\"" + classPrefix + "dialog-header\"" + ( (options.drag) ? " style=\"cursor: move;\"" : "" ) + ">";
html += "<strong class=\"" + classPrefix + "dialog-title\">" + options.title + "</strong>";
html += "</div>";
}
if (options.closed)
{
html += "<a href=\"javascript:;\" class=\"fa fa-close " + classPrefix + "dialog-close\"></a>";
}
html += "<div class=\"" + classPrefix + "dialog-container\">" + options.content;
if (options.footer || typeof options.footer === "string")
{
html += "<div class=\"" + classPrefix + "dialog-footer\">" + ( (typeof options.footer === "boolean") ? "" : options.footer) + "</div>";
}
html += "</div>";
html += "<div class=\"" + classPrefix + "dialog-mask " + classPrefix + "dialog-mask-bg\"></div>";
html += "<div class=\"" + classPrefix + "dialog-mask " + classPrefix + "dialog-mask-con\"></div>";
html += "</div>";
editor.append(html);
var dialog = editor.find("." + dialogName);
dialog.lockScreen = function(lock) {
if (options.lockScreen)
{
$("html,body").css("overflow", (lock) ? "hidden" : "");
}
return dialog;
};
dialog.showMask = function() {
if (options.mask)
{
editor.find("." + classPrefix + "mask").css(options.maskStyle).css("z-index", editormd.dialogZindex - 1).show();
}
return dialog;
};
dialog.hideMask = function() {
if (options.mask)
{
editor.find("." + classPrefix + "mask").hide();
}
return dialog;
};
dialog.loading = function(show) {
var loading = dialog.find("." + classPrefix + "dialog-mask");
loading[(show) ? "show" : "hide"]();
return dialog;
};
dialog.lockScreen(true).showMask();
dialog.show().css({
zIndex : editormd.dialogZindex,
border : (editormd.isIE8) ? "1px solid #ddd" : "",
width : (typeof options.width === "number") ? options.width + "px" : options.width,
height : (typeof options.height === "number") ? options.height + "px" : options.height
});
var dialogPosition = function(){
dialog.css({
top : ($(window).height() - dialog.height()) / 2 + "px",
left : ($(window).width() - dialog.width()) / 2 + "px"
});
};
dialogPosition();
$(window).resize(dialogPosition);
dialog.children("." + classPrefix + "dialog-close").bind(mouseOrTouch("click", "touchend"), function() {
dialog.hide().lockScreen(false).hideMask();
});
10 years ago
if (typeof options.buttons === "object")
10 years ago
{
var footer = dialog.footer = dialog.find("." + classPrefix + "dialog-footer");
for (var key in options.buttons)
{
var btn = options.buttons[key];
var btnClassName = classPrefix + key + "-btn";
footer.append("<button class=\"" + classPrefix + "btn " + btnClassName + "\">" + btn[0] + "</button>");
btn[1] = $.proxy(btn[1], dialog);
footer.children("." + btnClassName).bind(mouseOrTouch("click", "touchend"), btn[1]);
}
}
if (options.title !== "" && options.drag)
{
var posX, posY;
var dialogHeader = dialog.children("." + classPrefix + "dialog-header");
if (!options.mask) {
dialogHeader.bind(mouseOrTouch("click", "touchend"), function(){
editormd.dialogZindex += 2;
dialog.css("z-index", editormd.dialogZindex);
});
}
dialogHeader.mousedown(function(e) {
e = e || window.event; //IE
posX = e.clientX - parseInt(dialog[0].style.left);
posY = e.clientY - parseInt(dialog[0].style.top);
document.onmousemove = moveAction;
});
var userCanSelect = function (obj) {
obj.removeClass(classPrefix + "user-unselect").off("selectstart");
10 years ago
};
10 years ago
var userUnselect = function (obj) {
obj.addClass(classPrefix + "user-unselect").on("selectstart", function(event) { // selectstart for IE
return false;
});
10 years ago
};
10 years ago
var moveAction = function (e) {
e = e || window.event; //IE
var left, top, nowLeft = parseInt(dialog[0].style.left), nowTop = parseInt(dialog[0].style.top);
if( nowLeft >= 0 ) {
if( nowLeft + dialog.width() <= $(window).width()) {
left = e.clientX - posX;
} else {
left = $(window).width() - dialog.width();
document.onmousemove = null;
}
} else {
left = 0;
document.onmousemove = null;
}
if( nowTop >= 0 ) {
top = e.clientY - posY;
} else {
top = 0;
document.onmousemove = null;
}
document.onselectstart = function() {
return false;
};
userUnselect($("body"));
userUnselect(dialog);
dialog[0].style.left = left + "px";
dialog[0].style.top = top + "px";
10 years ago
};
10 years ago
document.onmouseup = function() {
userCanSelect($("body"));
userCanSelect(dialog);
document.onselectstart = null;
document.onmousemove = null;
};
dialogHeader.touchDraggable = function() {
var offset = null;
var start = function(e) {
var orig = e.originalEvent;
var pos = $(this).parent().position();
offset = {
x : orig.changedTouches[0].pageX - pos.left,
y : orig.changedTouches[0].pageY - pos.top
};
};
var move = function(e) {
e.preventDefault();
var orig = e.originalEvent;
$(this).parent().css({
top : orig.changedTouches[0].pageY - offset.y,
left : orig.changedTouches[0].pageX - offset.x
});
};
this.bind("touchstart", start).bind("touchmove", move);
};
dialogHeader.touchDraggable();
}
editormd.dialogZindex += 2;
return dialog;
};
10 years ago
/**
* 鼠标和触摸事件的判断/选择方法
10 years ago
* MouseEvent or TouchEvent type switch
*
10 years ago
* @param {String} [mouseEventType="click"] 供选择的鼠标事件
* @param {String} [touchEventType="touchend"] 供选择的触摸事件
* @returns {String} EventType 返回事件类型名称
*/
editormd.mouseOrTouch = function(mouseEventType, touchEventType) {
mouseEventType = mouseEventType || "click";
touchEventType = touchEventType || "touchend";
var eventType = mouseEventType;
10 years ago
try {
10 years ago
document.createEvent("TouchEvent");
eventType = touchEventType;
10 years ago
} catch(e) {}
10 years ago
return eventType;
10 years ago
};
10 years ago
/**
* 日期时间的格式化方法
10 years ago
* Datetime format method
*
10 years ago
* @param {String} [format=""] 日期时间的格式类似PHP的格式
* @returns {String} datefmt 返回格式化后的日期时间字符串
*/
editormd.dateFormat = function(format) {
format = format || "";
var addZero = function(d) {
return (d < 10) ? "0" + d : d;
};
10 years ago
var date = new Date();
10 years ago
var year = date.getFullYear();
var year2 = year.toString().slice(2, 4);
var month = addZero(date.getMonth() + 1);
var day = addZero(date.getDate());
var weekDay = date.getDay();
var hour = addZero(date.getHours());
var min = addZero(date.getMinutes());
var second = addZero(date.getSeconds());
var ms = addZero(date.getMilliseconds());
var datefmt = "";
var ymd = year2 + "-" + month + "-" + day;
var fymd = year + "-" + month + "-" + day;
var hms = hour + ":" + min + ":" + second;
switch (format)
{
case "UNIX Time" :
datefmt = date.getTime();
break;
case "UTC" :
datefmt = date.toUTCString();
break;
case "yy" :
datefmt = year2;
break;
case "year" :
case "yyyy" :
datefmt = year;
break;
case "month" :
case "mm" :
datefmt = month;
break;
case "cn-week-day" :
case "cn-wd" :
var cnWeekDays = ["日", "一", "二", "三", "四", "五", "六"];
datefmt = "星期" + cnWeekDays[weekDay];
break;
case "week-day" :
case "wd" :
10 years ago
var weekDays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
datefmt = weekDays[weekDay];
10 years ago
break;
case "day" :
case "dd" :
datefmt = day;
break;
case "hour" :
case "hh" :
datefmt = hour;
break;
case "min" :
case "ii" :
datefmt = min;
break;
case "second" :
case "ss" :
datefmt = second;
break;
case "ms" :
datefmt = ms;
10 years ago
break;
10 years ago
case "yy-mm-dd" :
datefmt = ymd;
break;
case "yyyy-mm-dd" :
datefmt = fymd;
break;
case "yyyy-mm-dd h:i:s ms" :
case "full + ms" :
datefmt = fymd + " " + hms + " " + ms;
10 years ago
break;
10 years ago
case "full" :
case "yyyy-mm-dd h:i:s" :
default:
datefmt = fymd + " " + hms;
10 years ago
break;
}
10 years ago
return datefmt;
};
10 years ago
10 years ago
return editormd;
10 years ago
10 years ago
}));