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.

4621 lines
156 KiB

3 years ago
  1. /*
  2. * Editor.md
  3. *
  4. * @file editormd.js
  5. * @version v1.5.0
  6. * @description Open source online markdown editor.
  7. * @license MIT License
  8. * @author Pandao
  9. * {@link https://github.com/pandao/editor.md}
  10. * @updateTime 2015-06-09
  11. */
  12. ;(function(factory) {
  13. "use strict";
  14. // CommonJS/Node.js
  15. if (typeof require === "function" && typeof exports === "object" && typeof module === "object")
  16. {
  17. module.exports = factory;
  18. }
  19. else if (typeof define === "function") // AMD/CMD/Sea.js
  20. {
  21. if (define.amd) // for Require.js
  22. {
  23. /* Require.js define replace */
  24. }
  25. else
  26. {
  27. define(["jquery"], factory); // for Sea.js
  28. }
  29. }
  30. else
  31. {
  32. window.editormd = factory();
  33. }
  34. }(function() {
  35. /* Require.js assignment replace */
  36. "use strict";
  37. var $ = (typeof (jQuery) !== "undefined") ? jQuery : Zepto;
  38. if (typeof ($) === "undefined") {
  39. return ;
  40. }
  41. /**
  42. * editormd
  43. *
  44. * @param {String} id 编辑器的ID
  45. * @param {Object} options 配置选项 Key/Value
  46. * @returns {Object} editormd 返回editormd对象
  47. */
  48. var editormd = function (id, options) {
  49. return new editormd.fn.init(id, options);
  50. };
  51. editormd.title = editormd.$name = "Editor.md";
  52. editormd.version = "1.5.0";
  53. editormd.homePage = "https://pandao.github.io/editor.md/";
  54. editormd.classPrefix = "editormd-";
  55. editormd.toolbarModes = {
  56. full : [
  57. "undo", "redo", "|",
  58. "bold", "del", "italic", "quote", "ucwords", "uppercase", "lowercase", "|",
  59. "h1", "h2", "h3", "h4", "h5", "h6", "|",
  60. "list-ul", "list-ol", "hr", "|",
  61. "link", "reference-link", "image", "code", "preformatted-text", "code-block", "table", "datetime", "emoji", "html-entities", "pagebreak", "|",
  62. "goto-line", "watch", "preview", "fullscreen", "clear", "search", "|",
  63. "help", "info"
  64. ],
  65. simple : [
  66. "undo", "redo", "|",
  67. "bold", "del", "italic", "quote", "uppercase", "lowercase", "|",
  68. "h1", "h2", "h3", "h4", "h5", "h6", "|",
  69. "list-ul", "list-ol", "hr", "|",
  70. "watch", "preview", "fullscreen", "|",
  71. "help", "info"
  72. ],
  73. mini : [
  74. "undo", "redo", "|",
  75. "watch", "preview", "|",
  76. "help", "info"
  77. ]
  78. };
  79. editormd.defaults = {
  80. mode : "gfm", //gfm or markdown
  81. name : "", // Form element name
  82. value : "", // value for CodeMirror, if mode not gfm/markdown
  83. theme : "", // Editor.md self themes, before v1.5.0 is CodeMirror theme, default empty
  84. editorTheme : "default", // Editor area, this is CodeMirror theme at v1.5.0
  85. previewTheme : "", // Preview area theme, default empty
  86. markdown : "", // Markdown source code
  87. appendMarkdown : "", // if in init textarea value not empty, append markdown to textarea
  88. width : "100%",
  89. height : "100%",
  90. path : "./lib/", // Dependents module file directory
  91. pluginPath : "", // If this empty, default use settings.path + "../plugins/"
  92. delay : 300, // Delay parse markdown to html, Uint : ms
  93. autoLoadModules : true, // Automatic load dependent module files
  94. watch : true,
  95. placeholder : "Enjoy Markdown! coding now...",
  96. gotoLine : true,
  97. codeFold : false,
  98. autoHeight : false,
  99. autoFocus : true,
  100. autoCloseTags : true,
  101. searchReplace : true,
  102. syncScrolling : true, // true | false | "single", default true
  103. readOnly : false,
  104. tabSize : 4,
  105. indentUnit : 4,
  106. lineNumbers : true,
  107. lineWrapping : true,
  108. autoCloseBrackets : true,
  109. showTrailingSpace : true,
  110. matchBrackets : true,
  111. indentWithTabs : true,
  112. styleSelectedText : true,
  113. matchWordHighlight : true, // options: true, false, "onselected"
  114. styleActiveLine : true, // Highlight the current line
  115. dialogLockScreen : true,
  116. dialogShowMask : true,
  117. dialogDraggable : true,
  118. dialogMaskBgColor : "#fff",
  119. dialogMaskOpacity : 0.1,
  120. fontSize : "13px",
  121. saveHTMLToTextarea : false,
  122. disabledKeyMaps : [],
  123. onload : function() {},
  124. onresize : function() {},
  125. onchange : function() {},
  126. onwatch : null,
  127. onunwatch : null,
  128. onpreviewing : function() {},
  129. onpreviewed : function() {},
  130. onfullscreen : function() {},
  131. onfullscreenExit : function() {},
  132. onscroll : function() {},
  133. onpreviewscroll : function() {},
  134. imageUpload : false,
  135. imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
  136. imageUploadURL : "",
  137. crossDomainUpload : false,
  138. uploadCallbackURL : "",
  139. toc : true, // Table of contents
  140. tocm : false, // Using [TOCM], auto create ToC dropdown menu
  141. tocTitle : "", // for ToC dropdown menu btn
  142. tocDropdown : false,
  143. tocContainer : "",
  144. tocStartLevel : 1, // Said from H1 to create ToC
  145. htmlDecode : false, // Open the HTML tag identification
  146. pageBreak : true, // Enable parse page break [========]
  147. atLink : true, // for @link
  148. emailLink : true, // for email address auto link
  149. taskList : false, // Enable Github Flavored Markdown task lists
  150. emoji : false, // :emoji: , Support Github emoji, Twitter Emoji (Twemoji);
  151. // Support FontAwesome icon emoji :fa-xxx: > Using fontAwesome icon web fonts;
  152. // Support Editor.md logo icon emoji :editormd-logo: :editormd-logo-1x: > 1~8x;
  153. tex : false, // TeX(LaTeX), based on KaTeX
  154. flowChart : false, // flowChart.js only support IE9+
  155. sequenceDiagram : false, // sequenceDiagram.js only support IE9+
  156. previewCodeHighlight : true,
  157. toolbar : true, // show/hide toolbar
  158. toolbarAutoFixed : true, // on window scroll auto fixed position
  159. toolbarIcons : "full",
  160. toolbarTitles : {},
  161. toolbarHandlers : {
  162. ucwords : function() {
  163. return editormd.toolbarHandlers.ucwords;
  164. },
  165. lowercase : function() {
  166. return editormd.toolbarHandlers.lowercase;
  167. }
  168. },
  169. toolbarCustomIcons : { // using html tag create toolbar icon, unused default <a> tag.
  170. lowercase : "<a href=\"javascript:;\" title=\"Lowercase\" unselectable=\"on\"><i class=\"fa\" name=\"lowercase\" style=\"font-size:24px;margin-top: -10px;\">a</i></a>",
  171. "ucwords" : "<a href=\"javascript:;\" title=\"ucwords\" unselectable=\"on\"><i class=\"fa\" name=\"ucwords\" style=\"font-size:20px;margin-top: -3px;\">Aa</i></a>"
  172. },
  173. toolbarIconsClass : {
  174. undo : "fa-undo",
  175. redo : "fa-repeat",
  176. bold : "fa-bold",
  177. del : "fa-strikethrough",
  178. italic : "fa-italic",
  179. quote : "fa-quote-left",
  180. uppercase : "fa-font",
  181. h1 : editormd.classPrefix + "bold",
  182. h2 : editormd.classPrefix + "bold",
  183. h3 : editormd.classPrefix + "bold",
  184. h4 : editormd.classPrefix + "bold",
  185. h5 : editormd.classPrefix + "bold",
  186. h6 : editormd.classPrefix + "bold",
  187. "list-ul" : "fa-list-ul",
  188. "list-ol" : "fa-list-ol",
  189. hr : "fa-minus",
  190. link : "fa-link",
  191. "reference-link" : "fa-anchor",
  192. image : "fa-picture-o",
  193. code : "fa-code",
  194. "preformatted-text" : "fa-file-code-o",
  195. "code-block" : "fa-file-code-o",
  196. table : "fa-table",
  197. datetime : "fa-clock-o",
  198. emoji : "fa-smile-o",
  199. "html-entities" : "fa-copyright",
  200. pagebreak : "fa-newspaper-o",
  201. "goto-line" : "fa-terminal", // fa-crosshairs
  202. watch : "fa-eye-slash",
  203. unwatch : "fa-eye",
  204. preview : "fa-desktop",
  205. search : "fa-search",
  206. fullscreen : "fa-arrows-alt",
  207. clear : "fa-eraser",
  208. help : "fa-question-circle",
  209. info : "fa-info-circle"
  210. },
  211. toolbarIconTexts : {},
  212. lang : {
  213. name : "zh-cn",
  214. description : "开源在线Markdown编辑器<br/>Open source online Markdown editor.",
  215. tocTitle : "目录",
  216. toolbar : {
  217. undo : "撤销(Ctrl+Z)",
  218. redo : "重做(Ctrl+Y)",
  219. bold : "粗体",
  220. del : "删除线",
  221. italic : "斜体",
  222. quote : "引用",
  223. ucwords : "将每个单词首字母转成大写",
  224. uppercase : "将所选转换成大写",
  225. lowercase : "将所选转换成小写",
  226. h1 : "标题1",
  227. h2 : "标题2",
  228. h3 : "标题3",
  229. h4 : "标题4",
  230. h5 : "标题5",
  231. h6 : "标题6",
  232. "list-ul" : "无序列表",
  233. "list-ol" : "有序列表",
  234. hr : "横线",
  235. link : "链接",
  236. "reference-link" : "引用链接",
  237. image : "添加图片",
  238. code : "行内代码",
  239. "preformatted-text" : "预格式文本 / 代码块(缩进风格)",
  240. "code-block" : "代码块(多语言风格)",
  241. table : "添加表格",
  242. datetime : "日期时间",
  243. emoji : "Emoji表情",
  244. "html-entities" : "HTML实体字符",
  245. pagebreak : "插入分页符",
  246. "goto-line" : "跳转到行",
  247. watch : "关闭实时预览",
  248. unwatch : "开启实时预览",
  249. preview : "全窗口预览HTML(按 Shift + ESC还原)",
  250. fullscreen : "全屏(按ESC还原)",
  251. clear : "清空",
  252. search : "搜索",
  253. help : "使用帮助",
  254. info : "关于" + editormd.title
  255. },
  256. buttons : {
  257. enter : "确定",
  258. cancel : "取消",
  259. close : "关闭"
  260. },
  261. dialog : {
  262. link : {
  263. title : "添加链接",
  264. url : "链接地址",
  265. urlTitle : "链接标题",
  266. urlEmpty : "错误:请填写链接地址。"
  267. },
  268. referenceLink : {
  269. title : "添加引用链接",
  270. name : "引用名称",
  271. url : "链接地址",
  272. urlId : "链接ID",
  273. urlTitle : "链接标题",
  274. nameEmpty: "错误:引用链接的名称不能为空。",
  275. idEmpty : "错误:请填写引用链接的ID。",
  276. urlEmpty : "错误:请填写引用链接的URL地址。"
  277. },
  278. image : {
  279. title : "添加图片",
  280. url : "图片地址",
  281. link : "图片链接",
  282. alt : "图片描述",
  283. uploadButton : "本地上传",
  284. imageURLEmpty : "错误:图片地址不能为空。",
  285. uploadFileEmpty : "错误:上传的图片不能为空。",
  286. formatNotAllowed : "错误:只允许上传图片文件,允许上传的图片文件格式有:"
  287. },
  288. preformattedText : {
  289. title : "添加预格式文本或代码块",
  290. emptyAlert : "错误:请填写预格式文本或代码的内容。"
  291. },
  292. codeBlock : {
  293. title : "添加代码块",
  294. selectLabel : "代码语言:",
  295. selectDefaultText : "请选择代码语言",
  296. otherLanguage : "其他语言",
  297. unselectedLanguageAlert : "错误:请选择代码所属的语言类型。",
  298. codeEmptyAlert : "错误:请填写代码内容。"
  299. },
  300. htmlEntities : {
  301. title : "HTML 实体字符"
  302. },
  303. help : {
  304. title : "使用帮助"
  305. }
  306. }
  307. }
  308. };
  309. editormd.classNames = {
  310. tex : editormd.classPrefix + "tex"
  311. };
  312. editormd.dialogZindex = 99999;
  313. editormd.$katex = null;
  314. editormd.$marked = null;
  315. editormd.$CodeMirror = null;
  316. editormd.$prettyPrint = null;
  317. var timer, flowchartTimer;
  318. editormd.prototype = editormd.fn = {
  319. state : {
  320. watching : false,
  321. loaded : false,
  322. preview : false,
  323. fullscreen : false
  324. },
  325. /**
  326. * 构造函数/实例初始化
  327. * Constructor / instance initialization
  328. *
  329. * @param {String} id 编辑器的ID
  330. * @param {Object} [options={}] 配置选项 Key/Value
  331. * @returns {editormd} 返回editormd的实例对象
  332. */
  333. init : function (id, options) {
  334. options = options || {};
  335. if (typeof id === "object")
  336. {
  337. options = id;
  338. }
  339. var _this = this;
  340. var classPrefix = this.classPrefix = editormd.classPrefix;
  341. var settings = this.settings = $.extend(true, editormd.defaults, options);
  342. id = (typeof id === "object") ? settings.id : id;
  343. var editor = this.editor = $("#" + id);
  344. this.id = id;
  345. this.lang = settings.lang;
  346. var classNames = this.classNames = {
  347. textarea : {
  348. html : classPrefix + "html-textarea",
  349. markdown : classPrefix + "markdown-textarea"
  350. }
  351. };
  352. settings.pluginPath = (settings.pluginPath === "") ? settings.path + "../plugins/" : settings.pluginPath;
  353. this.state.watching = (settings.watch) ? true : false;
  354. if ( !editor.hasClass("editormd") ) {
  355. editor.addClass("editormd");
  356. }
  357. editor.css({
  358. width : (typeof settings.width === "number") ? settings.width + "px" : settings.width,
  359. height : (typeof settings.height === "number") ? settings.height + "px" : settings.height
  360. });
  361. if (settings.autoHeight)
  362. {
  363. editor.css("height", "auto");
  364. }
  365. var markdownTextarea = this.markdownTextarea = editor.children("textarea");
  366. if (markdownTextarea.length < 1)
  367. {
  368. editor.append("<textarea></textarea>");
  369. markdownTextarea = this.markdownTextarea = editor.children("textarea");
  370. }
  371. markdownTextarea.addClass(classNames.textarea.markdown).attr("placeholder", settings.placeholder);
  372. if (typeof markdownTextarea.attr("name") === "undefined" || markdownTextarea.attr("name") === "")
  373. {
  374. markdownTextarea.attr("name", (settings.name !== "") ? settings.name : id + "-markdown-doc");
  375. }
  376. var appendElements = [
  377. (!settings.readOnly) ? "<a href=\"javascript:;\" class=\"fa fa-close " + classPrefix + "preview-close-btn\"></a>" : "",
  378. ( (settings.saveHTMLToTextarea) ? "<textarea class=\"" + classNames.textarea.html + "\" name=\"" + id + "-html-code\"></textarea>" : "" ),
  379. "<div class=\"" + classPrefix + "preview\"><div class=\"markdown-body " + classPrefix + "preview-container\"></div></div>",
  380. "<div class=\"" + classPrefix + "container-mask\" style=\"display:block;\"></div>",
  381. "<div class=\"" + classPrefix + "mask\"></div>"
  382. ].join("\n");
  383. editor.append(appendElements).addClass(classPrefix + "vertical");
  384. if (settings.theme !== "")
  385. {
  386. editor.addClass(classPrefix + "theme-" + settings.theme);
  387. }
  388. this.mask = editor.children("." + classPrefix + "mask");
  389. this.containerMask = editor.children("." + classPrefix + "container-mask");
  390. if (settings.markdown !== "")
  391. {
  392. markdownTextarea.val(settings.markdown);
  393. }
  394. if (settings.appendMarkdown !== "")
  395. {
  396. markdownTextarea.val(markdownTextarea.val() + settings.appendMarkdown);
  397. }
  398. this.htmlTextarea = editor.children("." + classNames.textarea.html);
  399. this.preview = editor.children("." + classPrefix + "preview");
  400. this.previewContainer = this.preview.children("." + classPrefix + "preview-container");
  401. if (settings.previewTheme !== "")
  402. {
  403. this.preview.addClass(classPrefix + "preview-theme-" + settings.previewTheme);
  404. }
  405. if (typeof define === "function" && define.amd)
  406. {
  407. if (typeof katex !== "undefined")
  408. {
  409. editormd.$katex = katex;
  410. }
  411. if (settings.searchReplace && !settings.readOnly)
  412. {
  413. editormd.loadCSS(settings.path + "codemirror/addon/dialog/dialog");
  414. editormd.loadCSS(settings.path + "codemirror/addon/search/matchesonscrollbar");
  415. }
  416. }
  417. if ((typeof define === "function" && define.amd) || !settings.autoLoadModules)
  418. {
  419. if (typeof CodeMirror !== "undefined") {
  420. editormd.$CodeMirror = CodeMirror;
  421. }
  422. if (typeof marked !== "undefined") {
  423. editormd.$marked = marked;
  424. }
  425. this.setCodeMirror().setToolbar().loadedDisplay();
  426. }
  427. else
  428. {
  429. this.loadQueues();
  430. }
  431. return this;
  432. },
  433. /**
  434. * 所需组件加载队列
  435. * Required components loading queue
  436. *
  437. * @returns {editormd} 返回editormd的实例对象
  438. */
  439. loadQueues : function() {
  440. var _this = this;
  441. var settings = this.settings;
  442. var loadPath = settings.path;
  443. var loadFlowChartOrSequenceDiagram = function() {
  444. if (editormd.isIE8)
  445. {
  446. _this.loadedDisplay();
  447. return ;
  448. }
  449. if (settings.flowChart || settings.sequenceDiagram)
  450. {
  451. editormd.loadScript(loadPath + "raphael.min", function() {
  452. editormd.loadScript(loadPath + "underscore.min", function() {
  453. if (!settings.flowChart && settings.sequenceDiagram)
  454. {
  455. editormd.loadScript(loadPath + "sequence-diagram.min", function() {
  456. _this.loadedDisplay();
  457. });
  458. }
  459. else if (settings.flowChart && !settings.sequenceDiagram)
  460. {
  461. editormd.loadScript(loadPath + "flowchart.min", function() {
  462. editormd.loadScript(loadPath + "jquery.flowchart.min", function() {
  463. _this.loadedDisplay();
  464. });
  465. });
  466. }
  467. else if (settings.flowChart && settings.sequenceDiagram)
  468. {
  469. editormd.loadScript(loadPath + "flowchart.min", function() {
  470. editormd.loadScript(loadPath + "jquery.flowchart.min", function() {
  471. editormd.loadScript(loadPath + "sequence-diagram.min", function() {
  472. _this.loadedDisplay();
  473. });
  474. });
  475. });
  476. }
  477. });
  478. });
  479. }
  480. else
  481. {
  482. _this.loadedDisplay();
  483. }
  484. };
  485. editormd.loadCSS(loadPath + "codemirror/codemirror.min");
  486. if (settings.searchReplace && !settings.readOnly)
  487. {
  488. editormd.loadCSS(loadPath + "codemirror/addon/dialog/dialog");
  489. editormd.loadCSS(loadPath + "codemirror/addon/search/matchesonscrollbar");
  490. }
  491. if (settings.codeFold)
  492. {
  493. editormd.loadCSS(loadPath + "codemirror/addon/fold/foldgutter");
  494. }
  495. editormd.loadScript(loadPath + "codemirror/codemirror.min", function() {
  496. editormd.$CodeMirror = CodeMirror;
  497. editormd.loadScript(loadPath + "codemirror/modes.min", function() {
  498. editormd.loadScript(loadPath + "codemirror/addons.min", function() {
  499. _this.setCodeMirror();
  500. if (settings.mode !== "gfm" && settings.mode !== "markdown")
  501. {
  502. _this.loadedDisplay();
  503. return false;
  504. }
  505. _this.setToolbar();
  506. editormd.loadScript(loadPath + "marked.min", function() {
  507. editormd.$marked = marked;
  508. if (settings.previewCodeHighlight)
  509. {
  510. editormd.loadScript(loadPath + "prettify.min", function() {
  511. loadFlowChartOrSequenceDiagram();
  512. });
  513. }
  514. else
  515. {
  516. loadFlowChartOrSequenceDiagram();
  517. }
  518. });
  519. });
  520. });
  521. });
  522. return this;
  523. },
  524. /**
  525. * 设置 Editor.md 的整体主题主要是工具栏
  526. * Setting Editor.md theme
  527. *
  528. * @returns {editormd} 返回editormd的实例对象
  529. */
  530. setTheme : function(theme) {
  531. var editor = this.editor;
  532. var oldTheme = this.settings.theme;
  533. var themePrefix = this.classPrefix + "theme-";
  534. editor.removeClass(themePrefix + oldTheme).addClass(themePrefix + theme);
  535. this.settings.theme = theme;
  536. return this;
  537. },
  538. /**
  539. * 设置 CodeMirror编辑区的主题
  540. * Setting CodeMirror (Editor area) theme
  541. *
  542. * @returns {editormd} 返回editormd的实例对象
  543. */
  544. setEditorTheme : function(theme) {
  545. var settings = this.settings;
  546. settings.editorTheme = theme;
  547. if (theme !== "default")
  548. {
  549. editormd.loadCSS(settings.path + "codemirror/theme/" + settings.editorTheme);
  550. }
  551. this.cm.setOption("theme", theme);
  552. return this;
  553. },
  554. /**
  555. * setEditorTheme() 的别名
  556. * setEditorTheme() alias
  557. *
  558. * @returns {editormd} 返回editormd的实例对象
  559. */
  560. setCodeMirrorTheme : function (theme) {
  561. this.setEditorTheme(theme);
  562. return this;
  563. },
  564. /**
  565. * 设置 Editor.md 的主题
  566. * Setting Editor.md theme
  567. *
  568. * @returns {editormd} 返回editormd的实例对象
  569. */
  570. setPreviewTheme : function(theme) {
  571. var preview = this.preview;
  572. var oldTheme = this.settings.previewTheme;
  573. var themePrefix = this.classPrefix + "preview-theme-";
  574. preview.removeClass(themePrefix + oldTheme).addClass(themePrefix + theme);
  575. this.settings.previewTheme = theme;
  576. return this;
  577. },
  578. /**
  579. * 配置和初始化CodeMirror组件
  580. * CodeMirror initialization
  581. *
  582. * @returns {editormd} 返回editormd的实例对象
  583. */
  584. setCodeMirror : function() {
  585. var settings = this.settings;
  586. var editor = this.editor;
  587. if (settings.editorTheme !== "default")
  588. {
  589. editormd.loadCSS(settings.path + "codemirror/theme/" + settings.editorTheme);
  590. }
  591. var codeMirrorConfig = {
  592. mode : settings.mode,
  593. theme : settings.editorTheme,
  594. tabSize : settings.tabSize,
  595. dragDrop : false,
  596. autofocus : settings.autoFocus,
  597. autoCloseTags : settings.autoCloseTags,
  598. readOnly : (settings.readOnly) ? "nocursor" : false,
  599. indentUnit : settings.indentUnit,
  600. lineNumbers : settings.lineNumbers,
  601. lineWrapping : settings.lineWrapping,
  602. extraKeys : {
  603. "Ctrl-Q": function(cm) {
  604. cm.foldCode(cm.getCursor());
  605. }
  606. },
  607. foldGutter : settings.codeFold,
  608. gutters : ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
  609. matchBrackets : settings.matchBrackets,
  610. indentWithTabs : settings.indentWithTabs,
  611. styleActiveLine : settings.styleActiveLine,
  612. styleSelectedText : settings.styleSelectedText,
  613. autoCloseBrackets : settings.autoCloseBrackets,
  614. showTrailingSpace : settings.showTrailingSpace,
  615. highlightSelectionMatches : ( (!settings.matchWordHighlight) ? false : { showToken: (settings.matchWordHighlight === "onselected") ? false : /\w/ } )
  616. };
  617. this.codeEditor = this.cm = editormd.$CodeMirror.fromTextArea(this.markdownTextarea[0], codeMirrorConfig);
  618. this.codeMirror = this.cmElement = editor.children(".CodeMirror");
  619. if (settings.value !== "")
  620. {
  621. this.cm.setValue(settings.value);
  622. }
  623. this.codeMirror.css({
  624. fontSize : settings.fontSize,
  625. width : (!settings.watch) ? "100%" : "50%"
  626. });
  627. if (settings.autoHeight)
  628. {
  629. this.codeMirror.css("height", "auto");
  630. this.cm.setOption("viewportMargin", Infinity);
  631. }
  632. if (!settings.lineNumbers)
  633. {
  634. this.codeMirror.find(".CodeMirror-gutters").css("border-right", "none");
  635. }
  636. return this;
  637. },
  638. /**
  639. * 获取CodeMirror的配置选项
  640. * Get CodeMirror setting options
  641. *
  642. * @returns {Mixed} return CodeMirror setting option value
  643. */
  644. getCodeMirrorOption : function(key) {
  645. return this.cm.getOption(key);
  646. },
  647. /**
  648. * 配置和重配置CodeMirror的选项
  649. * CodeMirror setting options / resettings
  650. *
  651. * @returns {editormd} 返回editormd的实例对象
  652. */
  653. setCodeMirrorOption : function(key, value) {
  654. this.cm.setOption(key, value);
  655. return this;
  656. },
  657. /**
  658. * 添加 CodeMirror 键盘快捷键
  659. * Add CodeMirror keyboard shortcuts key map
  660. *
  661. * @returns {editormd} 返回editormd的实例对象
  662. */
  663. addKeyMap : function(map, bottom) {
  664. this.cm.addKeyMap(map, bottom);
  665. return this;
  666. },
  667. /**
  668. * 移除 CodeMirror 键盘快捷键
  669. * Remove CodeMirror keyboard shortcuts key map
  670. *
  671. * @returns {editormd} 返回editormd的实例对象
  672. */
  673. removeKeyMap : function(map) {
  674. this.cm.removeKeyMap(map);
  675. return this;
  676. },
  677. /**
  678. * 跳转到指定的行
  679. * Goto CodeMirror line
  680. *
  681. * @param {String|Intiger} line line number or "first"|"last"
  682. * @returns {editormd} 返回editormd的实例对象
  683. */
  684. gotoLine : function (line) {
  685. var settings = this.settings;
  686. if (!settings.gotoLine)
  687. {
  688. return this;
  689. }
  690. var cm = this.cm;
  691. var editor = this.editor;
  692. var count = cm.lineCount();
  693. var preview = this.preview;
  694. if (typeof line === "string")
  695. {
  696. if(line === "last")
  697. {
  698. line = count;
  699. }
  700. if (line === "first")
  701. {
  702. line = 1;
  703. }
  704. }
  705. if (typeof line !== "number")
  706. {
  707. alert("Error: The line number must be an integer.");
  708. return this;
  709. }
  710. line = parseInt(line) - 1;
  711. if (line > count)
  712. {
  713. alert("Error: The line number range 1-" + count);
  714. return this;
  715. }
  716. cm.setCursor( {line : line, ch : 0} );
  717. var scrollInfo = cm.getScrollInfo();
  718. var clientHeight = scrollInfo.clientHeight;
  719. var coords = cm.charCoords({line : line, ch : 0}, "local");
  720. cm.scrollTo(null, (coords.top + coords.bottom - clientHeight) / 2);
  721. if (settings.watch)
  722. {
  723. var cmScroll = this.codeMirror.find(".CodeMirror-scroll")[0];
  724. var height = $(cmScroll).height();
  725. var scrollTop = cmScroll.scrollTop;
  726. var percent = (scrollTop / cmScroll.scrollHeight);
  727. if (scrollTop === 0)
  728. {
  729. preview.scrollTop(0);
  730. }
  731. else if (scrollTop + height >= cmScroll.scrollHeight - 16)
  732. {
  733. preview.scrollTop(preview[0].scrollHeight);
  734. }
  735. else
  736. {
  737. preview.scrollTop(preview[0].scrollHeight * percent);
  738. }
  739. }
  740. cm.focus();
  741. return this;
  742. },
  743. /**
  744. * 扩展当前实例对象可同时设置多个或者只设置一个
  745. * Extend editormd instance object, can mutil setting.
  746. *
  747. * @returns {editormd} this(editormd instance object.)
  748. */
  749. extend : function() {
  750. if (typeof arguments[1] !== "undefined")
  751. {
  752. if (typeof arguments[1] === "function")
  753. {
  754. arguments[1] = $.proxy(arguments[1], this);
  755. }
  756. this[arguments[0]] = arguments[1];
  757. }
  758. if (typeof arguments[0] === "object" && typeof arguments[0].length === "undefined")
  759. {
  760. $.extend(true, this, arguments[0]);
  761. }
  762. return this;
  763. },
  764. /**
  765. * 设置或扩展当前实例对象单个设置
  766. * Extend editormd instance object, one by one
  767. *
  768. * @param {String|Object} key option key
  769. * @param {String|Object} value option value
  770. * @returns {editormd} this(editormd instance object.)
  771. */
  772. set : function (key, value) {
  773. if (typeof value !== "undefined" && typeof value === "function")
  774. {
  775. value = $.proxy(value, this);
  776. }
  777. this[key] = value;
  778. return this;
  779. },
  780. /**
  781. * 重新配置
  782. * Resetting editor options
  783. *
  784. * @param {String|Object} key option key
  785. * @param {String|Object} value option value
  786. * @returns {editormd} this(editormd instance object.)
  787. */
  788. config : function(key, value) {
  789. var settings = this.settings;
  790. if (typeof key === "object")
  791. {
  792. settings = $.extend(true, settings, key);
  793. }
  794. if (typeof key === "string")
  795. {
  796. settings[key] = value;
  797. }
  798. this.settings = settings;
  799. this.recreate();
  800. return this;
  801. },
  802. /**
  803. * 注册事件处理方法
  804. * Bind editor event handle
  805. *
  806. * @param {String} eventType event type
  807. * @param {Function} callback 回调函数
  808. * @returns {editormd} this(editormd instance object.)
  809. */
  810. on : function(eventType, callback) {
  811. var settings = this.settings;
  812. if (typeof settings["on" + eventType] !== "undefined")
  813. {
  814. settings["on" + eventType] = $.proxy(callback, this);
  815. }
  816. return this;
  817. },
  818. /**
  819. * 解除事件处理方法
  820. * Unbind editor event handle
  821. *
  822. * @param {String} eventType event type
  823. * @returns {editormd} this(editormd instance object.)
  824. */
  825. off : function(eventType) {
  826. var settings = this.settings;
  827. if (typeof settings["on" + eventType] !== "undefined")
  828. {
  829. settings["on" + eventType] = function(){};
  830. }
  831. return this;
  832. },
  833. /**
  834. * 显示工具栏
  835. * Display toolbar
  836. *
  837. * @param {Function} [callback=function(){}] 回调函数
  838. * @returns {editormd} 返回editormd的实例对象
  839. */
  840. showToolbar : function(callback) {
  841. var settings = this.settings;
  842. if(settings.readOnly) {
  843. return this;
  844. }
  845. if (settings.toolbar && (this.toolbar.length < 1 || this.toolbar.find("." + this.classPrefix + "menu").html() === "") )
  846. {
  847. this.setToolbar();
  848. }
  849. settings.toolbar = true;
  850. this.toolbar.show();
  851. this.resize();
  852. $.proxy(callback || function(){}, this)();
  853. return this;
  854. },
  855. /**
  856. * 隐藏工具栏
  857. * Hide toolbar
  858. *
  859. * @param {Function} [callback=function(){}] 回调函数
  860. * @returns {editormd} this(editormd instance object.)
  861. */
  862. hideToolbar : function(callback) {
  863. var settings = this.settings;
  864. settings.toolbar = false;
  865. this.toolbar.hide();
  866. this.resize();
  867. $.proxy(callback || function(){}, this)();
  868. return this;
  869. },
  870. /**
  871. * 页面滚动时工具栏的固定定位
  872. * Set toolbar in window scroll auto fixed position
  873. *
  874. * @returns {editormd} 返回editormd的实例对象
  875. */
  876. setToolbarAutoFixed : function(fixed) {
  877. var state = this.state;
  878. var editor = this.editor;
  879. var toolbar = this.toolbar;
  880. var settings = this.settings;
  881. if (typeof fixed !== "undefined")
  882. {
  883. settings.toolbarAutoFixed = fixed;
  884. }
  885. var autoFixedHandle = function(){
  886. var $window = $(window);
  887. var top = $window.scrollTop();
  888. if (!settings.toolbarAutoFixed)
  889. {
  890. return false;
  891. }
  892. if (top - editor.offset().top > 10 && top < editor.height())
  893. {
  894. toolbar.css({
  895. position : "fixed",
  896. width : editor.width() + "px",
  897. left : ($window.width() - editor.width()) / 2 + "px"
  898. });
  899. }
  900. else
  901. {
  902. toolbar.css({
  903. position : "absolute",
  904. width : "100%",
  905. left : 0
  906. });
  907. }
  908. };
  909. if (!state.fullscreen && !state.preview && settings.toolbar && settings.toolbarAutoFixed)
  910. {
  911. $(window).bind("scroll", autoFixedHandle);
  912. }
  913. return this;
  914. },
  915. /**
  916. * 配置和初始化工具栏
  917. * Set toolbar and Initialization
  918. *
  919. * @returns {editormd} 返回editormd的实例对象
  920. */
  921. setToolbar : function() {
  922. var settings = this.settings;
  923. if(settings.readOnly) {
  924. return this;
  925. }
  926. var editor = this.editor;
  927. var preview = this.preview;
  928. var classPrefix = this.classPrefix;
  929. var toolbar = this.toolbar = editor.children("." + classPrefix + "toolbar");
  930. if (settings.toolbar && toolbar.length < 1)
  931. {
  932. var toolbarHTML = "<div class=\"" + classPrefix + "toolbar\"><div class=\"" + classPrefix + "toolbar-container\"><ul class=\"" + classPrefix + "menu\"></ul></div></div>";
  933. editor.append(toolbarHTML);
  934. toolbar = this.toolbar = editor.children("." + classPrefix + "toolbar");
  935. }
  936. if (!settings.toolbar)
  937. {
  938. toolbar.hide();
  939. return this;
  940. }
  941. toolbar.show();
  942. var icons = (typeof settings.toolbarIcons === "function") ? settings.toolbarIcons()
  943. : ((typeof settings.toolbarIcons === "string") ? editormd.toolbarModes[settings.toolbarIcons] : settings.toolbarIcons);
  944. var toolbarMenu = toolbar.find("." + this.classPrefix + "menu"), menu = "";
  945. var pullRight = false;
  946. for (var i = 0, len = icons.length; i < len; i++)
  947. {
  948. var name = icons[i];
  949. if (name === "||")
  950. {
  951. pullRight = true;
  952. }
  953. else if (name === "|")
  954. {
  955. menu += "<li class=\"divider\" unselectable=\"on\">|</li>";
  956. }
  957. else
  958. {
  959. var isHeader = (/h(\d)/.test(name));
  960. var index = name;
  961. if (name === "watch" && !settings.watch) {
  962. index = "unwatch";
  963. }
  964. var title = settings.lang.toolbar[index];
  965. var iconTexts = settings.toolbarIconTexts[index];
  966. var iconClass = settings.toolbarIconsClass[index];
  967. title = (typeof title === "undefined") ? "" : title;
  968. iconTexts = (typeof iconTexts === "undefined") ? "" : iconTexts;
  969. iconClass = (typeof iconClass === "undefined") ? "" : iconClass;
  970. var menuItem = pullRight ? "<li class=\"pull-right\">" : "<li>";
  971. if (typeof settings.toolbarCustomIcons[name] !== "undefined" && typeof settings.toolbarCustomIcons[name] !== "function")
  972. {
  973. menuItem += settings.toolbarCustomIcons[name];
  974. }
  975. else
  976. {
  977. menuItem += "<a href=\"javascript:;\" title=\"" + title + "\" unselectable=\"on\">";
  978. menuItem += "<i class=\"fa " + iconClass + "\" name=\""+name+"\" unselectable=\"on\">"+((isHeader) ? name.toUpperCase() : ( (iconClass === "") ? iconTexts : "") ) + "</i>";
  979. menuItem += "</a>";
  980. }
  981. menuItem += "</li>";
  982. menu = pullRight ? menuItem + menu : menu + menuItem;
  983. }
  984. }
  985. toolbarMenu.html(menu);
  986. toolbarMenu.find("[title=\"Lowercase\"]").attr("title", settings.lang.toolbar.lowercase);
  987. toolbarMenu.find("[title=\"ucwords\"]").attr("title", settings.lang.toolbar.ucwords);
  988. this.setToolbarHandler();
  989. this.setToolbarAutoFixed();
  990. return this;
  991. },
  992. /**
  993. * 工具栏图标事件处理对象序列
  994. * Get toolbar icons event handlers
  995. *
  996. * @param {Object} cm CodeMirror的实例对象
  997. * @param {String} name 要获取的事件处理器名称
  998. * @returns {Object} 返回处理对象序列
  999. */
  1000. dialogLockScreen : function() {
  1001. $.proxy(editormd.dialogLockScreen, this)();
  1002. return this;
  1003. },
  1004. dialogShowMask : function(dialog) {
  1005. $.proxy(editormd.dialogShowMask, this)(dialog);
  1006. return this;
  1007. },
  1008. getToolbarHandles : function(name) {
  1009. var toolbarHandlers = this.toolbarHandlers = editormd.toolbarHandlers;
  1010. return (name && typeof toolbarIconHandlers[name] !== "undefined") ? toolbarHandlers[name] : toolbarHandlers;
  1011. },
  1012. /**
  1013. * 工具栏图标事件处理器
  1014. * Bind toolbar icons event handle
  1015. *
  1016. * @returns {editormd} 返回editormd的实例对象
  1017. */
  1018. setToolbarHandler : function() {
  1019. var _this = this;
  1020. var settings = this.settings;
  1021. if (!settings.toolbar || settings.readOnly) {
  1022. return this;
  1023. }
  1024. var toolbar = this.toolbar;
  1025. var cm = this.cm;
  1026. var classPrefix = this.classPrefix;
  1027. var toolbarIcons = this.toolbarIcons = toolbar.find("." + classPrefix + "menu > li > a");
  1028. var toolbarIconHandlers = this.getToolbarHandles();
  1029. toolbarIcons.bind(editormd.mouseOrTouch("click", "touchend"), function(event) {
  1030. var icon = $(this).children(".fa");
  1031. var name = icon.attr("name");
  1032. var cursor = cm.getCursor();
  1033. var selection = cm.getSelection();
  1034. if (name === "") {
  1035. return ;
  1036. }
  1037. _this.activeIcon = icon;
  1038. if (typeof toolbarIconHandlers[name] !== "undefined")
  1039. {
  1040. $.proxy(toolbarIconHandlers[name], _this)(cm);
  1041. }
  1042. else
  1043. {
  1044. if (typeof settings.toolbarHandlers[name] !== "undefined")
  1045. {
  1046. $.proxy(settings.toolbarHandlers[name], _this)(cm, icon, cursor, selection);
  1047. }
  1048. }
  1049. if (name !== "link" && name !== "reference-link" && name !== "image" && name !== "code-block" &&
  1050. name !== "preformatted-text" && name !== "watch" && name !== "preview" && name !== "search" && name !== "fullscreen" && name !== "info")
  1051. {
  1052. cm.focus();
  1053. }
  1054. return false;
  1055. });
  1056. return this;
  1057. },
  1058. /**
  1059. * 动态创建对话框
  1060. * Creating custom dialogs
  1061. *
  1062. * @param {Object} options 配置项键值对 Key/Value
  1063. * @returns {dialog} 返回创建的dialog的jQuery实例对象
  1064. */
  1065. createDialog : function(options) {
  1066. return $.proxy(editormd.createDialog, this)(options);
  1067. },
  1068. /**
  1069. * 创建关于Editor.md的对话框
  1070. * Create about Editor.md dialog
  1071. *
  1072. * @returns {editormd} 返回editormd的实例对象
  1073. */
  1074. createInfoDialog : function() {
  1075. var _this = this;
  1076. var editor = this.editor;
  1077. var classPrefix = this.classPrefix;
  1078. var infoDialogHTML = [
  1079. "<div class=\"" + classPrefix + "dialog " + classPrefix + "dialog-info\" style=\"\">",
  1080. "<div class=\"" + classPrefix + "dialog-container\">",
  1081. "<h1><i class=\"editormd-logo editormd-logo-lg editormd-logo-color\"></i> " + editormd.title + "<small>v" + editormd.version + "</small></h1>",
  1082. "<p>" + this.lang.description + "</p>",
  1083. "<p style=\"margin: 10px 0 20px 0;\"><a href=\"" + editormd.homePage + "\" target=\"_blank\">" + editormd.homePage + " <i class=\"fa fa-external-link\"></i></a></p>",
  1084. "<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>",
  1085. "</div>",
  1086. "<a href=\"javascript:;\" class=\"fa fa-close " + classPrefix + "dialog-close\"></a>",
  1087. "</div>"
  1088. ].join("\n");
  1089. editor.append(infoDialogHTML);
  1090. var infoDialog = this.infoDialog = editor.children("." + classPrefix + "dialog-info");
  1091. infoDialog.find("." + classPrefix + "dialog-close").bind(editormd.mouseOrTouch("click", "touchend"), function() {
  1092. _this.hideInfoDialog();
  1093. });
  1094. infoDialog.css("border", (editormd.isIE8) ? "1px solid #ddd" : "").css("z-index", editormd.dialogZindex).show();
  1095. this.infoDialogPosition();
  1096. return this;
  1097. },
  1098. /**
  1099. * 关于Editor.md对话居中定位
  1100. * Editor.md dialog position handle
  1101. *
  1102. * @returns {editormd} 返回editormd的实例对象
  1103. */
  1104. infoDialogPosition : function() {
  1105. var infoDialog = this.infoDialog;
  1106. var _infoDialogPosition = function() {
  1107. infoDialog.css({
  1108. top : ($(window).height() - infoDialog.height()) / 2 + "px",
  1109. left : ($(window).width() - infoDialog.width()) / 2 + "px"
  1110. });
  1111. };
  1112. _infoDialogPosition();
  1113. $(window).resize(_infoDialogPosition);
  1114. return this;
  1115. },
  1116. /**
  1117. * 显示关于Editor.md
  1118. * Display about Editor.md dialog
  1119. *
  1120. * @returns {editormd} 返回editormd的实例对象
  1121. */
  1122. showInfoDialog : function() {
  1123. $("html,body").css("overflow-x", "hidden");
  1124. var _this = this;
  1125. var editor = this.editor;
  1126. var settings = this.settings;
  1127. var infoDialog = this.infoDialog = editor.children("." + this.classPrefix + "dialog-info");
  1128. if (infoDialog.length < 1)
  1129. {
  1130. this.createInfoDialog();
  1131. }
  1132. this.lockScreen(true);
  1133. this.mask.css({
  1134. opacity : settings.dialogMaskOpacity,
  1135. backgroundColor : settings.dialogMaskBgColor
  1136. }).show();
  1137. infoDialog.css("z-index", editormd.dialogZindex).show();
  1138. this.infoDialogPosition();
  1139. return this;
  1140. },
  1141. /**
  1142. * 隐藏关于Editor.md
  1143. * Hide about Editor.md dialog
  1144. *
  1145. * @returns {editormd} 返回editormd的实例对象
  1146. */
  1147. hideInfoDialog : function() {
  1148. $("html,body").css("overflow-x", "");
  1149. this.infoDialog.hide();
  1150. this.mask.hide();
  1151. this.lockScreen(false);
  1152. return this;
  1153. },
  1154. /**
  1155. * 锁屏
  1156. * lock screen
  1157. *
  1158. * @param {Boolean} lock Boolean 布尔值是否锁屏
  1159. * @returns {editormd} 返回editormd的实例对象
  1160. */
  1161. lockScreen : function(lock) {
  1162. editormd.lockScreen(lock);
  1163. this.resize();
  1164. return this;
  1165. },
  1166. /**
  1167. * 编辑器界面重建用于动态语言包或模块加载等
  1168. * Recreate editor
  1169. *
  1170. * @returns {editormd} 返回editormd的实例对象
  1171. */
  1172. recreate : function() {
  1173. var _this = this;
  1174. var editor = this.editor;
  1175. var settings = this.settings;
  1176. this.codeMirror.remove();
  1177. this.setCodeMirror();
  1178. if (!settings.readOnly)
  1179. {
  1180. if (editor.find(".editormd-dialog").length > 0) {
  1181. editor.find(".editormd-dialog").remove();
  1182. }
  1183. if (settings.toolbar)
  1184. {
  1185. this.getToolbarHandles();
  1186. this.setToolbar();
  1187. }
  1188. }
  1189. this.loadedDisplay(true);
  1190. return this;
  1191. },
  1192. /**
  1193. * 高亮预览HTML的pre代码部分
  1194. * highlight of preview codes
  1195. *
  1196. * @returns {editormd} 返回editormd的实例对象
  1197. */
  1198. previewCodeHighlight : function() {
  1199. var settings = this.settings;
  1200. var previewContainer = this.previewContainer;
  1201. if (settings.previewCodeHighlight)
  1202. {
  1203. previewContainer.find("pre").addClass("prettyprint linenums");
  1204. if (typeof prettyPrint !== "undefined")
  1205. {
  1206. prettyPrint();
  1207. }
  1208. }
  1209. return this;
  1210. },
  1211. /**
  1212. * 解析TeX(KaTeX)科学公式
  1213. * TeX(KaTeX) Renderer
  1214. *
  1215. * @returns {editormd} 返回editormd的实例对象
  1216. */
  1217. katexRender : function() {
  1218. if (timer === null)
  1219. {
  1220. return this;
  1221. }
  1222. this.previewContainer.find("." + editormd.classNames.tex).each(function(){
  1223. var tex = $(this);
  1224. editormd.$katex.render(tex.text(), tex[0]);
  1225. tex.find(".katex").css("font-size", "1.6em");
  1226. });
  1227. return this;
  1228. },
  1229. /**
  1230. * 解析和渲染流程图及时序图
  1231. * FlowChart and SequenceDiagram Renderer
  1232. *
  1233. * @returns {editormd} 返回editormd的实例对象
  1234. */
  1235. flowChartAndSequenceDiagramRender : function() {
  1236. var $this = this;
  1237. var settings = this.settings;
  1238. var previewContainer = this.previewContainer;
  1239. if (editormd.isIE8) {
  1240. return this;
  1241. }
  1242. if (settings.flowChart) {
  1243. if (flowchartTimer === null) {
  1244. return this;
  1245. }
  1246. previewContainer.find(".flowchart").flowChart();
  1247. }
  1248. if (settings.sequenceDiagram) {
  1249. previewContainer.find(".sequence-diagram").sequenceDiagram({theme: "simple"});
  1250. }
  1251. var preview = $this.preview;
  1252. var codeMirror = $this.codeMirror;
  1253. var codeView = codeMirror.find(".CodeMirror-scroll");
  1254. var height = codeView.height();
  1255. var scrollTop = codeView.scrollTop();
  1256. var percent = (scrollTop / codeView[0].scrollHeight);
  1257. var tocHeight = 0;
  1258. preview.find(".markdown-toc-list").each(function(){
  1259. tocHeight += $(this).height();
  1260. });
  1261. var tocMenuHeight = preview.find(".editormd-toc-menu").height();
  1262. tocMenuHeight = (!tocMenuHeight) ? 0 : tocMenuHeight;
  1263. if (scrollTop === 0)
  1264. {
  1265. preview.scrollTop(0);
  1266. }
  1267. else if (scrollTop + height >= codeView[0].scrollHeight - 16)
  1268. {
  1269. preview.scrollTop(preview[0].scrollHeight);
  1270. }
  1271. else
  1272. {
  1273. preview.scrollTop((preview[0].scrollHeight + tocHeight + tocMenuHeight) * percent);
  1274. }
  1275. return this;
  1276. },
  1277. /**
  1278. * 注册键盘快捷键处理
  1279. * Register CodeMirror keyMaps (keyboard shortcuts).
  1280. *
  1281. * @param {Object} keyMap KeyMap key/value {"(Ctrl/Shift/Alt)-Key" : function(){}}
  1282. * @returns {editormd} return this
  1283. */
  1284. registerKeyMaps : function(keyMap) {
  1285. var _this = this;
  1286. var cm = this.cm;
  1287. var settings = this.settings;
  1288. var toolbarHandlers = editormd.toolbarHandlers;
  1289. var disabledKeyMaps = settings.disabledKeyMaps;
  1290. keyMap = keyMap || null;
  1291. if (keyMap)
  1292. {
  1293. for (var i in keyMap)
  1294. {
  1295. if ($.inArray(i, disabledKeyMaps) < 0)
  1296. {
  1297. var map = {};
  1298. map[i] = keyMap[i];
  1299. cm.addKeyMap(keyMap);
  1300. }
  1301. }
  1302. }
  1303. else
  1304. {
  1305. for (var k in editormd.keyMaps)
  1306. {
  1307. var _keyMap = editormd.keyMaps[k];
  1308. var handle = (typeof _keyMap === "string") ? $.proxy(toolbarHandlers[_keyMap], _this) : $.proxy(_keyMap, _this);
  1309. if ($.inArray(k, ["F9", "F10", "F11"]) < 0 && $.inArray(k, disabledKeyMaps) < 0)
  1310. {
  1311. var _map = {};
  1312. _map[k] = handle;
  1313. cm.addKeyMap(_map);
  1314. }
  1315. }
  1316. $(window).keydown(function(event) {
  1317. var keymaps = {
  1318. "120" : "F9",
  1319. "121" : "F10",
  1320. "122" : "F11"
  1321. };
  1322. if ( $.inArray(keymaps[event.keyCode], disabledKeyMaps) < 0 )
  1323. {
  1324. switch (event.keyCode)
  1325. {
  1326. case 120:
  1327. $.proxy(toolbarHandlers["watch"], _this)();
  1328. return false;
  1329. break;
  1330. case 121:
  1331. $.proxy(toolbarHandlers["preview"], _this)();
  1332. return false;
  1333. break;
  1334. case 122:
  1335. $.proxy(toolbarHandlers["fullscreen"], _this)();
  1336. return false;
  1337. break;
  1338. default:
  1339. break;
  1340. }
  1341. }
  1342. });
  1343. }
  1344. return this;
  1345. },
  1346. /**
  1347. * 绑定同步滚动
  1348. *
  1349. * @returns {editormd} return this
  1350. */
  1351. bindScrollEvent : function() {
  1352. var _this = this;
  1353. var preview = this.preview;
  1354. var settings = this.settings;
  1355. var codeMirror = this.codeMirror;
  1356. var mouseOrTouch = editormd.mouseOrTouch;
  1357. if (!settings.syncScrolling) {
  1358. return this;
  1359. }
  1360. var cmBindScroll = function() {
  1361. codeMirror.find(".CodeMirror-scroll").bind(mouseOrTouch("scroll", "touchmove"), function(event) {
  1362. var height = $(this).height();
  1363. var scrollTop = $(this).scrollTop();
  1364. var percent = (scrollTop / $(this)[0].scrollHeight);
  1365. var tocHeight = 0;
  1366. preview.find(".markdown-toc-list").each(function(){
  1367. tocHeight += $(this).height();
  1368. });
  1369. var tocMenuHeight = preview.find(".editormd-toc-menu").height();
  1370. tocMenuHeight = (!tocMenuHeight) ? 0 : tocMenuHeight;
  1371. if (scrollTop === 0)
  1372. {
  1373. preview.scrollTop(0);
  1374. }
  1375. else if (scrollTop + height >= $(this)[0].scrollHeight - 16)
  1376. {
  1377. preview.scrollTop(preview[0].scrollHeight);
  1378. }
  1379. else
  1380. {
  1381. preview.scrollTop((preview[0].scrollHeight + tocHeight + tocMenuHeight) * percent);
  1382. }
  1383. $.proxy(settings.onscroll, _this)(event);
  1384. });
  1385. };
  1386. var cmUnbindScroll = function() {
  1387. codeMirror.find(".CodeMirror-scroll").unbind(mouseOrTouch("scroll", "touchmove"));
  1388. };
  1389. var previewBindScroll = function() {
  1390. preview.bind(mouseOrTouch("scroll", "touchmove"), function(event) {
  1391. var height = $(this).height();
  1392. var scrollTop = $(this).scrollTop();
  1393. var percent = (scrollTop / $(this)[0].scrollHeight);
  1394. var codeView = codeMirror.find(".CodeMirror-scroll");
  1395. if(scrollTop === 0)
  1396. {
  1397. codeView.scrollTop(0);
  1398. }
  1399. else if (scrollTop + height >= $(this)[0].scrollHeight)
  1400. {
  1401. codeView.scrollTop(codeView[0].scrollHeight);
  1402. }
  1403. else
  1404. {
  1405. codeView.scrollTop(codeView[0].scrollHeight * percent);
  1406. }
  1407. $.proxy(settings.onpreviewscroll, _this)(event);
  1408. });
  1409. };
  1410. var previewUnbindScroll = function() {
  1411. preview.unbind(mouseOrTouch("scroll", "touchmove"));
  1412. };
  1413. codeMirror.bind({
  1414. mouseover : cmBindScroll,
  1415. mouseout : cmUnbindScroll,
  1416. touchstart : cmBindScroll,
  1417. touchend : cmUnbindScroll
  1418. });
  1419. if (settings.syncScrolling === "single") {
  1420. return this;
  1421. }
  1422. preview.bind({
  1423. mouseover : previewBindScroll,
  1424. mouseout : previewUnbindScroll,
  1425. touchstart : previewBindScroll,
  1426. touchend : previewUnbindScroll
  1427. });
  1428. return this;
  1429. },
  1430. bindChangeEvent : function() {
  1431. var _this = this;
  1432. var cm = this.cm;
  1433. var settings = this.settings;
  1434. if (!settings.syncScrolling) {
  1435. return this;
  1436. }
  1437. cm.on("change", function(_cm, changeObj) {
  1438. if (settings.watch)
  1439. {
  1440. _this.previewContainer.css("padding", settings.autoHeight ? "20px 20px 50px 40px" : "20px");
  1441. }
  1442. timer = setTimeout(function() {
  1443. clearTimeout(timer);
  1444. _this.save();
  1445. timer = null;
  1446. }, settings.delay);
  1447. });
  1448. return this;
  1449. },
  1450. /**
  1451. * 加载队列完成之后的显示处理
  1452. * Display handle of the module queues loaded after.
  1453. *
  1454. * @param {Boolean} recreate 是否为重建编辑器
  1455. * @returns {editormd} 返回editormd的实例对象
  1456. */
  1457. loadedDisplay : function(recreate) {
  1458. recreate = recreate || false;
  1459. var _this = this;
  1460. var editor = this.editor;
  1461. var preview = this.preview;
  1462. var settings = this.settings;
  1463. this.containerMask.hide();
  1464. this.save();
  1465. if (settings.watch) {
  1466. preview.show();
  1467. }
  1468. editor.data("oldWidth", editor.width()).data("oldHeight", editor.height()); // 为了兼容Zepto
  1469. this.resize();
  1470. this.registerKeyMaps();
  1471. $(window).resize(function(){
  1472. _this.resize();
  1473. });
  1474. this.bindScrollEvent().bindChangeEvent();
  1475. if (!recreate)
  1476. {
  1477. $.proxy(settings.onload, this)();
  1478. }
  1479. this.state.loaded = true;
  1480. return this;
  1481. },
  1482. /**
  1483. * 设置编辑器的宽度
  1484. * Set editor width
  1485. *
  1486. * @param {Number|String} width 编辑器宽度值
  1487. * @returns {editormd} 返回editormd的实例对象
  1488. */
  1489. width : function(width) {
  1490. this.editor.css("width", (typeof width === "number") ? width + "px" : width);
  1491. this.resize();
  1492. return this;
  1493. },
  1494. /**
  1495. * 设置编辑器的高度
  1496. * Set editor height
  1497. *
  1498. * @param {Number|String} height 编辑器高度值
  1499. * @returns {editormd} 返回editormd的实例对象
  1500. */
  1501. height : function(height) {
  1502. this.editor.css("height", (typeof height === "number") ? height + "px" : height);
  1503. this.resize();
  1504. return this;
  1505. },
  1506. /**
  1507. * 调整编辑器的尺寸和布局
  1508. * Resize editor layout
  1509. *
  1510. * @param {Number|String} [width=null] 编辑器宽度值
  1511. * @param {Number|String} [height=null] 编辑器高度值
  1512. * @returns {editormd} 返回editormd的实例对象
  1513. */
  1514. resize : function(width, height) {
  1515. width = width || null;
  1516. height = height || null;
  1517. var state = this.state;
  1518. var editor = this.editor;
  1519. var preview = this.preview;
  1520. var toolbar = this.toolbar;
  1521. var settings = this.settings;
  1522. var codeMirror = this.codeMirror;
  1523. if (width)
  1524. {
  1525. editor.css("width", (typeof width === "number") ? width + "px" : width);
  1526. }
  1527. if (settings.autoHeight && !state.fullscreen && !state.preview)
  1528. {
  1529. editor.css("height", "auto");
  1530. codeMirror.css("height", "auto");
  1531. }
  1532. else
  1533. {
  1534. if (height)
  1535. {
  1536. editor.css("height", (typeof height === "number") ? height + "px" : height);
  1537. }
  1538. if (state.fullscreen)
  1539. {
  1540. editor.height($(window).height());
  1541. }
  1542. if (settings.toolbar && !settings.readOnly)
  1543. {
  1544. codeMirror.css("margin-top", toolbar.height() + 1).height(editor.height() - toolbar.height());
  1545. }
  1546. else
  1547. {
  1548. codeMirror.css("margin-top", 0).height(editor.height());
  1549. }
  1550. }
  1551. if(settings.watch)
  1552. {
  1553. codeMirror.width(editor.width() / 2);
  1554. preview.width((!state.preview) ? editor.width() / 2 : editor.width());
  1555. this.previewContainer.css("padding", settings.autoHeight ? "20px 20px 50px 40px" : "20px");
  1556. if (settings.toolbar && !settings.readOnly)
  1557. {
  1558. preview.css("top", toolbar.height() + 1);
  1559. }
  1560. else
  1561. {
  1562. preview.css("top", 0);
  1563. }
  1564. if (settings.autoHeight && !state.fullscreen && !state.preview)
  1565. {
  1566. preview.height("");
  1567. }
  1568. else
  1569. {
  1570. var previewHeight = (settings.toolbar && !settings.readOnly) ? editor.height() - toolbar.height() : editor.height();
  1571. preview.height(previewHeight);
  1572. }
  1573. }
  1574. else
  1575. {
  1576. codeMirror.width(editor.width());
  1577. preview.hide();
  1578. }
  1579. if (state.loaded)
  1580. {
  1581. $.proxy(settings.onresize, this)();
  1582. }
  1583. return this;
  1584. },
  1585. /**
  1586. * 解析和保存Markdown代码
  1587. * Parse & Saving Markdown source code
  1588. *
  1589. * @returns {editormd} 返回editormd的实例对象
  1590. */
  1591. save : function() {
  1592. if (timer === null)
  1593. {
  1594. return this;
  1595. }
  1596. var _this = this;
  1597. var state = this.state;
  1598. var settings = this.settings;
  1599. var cm = this.cm;
  1600. var cmValue = cm.getValue();
  1601. var previewContainer = this.previewContainer;
  1602. if (settings.mode !== "gfm" && settings.mode !== "markdown")
  1603. {
  1604. this.markdownTextarea.val(cmValue);
  1605. return this;
  1606. }
  1607. var marked = editormd.$marked;
  1608. var markdownToC = this.markdownToC = [];
  1609. var rendererOptions = this.markedRendererOptions = {
  1610. toc : settings.toc,
  1611. tocm : settings.tocm,
  1612. tocStartLevel : settings.tocStartLevel,
  1613. pageBreak : settings.pageBreak,
  1614. taskList : settings.taskList,
  1615. emoji : settings.emoji,
  1616. tex : settings.tex,
  1617. atLink : settings.atLink, // for @link
  1618. emailLink : settings.emailLink, // for mail address auto link
  1619. flowChart : settings.flowChart,
  1620. sequenceDiagram : settings.sequenceDiagram,
  1621. previewCodeHighlight : settings.previewCodeHighlight,
  1622. };
  1623. var markedOptions = this.markedOptions = {
  1624. renderer : editormd.markedRenderer(markdownToC, rendererOptions),
  1625. gfm : true,
  1626. tables : true,
  1627. breaks : true,
  1628. pedantic : false,
  1629. sanitize : (settings.htmlDecode) ? false : true, // 关闭忽略HTML标签,即开启识别HTML标签,默认为false
  1630. smartLists : true,
  1631. smartypants : true
  1632. };
  1633. marked.setOptions(markedOptions);
  1634. var newMarkdownDoc = editormd.$marked(cmValue, markedOptions);
  1635. //console.info("cmValue", cmValue, newMarkdownDoc);
  1636. newMarkdownDoc = editormd.filterHTMLTags(newMarkdownDoc, settings.htmlDecode);
  1637. //console.error("cmValue", cmValue, newMarkdownDoc);
  1638. this.markdownTextarea.text(cmValue);
  1639. cm.save();
  1640. if (settings.saveHTMLToTextarea)
  1641. {
  1642. this.htmlTextarea.text(newMarkdownDoc);
  1643. }
  1644. if(settings.watch || (!settings.watch && state.preview))
  1645. {
  1646. previewContainer.html(newMarkdownDoc);
  1647. this.previewCodeHighlight();
  1648. if (settings.toc)
  1649. {
  1650. var tocContainer = (settings.tocContainer === "") ? previewContainer : $(settings.tocContainer);
  1651. var tocMenu = tocContainer.find("." + this.classPrefix + "toc-menu");
  1652. tocContainer.attr("previewContainer", (settings.tocContainer === "") ? "true" : "false");
  1653. if (settings.tocContainer !== "" && tocMenu.length > 0)
  1654. {
  1655. tocMenu.remove();
  1656. }
  1657. editormd.markdownToCRenderer(markdownToC, tocContainer, settings.tocDropdown, settings.tocStartLevel);
  1658. if (settings.tocDropdown || tocContainer.find("." + this.classPrefix + "toc-menu").length > 0)
  1659. {
  1660. editormd.tocDropdownMenu(tocContainer, (settings.tocTitle !== "") ? settings.tocTitle : this.lang.tocTitle);
  1661. }
  1662. if (settings.tocContainer !== "")
  1663. {
  1664. previewContainer.find(".markdown-toc").css("border", "none");
  1665. }
  1666. }
  1667. if (settings.tex)
  1668. {
  1669. if (!editormd.kaTeXLoaded && settings.autoLoadModules)
  1670. {
  1671. editormd.loadKaTeX(function() {
  1672. editormd.$katex = katex;
  1673. editormd.kaTeXLoaded = true;
  1674. _this.katexRender();
  1675. });
  1676. }
  1677. else
  1678. {
  1679. editormd.$katex = katex;
  1680. this.katexRender();
  1681. }
  1682. }
  1683. if (settings.flowChart || settings.sequenceDiagram)
  1684. {
  1685. flowchartTimer = setTimeout(function(){
  1686. clearTimeout(flowchartTimer);
  1687. _this.flowChartAndSequenceDiagramRender();
  1688. flowchartTimer = null;
  1689. }, 10);
  1690. }
  1691. if (state.loaded)
  1692. {
  1693. $.proxy(settings.onchange, this)();
  1694. }
  1695. }
  1696. return this;
  1697. },
  1698. /**
  1699. * 聚焦光标位置
  1700. * Focusing the cursor position
  1701. *
  1702. * @returns {editormd} 返回editormd的实例对象
  1703. */
  1704. focus : function() {
  1705. this.cm.focus();
  1706. return this;
  1707. },
  1708. /**
  1709. * 设置光标的位置
  1710. * Set cursor position
  1711. *
  1712. * @param {Object} cursor 要设置的光标位置键值对象{line:1, ch:0}
  1713. * @returns {editormd} 返回editormd的实例对象
  1714. */
  1715. setCursor : function(cursor) {
  1716. this.cm.setCursor(cursor);
  1717. return this;
  1718. },
  1719. /**
  1720. * 获取当前光标的位置
  1721. * Get the current position of the cursor
  1722. *
  1723. * @returns {Cursor} 返回一个光标Cursor对象
  1724. */
  1725. getCursor : function() {
  1726. return this.cm.getCursor();
  1727. },
  1728. /**
  1729. * 设置光标选中的范围
  1730. * Set cursor selected ranges
  1731. *
  1732. * @param {Object} from 开始位置的光标键值对象{line:1, ch:0}
  1733. * @param {Object} to 结束位置的光标键值对象{line:1, ch:0}
  1734. * @returns {editormd} 返回editormd的实例对象
  1735. */
  1736. setSelection : function(from, to) {
  1737. this.cm.setSelection(from, to);
  1738. return this;
  1739. },
  1740. /**
  1741. * 获取光标选中的文本
  1742. * Get the texts from cursor selected
  1743. *
  1744. * @returns {String} 返回选中文本的字符串形式
  1745. */
  1746. getSelection : function() {
  1747. return this.cm.getSelection();
  1748. },
  1749. /**
  1750. * 设置光标选中的文本范围
  1751. * Set the cursor selection ranges
  1752. *
  1753. * @param {Array} ranges cursor selection ranges array
  1754. * @returns {Array} return this
  1755. */
  1756. setSelections : function(ranges) {
  1757. this.cm.setSelections(ranges);
  1758. return this;
  1759. },
  1760. /**
  1761. * 获取光标选中的文本范围
  1762. * Get the cursor selection ranges
  1763. *
  1764. * @returns {Array} return selection ranges array
  1765. */
  1766. getSelections : function() {
  1767. return this.cm.getSelections();
  1768. },
  1769. /**
  1770. * 替换当前光标选中的文本或在当前光标处插入新字符
  1771. * Replace the text at the current cursor selected or insert a new character at the current cursor position
  1772. *
  1773. * @param {String} value 要插入的字符值
  1774. * @returns {editormd} 返回editormd的实例对象
  1775. */
  1776. replaceSelection : function(value) {
  1777. this.cm.replaceSelection(value);
  1778. return this;
  1779. },
  1780. /**
  1781. * 在当前光标处插入新字符
  1782. * Insert a new character at the current cursor position
  1783. *
  1784. * 同replaceSelection()方法
  1785. * With the replaceSelection() method
  1786. *
  1787. * @param {String} value 要插入的字符值
  1788. * @returns {editormd} 返回editormd的实例对象
  1789. */
  1790. insertValue : function(value) {
  1791. this.replaceSelection(value);
  1792. return this;
  1793. },
  1794. /**
  1795. * 追加markdown
  1796. * append Markdown to editor
  1797. *
  1798. * @param {String} md 要追加的markdown源文档
  1799. * @returns {editormd} 返回editormd的实例对象
  1800. */
  1801. appendMarkdown : function(md) {
  1802. var settings = this.settings;
  1803. var cm = this.cm;
  1804. cm.setValue(cm.getValue() + md);
  1805. return this;
  1806. },
  1807. /**
  1808. * 设置和传入编辑器的markdown源文档
  1809. * Set Markdown source document
  1810. *
  1811. * @param {String} md 要传入的markdown源文档
  1812. * @returns {editormd} 返回editormd的实例对象
  1813. */
  1814. setMarkdown : function(md) {
  1815. this.cm.setValue(md || this.settings.markdown);
  1816. return this;
  1817. },
  1818. /**
  1819. * 获取编辑器的markdown源文档
  1820. * Set Editor.md markdown/CodeMirror value
  1821. *
  1822. * @returns {editormd} 返回editormd的实例对象
  1823. */
  1824. getMarkdown : function() {
  1825. return this.cm.getValue();
  1826. },
  1827. /**
  1828. * 获取编辑器的源文档
  1829. * Get CodeMirror value
  1830. *
  1831. * @returns {editormd} 返回editormd的实例对象
  1832. */
  1833. getValue : function() {
  1834. return this.cm.getValue();
  1835. },
  1836. /**
  1837. * 设置编辑器的源文档
  1838. * Set CodeMirror value
  1839. *
  1840. * @param {String} value set code/value/string/text
  1841. * @returns {editormd} 返回editormd的实例对象
  1842. */
  1843. setValue : function(value) {
  1844. this.cm.setValue(value);
  1845. return this;
  1846. },
  1847. /**
  1848. * 清空编辑器
  1849. * Empty CodeMirror editor container
  1850. *
  1851. * @returns {editormd} 返回editormd的实例对象
  1852. */
  1853. clear : function() {
  1854. this.cm.setValue("");
  1855. return this;
  1856. },
  1857. /**
  1858. * 获取解析后存放在Textarea的HTML源码
  1859. * Get parsed html code from Textarea
  1860. *
  1861. * @returns {String} 返回HTML源码
  1862. */
  1863. getHTML : function() {
  1864. if (!this.settings.saveHTMLToTextarea)
  1865. {
  1866. alert("Error: settings.saveHTMLToTextarea == false");
  1867. return false;
  1868. }
  1869. return this.htmlTextarea.val();
  1870. },
  1871. /**
  1872. * getHTML()的别名
  1873. * getHTML (alias)
  1874. *
  1875. * @returns {String} Return html code 返回HTML源码
  1876. */
  1877. getTextareaSavedHTML : function() {
  1878. return this.getHTML();
  1879. },
  1880. /**
  1881. * 获取预览窗口的HTML源码
  1882. * Get html from preview container
  1883. *
  1884. * @returns {editormd} 返回editormd的实例对象
  1885. */
  1886. getPreviewedHTML : function() {
  1887. if (!this.settings.watch)
  1888. {
  1889. alert("Error: settings.watch == false");
  1890. return false;
  1891. }
  1892. return this.previewContainer.html();
  1893. },
  1894. /**
  1895. * 开启实时预览
  1896. * Enable real-time watching
  1897. *
  1898. * @returns {editormd} 返回editormd的实例对象
  1899. */
  1900. watch : function(callback) {
  1901. var settings = this.settings;
  1902. if ($.inArray(settings.mode, ["gfm", "markdown"]) < 0)
  1903. {
  1904. return this;
  1905. }
  1906. this.state.watching = settings.watch = true;
  1907. this.preview.show();
  1908. if (this.toolbar)
  1909. {
  1910. var watchIcon = settings.toolbarIconsClass.watch;
  1911. var unWatchIcon = settings.toolbarIconsClass.unwatch;
  1912. var icon = this.toolbar.find(".fa[name=watch]");
  1913. icon.parent().attr("title", settings.lang.toolbar.watch);
  1914. icon.removeClass(unWatchIcon).addClass(watchIcon);
  1915. }
  1916. this.codeMirror.css("border-right", "1px solid #ddd").width(this.editor.width() / 2);
  1917. timer = 0;
  1918. this.save().resize();
  1919. if (!settings.onwatch)
  1920. {
  1921. settings.onwatch = callback || function() {};
  1922. }
  1923. $.proxy(settings.onwatch, this)();
  1924. return this;
  1925. },
  1926. /**
  1927. * 关闭实时预览
  1928. * Disable real-time watching
  1929. *
  1930. * @returns {editormd} 返回editormd的实例对象
  1931. */
  1932. unwatch : function(callback) {
  1933. var settings = this.settings;
  1934. this.state.watching = settings.watch = false;
  1935. this.preview.hide();
  1936. if (this.toolbar)
  1937. {
  1938. var watchIcon = settings.toolbarIconsClass.watch;
  1939. var unWatchIcon = settings.toolbarIconsClass.unwatch;
  1940. var icon = this.toolbar.find(".fa[name=watch]");
  1941. icon.parent().attr("title", settings.lang.toolbar.unwatch);
  1942. icon.removeClass(watchIcon).addClass(unWatchIcon);
  1943. }
  1944. this.codeMirror.css("border-right", "none").width(this.editor.width());
  1945. this.resize();
  1946. if (!settings.onunwatch)
  1947. {
  1948. settings.onunwatch = callback || function() {};
  1949. }
  1950. $.proxy(settings.onunwatch, this)();
  1951. return this;
  1952. },
  1953. /**
  1954. * 显示编辑器
  1955. * Show editor
  1956. *
  1957. * @param {Function} [callback=function()] 回调函数
  1958. * @returns {editormd} 返回editormd的实例对象
  1959. */
  1960. show : function(callback) {
  1961. callback = callback || function() {};
  1962. var _this = this;
  1963. this.editor.show(0, function() {
  1964. $.proxy(callback, _this)();
  1965. });
  1966. return this;
  1967. },
  1968. /**
  1969. * 隐藏编辑器
  1970. * Hide editor
  1971. *
  1972. * @param {Function} [callback=function()] 回调函数
  1973. * @returns {editormd} 返回editormd的实例对象
  1974. */
  1975. hide : function(callback) {
  1976. callback = callback || function() {};
  1977. var _this = this;
  1978. this.editor.hide(0, function() {
  1979. $.proxy(callback, _this)();
  1980. });
  1981. return this;
  1982. },
  1983. /**
  1984. * 隐藏编辑器部分只预览HTML
  1985. * Enter preview html state
  1986. *
  1987. * @returns {editormd} 返回editormd的实例对象
  1988. */
  1989. previewing : function() {
  1990. var _this = this;
  1991. var editor = this.editor;
  1992. var preview = this.preview;
  1993. var toolbar = this.toolbar;
  1994. var settings = this.settings;
  1995. var codeMirror = this.codeMirror;
  1996. var previewContainer = this.previewContainer;
  1997. if ($.inArray(settings.mode, ["gfm", "markdown"]) < 0) {
  1998. return this;
  1999. }
  2000. if (settings.toolbar && toolbar) {
  2001. toolbar.toggle();
  2002. toolbar.find(".fa[name=preview]").toggleClass("active");
  2003. }
  2004. codeMirror.toggle();
  2005. var escHandle = function(event) {
  2006. if (event.shiftKey && event.keyCode === 27) {
  2007. _this.previewed();
  2008. }
  2009. };
  2010. if (codeMirror.css("display") === "none") // 为了兼容Zepto,而不使用codeMirror.is(":hidden")
  2011. {
  2012. this.state.preview = true;
  2013. if (this.state.fullscreen) {
  2014. preview.css("background", "#fff");
  2015. }
  2016. editor.find("." + this.classPrefix + "preview-close-btn").show().bind(editormd.mouseOrTouch("click", "touchend"), function(){
  2017. _this.previewed();
  2018. });
  2019. if (!settings.watch)
  2020. {
  2021. this.save();
  2022. }
  2023. else
  2024. {
  2025. previewContainer.css("padding", "");
  2026. }
  2027. previewContainer.addClass(this.classPrefix + "preview-active");
  2028. preview.show().css({
  2029. position : "",
  2030. top : 0,
  2031. width : editor.width(),
  2032. height : (settings.autoHeight && !this.state.fullscreen) ? "auto" : editor.height()
  2033. });
  2034. if (this.state.loaded)
  2035. {
  2036. $.proxy(settings.onpreviewing, this)();
  2037. }
  2038. $(window).bind("keyup", escHandle);
  2039. }
  2040. else
  2041. {
  2042. $(window).unbind("keyup", escHandle);
  2043. this.previewed();
  2044. }
  2045. },
  2046. /**
  2047. * 显示编辑器部分退出只预览HTML
  2048. * Exit preview html state
  2049. *
  2050. * @returns {editormd} 返回editormd的实例对象
  2051. */
  2052. previewed : function() {
  2053. var editor = this.editor;
  2054. var preview = this.preview;
  2055. var toolbar = this.toolbar;
  2056. var settings = this.settings;
  2057. var previewContainer = this.previewContainer;
  2058. var previewCloseBtn = editor.find("." + this.classPrefix + "preview-close-btn");
  2059. this.state.preview = false;
  2060. this.codeMirror.show();
  2061. if (settings.toolbar) {
  2062. toolbar.show();
  2063. }
  2064. preview[(settings.watch) ? "show" : "hide"]();
  2065. previewCloseBtn.hide().unbind(editormd.mouseOrTouch("click", "touchend"));
  2066. previewContainer.removeClass(this.classPrefix + "preview-active");
  2067. if (settings.watch)
  2068. {
  2069. previewContainer.css("padding", "20px");
  2070. }
  2071. preview.css({
  2072. background : null,
  2073. position : "absolute",
  2074. width : editor.width() / 2,
  2075. height : (settings.autoHeight && !this.state.fullscreen) ? "auto" : editor.height() - toolbar.height(),
  2076. top : (settings.toolbar) ? toolbar.height() : 0
  2077. });
  2078. if (this.state.loaded)
  2079. {
  2080. $.proxy(settings.onpreviewed, this)();
  2081. }
  2082. return this;
  2083. },
  2084. /**
  2085. * 编辑器全屏显示
  2086. * Fullscreen show
  2087. *
  2088. * @returns {editormd} 返回editormd的实例对象
  2089. */
  2090. fullscreen : function() {
  2091. var _this = this;
  2092. var state = this.state;
  2093. var editor = this.editor;
  2094. var preview = this.preview;
  2095. var toolbar = this.toolbar;
  2096. var settings = this.settings;
  2097. var fullscreenClass = this.classPrefix + "fullscreen";
  2098. if (toolbar) {
  2099. toolbar.find(".fa[name=fullscreen]").parent().toggleClass("active");
  2100. }
  2101. var escHandle = function(event) {
  2102. if (!event.shiftKey && event.keyCode === 27)
  2103. {
  2104. if (state.fullscreen)
  2105. {
  2106. _this.fullscreenExit();
  2107. }
  2108. }
  2109. };
  2110. if (!editor.hasClass(fullscreenClass))
  2111. {
  2112. state.fullscreen = true;
  2113. $("html,body").css("overflow", "hidden");
  2114. editor.css({
  2115. width : $(window).width(),
  2116. height : $(window).height()
  2117. }).addClass(fullscreenClass);
  2118. this.resize();
  2119. $.proxy(settings.onfullscreen, this)();
  2120. $(window).bind("keyup", escHandle);
  2121. }
  2122. else
  2123. {
  2124. $(window).unbind("keyup", escHandle);
  2125. this.fullscreenExit();
  2126. }
  2127. return this;
  2128. },
  2129. /**
  2130. * 编辑器退出全屏显示
  2131. * Exit fullscreen state
  2132. *
  2133. * @returns {editormd} 返回editormd的实例对象
  2134. */
  2135. fullscreenExit : function() {
  2136. var editor = this.editor;
  2137. var settings = this.settings;
  2138. var toolbar = this.toolbar;
  2139. var fullscreenClass = this.classPrefix + "fullscreen";
  2140. this.state.fullscreen = false;
  2141. if (toolbar) {
  2142. toolbar.find(".fa[name=fullscreen]").parent().removeClass("active");
  2143. }
  2144. $("html,body").css("overflow", "");
  2145. editor.css({
  2146. width : editor.data("oldWidth"),
  2147. height : editor.data("oldHeight")
  2148. }).removeClass(fullscreenClass);
  2149. this.resize();
  2150. $.proxy(settings.onfullscreenExit, this)();
  2151. return this;
  2152. },
  2153. /**
  2154. * 加载并执行插件
  2155. * Load and execute the plugin
  2156. *
  2157. * @param {String} name plugin name / function name
  2158. * @param {String} path plugin load path
  2159. * @returns {editormd} 返回editormd的实例对象
  2160. */
  2161. executePlugin : function(name, path) {
  2162. var _this = this;
  2163. var cm = this.cm;
  2164. var settings = this.settings;
  2165. path = settings.pluginPath + path;
  2166. if (typeof define === "function")
  2167. {
  2168. if (typeof this[name] === "undefined")
  2169. {
  2170. alert("Error: " + name + " plugin is not found, you are not load this plugin.");
  2171. return this;
  2172. }
  2173. this[name](cm);
  2174. return this;
  2175. }
  2176. if ($.inArray(path, editormd.loadFiles.plugin) < 0)
  2177. {
  2178. editormd.loadPlugin(path, function() {
  2179. editormd.loadPlugins[name] = _this[name];
  2180. _this[name](cm);
  2181. });
  2182. }
  2183. else
  2184. {
  2185. $.proxy(editormd.loadPlugins[name], this)(cm);
  2186. }
  2187. return this;
  2188. },
  2189. /**
  2190. * 搜索替换
  2191. * Search & replace
  2192. *
  2193. * @param {String} command CodeMirror serach commands, "find, fintNext, fintPrev, clearSearch, replace, replaceAll"
  2194. * @returns {editormd} return this
  2195. */
  2196. search : function(command) {
  2197. var settings = this.settings;
  2198. if (!settings.searchReplace)
  2199. {
  2200. alert("Error: settings.searchReplace == false");
  2201. return this;
  2202. }
  2203. if (!settings.readOnly)
  2204. {
  2205. this.cm.execCommand(command || "find");
  2206. }
  2207. return this;
  2208. },
  2209. searchReplace : function() {
  2210. this.search("replace");
  2211. return this;
  2212. },
  2213. searchReplaceAll : function() {
  2214. this.search("replaceAll");
  2215. return this;
  2216. }
  2217. };
  2218. editormd.fn.init.prototype = editormd.fn;
  2219. /**
  2220. * 锁屏
  2221. * lock screen when dialog opening
  2222. *
  2223. * @returns {void}
  2224. */
  2225. editormd.dialogLockScreen = function() {
  2226. var settings = this.settings || {dialogLockScreen : true};
  2227. if (settings.dialogLockScreen)
  2228. {
  2229. $("html,body").css("overflow", "hidden");
  2230. this.resize();
  2231. }
  2232. };
  2233. /**
  2234. * 显示透明背景层
  2235. * Display mask layer when dialog opening
  2236. *
  2237. * @param {Object} dialog dialog jQuery object
  2238. * @returns {void}
  2239. */
  2240. editormd.dialogShowMask = function(dialog) {
  2241. var editor = this.editor;
  2242. var settings = this.settings || {dialogShowMask : true};
  2243. dialog.css({
  2244. top : ($(window).height() - dialog.height()) / 2 + "px",
  2245. left : ($(window).width() - dialog.width()) / 2 + "px"
  2246. });
  2247. if (settings.dialogShowMask) {
  2248. editor.children("." + this.classPrefix + "mask").css("z-index", parseInt(dialog.css("z-index")) - 1).show();
  2249. }
  2250. };
  2251. editormd.toolbarHandlers = {
  2252. undo : function() {
  2253. this.cm.undo();
  2254. },
  2255. redo : function() {
  2256. this.cm.redo();
  2257. },
  2258. bold : function() {
  2259. var cm = this.cm;
  2260. var cursor = cm.getCursor();
  2261. var selection = cm.getSelection();
  2262. cm.replaceSelection("**" + selection + "**");
  2263. if(selection === "") {
  2264. cm.setCursor(cursor.line, cursor.ch + 2);
  2265. }
  2266. },
  2267. del : function() {
  2268. var cm = this.cm;
  2269. var cursor = cm.getCursor();
  2270. var selection = cm.getSelection();
  2271. cm.replaceSelection("~~" + selection + "~~");
  2272. if(selection === "") {
  2273. cm.setCursor(cursor.line, cursor.ch + 2);
  2274. }
  2275. },
  2276. italic : function() {
  2277. var cm = this.cm;
  2278. var cursor = cm.getCursor();
  2279. var selection = cm.getSelection();
  2280. cm.replaceSelection("*" + selection + "*");
  2281. if(selection === "") {
  2282. cm.setCursor(cursor.line, cursor.ch + 1);
  2283. }
  2284. },
  2285. quote : function() {
  2286. var cm = this.cm;
  2287. var cursor = cm.getCursor();
  2288. var selection = cm.getSelection();
  2289. if (cursor.ch !== 0)
  2290. {
  2291. cm.setCursor(cursor.line, 0);
  2292. cm.replaceSelection("> " + selection);
  2293. cm.setCursor(cursor.line, cursor.ch + 2);
  2294. }
  2295. else
  2296. {
  2297. cm.replaceSelection("> " + selection);
  2298. }
  2299. //cm.replaceSelection("> " + selection);
  2300. //cm.setCursor(cursor.line, (selection === "") ? cursor.ch + 2 : cursor.ch + selection.length + 2);
  2301. },
  2302. ucfirst : function() {
  2303. var cm = this.cm;
  2304. var selection = cm.getSelection();
  2305. var selections = cm.listSelections();
  2306. cm.replaceSelection(editormd.firstUpperCase(selection));
  2307. cm.setSelections(selections);
  2308. },
  2309. ucwords : function() {
  2310. var cm = this.cm;
  2311. var selection = cm.getSelection();
  2312. var selections = cm.listSelections();
  2313. cm.replaceSelection(editormd.wordsFirstUpperCase(selection));
  2314. cm.setSelections(selections);
  2315. },
  2316. uppercase : function() {
  2317. var cm = this.cm;
  2318. var selection = cm.getSelection();
  2319. var selections = cm.listSelections();
  2320. cm.replaceSelection(selection.toUpperCase());
  2321. cm.setSelections(selections);
  2322. },
  2323. lowercase : function() {
  2324. var cm = this.cm;
  2325. var cursor = cm.getCursor();
  2326. var selection = cm.getSelection();
  2327. var selections = cm.listSelections();
  2328. cm.replaceSelection(selection.toLowerCase());
  2329. cm.setSelections(selections);
  2330. },
  2331. h1 : function() {
  2332. var cm = this.cm;
  2333. var cursor = cm.getCursor();
  2334. var selection = cm.getSelection();
  2335. if (cursor.ch !== 0)
  2336. {
  2337. cm.setCursor(cursor.line, 0);
  2338. cm.replaceSelection("# " + selection);
  2339. cm.setCursor(cursor.line, cursor.ch + 2);
  2340. }
  2341. else
  2342. {
  2343. cm.replaceSelection("# " + selection);
  2344. }
  2345. },
  2346. h2 : function() {
  2347. var cm = this.cm;
  2348. var cursor = cm.getCursor();
  2349. var selection = cm.getSelection();
  2350. if (cursor.ch !== 0)
  2351. {
  2352. cm.setCursor(cursor.line, 0);
  2353. cm.replaceSelection("## " + selection);
  2354. cm.setCursor(cursor.line, cursor.ch + 3);
  2355. }
  2356. else
  2357. {
  2358. cm.replaceSelection("## " + selection);
  2359. }
  2360. },
  2361. h3 : function() {
  2362. var cm = this.cm;
  2363. var cursor = cm.getCursor();
  2364. var selection = cm.getSelection();
  2365. if (cursor.ch !== 0)
  2366. {
  2367. cm.setCursor(cursor.line, 0);
  2368. cm.replaceSelection("### " + selection);
  2369. cm.setCursor(cursor.line, cursor.ch + 4);
  2370. }
  2371. else
  2372. {
  2373. cm.replaceSelection("### " + selection);
  2374. }
  2375. },
  2376. h4 : function() {
  2377. var cm = this.cm;
  2378. var cursor = cm.getCursor();
  2379. var selection = cm.getSelection();
  2380. if (cursor.ch !== 0)
  2381. {
  2382. cm.setCursor(cursor.line, 0);
  2383. cm.replaceSelection("#### " + selection);
  2384. cm.setCursor(cursor.line, cursor.ch + 5);
  2385. }
  2386. else
  2387. {
  2388. cm.replaceSelection("#### " + selection);
  2389. }
  2390. },
  2391. h5 : function() {
  2392. var cm = this.cm;
  2393. var cursor = cm.getCursor();
  2394. var selection = cm.getSelection();
  2395. if (cursor.ch !== 0)
  2396. {
  2397. cm.setCursor(cursor.line, 0);
  2398. cm.replaceSelection("##### " + selection);
  2399. cm.setCursor(cursor.line, cursor.ch + 6);
  2400. }
  2401. else
  2402. {
  2403. cm.replaceSelection("##### " + selection);
  2404. }
  2405. },
  2406. h6 : function() {
  2407. var cm = this.cm;
  2408. var cursor = cm.getCursor();
  2409. var selection = cm.getSelection();
  2410. if (cursor.ch !== 0)
  2411. {
  2412. cm.setCursor(cursor.line, 0);
  2413. cm.replaceSelection("###### " + selection);
  2414. cm.setCursor(cursor.line, cursor.ch + 7);
  2415. }
  2416. else
  2417. {
  2418. cm.replaceSelection("###### " + selection);
  2419. }
  2420. },
  2421. "list-ul" : function() {
  2422. var cm = this.cm;
  2423. var cursor = cm.getCursor();
  2424. var selection = cm.getSelection();
  2425. if (selection === "")
  2426. {
  2427. cm.replaceSelection("- " + selection);
  2428. }
  2429. else
  2430. {
  2431. var selectionText = selection.split("\n");
  2432. for (var i = 0, len = selectionText.length; i < len; i++)
  2433. {
  2434. selectionText[i] = (selectionText[i] === "") ? "" : "- " + selectionText[i];
  2435. }
  2436. cm.replaceSelection(selectionText.join("\n"));
  2437. }
  2438. },
  2439. "list-ol" : function() {
  2440. var cm = this.cm;
  2441. var cursor = cm.getCursor();
  2442. var selection = cm.getSelection();
  2443. if(selection === "")
  2444. {
  2445. cm.replaceSelection("1. " + selection);
  2446. }
  2447. else
  2448. {
  2449. var selectionText = selection.split("\n");
  2450. for (var i = 0, len = selectionText.length; i < len; i++)
  2451. {
  2452. selectionText[i] = (selectionText[i] === "") ? "" : (i+1) + ". " + selectionText[i];
  2453. }
  2454. cm.replaceSelection(selectionText.join("\n"));
  2455. }
  2456. },
  2457. hr : function() {
  2458. var cm = this.cm;
  2459. var cursor = cm.getCursor();
  2460. var selection = cm.getSelection();
  2461. cm.replaceSelection(((cursor.ch !== 0) ? "\n\n" : "\n") + "------------\n\n");
  2462. },
  2463. tex : function() {
  2464. if (!this.settings.tex)
  2465. {
  2466. alert("settings.tex === false");
  2467. return this;
  2468. }
  2469. var cm = this.cm;
  2470. var cursor = cm.getCursor();
  2471. var selection = cm.getSelection();
  2472. cm.replaceSelection("$$" + selection + "$$");
  2473. if(selection === "") {
  2474. cm.setCursor(cursor.line, cursor.ch + 2);
  2475. }
  2476. },
  2477. link : function() {
  2478. this.executePlugin("linkDialog", "link-dialog/link-dialog");
  2479. },
  2480. "reference-link" : function() {
  2481. this.executePlugin("referenceLinkDialog", "reference-link-dialog/reference-link-dialog");
  2482. },
  2483. pagebreak : function() {
  2484. if (!this.settings.pageBreak)
  2485. {
  2486. alert("settings.pageBreak === false");
  2487. return this;
  2488. }
  2489. var cm = this.cm;
  2490. var selection = cm.getSelection();
  2491. cm.replaceSelection("\r\n[========]\r\n");
  2492. },
  2493. image : function() {
  2494. this.executePlugin("imageDialog", "image-dialog/image-dialog");
  2495. },
  2496. code : function() {
  2497. var cm = this.cm;
  2498. var cursor = cm.getCursor();
  2499. var selection = cm.getSelection();
  2500. cm.replaceSelection("`" + selection + "`");
  2501. if (selection === "") {
  2502. cm.setCursor(cursor.line, cursor.ch + 1);
  2503. }
  2504. },
  2505. "code-block" : function() {
  2506. this.executePlugin("codeBlockDialog", "code-block-dialog/code-block-dialog");
  2507. },
  2508. "preformatted-text" : function() {
  2509. this.executePlugin("preformattedTextDialog", "preformatted-text-dialog/preformatted-text-dialog");
  2510. },
  2511. table : function() {
  2512. this.executePlugin("tableDialog", "table-dialog/table-dialog");
  2513. },
  2514. datetime : function() {
  2515. var cm = this.cm;
  2516. var selection = cm.getSelection();
  2517. var date = new Date();
  2518. var langName = this.settings.lang.name;
  2519. var datefmt = editormd.dateFormat() + " " + editormd.dateFormat((langName === "zh-cn" || langName === "zh-tw") ? "cn-week-day" : "week-day");
  2520. cm.replaceSelection(datefmt);
  2521. },
  2522. emoji : function() {
  2523. this.executePlugin("emojiDialog", "emoji-dialog/emoji-dialog");
  2524. },
  2525. "html-entities" : function() {
  2526. this.executePlugin("htmlEntitiesDialog", "html-entities-dialog/html-entities-dialog");
  2527. },
  2528. "goto-line" : function() {
  2529. this.executePlugin("gotoLineDialog", "goto-line-dialog/goto-line-dialog");
  2530. },
  2531. watch : function() {
  2532. this[this.settings.watch ? "unwatch" : "watch"]();
  2533. },
  2534. preview : function() {
  2535. this.previewing();
  2536. },
  2537. fullscreen : function() {
  2538. this.fullscreen();
  2539. },
  2540. clear : function() {
  2541. this.clear();
  2542. },
  2543. search : function() {
  2544. this.search();
  2545. },
  2546. help : function() {
  2547. this.executePlugin("helpDialog", "help-dialog/help-dialog");
  2548. },
  2549. info : function() {
  2550. this.showInfoDialog();
  2551. }
  2552. };
  2553. editormd.keyMaps = {
  2554. "Ctrl-1" : "h1",
  2555. "Ctrl-2" : "h2",
  2556. "Ctrl-3" : "h3",
  2557. "Ctrl-4" : "h4",
  2558. "Ctrl-5" : "h5",
  2559. "Ctrl-6" : "h6",
  2560. "Ctrl-B" : "bold", // if this is string == editormd.toolbarHandlers.xxxx
  2561. "Ctrl-D" : "datetime",
  2562. "Ctrl-E" : function() { // emoji
  2563. var cm = this.cm;
  2564. var cursor = cm.getCursor();
  2565. var selection = cm.getSelection();
  2566. if (!this.settings.emoji)
  2567. {
  2568. alert("Error: settings.emoji == false");
  2569. return ;
  2570. }
  2571. cm.replaceSelection(":" + selection + ":");
  2572. if (selection === "") {
  2573. cm.setCursor(cursor.line, cursor.ch + 1);
  2574. }
  2575. },
  2576. "Ctrl-Alt-G" : "goto-line",
  2577. "Ctrl-H" : "hr",
  2578. "Ctrl-I" : "italic",
  2579. "Ctrl-K" : "code",
  2580. "Ctrl-L" : function() {
  2581. var cm = this.cm;
  2582. var cursor = cm.getCursor();
  2583. var selection = cm.getSelection();
  2584. var title = (selection === "") ? "" : " \""+selection+"\"";
  2585. cm.replaceSelection("[" + selection + "]("+title+")");
  2586. if (selection === "") {
  2587. cm.setCursor(cursor.line, cursor.ch + 1);
  2588. }
  2589. },
  2590. "Ctrl-U" : "list-ul",
  2591. "Shift-Ctrl-A" : function() {
  2592. var cm = this.cm;
  2593. var cursor = cm.getCursor();
  2594. var selection = cm.getSelection();
  2595. if (!this.settings.atLink)
  2596. {
  2597. alert("Error: settings.atLink == false");
  2598. return ;
  2599. }
  2600. cm.replaceSelection("@" + selection);
  2601. if (selection === "") {
  2602. cm.setCursor(cursor.line, cursor.ch + 1);
  2603. }
  2604. },
  2605. "Shift-Ctrl-C" : "code",
  2606. "Shift-Ctrl-Q" : "quote",
  2607. "Shift-Ctrl-S" : "del",
  2608. "Shift-Ctrl-K" : "tex", // KaTeX
  2609. "Shift-Alt-C" : function() {
  2610. var cm = this.cm;
  2611. var cursor = cm.getCursor();
  2612. var selection = cm.getSelection();
  2613. cm.replaceSelection(["```", selection, "```"].join("\n"));
  2614. if (selection === "") {
  2615. cm.setCursor(cursor.line, cursor.ch + 3);
  2616. }
  2617. },
  2618. "Shift-Ctrl-Alt-C" : "code-block",
  2619. "Shift-Ctrl-H" : "html-entities",
  2620. "Shift-Alt-H" : "help",
  2621. "Shift-Ctrl-E" : "emoji",
  2622. "Shift-Ctrl-U" : "uppercase",
  2623. "Shift-Alt-U" : "ucwords",
  2624. "Shift-Ctrl-Alt-U" : "ucfirst",
  2625. "Shift-Alt-L" : "lowercase",
  2626. "Shift-Ctrl-I" : function() {
  2627. var cm = this.cm;
  2628. var cursor = cm.getCursor();
  2629. var selection = cm.getSelection();
  2630. var title = (selection === "") ? "" : " \""+selection+"\"";
  2631. cm.replaceSelection("![" + selection + "]("+title+")");
  2632. if (selection === "") {
  2633. cm.setCursor(cursor.line, cursor.ch + 4);
  2634. }
  2635. },
  2636. "Shift-Ctrl-Alt-I" : "image",
  2637. "Shift-Ctrl-L" : "link",
  2638. "Shift-Ctrl-O" : "list-ol",
  2639. "Shift-Ctrl-P" : "preformatted-text",
  2640. "Shift-Ctrl-T" : "table",
  2641. "Shift-Alt-P" : "pagebreak",
  2642. "F9" : "watch",
  2643. "F10" : "preview",
  2644. "F11" : "fullscreen",
  2645. };
  2646. /**
  2647. * 清除字符串两边的空格
  2648. * Clear the space of strings both sides.
  2649. *
  2650. * @param {String} str string
  2651. * @returns {String} trimed string
  2652. */
  2653. var trim = function(str) {
  2654. return (!String.prototype.trim) ? str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "") : str.trim();
  2655. };
  2656. editormd.trim = trim;
  2657. /**
  2658. * 所有单词首字母大写
  2659. * Words first to uppercase
  2660. *
  2661. * @param {String} str string
  2662. * @returns {String} string
  2663. */
  2664. var ucwords = function (str) {
  2665. return str.toLowerCase().replace(/\b(\w)|\s(\w)/g, function($1) {
  2666. return $1.toUpperCase();
  2667. });
  2668. };
  2669. editormd.ucwords = editormd.wordsFirstUpperCase = ucwords;
  2670. /**
  2671. * 字符串首字母大写
  2672. * Only string first char to uppercase
  2673. *
  2674. * @param {String} str string
  2675. * @returns {String} string
  2676. */
  2677. var firstUpperCase = function(str) {
  2678. return str.toLowerCase().replace(/\b(\w)/, function($1){
  2679. return $1.toUpperCase();
  2680. });
  2681. };
  2682. var ucfirst = firstUpperCase;
  2683. editormd.firstUpperCase = editormd.ucfirst = firstUpperCase;
  2684. editormd.urls = {
  2685. atLinkBase : "https://github.com/"
  2686. };
  2687. editormd.regexs = {
  2688. atLink : /@(\w+)/g,
  2689. email : /(\w+)@(\w+)\.(\w+)\.?(\w+)?/g,
  2690. emailLink : /(mailto:)?([\w\.\_]+)@(\w+)\.(\w+)\.?(\w+)?/g,
  2691. emoji : /:([\w\+-]+):/g,
  2692. emojiDatetime : /(\d{2}:\d{2}:\d{2})/g,
  2693. twemoji : /:(tw-([\w]+)-?(\w+)?):/g,
  2694. fontAwesome : /:(fa-([\w]+)(-(\w+)){0,}):/g,
  2695. editormdLogo : /:(editormd-logo-?(\w+)?):/g,
  2696. pageBreak : /^\[[=]{8,}\]$/
  2697. };
  2698. // Emoji graphics files url path
  2699. editormd.emoji = {
  2700. path : "http://www.emoji-cheat-sheet.com/graphics/emojis/",
  2701. ext : ".png"
  2702. };
  2703. // Twitter Emoji (Twemoji) graphics files url path
  2704. editormd.twemoji = {
  2705. path : "http://twemoji.maxcdn.com/36x36/",
  2706. ext : ".png"
  2707. };
  2708. /**
  2709. * 自定义marked的解析器
  2710. * Custom Marked renderer rules
  2711. *
  2712. * @param {Array} markdownToC 传入用于接收TOC的数组
  2713. * @returns {Renderer} markedRenderer 返回marked的Renderer自定义对象
  2714. */
  2715. editormd.markedRenderer = function(markdownToC, options) {
  2716. var defaults = {
  2717. toc : true, // Table of contents
  2718. tocm : false,
  2719. tocStartLevel : 1, // Said from H1 to create ToC
  2720. pageBreak : true,
  2721. atLink : true, // for @link
  2722. emailLink : true, // for mail address auto link
  2723. taskList : false, // Enable Github Flavored Markdown task lists
  2724. emoji : false, // :emoji: , Support Twemoji, fontAwesome, Editor.md logo emojis.
  2725. tex : false, // TeX(LaTeX), based on KaTeX
  2726. flowChart : false, // flowChart.js only support IE9+
  2727. sequenceDiagram : false, // sequenceDiagram.js only support IE9+
  2728. };
  2729. var settings = $.extend(defaults, options || {});
  2730. var marked = editormd.$marked;
  2731. var markedRenderer = new marked.Renderer();
  2732. markdownToC = markdownToC || [];
  2733. var regexs = editormd.regexs;
  2734. var atLinkReg = regexs.atLink;
  2735. var emojiReg = regexs.emoji;
  2736. var emailReg = regexs.email;
  2737. var emailLinkReg = regexs.emailLink;
  2738. var twemojiReg = regexs.twemoji;
  2739. var faIconReg = regexs.fontAwesome;
  2740. var editormdLogoReg = regexs.editormdLogo;
  2741. var pageBreakReg = regexs.pageBreak;
  2742. markedRenderer.emoji = function(text) {
  2743. text = text.replace(editormd.regexs.emojiDatetime, function($1) {
  2744. return $1.replace(/:/g, "&#58;");
  2745. });
  2746. var matchs = text.match(emojiReg);
  2747. if (!matchs || !settings.emoji) {
  2748. return text;
  2749. }
  2750. for (var i = 0, len = matchs.length; i < len; i++)
  2751. {
  2752. if (matchs[i] === ":+1:") {
  2753. matchs[i] = ":\\+1:";
  2754. }
  2755. text = text.replace(new RegExp(matchs[i]), function($1, $2){
  2756. var faMatchs = $1.match(faIconReg);
  2757. var name = $1.replace(/:/g, "");
  2758. if (faMatchs)
  2759. {
  2760. for (var fa = 0, len1 = faMatchs.length; fa < len1; fa++)
  2761. {
  2762. var faName = faMatchs[fa].replace(/:/g, "");
  2763. return "<i class=\"fa " + faName + " fa-emoji\" title=\"" + faName.replace("fa-", "") + "\"></i>";
  2764. }
  2765. }
  2766. else
  2767. {
  2768. var emdlogoMathcs = $1.match(editormdLogoReg);
  2769. var twemojiMatchs = $1.match(twemojiReg);
  2770. if (emdlogoMathcs)
  2771. {
  2772. for (var x = 0, len2 = emdlogoMathcs.length; x < len2; x++)
  2773. {
  2774. var logoName = emdlogoMathcs[x].replace(/:/g, "");
  2775. return "<i class=\"" + logoName + "\" title=\"Editor.md logo (" + logoName + ")\"></i>";
  2776. }
  2777. }
  2778. else if (twemojiMatchs)
  2779. {
  2780. for (var t = 0, len3 = twemojiMatchs.length; t < len3; t++)
  2781. {
  2782. var twe = twemojiMatchs[t].replace(/:/g, "").replace("tw-", "");
  2783. return "<img src=\"" + editormd.twemoji.path + twe + editormd.twemoji.ext + "\" title=\"twemoji-" + twe + "\" alt=\"twemoji-" + twe + "\" class=\"emoji twemoji\" />";
  2784. }
  2785. }
  2786. else
  2787. {
  2788. var src = (name === "+1") ? "plus1" : name;
  2789. src = (src === "black_large_square") ? "black_square" : src;
  2790. src = (src === "moon") ? "waxing_gibbous_moon" : src;
  2791. return "<img src=\"" + editormd.emoji.path + src + editormd.emoji.ext + "\" class=\"emoji\" title=\"&#58;" + name + "&#58;\" alt=\"&#58;" + name + "&#58;\" />";
  2792. }
  2793. }
  2794. });
  2795. }
  2796. return text;
  2797. };
  2798. markedRenderer.atLink = function(text) {
  2799. if (atLinkReg.test(text))
  2800. {
  2801. if (settings.atLink)
  2802. {
  2803. text = text.replace(emailReg, function($1, $2, $3, $4) {
  2804. return $1.replace(/@/g, "_#_&#64;_#_");
  2805. });
  2806. text = text.replace(atLinkReg, function($1, $2) {
  2807. return "<a href=\"" + editormd.urls.atLinkBase + "" + $2 + "\" title=\"&#64;" + $2 + "\" class=\"at-link\">" + $1 + "</a>";
  2808. }).replace(/_#_&#64;_#_/g, "@");
  2809. }
  2810. if (settings.emailLink)
  2811. {
  2812. text = text.replace(emailLinkReg, function($1, $2, $3, $4, $5) {
  2813. return (!$2 && $.inArray($5, "jpg|jpeg|png|gif|webp|ico|icon|pdf".split("|")) < 0) ? "<a href=\"mailto:" + $1 + "\">"+$1+"</a>" : $1;
  2814. });
  2815. }
  2816. return text;
  2817. }
  2818. return text;
  2819. };
  2820. markedRenderer.link = function (href, title, text) {
  2821. if (this.options.sanitize) {
  2822. try {
  2823. var prot = decodeURIComponent(unescape(href)).replace(/[^\w:]/g,"").toLowerCase();
  2824. } catch(e) {
  2825. return "";
  2826. }
  2827. if (prot.indexOf("javascript:") === 0) {
  2828. return "";
  2829. }
  2830. }
  2831. var out = "<a href=\"" + href + "\"";
  2832. if (atLinkReg.test(title) || atLinkReg.test(text))
  2833. {
  2834. if (title)
  2835. {
  2836. out += " title=\"" + title.replace(/@/g, "&#64;");
  2837. }
  2838. return out + "\">" + text.replace(/@/g, "&#64;") + "</a>";
  2839. }
  2840. if (title) {
  2841. out += " title=\"" + title + "\"";
  2842. }
  2843. out += ">" + text + "</a>";
  2844. return out;
  2845. };
  2846. markedRenderer.heading = function(text, level, raw) {
  2847. var linkText = text;
  2848. var hasLinkReg = /\s*\<a\s*href\=\"(.*)\"\s*([^\>]*)\>(.*)\<\/a\>\s*/;
  2849. var getLinkTextReg = /\s*\<a\s*([^\>]+)\>([^\>]*)\<\/a\>\s*/g;
  2850. if (hasLinkReg.test(text))
  2851. {
  2852. var tempText = [];
  2853. text = text.split(/\<a\s*([^\>]+)\>([^\>]*)\<\/a\>/);
  2854. for (var i = 0, len = text.length; i < len; i++)
  2855. {
  2856. tempText.push(text[i].replace(/\s*href\=\"(.*)\"\s*/g, ""));
  2857. }
  2858. text = tempText.join(" ");
  2859. }
  2860. text = trim(text);
  2861. var escapedText = text.toLowerCase().replace(/[^\w]+/g, "-");
  2862. var toc = {
  2863. text : text,
  2864. level : level,
  2865. slug : escapedText
  2866. };
  2867. var isChinese = /^[\u4e00-\u9fa5]+$/.test(text);
  2868. var id = (isChinese) ? escape(text).replace(/\%/g, "") : text.toLowerCase().replace(/[^\w]+/g, "-");
  2869. markdownToC.push(toc);
  2870. var headingHTML = "<h" + level + " id=\"h"+ level + "-" + this.options.headerPrefix + id +"\">";
  2871. headingHTML += "<a name=\"" + text + "\" class=\"reference-link\"></a>";
  2872. headingHTML += "<span class=\"header-link octicon octicon-link\"></span>";
  2873. headingHTML += (hasLinkReg) ? this.atLink(this.emoji(linkText)) : this.atLink(this.emoji(text));
  2874. headingHTML += "</h" + level + ">";
  2875. return headingHTML;
  2876. };
  2877. markedRenderer.pageBreak = function(text) {
  2878. if (pageBreakReg.test(text) && settings.pageBreak)
  2879. {
  2880. text = "<hr style=\"page-break-after:always;\" class=\"page-break editormd-page-break\" />";
  2881. }
  2882. return text;
  2883. };
  2884. markedRenderer.paragraph = function(text) {
  2885. var isTeXInline = /\$\$(.*)\$\$/g.test(text);
  2886. var isTeXLine = /^\$\$(.*)\$\$$/.test(text);
  2887. var isTeXAddClass = (isTeXLine) ? " class=\"" + editormd.classNames.tex + "\"" : "";
  2888. var isToC = (settings.tocm) ? /^(\[TOC\]|\[TOCM\])$/.test(text) : /^\[TOC\]$/.test(text);
  2889. var isToCMenu = /^\[TOCM\]$/.test(text);
  2890. if (!isTeXLine && isTeXInline)
  2891. {
  2892. text = text.replace(/(\$\$([^\$]*)\$\$)+/g, function($1, $2) {
  2893. return "<span class=\"" + editormd.classNames.tex + "\">" + $2.replace(/\$/g, "") + "</span>";
  2894. });
  2895. }
  2896. else
  2897. {
  2898. text = (isTeXLine) ? text.replace(/\$/g, "") : text;
  2899. }
  2900. var tocHTML = "<div class=\"markdown-toc editormd-markdown-toc\">" + text + "</div>";
  2901. return (isToC) ? ( (isToCMenu) ? "<div class=\"editormd-toc-menu\">" + tocHTML + "</div><br/>" : tocHTML )
  2902. : ( (pageBreakReg.test(text)) ? this.pageBreak(text) : "<p" + isTeXAddClass + ">" + this.atLink(this.emoji(text)) + "</p>\n" );
  2903. };
  2904. markedRenderer.code = function (code, lang, escaped) {
  2905. if (lang === "seq" || lang === "sequence")
  2906. {
  2907. return "<div class=\"sequence-diagram\">" + code + "</div>";
  2908. }
  2909. else if ( lang === "flow")
  2910. {
  2911. return "<div class=\"flowchart\">" + code + "</div>";
  2912. }
  2913. else if ( lang === "math" || lang === "latex" || lang === "katex")
  2914. {
  2915. return "<p class=\"" + editormd.classNames.tex + "\">" + code + "</p>";
  2916. }
  2917. else
  2918. {
  2919. return marked.Renderer.prototype.code.apply(this, arguments);
  2920. }
  2921. };
  2922. markedRenderer.tablecell = function(content, flags) {
  2923. var type = (flags.header) ? "th" : "td";
  2924. var tag = (flags.align) ? "<" + type +" style=\"text-align:" + flags.align + "\">" : "<" + type + ">";
  2925. return tag + this.atLink(this.emoji(content)) + "</" + type + ">\n";
  2926. };
  2927. markedRenderer.listitem = function(text) {
  2928. if (settings.taskList && /^\s*\[[x\s]\]\s*/.test(text))
  2929. {
  2930. text = text.replace(/^\s*\[\s\]\s*/, "<input type=\"checkbox\" class=\"task-list-item-checkbox\" /> ")
  2931. .replace(/^\s*\[x\]\s*/, "<input type=\"checkbox\" class=\"task-list-item-checkbox\" checked disabled /> ");
  2932. return "<li style=\"list-style: none;\">" + this.atLink(this.emoji(text)) + "</li>";
  2933. }
  2934. else
  2935. {
  2936. return "<li>" + this.atLink(this.emoji(text)) + "</li>";
  2937. }
  2938. };
  2939. return markedRenderer;
  2940. };
  2941. /**
  2942. *
  2943. * 生成TOC(Table of Contents)
  2944. * Creating ToC (Table of Contents)
  2945. *
  2946. * @param {Array} toc 从marked获取的TOC数组列表
  2947. * @param {Element} container 插入TOC的容器元素
  2948. * @param {Integer} startLevel Hx 起始层级
  2949. * @returns {Object} tocContainer 返回ToC列表容器层的jQuery对象元素
  2950. */
  2951. editormd.markdownToCRenderer = function(toc, container, tocDropdown, startLevel) {
  2952. var html = "";
  2953. var lastLevel = 0;
  2954. var classPrefix = this.classPrefix;
  2955. startLevel = startLevel || 1;
  2956. for (var i = 0, len = toc.length; i < len; i++)
  2957. {
  2958. var text = toc[i].text;
  2959. var level = toc[i].level;
  2960. if (level < startLevel) {
  2961. continue;
  2962. }
  2963. if (level > lastLevel)
  2964. {
  2965. html += "";
  2966. }
  2967. else if (level < lastLevel)
  2968. {
  2969. html += (new Array(lastLevel - level + 2)).join("</ul></li>");
  2970. }
  2971. else
  2972. {
  2973. html += "</ul></li>";
  2974. }
  2975. html += "<li><a class=\"toc-level-" + level + "\" href=\"#" + text + "\" level=\"" + level + "\">" + text + "</a><ul>";
  2976. lastLevel = level;
  2977. }
  2978. var tocContainer = container.find(".markdown-toc");
  2979. if ((tocContainer.length < 1 && container.attr("previewContainer") === "false"))
  2980. {
  2981. var tocHTML = "<div class=\"markdown-toc " + classPrefix + "markdown-toc\"></div>";
  2982. tocHTML = (tocDropdown) ? "<div class=\"" + classPrefix + "toc-menu\">" + tocHTML + "</div>" : tocHTML;
  2983. container.html(tocHTML);
  2984. tocContainer = container.find(".markdown-toc");
  2985. }
  2986. if (tocDropdown)
  2987. {
  2988. tocContainer.wrap("<div class=\"" + classPrefix + "toc-menu\"></div><br/>");
  2989. }
  2990. tocContainer.html("<ul class=\"markdown-toc-list\"></ul>").children(".markdown-toc-list").html(html.replace(/\r?\n?\<ul\>\<\/ul\>/g, ""));
  2991. return tocContainer;
  2992. };
  2993. /**
  2994. *
  2995. * 生成TOC下拉菜单
  2996. * Creating ToC dropdown menu
  2997. *
  2998. * @param {Object} container 插入TOC的容器jQuery对象元素
  2999. * @param {String} tocTitle ToC title
  3000. * @returns {Object} return toc-menu object
  3001. */
  3002. editormd.tocDropdownMenu = function(container, tocTitle) {
  3003. tocTitle = tocTitle || "Table of Contents";
  3004. var zindex = 400;
  3005. var tocMenus = container.find("." + this.classPrefix + "toc-menu");
  3006. tocMenus.each(function() {
  3007. var $this = $(this);
  3008. var toc = $this.children(".markdown-toc");
  3009. var icon = "<i class=\"fa fa-angle-down\"></i>";
  3010. var btn = "<a href=\"javascript:;\" class=\"toc-menu-btn\">" + icon + tocTitle + "</a>";
  3011. var menu = toc.children("ul");
  3012. var list = menu.find("li");
  3013. toc.append(btn);
  3014. list.first().before("<li><h1>" + tocTitle + " " + icon + "</h1></li>");
  3015. $this.mouseover(function(){
  3016. menu.show();
  3017. list.each(function(){
  3018. var li = $(this);
  3019. var ul = li.children("ul");
  3020. if (ul.html() === "")
  3021. {
  3022. ul.remove();
  3023. }
  3024. if (ul.length > 0 && ul.html() !== "")
  3025. {
  3026. var firstA = li.children("a").first();
  3027. if (firstA.children(".fa").length < 1)
  3028. {
  3029. firstA.append( $(icon).css({ float:"right", paddingTop:"4px" }) );
  3030. }
  3031. }
  3032. li.mouseover(function(){
  3033. ul.css("z-index", zindex).show();
  3034. zindex += 1;
  3035. }).mouseleave(function(){
  3036. ul.hide();
  3037. });
  3038. });
  3039. }).mouseleave(function(){
  3040. menu.hide();
  3041. });
  3042. });
  3043. return tocMenus;
  3044. };
  3045. /**
  3046. * 简单地过滤指定的HTML标签
  3047. * Filter custom html tags
  3048. *
  3049. * @param {String} html 要过滤HTML
  3050. * @param {String} filters 要过滤的标签
  3051. * @returns {String} html 返回过滤的HTML
  3052. */
  3053. editormd.filterHTMLTags = function(html, filters) {
  3054. if (typeof html !== "string") {
  3055. html = new String(html);
  3056. }
  3057. if (typeof filters !== "string") {
  3058. return html;
  3059. }
  3060. var expression = filters.split("|");
  3061. var filterTags = expression[0].split(",");
  3062. var attrs = expression[1];
  3063. for (var i = 0, len = filterTags.length; i < len; i++)
  3064. {
  3065. var tag = filterTags[i];
  3066. html = html.replace(new RegExp("\<\s*" + tag + "\s*([^\>]*)\>([^\>]*)\<\s*\/" + tag + "\s*\>", "igm"), "");
  3067. }
  3068. //return html;
  3069. if (typeof attrs !== "undefined")
  3070. {
  3071. var htmlTagRegex = /\<(\w+)\s*([^\>]*)\>([^\>]*)\<\/(\w+)\>/ig;
  3072. if (attrs === "*")
  3073. {
  3074. html = html.replace(htmlTagRegex, function($1, $2, $3, $4, $5) {
  3075. return "<" + $2 + ">" + $4 + "</" + $5 + ">";
  3076. });
  3077. }
  3078. else if (attrs === "on*")
  3079. {
  3080. html = html.replace(htmlTagRegex, function($1, $2, $3, $4, $5) {
  3081. var el = $("<" + $2 + ">" + $4 + "</" + $5 + ">");
  3082. var _attrs = $($1)[0].attributes;
  3083. var $attrs = {};
  3084. $.each(_attrs, function(i, e) {
  3085. if (e.nodeName !== '"') $attrs[e.nodeName] = e.nodeValue;
  3086. });
  3087. $.each($attrs, function(i) {
  3088. if (i.indexOf("on") === 0) {
  3089. delete $attrs[i];
  3090. }
  3091. });
  3092. el.attr($attrs);
  3093. var text = (typeof el[1] !== "undefined") ? $(el[1]).text() : "";
  3094. return el[0].outerHTML + text;
  3095. });
  3096. }
  3097. else if (attrs === "filterXSS")
  3098. {
  3099. var tags = ['a','abbr','address',
  3100. 'area','article','aside','audio','b','bdi','bdo','big','blockquote','br','caption','center','cite','code','col','colgroup','dd','del','details','div','dl','dt','em','font','footer','h1','h2','h3','h4','h5','h6','header','hr','i','img','ins','li','mark','nav','ol','p','pre','s','section','small','span','sub','sup','strong','table','tbody','td','tfoot','th','thead','tr','tt','u','ul','video','input'],
  3101. tagAttrs = ['target','title','shape','coords','href','alt','autoplay','controls','loop','preload','src','dir','cite','align','valign','span','width','height','datetime','open','color','size','face','border','rowspan','colspan','style','class','id','name','type','checked','disabled'],
  3102. whiteList = (function(){
  3103. var result = {};
  3104. for(var i=0,len=tags.length; i<len; i++){
  3105. result[tags[i]] = tagAttrs;
  3106. };
  3107. return result;
  3108. })();
  3109. html = filterXSS(html,{
  3110. whiteList:whiteList
  3111. });
  3112. }
  3113. else
  3114. {
  3115. html = html.replace(htmlTagRegex, function($1, $2, $3, $4) {
  3116. var filterAttrs = attrs.split(",");
  3117. var el = $($1);
  3118. el.html($4);
  3119. $.each(filterAttrs, function(i) {
  3120. el.attr(filterAttrs[i], null);
  3121. });
  3122. return el[0].outerHTML;
  3123. });
  3124. }
  3125. }
  3126. return html;
  3127. };
  3128. /**
  3129. * 将Markdown文档解析为HTML用于前台显示
  3130. * Parse Markdown to HTML for Font-end preview.
  3131. *
  3132. * @param {String} id 用于显示HTML的对象ID
  3133. * @param {Object} [options={}] 配置选项可选
  3134. * @returns {Object} div 返回jQuery对象元素
  3135. */
  3136. editormd.markdownToHTML = function(id, options) {
  3137. var defaults = {
  3138. gfm : true,
  3139. toc : true,
  3140. tocm : false,
  3141. tocStartLevel : 1,
  3142. tocTitle : "目录",
  3143. tocDropdown : false,
  3144. tocContainer : "",
  3145. markdown : "",
  3146. markdownSourceCode : false,
  3147. htmlDecode : false,
  3148. autoLoadKaTeX : true,
  3149. pageBreak : true,
  3150. atLink : true, // for @link
  3151. emailLink : true, // for mail address auto link
  3152. tex : false,
  3153. taskList : false, // Github Flavored Markdown task lists
  3154. emoji : false,
  3155. flowChart : false,
  3156. sequenceDiagram : false,
  3157. previewCodeHighlight : true
  3158. };
  3159. editormd.$marked = marked;
  3160. var div = $("#" + id);
  3161. var settings = div.settings = $.extend(true, defaults, options || {});
  3162. var saveTo = div.find("textarea");
  3163. if (saveTo.length < 1)
  3164. {
  3165. div.append("<textarea></textarea>");
  3166. saveTo = div.find("textarea");
  3167. }
  3168. var markdownDoc = (settings.markdown === "") ? saveTo.val() : settings.markdown;
  3169. var markdownToC = [];
  3170. var rendererOptions = {
  3171. toc : settings.toc,
  3172. tocm : settings.tocm,
  3173. tocStartLevel : settings.tocStartLevel,
  3174. taskList : settings.taskList,
  3175. emoji : settings.emoji,
  3176. tex : settings.tex,
  3177. pageBreak : settings.pageBreak,
  3178. atLink : settings.atLink, // for @link
  3179. emailLink : settings.emailLink, // for mail address auto link
  3180. flowChart : settings.flowChart,
  3181. sequenceDiagram : settings.sequenceDiagram,
  3182. previewCodeHighlight : settings.previewCodeHighlight,
  3183. };
  3184. var markedOptions = {
  3185. renderer : editormd.markedRenderer(markdownToC, rendererOptions),
  3186. gfm : settings.gfm,
  3187. tables : true,
  3188. breaks : true,
  3189. pedantic : false,
  3190. sanitize : (settings.htmlDecode) ? false : true, // 是否忽略HTML标签,即是否开启HTML标签解析,为了安全性,默认不开启
  3191. smartLists : true,
  3192. smartypants : true
  3193. };
  3194. markdownDoc = new String(markdownDoc);
  3195. var markdownParsed = marked(markdownDoc, markedOptions);
  3196. markdownParsed = editormd.filterHTMLTags(markdownParsed, settings.htmlDecode);
  3197. if (settings.markdownSourceCode) {
  3198. saveTo.text(markdownDoc);
  3199. } else {
  3200. saveTo.remove();
  3201. }
  3202. div.addClass("markdown-body " + this.classPrefix + "html-preview").append(markdownParsed);
  3203. var tocContainer = (settings.tocContainer !== "") ? $(settings.tocContainer) : div;
  3204. if (settings.tocContainer !== "")
  3205. {
  3206. tocContainer.attr("previewContainer", false);
  3207. }
  3208. if (settings.toc)
  3209. {
  3210. div.tocContainer = this.markdownToCRenderer(markdownToC, tocContainer, settings.tocDropdown, settings.tocStartLevel);
  3211. if (settings.tocDropdown || div.find("." + this.classPrefix + "toc-menu").length > 0)
  3212. {
  3213. this.tocDropdownMenu(div, settings.tocTitle);
  3214. }
  3215. if (settings.tocContainer !== "")
  3216. {
  3217. div.find(".editormd-toc-menu, .editormd-markdown-toc").remove();
  3218. }
  3219. }
  3220. if (settings.previewCodeHighlight)
  3221. {
  3222. div.find("pre").addClass("prettyprint linenums");
  3223. prettyPrint();
  3224. }
  3225. if (!editormd.isIE8)
  3226. {
  3227. if (settings.flowChart) {
  3228. div.find(".flowchart").flowChart();
  3229. }
  3230. if (settings.sequenceDiagram) {
  3231. div.find(".sequence-diagram").sequenceDiagram({theme: "simple"});
  3232. }
  3233. }
  3234. if (settings.tex)
  3235. {
  3236. var katexHandle = function() {
  3237. div.find("." + editormd.classNames.tex).each(function(){
  3238. var tex = $(this);
  3239. katex.render(tex.html().replace(/&lt;/g, "<").replace(/&gt;/g, ">"), tex[0]);
  3240. tex.find(".katex").css("font-size", "1.6em");
  3241. });
  3242. };
  3243. if (settings.autoLoadKaTeX && !editormd.$katex && !editormd.kaTeXLoaded)
  3244. {
  3245. this.loadKaTeX(function() {
  3246. editormd.$katex = katex;
  3247. editormd.kaTeXLoaded = true;
  3248. katexHandle();
  3249. });
  3250. }
  3251. else
  3252. {
  3253. katexHandle();
  3254. }
  3255. }
  3256. div.getMarkdown = function() {
  3257. return saveTo.val();
  3258. };
  3259. return div;
  3260. };
  3261. // Editor.md themes, change toolbar themes etc.
  3262. // added @1.5.0
  3263. editormd.themes = ["default", "dark"];
  3264. // Preview area themes
  3265. // added @1.5.0
  3266. editormd.previewThemes = ["default", "dark"];
  3267. // CodeMirror / editor area themes
  3268. // @1.5.0 rename -> editorThemes, old version -> themes
  3269. editormd.editorThemes = [
  3270. "default", "3024-day", "3024-night",
  3271. "ambiance", "ambiance-mobile",
  3272. "base16-dark", "base16-light", "blackboard",
  3273. "cobalt",
  3274. "eclipse", "elegant", "erlang-dark",
  3275. "lesser-dark",
  3276. "mbo", "mdn-like", "midnight", "monokai",
  3277. "neat", "neo", "night",
  3278. "paraiso-dark", "paraiso-light", "pastel-on-dark",
  3279. "rubyblue",
  3280. "solarized",
  3281. "the-matrix", "tomorrow-night-eighties", "twilight",
  3282. "vibrant-ink",
  3283. "xq-dark", "xq-light"
  3284. ];
  3285. editormd.loadPlugins = {};
  3286. editormd.loadFiles = {
  3287. js : [],
  3288. css : [],
  3289. plugin : []
  3290. };
  3291. /**
  3292. * 动态加载Editor.md插件但不立即执行
  3293. * Load editor.md plugins
  3294. *
  3295. * @param {String} fileName 插件文件路径
  3296. * @param {Function} [callback=function()] 加载成功后执行的回调函数
  3297. * @param {String} [into="head"] 嵌入页面的位置
  3298. */
  3299. editormd.loadPlugin = function(fileName, callback, into) {
  3300. callback = callback || function() {};
  3301. this.loadScript(fileName, function() {
  3302. editormd.loadFiles.plugin.push(fileName);
  3303. callback();
  3304. }, into);
  3305. };
  3306. /**
  3307. * 动态加载CSS文件的方法
  3308. * Load css file method
  3309. *
  3310. * @param {String} fileName CSS文件名
  3311. * @param {Function} [callback=function()] 加载成功后执行的回调函数
  3312. * @param {String} [into="head"] 嵌入页面的位置
  3313. */
  3314. editormd.loadCSS = function(fileName, callback, into) {
  3315. into = into || "head";
  3316. callback = callback || function() {};
  3317. var css = document.createElement("link");
  3318. css.type = "text/css";
  3319. css.rel = "stylesheet";
  3320. css.onload = css.onreadystatechange = function() {
  3321. editormd.loadFiles.css.push(fileName);
  3322. callback();
  3323. };
  3324. css.href = fileName + ".css";
  3325. if(into === "head") {
  3326. document.getElementsByTagName("head")[0].appendChild(css);
  3327. } else {
  3328. document.body.appendChild(css);
  3329. }
  3330. };
  3331. editormd.isIE = (navigator.appName == "Microsoft Internet Explorer");
  3332. editormd.isIE8 = (editormd.isIE && navigator.appVersion.match(/8./i) == "8.");
  3333. /**
  3334. * 动态加载JS文件的方法
  3335. * Load javascript file method
  3336. *
  3337. * @param {String} fileName JS文件名
  3338. * @param {Function} [callback=function()] 加载成功后执行的回调函数
  3339. * @param {String} [into="head"] 嵌入页面的位置
  3340. */
  3341. editormd.loadScript = function(fileName, callback, into) {
  3342. into = into || "head";
  3343. callback = callback || function() {};
  3344. var script = null;
  3345. script = document.createElement("script");
  3346. script.id = fileName.replace(/[\./]+/g, "-");
  3347. script.type = "text/javascript";
  3348. script.src = fileName + ".js";
  3349. if (editormd.isIE8)
  3350. {
  3351. script.onreadystatechange = function() {
  3352. if(script.readyState)
  3353. {
  3354. if (script.readyState === "loaded" || script.readyState === "complete")
  3355. {
  3356. script.onreadystatechange = null;
  3357. editormd.loadFiles.js.push(fileName);
  3358. callback();
  3359. }
  3360. }
  3361. };
  3362. }
  3363. else
  3364. {
  3365. script.onload = function() {
  3366. editormd.loadFiles.js.push(fileName);
  3367. callback();
  3368. };
  3369. }
  3370. if (into === "head") {
  3371. document.getElementsByTagName("head")[0].appendChild(script);
  3372. } else {
  3373. document.body.appendChild(script);
  3374. }
  3375. };
  3376. // 使用国外的CDN,加载速度有时会很慢,或者自定义URL
  3377. // You can custom KaTeX load url.
  3378. editormd.katexURL = {
  3379. css : "//cdn.staticfile.org/KaTeX/0.3.0/katex.min",
  3380. js : "//cdn.staticfile.org/KaTeX/0.3.0/katex.min"
  3381. };
  3382. editormd.kaTeXLoaded = false;
  3383. /**
  3384. * 加载KaTeX文件
  3385. * load KaTeX files
  3386. *
  3387. * @param {Function} [callback=function()] 加载成功后执行的回调函数
  3388. */
  3389. editormd.loadKaTeX = function (callback) {
  3390. editormd.loadCSS(editormd.katexURL.css, function(){
  3391. editormd.loadScript(editormd.katexURL.js, callback || function(){});
  3392. });
  3393. };
  3394. /**
  3395. * 锁屏
  3396. * lock screen
  3397. *
  3398. * @param {Boolean} lock Boolean 布尔值是否锁屏
  3399. * @returns {void}
  3400. */
  3401. editormd.lockScreen = function(lock) {
  3402. $("html,body").css("overflow", (lock) ? "hidden" : "");
  3403. };
  3404. /**
  3405. * 动态创建对话框
  3406. * Creating custom dialogs
  3407. *
  3408. * @param {Object} options 配置项键值对 Key/Value
  3409. * @returns {dialog} 返回创建的dialog的jQuery实例对象
  3410. */
  3411. editormd.createDialog = function(options) {
  3412. var defaults = {
  3413. name : "",
  3414. width : 420,
  3415. height: 240,
  3416. title : "",
  3417. drag : true,
  3418. closed : true,
  3419. content : "",
  3420. mask : true,
  3421. maskStyle : {
  3422. backgroundColor : "#fff",
  3423. opacity : 0.1
  3424. },
  3425. lockScreen : true,
  3426. footer : true,
  3427. buttons : false
  3428. };
  3429. options = $.extend(true, defaults, options);
  3430. var $this = this;
  3431. var editor = this.editor;
  3432. var classPrefix = editormd.classPrefix;
  3433. var guid = (new Date()).getTime();
  3434. var dialogName = ( (options.name === "") ? classPrefix + "dialog-" + guid : options.name);
  3435. var mouseOrTouch = editormd.mouseOrTouch;
  3436. var html = "<div class=\"" + classPrefix + "dialog " + dialogName + "\">";
  3437. if (options.title !== "")
  3438. {
  3439. html += "<div class=\"" + classPrefix + "dialog-header\"" + ( (options.drag) ? " style=\"cursor: move;\"" : "" ) + ">";
  3440. html += "<strong class=\"" + classPrefix + "dialog-title\">" + options.title + "</strong>";
  3441. html += "</div>";
  3442. }
  3443. if (options.closed)
  3444. {
  3445. html += "<a href=\"javascript:;\" class=\"fa fa-close " + classPrefix + "dialog-close\"></a>";
  3446. }
  3447. html += "<div class=\"" + classPrefix + "dialog-container\">" + options.content;
  3448. if (options.footer || typeof options.footer === "string")
  3449. {
  3450. html += "<div class=\"" + classPrefix + "dialog-footer\">" + ( (typeof options.footer === "boolean") ? "" : options.footer) + "</div>";
  3451. }
  3452. html += "</div>";
  3453. html += "<div class=\"" + classPrefix + "dialog-mask " + classPrefix + "dialog-mask-bg\"></div>";
  3454. html += "<div class=\"" + classPrefix + "dialog-mask " + classPrefix + "dialog-mask-con\"></div>";
  3455. html += "</div>";
  3456. editor.append(html);
  3457. var dialog = editor.find("." + dialogName);
  3458. dialog.lockScreen = function(lock) {
  3459. if (options.lockScreen)
  3460. {
  3461. $("html,body").css("overflow", (lock) ? "hidden" : "");
  3462. $this.resize();
  3463. }
  3464. return dialog;
  3465. };
  3466. dialog.showMask = function() {
  3467. if (options.mask)
  3468. {
  3469. editor.find("." + classPrefix + "mask").css(options.maskStyle).css("z-index", editormd.dialogZindex - 1).show();
  3470. }
  3471. return dialog;
  3472. };
  3473. dialog.hideMask = function() {
  3474. if (options.mask)
  3475. {
  3476. editor.find("." + classPrefix + "mask").hide();
  3477. }
  3478. return dialog;
  3479. };
  3480. dialog.loading = function(show) {
  3481. var loading = dialog.find("." + classPrefix + "dialog-mask");
  3482. loading[(show) ? "show" : "hide"]();
  3483. return dialog;
  3484. };
  3485. dialog.lockScreen(true).showMask();
  3486. dialog.show().css({
  3487. zIndex : editormd.dialogZindex,
  3488. border : (editormd.isIE8) ? "1px solid #ddd" : "",
  3489. width : (typeof options.width === "number") ? options.width + "px" : options.width,
  3490. height : (typeof options.height === "number") ? options.height + "px" : options.height
  3491. });
  3492. var dialogPosition = function(){
  3493. dialog.css({
  3494. top : ($(window).height() - dialog.height()) / 2 + "px",
  3495. left : ($(window).width() - dialog.width()) / 2 + "px"
  3496. });
  3497. };
  3498. dialogPosition();
  3499. $(window).resize(dialogPosition);
  3500. dialog.children("." + classPrefix + "dialog-close").bind(mouseOrTouch("click", "touchend"), function() {
  3501. dialog.hide().lockScreen(false).hideMask();
  3502. });
  3503. if (typeof options.buttons === "object")
  3504. {
  3505. var footer = dialog.footer = dialog.find("." + classPrefix + "dialog-footer");
  3506. for (var key in options.buttons)
  3507. {
  3508. var btn = options.buttons[key];
  3509. var btnClassName = classPrefix + key + "-btn";
  3510. footer.append("<button class=\"" + classPrefix + "btn " + btnClassName + "\">" + btn[0] + "</button>");
  3511. btn[1] = $.proxy(btn[1], dialog);
  3512. footer.children("." + btnClassName).bind(mouseOrTouch("click", "touchend"), btn[1]);
  3513. }
  3514. }
  3515. if (options.title !== "" && options.drag)
  3516. {
  3517. var posX, posY;
  3518. var dialogHeader = dialog.children("." + classPrefix + "dialog-header");
  3519. if (!options.mask) {
  3520. dialogHeader.bind(mouseOrTouch("click", "touchend"), function(){
  3521. editormd.dialogZindex += 2;
  3522. dialog.css("z-index", editormd.dialogZindex);
  3523. });
  3524. }
  3525. dialogHeader.mousedown(function(e) {
  3526. e = e || window.event; //IE
  3527. posX = e.clientX - parseInt(dialog[0].style.left);
  3528. posY = e.clientY - parseInt(dialog[0].style.top);
  3529. document.onmousemove = moveAction;
  3530. });
  3531. var userCanSelect = function (obj) {
  3532. obj.removeClass(classPrefix + "user-unselect").off("selectstart");
  3533. };
  3534. var userUnselect = function (obj) {
  3535. obj.addClass(classPrefix + "user-unselect").on("selectstart", function(event) { // selectstart for IE
  3536. return false;
  3537. });
  3538. };
  3539. var moveAction = function (e) {
  3540. e = e || window.event; //IE
  3541. var left, top, nowLeft = parseInt(dialog[0].style.left), nowTop = parseInt(dialog[0].style.top);
  3542. if( nowLeft >= 0 ) {
  3543. if( nowLeft + dialog.width() <= $(window).width()) {
  3544. left = e.clientX - posX;
  3545. } else {
  3546. left = $(window).width() - dialog.width();
  3547. document.onmousemove = null;
  3548. }
  3549. } else {
  3550. left = 0;
  3551. document.onmousemove = null;
  3552. }
  3553. if( nowTop >= 0 ) {
  3554. top = e.clientY - posY;
  3555. } else {
  3556. top = 0;
  3557. document.onmousemove = null;
  3558. }
  3559. document.onselectstart = function() {
  3560. return false;
  3561. };
  3562. userUnselect($("body"));
  3563. userUnselect(dialog);
  3564. dialog[0].style.left = left + "px";
  3565. dialog[0].style.top = top + "px";
  3566. };
  3567. document.onmouseup = function() {
  3568. userCanSelect($("body"));
  3569. userCanSelect(dialog);
  3570. document.onselectstart = null;
  3571. document.onmousemove = null;
  3572. };
  3573. dialogHeader.touchDraggable = function() {
  3574. var offset = null;
  3575. var start = function(e) {
  3576. var orig = e.originalEvent;
  3577. var pos = $(this).parent().position();
  3578. offset = {
  3579. x : orig.changedTouches[0].pageX - pos.left,
  3580. y : orig.changedTouches[0].pageY - pos.top
  3581. };
  3582. };
  3583. var move = function(e) {
  3584. e.preventDefault();
  3585. var orig = e.originalEvent;
  3586. $(this).parent().css({
  3587. top : orig.changedTouches[0].pageY - offset.y,
  3588. left : orig.changedTouches[0].pageX - offset.x
  3589. });
  3590. };
  3591. this.bind("touchstart", start).bind("touchmove", move);
  3592. };
  3593. dialogHeader.touchDraggable();
  3594. }
  3595. editormd.dialogZindex += 2;
  3596. return dialog;
  3597. };
  3598. /**
  3599. * 鼠标和触摸事件的判断/选择方法
  3600. * MouseEvent or TouchEvent type switch
  3601. *
  3602. * @param {String} [mouseEventType="click"] 供选择的鼠标事件
  3603. * @param {String} [touchEventType="touchend"] 供选择的触摸事件
  3604. * @returns {String} EventType 返回事件类型名称
  3605. */
  3606. editormd.mouseOrTouch = function(mouseEventType, touchEventType) {
  3607. mouseEventType = mouseEventType || "click";
  3608. touchEventType = touchEventType || "touchend";
  3609. var eventType = mouseEventType;
  3610. var userAgentInfo = navigator.userAgent;
  3611. var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
  3612. var flag = true;
  3613. for (var v = 0; v < Agents.length; v++) {
  3614. if (userAgentInfo.indexOf(Agents[v]) > 0) {
  3615. flag = false;
  3616. break;
  3617. }
  3618. }
  3619. if(!flag){
  3620. eventType = touchEventType;
  3621. }
  3622. return eventType;
  3623. };
  3624. /**
  3625. * 日期时间的格式化方法
  3626. * Datetime format method
  3627. *
  3628. * @param {String} [format=""] 日期时间的格式类似PHP的格式
  3629. * @returns {String} datefmt 返回格式化后的日期时间字符串
  3630. */
  3631. editormd.dateFormat = function(format) {
  3632. format = format || "";
  3633. var addZero = function(d) {
  3634. return (d < 10) ? "0" + d : d;
  3635. };
  3636. var date = new Date();
  3637. var year = date.getFullYear();
  3638. var year2 = year.toString().slice(2, 4);
  3639. var month = addZero(date.getMonth() + 1);
  3640. var day = addZero(date.getDate());
  3641. var weekDay = date.getDay();
  3642. var hour = addZero(date.getHours());
  3643. var min = addZero(date.getMinutes());
  3644. var second = addZero(date.getSeconds());
  3645. var ms = addZero(date.getMilliseconds());
  3646. var datefmt = "";
  3647. var ymd = year2 + "-" + month + "-" + day;
  3648. var fymd = year + "-" + month + "-" + day;
  3649. var hms = hour + ":" + min + ":" + second;
  3650. switch (format)
  3651. {
  3652. case "UNIX Time" :
  3653. datefmt = date.getTime();
  3654. break;
  3655. case "UTC" :
  3656. datefmt = date.toUTCString();
  3657. break;
  3658. case "yy" :
  3659. datefmt = year2;
  3660. break;
  3661. case "year" :
  3662. case "yyyy" :
  3663. datefmt = year;
  3664. break;
  3665. case "month" :
  3666. case "mm" :
  3667. datefmt = month;
  3668. break;
  3669. case "cn-week-day" :
  3670. case "cn-wd" :
  3671. var cnWeekDays = ["日", "一", "二", "三", "四", "五", "六"];
  3672. datefmt = "星期" + cnWeekDays[weekDay];
  3673. break;
  3674. case "week-day" :
  3675. case "wd" :
  3676. var weekDays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
  3677. datefmt = weekDays[weekDay];
  3678. break;
  3679. case "day" :
  3680. case "dd" :
  3681. datefmt = day;
  3682. break;
  3683. case "hour" :
  3684. case "hh" :
  3685. datefmt = hour;
  3686. break;
  3687. case "min" :
  3688. case "ii" :
  3689. datefmt = min;
  3690. break;
  3691. case "second" :
  3692. case "ss" :
  3693. datefmt = second;
  3694. break;
  3695. case "ms" :
  3696. datefmt = ms;
  3697. break;
  3698. case "yy-mm-dd" :
  3699. datefmt = ymd;
  3700. break;
  3701. case "yyyy-mm-dd" :
  3702. datefmt = fymd;
  3703. break;
  3704. case "yyyy-mm-dd h:i:s ms" :
  3705. case "full + ms" :
  3706. datefmt = fymd + " " + hms + " " + ms;
  3707. break;
  3708. case "full" :
  3709. case "yyyy-mm-dd h:i:s" :
  3710. default:
  3711. datefmt = fymd + " " + hms;
  3712. break;
  3713. }
  3714. return datefmt;
  3715. };
  3716. return editormd;
  3717. }));