- /* - * Editor.md - * - * @file editormd.js - * @version v1.4.5 - * @description Open source online markdown editor. - * @license MIT License - * @author Pandao - * {@link https://github.com/pandao/editor.md} - * @updateTime 2015-06-02 - */ - -;(function(factory) { - "use strict"; - - // CommonJS/Node.js - if (typeof require === "function" && typeof exports === "object" && typeof module === "object") - { - module.exports = factory; - } - else if (typeof define === "function") // AMD/CMD/Sea.js - { - if (define.amd) // for Require.js - { - /* Require.js define replace */ - } - else - { - define(["jquery"], factory); // for Sea.js - } - } - else - { - window.editormd = factory(); - } - -}(function() { - - /* Require.js assignment replace */ - - "use strict"; - - var $ = (typeof (jQuery) !== "undefined") ? jQuery : Zepto; - - if (typeof ($) === "undefined") { - return ; - } - - /** - * editormd - * - * @param {String} id 编辑器的ID - * @param {Object} options 配置选项 Key/Value - * @returns {Object} editormd 返回editormd对象 - */ - - var editormd = function (id, options) { - return new editormd.fn.init(id, options); - }; - - editormd.title = editormd.$name = "Editor.md"; - editormd.version = "1.4.5"; - editormd.homePage = "https://pandao.github.io/editor.md/"; - editormd.classPrefix = "editormd-"; - - editormd.toolbarModes = { - full : [ - "undo", "redo", "|", - "bold", "del", "italic", "quote", "ucwords", "uppercase", "lowercase", "|", - "h1", "h2", "h3", "h4", "h5", "h6", "|", - "list-ul", "list-ol", "hr", "|", - "link", "reference-link", "image", "code", "preformatted-text", "code-block", "table", "datetime", "emoji", "html-entities", "pagebreak", "|", - "goto-line", "watch", "preview", "fullscreen", "clear", "search", "|", - "help", "info" - ], - simple : [ - "undo", "redo", "|", - "bold", "del", "italic", "quote", "uppercase", "lowercase", "|", - "h1", "h2", "h3", "h4", "h5", "h6", "|", - "list-ul", "list-ol", "hr", "|", - "watch", "preview", "fullscreen", "|", - "help", "info" - ], - mini : [ - "undo", "redo", "|", - "watch", "preview", "|", - "help", "info" - ] - }; - - editormd.defaults = { - mode : "gfm", //gfm or markdown - theme : "default", - name : "", - value : "", // value for CodeMirror, if mode not gfm/markdown - markdown : "", - appendMarkdown : "", // if in init textarea value not empty, append markdown to textarea - width : "100%", - height : "100%", - path : "./lib/", // Dependents module file directory - pluginPath : "", // If this empty, default use settings.path + "../plugins/" - delay : 300, // Delay parse markdown to html, Uint : ms - autoLoadModules : true, // Automatic load dependent module files - watch : true, - placeholder : "Enjoy Markdown! coding now...", - gotoLine : true, - codeFold : false, - autoHeight : false, - autoFocus : true, - autoCloseTags : true, - searchReplace : true, - syncScrolling : true, - readOnly : false, - tabSize : 4, - indentUnit : 4, - lineNumbers : true, - lineWrapping : true, - autoCloseBrackets : true, - showTrailingSpace : true, - matchBrackets : true, - indentWithTabs : true, - styleSelectedText : true, - matchWordHighlight : true, // options: true, false, "onselected" - styleActiveLine : true, // Highlight the current line - dialogLockScreen : true, - dialogShowMask : true, - dialogDraggable : true, - dialogMaskBgColor : "#fff", - dialogMaskOpacity : 0.1, - fontSize : "13px", - saveHTMLToTextarea : false, - disabledKeyMaps : [], - - onload : function() {}, - onresize : function() {}, - onchange : function() {}, - onwatch : null, - onunwatch : null, - onpreviewing : function() {}, - onpreviewed : function() {}, - onfullscreen : function() {}, - onfullscreenExit : function() {}, - onscroll : function() {}, - onpreviewscroll : function() {}, - - imageUpload : false, - imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"], - imageUploadURL : "", - crossDomainUpload : false, - uploadCallbackURL : "", - - toc : true, // Table of contents - tocm : false, // Using [TOCM], auto create ToC dropdown menu - tocTitle : "", // for ToC dropdown menu btn - tocDropdown : false, - tocContainer : "", - tocStartLevel : 1, // Said from H1 to create ToC - htmlDecode : false, // Open the HTML tag identification - pageBreak : true, // Enable parse page break [========] - atLink : true, // for @link - emailLink : true, // for email address auto link - taskList : false, // Enable Github Flavored Markdown task lists - emoji : false, // :emoji: , Support Github emoji, Twitter Emoji (Twemoji); - // Support FontAwesome icon emoji :fa-xxx: > Using fontAwesome icon web fonts; - // Support Editor.md logo icon emoji :editormd-logo: :editormd-logo-1x: > 1~8x; - tex : false, // TeX(LaTeX), based on KaTeX - flowChart : false, // flowChart.js only support IE9+ - sequenceDiagram : false, // sequenceDiagram.js only support IE9+ - previewCodeHighlight : true, - - toolbar : true, // show/hide toolbar - toolbarAutoFixed : true, // on window scroll auto fixed position - toolbarIcons : "full", - toolbarTitles : {}, - toolbarHandlers : { - ucwords : function() { - return editormd.toolbarHandlers.ucwords; - }, - lowercase : function() { - return editormd.toolbarHandlers.lowercase; - } - }, - toolbarCustomIcons : { // using html tag create toolbar icon, unused default <a> tag. - lowercase : "<a href=\"javascript:;\" title=\"Lowercase\" unselectable=\"on\"><i class=\"fa\" name=\"lowercase\" style=\"font-size:24px;margin-top: -10px;\">a</i></a>", - "ucwords" : "<a href=\"javascript:;\" title=\"ucwords\" unselectable=\"on\"><i class=\"fa\" name=\"ucwords\" style=\"font-size:20px;margin-top: -3px;\">Aa</i></a>" - }, - toolbarIconsClass : { - undo : "fa-undo", - redo : "fa-repeat", - bold : "fa-bold", - del : "fa-strikethrough", - italic : "fa-italic", - quote : "fa-quote-left", - uppercase : "fa-font", - h1 : editormd.classPrefix + "bold", - h2 : editormd.classPrefix + "bold", - h3 : editormd.classPrefix + "bold", - h4 : editormd.classPrefix + "bold", - h5 : editormd.classPrefix + "bold", - h6 : editormd.classPrefix + "bold", - "list-ul" : "fa-list-ul", - "list-ol" : "fa-list-ol", - hr : "fa-minus", - link : "fa-link", - "reference-link" : "fa-anchor", - image : "fa-picture-o", - code : "fa-code", - "preformatted-text" : "fa-file-code-o", - "code-block" : "fa-file-code-o", - table : "fa-table", - datetime : "fa-clock-o", - emoji : "fa-smile-o", - "html-entities" : "fa-copyright", - pagebreak : "fa-newspaper-o", - "goto-line" : "fa-terminal", // fa-crosshairs - watch : "fa-eye-slash", - unwatch : "fa-eye", - preview : "fa-desktop", - search : "fa-search", - fullscreen : "fa-arrows-alt", - clear : "fa-eraser", - help : "fa-question-circle", - info : "fa-info-circle" - }, - toolbarIconTexts : {}, - - lang : { - name : "zh-cn", - description : "开源在线Markdown编辑器<br/>Open source online Markdown editor.", - tocTitle : "目录", - toolbar : { - undo : "撤销(Ctrl+Z)", - redo : "重做(Ctrl+Y)", - bold : "粗体", - del : "删除线", - italic : "斜体", - quote : "引用", - ucwords : "将每个单词首字母转成大写", - uppercase : "将所选转换成大写", - lowercase : "将所选转换成小写", - h1 : "标题1", - h2 : "标题2", - h3 : "标题3", - h4 : "标题4", - h5 : "标题5", - h6 : "标题6", - "list-ul" : "无序列表", - "list-ol" : "有序列表", - hr : "横线", - link : "链接", - "reference-link" : "引用链接", - image : "添加图片", - code : "行内代码", - "preformatted-text" : "预格式文本 / 代码块(缩进风格)", - "code-block" : "代码块(多语言风格)", - table : "添加表格", - datetime : "日期时间", - emoji : "Emoji表情", - "html-entities" : "HTML实体字符", - pagebreak : "插入分页符", - "goto-line" : "跳转到行", - watch : "关闭实时预览", - unwatch : "开启实时预览", - preview : "全窗口预览HTML(按 Shift + ESC还原)", - fullscreen : "全屏(按ESC还原)", - clear : "清空", - search : "搜索", - help : "使用帮助", - info : "关于" + editormd.title - }, - buttons : { - enter : "确定", - cancel : "取消", - close : "关闭" - }, - dialog : { - link : { - title : "添加链接", - url : "链接地址", - urlTitle : "链接标题", - urlEmpty : "错误:请填写链接地址。" - }, - referenceLink : { - title : "添加引用链接", - name : "引用名称", - url : "链接地址", - urlId : "链接ID", - urlTitle : "链接标题", - nameEmpty: "错误:引用链接的名称不能为空。", - idEmpty : "错误:请填写引用链接的ID。", - urlEmpty : "错误:请填写引用链接的URL地址。" - }, - image : { - title : "添加图片", - url : "图片地址", - link : "图片链接", - alt : "图片描述", - uploadButton : "本地上传", - imageURLEmpty : "错误:图片地址不能为空。", - uploadFileEmpty : "错误:上传的图片不能为空。", - formatNotAllowed : "错误:只允许上传图片文件,允许上传的图片文件格式有:" - }, - preformattedText : { - title : "添加预格式文本或代码块", - emptyAlert : "错误:请填写预格式文本或代码的内容。" - }, - codeBlock : { - title : "添加代码块", - selectLabel : "代码语言:", - selectDefaultText : "请选择代码语言", - otherLanguage : "其他语言", - unselectedLanguageAlert : "错误:请选择代码所属的语言类型。", - codeEmptyAlert : "错误:请填写代码内容。" - }, - htmlEntities : { - title : "HTML 实体字符" - }, - help : { - title : "使用帮助" - } - } - } - }; - - editormd.classNames = { - tex : editormd.classPrefix + "tex" - }; - - editormd.dialogZindex = 99999; - - editormd.$katex = null; - editormd.$marked = null; - editormd.$CodeMirror = null; - editormd.$prettyPrint = null; - - var timer, flowchartTimer; - - editormd.prototype = editormd.fn = { - state : { - watching : false, - loaded : false, - preview : false, - fullscreen : false - }, - - /** - * 构造函数/实例初始化 - * Constructor / instance initialization - * - * @param {String} id 编辑器的ID - * @param {Object} [options={}] 配置选项 Key/Value - * @returns {editormd} 返回editormd的实例对象 - */ - - init : function (id, options) { - - options = options || {}; - - if (typeof id === "object") - { - options = id; - } - - var _this = this; - var classPrefix = this.classPrefix = editormd.classPrefix; - var settings = this.settings = $.extend(true, editormd.defaults, options); - - id = (typeof id === "object") ? settings.id : id; - - var editor = this.editor = $("#" + id); - - this.id = id; - this.lang = settings.lang; - - var classNames = this.classNames = { - textarea : { - html : classPrefix + "html-textarea", - markdown : classPrefix + "markdown-textarea" - } - }; - - settings.pluginPath = (settings.pluginPath === "") ? settings.path + "../plugins/" : settings.pluginPath; - - this.state.watching = (settings.watch) ? true : false; - - if ( !editor.hasClass("editormd") ) { - editor.addClass("editormd"); - } - - editor.css({ - width : (typeof settings.width === "number") ? settings.width + "px" : settings.width, - height : (typeof settings.height === "number") ? settings.height + "px" : settings.height - }); - - if (settings.autoHeight) - { - editor.css("height", "auto"); - } - - var markdownTextarea = this.markdownTextarea = editor.children("textarea"); - - if (markdownTextarea.length < 1) - { - editor.append("<textarea></textarea>"); - markdownTextarea = this.markdownTextarea = editor.children("textarea"); - } - - markdownTextarea.addClass(classNames.textarea.markdown).attr("placeholder", settings.placeholder); - - if (typeof markdownTextarea.attr("name") === "undefined" || markdownTextarea.attr("name") === "") - { - markdownTextarea.attr("name", (settings.name !== "") ? settings.name : id + "-markdown-doc"); - } - - var appendElements = [ - (!settings.readOnly) ? "<a href=\"javascript:;\" class=\"fa fa-close " + classPrefix + "preview-close-btn\"></a>" : "", - ( (settings.saveHTMLToTextarea) ? "<textarea class=\"" + classNames.textarea.html + "\" name=\"" + id + "-html-code\"></textarea>" : "" ), - "<div class=\"" + classPrefix + "preview\"><div class=\"markdown-body " + classPrefix + "preview-container\"></div></div>", - "<div class=\"" + classPrefix + "container-mask\" style=\"display:block;\"></div>", - "<div class=\"" + classPrefix + "mask\"></div>" - ].join("\n"); - - editor.append(appendElements).addClass(classPrefix + "vertical"); - - this.mask = editor.children("." + classPrefix + "mask"); - this.containerMask = editor.children("." + classPrefix + "container-mask"); - - if (settings.markdown !== "") - { - markdownTextarea.val(settings.markdown); - } - - if (settings.appendMarkdown !== "") - { - markdownTextarea.val(markdownTextarea.val() + settings.appendMarkdown); - } - - this.htmlTextarea = editor.children("." + classNames.textarea.html); - this.preview = editor.children("." + classPrefix + "preview"); - this.previewContainer = this.preview.children("." + classPrefix + "preview-container"); - - if (typeof define === "function" && define.amd) - { - if (typeof katex !== "undefined") - { - editormd.$katex = katex; - } - - if (settings.searchReplace && !settings.readOnly) - { - editormd.loadCSS(settings.path + "codemirror/addon/dialog/dialog"); - editormd.loadCSS(settings.path + "codemirror/addon/search/matchesonscrollbar"); - } - } - - if ((typeof define === "function" && define.amd) || !settings.autoLoadModules) - { - if (typeof CodeMirror !== "undefined") { - editormd.$CodeMirror = CodeMirror; - } - - if (typeof marked !== "undefined") { - editormd.$marked = marked; - } - - this.setCodeMirror().setToolbar().loadedDisplay(); - } - else - { - this.loadQueues(); - } - - return this; - }, - - /** - * 所需组件加载队列 - * Required components loading queue - * - * @returns {editormd} 返回editormd的实例对象 - */ - - loadQueues : function() { - var _this = this; - var settings = this.settings; - var loadPath = settings.path; - - var loadFlowChartOrSequenceDiagram = function() { - - if (editormd.isIE8) - { - _this.loadedDisplay(); - - return ; - } - - if (settings.flowChart || settings.sequenceDiagram) - { - editormd.loadScript(loadPath + "raphael.min", function() { - - editormd.loadScript(loadPath + "underscore.min", function() { - - if (!settings.flowChart && settings.sequenceDiagram) - { - editormd.loadScript(loadPath + "sequence-diagram.min", function() { - _this.loadedDisplay(); - }); - } - else if (settings.flowChart && !settings.sequenceDiagram) - { - editormd.loadScript(loadPath + "flowchart.min", function() { - editormd.loadScript(loadPath + "jquery.flowchart.min", function() { - _this.loadedDisplay(); - }); - }); - } - else if (settings.flowChart && settings.sequenceDiagram) - { - editormd.loadScript(loadPath + "flowchart.min", function() { - editormd.loadScript(loadPath + "jquery.flowchart.min", function() { - editormd.loadScript(loadPath + "sequence-diagram.min", function() { - _this.loadedDisplay(); - }); - }); - }); - } - }); - - }); - } - else - { - _this.loadedDisplay(); - } - }; - - editormd.loadCSS(loadPath + "codemirror/codemirror.min"); - - if (settings.searchReplace && !settings.readOnly) - { - editormd.loadCSS(loadPath + "codemirror/addon/dialog/dialog"); - editormd.loadCSS(loadPath + "codemirror/addon/search/matchesonscrollbar"); - } - - if (settings.codeFold) - { - editormd.loadCSS(loadPath + "codemirror/addon/fold/foldgutter"); - } - - editormd.loadScript(loadPath + "codemirror/codemirror.min", function() { - editormd.$CodeMirror = CodeMirror; - - editormd.loadScript(loadPath + "codemirror/modes.min", function() { - - editormd.loadScript(loadPath + "codemirror/addons.min", function() { - - _this.setCodeMirror(); - - if (settings.mode !== "gfm" && settings.mode !== "markdown") - { - _this.loadedDisplay(); - - return false; - } - - _this.setToolbar(); - - editormd.loadScript(loadPath + "marked.min", function() { - - editormd.$marked = marked; - - if (settings.previewCodeHighlight) - { - editormd.loadScript(loadPath + "prettify.min", function() { - loadFlowChartOrSequenceDiagram(); - }); - } - else - { - loadFlowChartOrSequenceDiagram(); - } - }); - - }); - - }); - - }); - - return this; - }, - - /** - * 设置CodeMirror的主题 - * Setting CodeMirror theme - * - * @returns {editormd} 返回editormd的实例对象 - */ - - setTheme : function(theme) { - var settings = this.settings; - settings.theme = theme; - - if (theme !== "default") - { - editormd.loadCSS(settings.path + "codemirror/theme/" + settings.theme); - } - - this.cm.setOption("theme", theme); - - return this; - }, - - /** - * 配置和初始化CodeMirror组件 - * CodeMirror initialization - * - * @returns {editormd} 返回editormd的实例对象 - */ - - setCodeMirror : function() { - var settings = this.settings; - var editor = this.editor; - - if (settings.theme !== "default") - { - editormd.loadCSS(settings.path + "codemirror/theme/" + settings.theme); - } - - var codeMirrorConfig = { - mode : settings.mode, - theme : settings.theme, - tabSize : settings.tabSize, - dragDrop : false, - autofocus : settings.autoFocus, - autoCloseTags : settings.autoCloseTags, - readOnly : (settings.readOnly) ? "nocursor" : false, - indentUnit : settings.indentUnit, - lineNumbers : settings.lineNumbers, - lineWrapping : settings.lineWrapping, - extraKeys : { - "Ctrl-Q": function(cm) { - cm.foldCode(cm.getCursor()); - } - }, - foldGutter : settings.codeFold, - gutters : ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], - matchBrackets : settings.matchBrackets, - indentWithTabs : settings.indentWithTabs, - styleActiveLine : settings.styleActiveLine, - styleSelectedText : settings.styleSelectedText, - autoCloseBrackets : settings.autoCloseBrackets, - showTrailingSpace : settings.showTrailingSpace, - highlightSelectionMatches : ( (!settings.matchWordHighlight) ? false : { showToken: (settings.matchWordHighlight === "onselected") ? false : /\w/ } ) - }; - - this.codeEditor = this.cm = editormd.$CodeMirror.fromTextArea(this.markdownTextarea[0], codeMirrorConfig); - this.codeMirror = this.cmElement = editor.children(".CodeMirror"); - - if (settings.value !== "") - { - this.cm.setValue(settings.value); - } - - this.codeMirror.css({ - fontSize : settings.fontSize, - width : (!settings.watch) ? "100%" : "50%" - }); - - if (settings.autoHeight) - { - this.codeMirror.css("height", "auto"); - this.cm.setOption("viewportMargin", Infinity); - } - - return this; - }, - - /** - * 获取CodeMirror的配置选项 - * Get CodeMirror setting options - * - * @returns {Mixed} return CodeMirror setting option value - */ - - getCodeMirrorOption : function(key) { - return this.cm.getOption(key); - }, - - /** - * 配置和重配置CodeMirror的选项 - * CodeMirror setting options / resettings - * - * @returns {editormd} 返回editormd的实例对象 - */ - - setCodeMirrorOption : function(key, value) { - - this.cm.setOption(key, value); - - return this; - }, - - /** - * 添加 CodeMirror 键盘快捷键 - * Add CodeMirror keyboard shortcuts key map - * - * @returns {editormd} 返回editormd的实例对象 - */ - - addKeyMap : function(map, bottom) { - this.cm.addKeyMap(map, bottom); - - return this; - }, - - /** - * 移除 CodeMirror 键盘快捷键 - * Remove CodeMirror keyboard shortcuts key map - * - * @returns {editormd} 返回editormd的实例对象 - */ - - removeKeyMap : function(map) { - this.cm.removeKeyMap(map); - - return this; - }, - - /** - * 跳转到指定的行 - * Goto CodeMirror line - * - * @param {String|Intiger} line line number or "first"|"last" - * @returns {editormd} 返回editormd的实例对象 - */ - - gotoLine : function (line) { - - var settings = this.settings; - - if (!settings.gotoLine) - { - return this; - } - - var cm = this.cm; - var editor = this.editor; - var count = cm.lineCount(); - var preview = this.preview; - - if (typeof line === "string") - { - if(line === "last") - { - line = count; - } - - if (line === "first") - { - line = 1; - } - } - - if (typeof line !== "number") - { - alert("Error: The line number must be an integer."); - return this; - } - - line = parseInt(line) - 1; - - if (line > count) - { - alert("Error: The line number range 1-" + count); - - return this; - } - - cm.setCursor( {line : line, ch : 0} ); - - var scrollInfo = cm.getScrollInfo(); - var clientHeight = scrollInfo.clientHeight; - var coords = cm.charCoords({line : line, ch : 0}, "local"); - - cm.scrollTo(null, (coords.top + coords.bottom - clientHeight) / 2); - - if (settings.watch) - { - var cmScroll = this.codeMirror.find(".CodeMirror-scroll")[0]; - var height = $(cmScroll).height(); - var scrollTop = cmScroll.scrollTop; - var percent = (scrollTop / cmScroll.scrollHeight); - - if (scrollTop === 0) - { - preview.scrollTop(0); - } - else if (scrollTop + height >= cmScroll.scrollHeight - 16) - { - preview.scrollTop(preview[0].scrollHeight); - } - else - { - preview.scrollTop(preview[0].scrollHeight * percent); - } - } - - cm.focus(); - - return this; - }, - - /** - * 扩展当前实例对象,可同时设置多个或者只设置一个 - * Extend editormd instance object, can mutil setting. - * - * @returns {editormd} this(editormd instance object.) - */ - - extend : function() { - if (typeof arguments[1] !== "undefined") - { - if (typeof arguments[1] === "function") - { - arguments[1] = $.proxy(arguments[1], this); - } - - this[arguments[0]] = arguments[1]; - } - - if (typeof arguments[0] === "object" && typeof arguments[0].length === "undefined") - { - $.extend(true, this, arguments[0]); - } - - return this; - }, - - /** - * 设置或扩展当前实例对象,单个设置 - * Extend editormd instance object, one by one - * - * @param {String|Object} key option key - * @param {String|Object} value option value - * @returns {editormd} this(editormd instance object.) - */ - - set : function (key, value) { - - if (typeof value !== "undefined" && typeof value === "function") - { - value = $.proxy(value, this); - } - - this[key] = value; - - return this; - }, - - /** - * 重新配置 - * Resetting editor options - * - * @param {String|Object} key option key - * @param {String|Object} value option value - * @returns {editormd} this(editormd instance object.) - */ - - config : function(key, value) { - var settings = this.settings; - - if (typeof key === "object") - { - settings = $.extend(true, settings, key); - } - - if (typeof key === "string") - { - settings[key] = value; - } - - this.settings = settings; - this.recreate(); - - return this; - }, - - /** - * 注册事件处理方法 - * Bind editor event handle - * - * @param {String} eventType event type - * @param {Function} callback 回调函数 - * @returns {editormd} this(editormd instance object.) - */ - - on : function(eventType, callback) { - var settings = this.settings; - - if (typeof settings["on" + eventType] !== "undefined") - { - settings["on" + eventType] = $.proxy(callback, this); - } - - return this; - }, - - /** - * 解除事件处理方法 - * Unbind editor event handle - * - * @param {String} eventType event type - * @returns {editormd} this(editormd instance object.) - */ - - off : function(eventType) { - var settings = this.settings; - - if (typeof settings["on" + eventType] !== "undefined") - { - settings["on" + eventType] = function(){}; - } - - return this; - }, - - /** - * 显示工具栏 - * Display toolbar - * - * @param {Function} [callback=function(){}] 回调函数 - * @returns {editormd} 返回editormd的实例对象 - */ - - showToolbar : function(callback) { - var settings = this.settings; - - if(settings.readOnly) { - return this; - } - - if (settings.toolbar && (this.toolbar.length < 1 || this.toolbar.find("." + this.classPrefix + "menu").html() === "") ) - { - this.setToolbar(); - } - - settings.toolbar = true; - - this.toolbar.show(); - this.resize(); - - $.proxy(callback || function(){}, this)(); - - return this; - }, - - /** - * 隐藏工具栏 - * Hide toolbar - * - * @param {Function} [callback=function(){}] 回调函数 - * @returns {editormd} this(editormd instance object.) - */ - - hideToolbar : function(callback) { - var settings = this.settings; - - settings.toolbar = false; - this.toolbar.hide(); - this.resize(); - - $.proxy(callback || function(){}, this)(); - - return this; - }, - - /** - * 页面滚动时工具栏的固定定位 - * Set toolbar in window scroll auto fixed position - * - * @returns {editormd} 返回editormd的实例对象 - */ - - setToolbarAutoFixed : function(fixed) { - - var state = this.state; - var editor = this.editor; - var toolbar = this.toolbar; - var settings = this.settings; - - if (typeof fixed !== "undefined") - { - settings.toolbarAutoFixed = fixed; - } - - var autoFixedHandle = function(){ - var $window = $(window); - var top = $window.scrollTop(); - - if (!settings.toolbarAutoFixed) - { - return false; - } - - if (top - editor.offset().top > 10 && top < editor.height()) - { - toolbar.css({ - position : "fixed", - width : editor.width() + "px", - left : ($window.width() - editor.width()) / 2 + "px" - }); - } - else - { - toolbar.css({ - position : "absolute", - width : "100%", - left : 0 - }); - } - }; - - if (!state.fullscreen && !state.preview && settings.toolbar && settings.toolbarAutoFixed) - { - $(window).bind("scroll", autoFixedHandle); - } - - return this; - }, - - /** - * 配置和初始化工具栏 - * Set toolbar and Initialization - * - * @returns {editormd} 返回editormd的实例对象 - */ - - setToolbar : function() { - var settings = this.settings; - - if(settings.readOnly) { - return this; - } - - var editor = this.editor; - var preview = this.preview; - var classPrefix = this.classPrefix; - - var toolbar = this.toolbar = editor.children("." + classPrefix + "toolbar"); - - if (settings.toolbar && toolbar.length < 1) - { - var toolbarHTML = "<div class=\"" + classPrefix + "toolbar\"><div class=\"" + classPrefix + "toolbar-container\"><ul class=\"" + classPrefix + "menu\"></ul></div></div>"; - - editor.append(toolbarHTML); - toolbar = this.toolbar = editor.children("." + classPrefix + "toolbar"); - } - - if (!settings.toolbar) - { - toolbar.hide(); - - return this; - } - - toolbar.show(); - - var icons = (typeof settings.toolbarIcons === "function") ? settings.toolbarIcons() - : ((typeof settings.toolbarIcons === "string") ? editormd.toolbarModes[settings.toolbarIcons] : settings.toolbarIcons); - - var toolbarMenu = toolbar.find("." + this.classPrefix + "menu"), menu = ""; - var pullRight = false; - - for (var i = 0, len = icons.length; i < len; i++) - { - var name = icons[i]; - - if (name === "||") - { - pullRight = true; - } - else if (name === "|") - { - menu += "<li class=\"divider\" unselectable=\"on\">|</li>"; - } - else - { - var isHeader = (/h(\d)/.test(name)); - var index = name; - - if (name === "watch" && !settings.watch) { - index = "unwatch"; - } - - var title = settings.lang.toolbar[index]; - var iconTexts = settings.toolbarIconTexts[index]; - var iconClass = settings.toolbarIconsClass[index]; - - title = (typeof title === "undefined") ? "" : title; - iconTexts = (typeof iconTexts === "undefined") ? "" : iconTexts; - iconClass = (typeof iconClass === "undefined") ? "" : iconClass; - - var menuItem = pullRight ? "<li class=\"pull-right\">" : "<li>"; - - if (typeof settings.toolbarCustomIcons[name] !== "undefined" && typeof settings.toolbarCustomIcons[name] !== "function") - { - menuItem += settings.toolbarCustomIcons[name]; - } - else - { - menuItem += "<a href=\"javascript:;\" title=\"" + title + "\" unselectable=\"on\">"; - menuItem += "<i class=\"fa " + iconClass + "\" name=\""+name+"\" unselectable=\"on\">"+((isHeader) ? name.toUpperCase() : ( (iconClass === "") ? iconTexts : "") ) + "</i>"; - menuItem += "</a>"; - } - - menuItem += "</li>"; - - menu = pullRight ? menuItem + menu : menu + menuItem; - } - } - - toolbarMenu.html(menu); - - toolbarMenu.find("[title=\"Lowercase\"]").attr("title", settings.lang.toolbar.lowercase); - toolbarMenu.find("[title=\"ucwords\"]").attr("title", settings.lang.toolbar.ucwords); - - this.setToolbarHandler(); - this.setToolbarAutoFixed(); - - return this; - }, - - /** - * 工具栏图标事件处理对象序列 - * Get toolbar icons event handlers - * - * @param {Object} cm CodeMirror的实例对象 - * @param {String} name 要获取的事件处理器名称 - * @returns {Object} 返回处理对象序列 - */ - - dialogLockScreen : function() { - $.proxy(editormd.dialogLockScreen, this)(); - - return this; - }, - - dialogShowMask : function(dialog) { - $.proxy(editormd.dialogShowMask, this)(dialog); - - return this; - }, - - getToolbarHandles : function(name) { - var toolbarHandlers = this.toolbarHandlers = editormd.toolbarHandlers; - - return (name && typeof toolbarIconHandlers[name] !== "undefined") ? toolbarHandlers[name] : toolbarHandlers; - }, - - /** - * 工具栏图标事件处理器 - * Bind toolbar icons event handle - * - * @returns {editormd} 返回editormd的实例对象 - */ - - setToolbarHandler : function() { - var _this = this; - var settings = this.settings; - - if (!settings.toolbar || settings.readOnly) { - return this; - } - - var toolbar = this.toolbar; - var cm = this.cm; - var classPrefix = this.classPrefix; - var toolbarIcons = this.toolbarIcons = toolbar.find("." + classPrefix + "menu > li > a"); - var toolbarIconHandlers = this.getToolbarHandles(); - - toolbarIcons.bind(editormd.mouseOrTouch("click", "touchend"), function(event) { - - var icon = $(this).children(".fa"); - var name = icon.attr("name"); - var cursor = cm.getCursor(); - var selection = cm.getSelection(); - - if (name === "") { - return ; - } - - _this.activeIcon = icon; - - if (typeof toolbarIconHandlers[name] !== "undefined") - { - $.proxy(toolbarIconHandlers[name], _this)(cm); - } - else - { - if (typeof settings.toolbarHandlers[name] !== "undefined") - { - $.proxy(settings.toolbarHandlers[name], _this)(cm, icon, cursor, selection); - } - } - - if (name !== "link" && name !== "reference-link" && name !== "image" && name !== "code-block" && - name !== "preformatted-text" && name !== "watch" && name !== "preview" && name !== "search" && name !== "fullscreen" && name !== "info") - { - cm.focus(); - } - - return false; - - }); - - return this; - }, - - /** - * 动态创建对话框 - * Creating custom dialogs - * - * @param {Object} options 配置项键值对 Key/Value - * @returns {dialog} 返回创建的dialog的jQuery实例对象 - */ - - createDialog : function(options) { - return $.proxy(editormd.createDialog, this)(options); - }, - - /** - * 创建关于Editor.md的对话框 - * Create about Editor.md dialog - * - * @returns {editormd} 返回editormd的实例对象 - */ - - createInfoDialog : function() { - var _this = this; - var editor = this.editor; - var classPrefix = this.classPrefix; - - var infoDialogHTML = [ - "<div class=\"" + classPrefix + "dialog " + classPrefix + "dialog-info\" style=\"\">", - "<div class=\"" + classPrefix + "dialog-container\">", - "<h1><i class=\"editormd-logo editormd-logo-lg editormd-logo-color\"></i> " + editormd.title + "<small>v" + editormd.version + "</small></h1>", - "<p>" + this.lang.description + "</p>", - "<p style=\"margin: 10px 0 20px 0;\"><a href=\"" + editormd.homePage + "\" target=\"_blank\">" + editormd.homePage + " <i class=\"fa fa-external-link\"></i></a></p>", - "<p style=\"font-size: 0.85em;\">Copyright © 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>", - "</div>", - "<a href=\"javascript:;\" class=\"fa fa-close " + classPrefix + "dialog-close\"></a>", - "</div>" - ].join("\n"); - - editor.append(infoDialogHTML); - - var infoDialog = this.infoDialog = editor.children("." + classPrefix + "dialog-info"); - - infoDialog.find("." + classPrefix + "dialog-close").bind(editormd.mouseOrTouch("click", "touchend"), function() { - _this.hideInfoDialog(); - }); - - infoDialog.css("border", (editormd.isIE8) ? "1px solid #ddd" : "").css("z-index", editormd.dialogZindex).show(); - - this.infoDialogPosition(); - - return this; - }, - - /** - * 关于Editor.md对话居中定位 - * Editor.md dialog position handle - * - * @returns {editormd} 返回editormd的实例对象 - */ - - infoDialogPosition : function() { - var infoDialog = this.infoDialog; - - var _infoDialogPosition = function() { - infoDialog.css({ - top : ($(window).height() - infoDialog.height()) / 2 + "px", - left : ($(window).width() - infoDialog.width()) / 2 + "px" - }); - }; - - _infoDialogPosition(); - - $(window).resize(_infoDialogPosition); - - return this; - }, - - /** - * 显示关于Editor.md - * Display about Editor.md dialog - * - * @returns {editormd} 返回editormd的实例对象 - */ - - showInfoDialog : function() { - - $("html,body").css("overflow-x", "hidden"); - - var _this = this; - var editor = this.editor; - var settings = this.settings; - var infoDialog = this.infoDialog = editor.children("." + this.classPrefix + "dialog-info"); - - if (infoDialog.length < 1) - { - this.createInfoDialog(); - } - - this.lockScreen(true); - - this.mask.css({ - opacity : settings.dialogMaskOpacity, - backgroundColor : settings.dialogMaskBgColor - }).show(); - - infoDialog.css("z-index", editormd.dialogZindex).show(); - - this.infoDialogPosition(); - - return this; - }, - - /** - * 隐藏关于Editor.md - * Hide about Editor.md dialog - * - * @returns {editormd} 返回editormd的实例对象 - */ - - hideInfoDialog : function() { - $("html,body").css("overflow-x", ""); - this.infoDialog.hide(); - this.mask.hide(); - this.lockScreen(false); - - return this; - }, - - /** - * 锁屏 - * lock screen - * - * @param {Boolean} lock Boolean 布尔值,是否锁屏 - * @returns {editormd} 返回editormd的实例对象 - */ - - lockScreen : function(lock) { - editormd.lockScreen(lock); - - return this; - }, - - /** - * 编辑器界面重建,用于动态语言包或模块加载等 - * Recreate editor - * - * @returns {editormd} 返回editormd的实例对象 - */ - - recreate : function() { - var _this = this; - var editor = this.editor; - var settings = this.settings; - - this.codeMirror.remove(); - - this.setCodeMirror(); - - if (!settings.readOnly) - { - if (editor.find(".editormd-dialog").length > 0) { - editor.find(".editormd-dialog").remove(); - } - - if (settings.toolbar) - { - this.getToolbarHandles(); - this.setToolbar(); - } - } - - this.loadedDisplay(true); - - return this; - }, - - /** - * 高亮预览HTML的pre代码部分 - * highlight of preview codes - * - * @returns {editormd} 返回editormd的实例对象 - */ - - previewCodeHighlight : function() { - var settings = this.settings; - var previewContainer = this.previewContainer; - - if (settings.previewCodeHighlight) - { - previewContainer.find("pre").addClass("prettyprint linenums"); - - if (typeof prettyPrint !== "undefined") - { - prettyPrint(); - } - } - - return this; - }, - - /** - * 解析TeX(KaTeX)科学公式 - * TeX(KaTeX) Renderer - * - * @returns {editormd} 返回editormd的实例对象 - */ - - katexRender : function() { - - if (timer === null) - { - return this; - } - - this.previewContainer.find("." + editormd.classNames.tex).each(function(){ - var tex = $(this); - editormd.$katex.render(tex.text(), tex[0]); - }); - - return this; - }, - - /** - * 解析和渲染流程图及时序图 - * FlowChart and SequenceDiagram Renderer - * - * @returns {editormd} 返回editormd的实例对象 - */ - - flowChartAndSequenceDiagramRender : function() { - - var settings = this.settings; - var previewContainer = this.previewContainer; - - if (editormd.isIE8) { - return this; - } - - if (settings.flowChart) { - if (flowchartTimer === null) { - return this; - } - - previewContainer.find(".flowchart").flowChart(); - } - - if (settings.sequenceDiagram) { - previewContainer.find(".sequence-diagram").sequenceDiagram({theme: "simple"}); - } - - return this; - }, - - /** - * 注册键盘快捷键处理 - * Register CodeMirror keyMaps (keyboard shortcuts). - * - * @param {Object} keyMap KeyMap key/value {"(Ctrl/Shift/Alt)-Key" : function(){}} - * @returns {editormd} return this - */ - - registerKeyMaps : function(keyMap) { - - var _this = this; - var cm = this.cm; - var settings = this.settings; - var toolbarHandlers = editormd.toolbarHandlers; - var disabledKeyMaps = settings.disabledKeyMaps; - - keyMap = keyMap || null; - - if (keyMap) - { - for (var i in keyMap) - { - if ($.inArray(i, disabledKeyMaps) < 0) - { - var map = {}; - map[i] = keyMap[i]; - - cm.addKeyMap(keyMap); - } - } - } - else - { - for (var k in editormd.keyMaps) - { - var _keyMap = editormd.keyMaps[k]; - var handle = (typeof _keyMap === "string") ? $.proxy(toolbarHandlers[_keyMap], _this) : $.proxy(_keyMap, _this); - - if ($.inArray(k, ["F9", "F10", "F11"]) < 0 && $.inArray(k, disabledKeyMaps) < 0) - { - var _map = {}; - _map[k] = handle; - - cm.addKeyMap(_map); - } - } - - $(window).keydown(function(event) { - - var keymaps = { - "120" : "F9", - "121" : "F10", - "122" : "F11" - }; - - if ( $.inArray(keymaps[event.keyCode], disabledKeyMaps) < 0 ) - { - switch (event.keyCode) - { - case 120: - $.proxy(toolbarHandlers["watch"], _this)(); - return false; - break; - - case 121: - $.proxy(toolbarHandlers["preview"], _this)(); - return false; - break; - - case 122: - $.proxy(toolbarHandlers["fullscreen"], _this)(); - return false; - break; - - default: - break; - } - } - }); - } - - return this; - }, - - bindScrollEvent : function() { - - var _this = this; - var preview = this.preview; - var settings = this.settings; - var codeMirror = this.codeMirror; - var mouseOrTouch = editormd.mouseOrTouch; - - if (!settings.syncScrolling) { - return this; - } - - var cmBindScroll = function() { - codeMirror.find(".CodeMirror-scroll").bind(mouseOrTouch("scroll", "touchmove"), function(event) { - var height = $(this).height(); - var scrollTop = $(this).scrollTop(); - var percent = (scrollTop / $(this)[0].scrollHeight); - - if (scrollTop === 0) - { - preview.scrollTop(0); - } - else if (scrollTop + height >= $(this)[0].scrollHeight - 16) - { - preview.scrollTop(preview[0].scrollHeight); - } - else - { - preview.scrollTop(preview[0].scrollHeight * percent); - } - - $.proxy(settings.onscroll, _this)(event); - }); - }; - - var cmUnbindScroll = function() { - codeMirror.find(".CodeMirror-scroll").unbind(mouseOrTouch("scroll", "touchmove")); - }; - - var previewBindScroll = function() { - - preview.bind(mouseOrTouch("scroll", "touchmove"), function(event) { - var height = $(this).height(); - var scrollTop = $(this).scrollTop(); - var percent = (scrollTop / $(this)[0].scrollHeight); - var codeView = codeMirror.find(".CodeMirror-scroll"); - - if(scrollTop === 0) - { - codeView.scrollTop(0); - } - else if (scrollTop + height >= $(this)[0].scrollHeight) - { - codeView.scrollTop(codeView[0].scrollHeight); - } - else - { - codeView.scrollTop(codeView[0].scrollHeight * percent); - } - - $.proxy(settings.onpreviewscroll, _this)(event); - }); - - }; - - var previewUnbindScroll = function() { - preview.unbind(mouseOrTouch("scroll", "touchmove")); - }; - - codeMirror.bind({ - mouseover : cmBindScroll, - mouseout : cmUnbindScroll, - touchstart : cmBindScroll, - touchend : cmUnbindScroll - }); - - preview.bind({ - mouseover : previewBindScroll, - mouseout : previewUnbindScroll, - touchstart : previewBindScroll, - touchend : previewUnbindScroll - }); - - return this; - }, - - bindChangeEvent : function() { - - var _this = this; - var cm = this.cm; - var settings = this.settings; - - if (!settings.syncScrolling) { - return this; - } - - cm.on("change", function(_cm, changeObj) { - - if (settings.watch) - { - _this.previewContainer.css("padding", settings.autoHeight ? "20px 20px 50px 40px" : "20px"); - } - - timer = setTimeout(function() { - clearTimeout(timer); - _this.save(); - timer = null; - }, settings.delay); - }); - - return this; - }, - - /** - * 加载队列完成之后的显示处理 - * Display handle of the module queues loaded after. - * - * @param {Boolean} recreate 是否为重建编辑器 - * @returns {editormd} 返回editormd的实例对象 - */ - - loadedDisplay : function(recreate) { - - recreate = recreate || false; - - var _this = this; - var editor = this.editor; - var preview = this.preview; - var settings = this.settings; - - this.containerMask.hide(); - - this.save(); - - if (settings.watch) { - preview.show(); - } - - editor.data("oldWidth", editor.width()).data("oldHeight", editor.height()); // 为了兼容Zepto - - this.resize(); - this.registerKeyMaps(); - - $(window).resize(function(){ - _this.resize(); - }); - - this.bindScrollEvent().bindChangeEvent(); - - if (!recreate) - { - $.proxy(settings.onload, this)(); - } - - this.state.loaded = true; - - return this; - }, - - /** - * 设置编辑器的宽度 - * Set editor width - * - * @param {Number|String} width 编辑器宽度值 - * @returns {editormd} 返回editormd的实例对象 - */ - - width : function(width) { - - this.editor.css("width", (typeof width === "number") ? width + "px" : width); - this.resize(); - - return this; - }, - - /** - * 设置编辑器的高度 - * Set editor height - * - * @param {Number|String} height 编辑器高度值 - * @returns {editormd} 返回editormd的实例对象 - */ - - height : function(height) { - - this.editor.css("height", (typeof height === "number") ? height + "px" : height); - this.resize(); - - return this; - }, - - /** - * 调整编辑器的尺寸和布局 - * Resize editor layout - * - * @param {Number|String} [width=null] 编辑器宽度值 - * @param {Number|String} [height=null] 编辑器高度值 - * @returns {editormd} 返回editormd的实例对象 - */ - - resize : function(width, height) { - - width = width || null; - height = height || null; - - var state = this.state; - var editor = this.editor; - var preview = this.preview; - var toolbar = this.toolbar; - var settings = this.settings; - var codeMirror = this.codeMirror; - - if (width) - { - editor.css("width", (typeof width === "number") ? width + "px" : width); - } - - if (settings.autoHeight && !state.fullscreen && !state.preview) - { - editor.css("height", "auto"); - codeMirror.css("height", "auto"); - } - else - { - if (height) - { - editor.css("height", (typeof height === "number") ? height + "px" : height); - } - - if (state.fullscreen) - { - editor.height($(window).height()); - } - - if (settings.toolbar && !settings.readOnly) - { - codeMirror.css("margin-top", toolbar.height() + 1).height(editor.height() - toolbar.height()); - } - else - { - codeMirror.css("margin-top", 0).height(editor.height()); - } - } - - if(settings.watch) - { - codeMirror.width(editor.width() / 2); - preview.width((!state.preview) ? editor.width() / 2 : editor.width()); - - this.previewContainer.css("padding", settings.autoHeight ? "20px 20px 50px 40px" : "20px"); - - if (settings.toolbar && !settings.readOnly) - { - preview.css("top", toolbar.height()); - } - else - { - preview.css("top", 0); - } - - if (settings.autoHeight && !state.fullscreen && !state.preview) - { - preview.height(""); - } - else - { - preview.height((settings.toolbar && !settings.readOnly) ? editor.height() - toolbar.height() : editor.height()); - } - } - else - { - codeMirror.width(editor.width()); - preview.hide(); - } - - if (state.loaded) - { - $.proxy(settings.onresize, this)(); - } - - return this; - }, - - /** - * 解析和保存Markdown代码 - * Parse & Saving Markdown source code - * - * @returns {editormd} 返回editormd的实例对象 - */ - - save : function() { - - if (timer === null) - { - return this; - } - - var _this = this; - var state = this.state; - var settings = this.settings; - var cm = this.cm; - var cmValue = cm.getValue(); - var previewContainer = this.previewContainer; - - if (settings.mode !== "gfm" && settings.mode !== "markdown") - { - this.markdownTextarea.val(cmValue); - - return this; - } - - var marked = editormd.$marked; - var markdownToC = this.markdownToC = []; - var rendererOptions = this.markedRendererOptions = { - toc : settings.toc, - tocm : settings.tocm, - tocStartLevel : settings.tocStartLevel, - pageBreak : settings.pageBreak, - taskList : settings.taskList, - emoji : settings.emoji, - tex : settings.tex, - atLink : settings.atLink, // for @link - emailLink : settings.emailLink, // for mail address auto link - flowChart : settings.flowChart, - sequenceDiagram : settings.sequenceDiagram, - previewCodeHighlight : settings.previewCodeHighlight, - }; - - var markedOptions = this.markedOptions = { - renderer : editormd.markedRenderer(markdownToC, rendererOptions), - gfm : true, - tables : true, - breaks : true, - pedantic : false, - sanitize : (settings.htmlDecode) ? false : true, // 关闭忽略HTML标签,即开启识别HTML标签,默认为false - smartLists : true, - smartypants : true - }; - - marked.setOptions(markedOptions); - - cmValue = editormd.filterHTMLTags(cmValue, settings.htmlDecode); - - var newMarkdownDoc = editormd.$marked(cmValue, markedOptions); - - //console.log("cmValue", cmValue, this.markdownTextarea, this.htmlTextarea); - - this.markdownTextarea.text(cmValue); - - cm.save(); - - if (settings.saveHTMLToTextarea) - { - this.htmlTextarea.text(newMarkdownDoc); - } - - if(settings.watch || (!settings.watch && state.preview)) - { - previewContainer.html(newMarkdownDoc); - - this.previewCodeHighlight(); - - if (settings.toc) - { - var tocContainer = (settings.tocContainer === "") ? previewContainer : $(settings.tocContainer); - var tocMenu = tocContainer.find("." + this.classPrefix + "toc-menu"); - - tocContainer.attr("previewContainer", (settings.tocContainer === "") ? "true" : "false"); - - if (settings.tocContainer !== "" && tocMenu.length > 0) - { - tocMenu.remove(); - } - - editormd.markdownToCRenderer(markdownToC, tocContainer, settings.tocDropdown, settings.tocStartLevel); - - if (settings.tocDropdown || tocContainer.find("." + this.classPrefix + "toc-menu").length > 0) - { - editormd.tocDropdownMenu(tocContainer, (settings.tocTitle !== "") ? settings.tocTitle : this.lang.tocTitle); - } - - if (settings.tocContainer !== "") - { - previewContainer.find(".markdown-toc").css("border", "none"); - } - } - - if (settings.tex) - { - if (!editormd.kaTeXLoaded && settings.autoLoadModules) - { - editormd.loadKaTeX(function() { - editormd.$katex = katex; - editormd.kaTeXLoaded = true; - _this.katexRender(); - }); - } - else - { - editormd.$katex = katex; - this.katexRender(); - } - } - - if (settings.flowChart || settings.sequenceDiagram) - { - flowchartTimer = setTimeout(function(){ - clearTimeout(flowchartTimer); - _this.flowChartAndSequenceDiagramRender(); - flowchartTimer = null; - }, 10); - } - - if (state.loaded) - { - $.proxy(settings.onchange, this)(); - } - } - - return this; - }, - - /** - * 聚焦光标位置 - * Focusing the cursor position - * - * @returns {editormd} 返回editormd的实例对象 - */ - - focus : function() { - this.cm.focus(); - - return this; - }, - - /** - * 设置光标的位置 - * Set cursor position - * - * @param {Object} cursor 要设置的光标位置键值对象,例:{line:1, ch:0} - * @returns {editormd} 返回editormd的实例对象 - */ - - setCursor : function(cursor) { - this.cm.setCursor(cursor); - - return this; - }, - - /** - * 获取当前光标的位置 - * Get the current position of the cursor - * - * @returns {Cursor} 返回一个光标Cursor对象 - */ - - getCursor : function() { - return this.cm.getCursor(); - }, - - /** - * 设置光标选中的范围 - * Set cursor selected ranges - * - * @param {Object} from 开始位置的光标键值对象,例:{line:1, ch:0} - * @param {Object} to 结束位置的光标键值对象,例:{line:1, ch:0} - * @returns {editormd} 返回editormd的实例对象 - */ - - setSelection : function(from, to) { - - this.cm.setSelection(from, to); - - return this; - }, - - /** - * 获取光标选中的文本 - * Get the texts from cursor selected - * - * @returns {String} 返回选中文本的字符串形式 - */ - - getSelection : function() { - return this.cm.getSelection(); - }, - - /** - * 设置光标选中的文本范围 - * Set the cursor selection ranges - * - * @param {Array} ranges cursor selection ranges array - * @returns {Array} return this - */ - - setSelections : function(ranges) { - this.cm.setSelections(ranges); - - return this; - }, - - /** - * 获取光标选中的文本范围 - * Get the cursor selection ranges - * - * @returns {Array} return selection ranges array - */ - - getSelections : function() { - return this.cm.getSelections(); - }, - - /** - * 替换当前光标选中的文本或在当前光标处插入新字符 - * Replace the text at the current cursor selected or insert a new character at the current cursor position - * - * @param {String} value 要插入的字符值 - * @returns {editormd} 返回editormd的实例对象 - */ - - replaceSelection : function(value) { - this.cm.replaceSelection(value); - - return this; - }, - - /** - * 在当前光标处插入新字符 - * Insert a new character at the current cursor position - * - * 同replaceSelection()方法 - * With the replaceSelection() method - * - * @param {String} value 要插入的字符值 - * @returns {editormd} 返回editormd的实例对象 - */ - - insertValue : function(value) { - this.replaceSelection(value); - - return this; - }, - - /** - * 追加markdown - * append Markdown to editor - * - * @param {String} md 要追加的markdown源文档 - * @returns {editormd} 返回editormd的实例对象 - */ - - appendMarkdown : function(md) { - var settings = this.settings; - var cm = this.cm; - - cm.setValue(cm.getValue() + md); - - return this; - }, - - /** - * 设置和传入编辑器的markdown源文档 - * Set Markdown source document - * - * @param {String} md 要传入的markdown源文档 - * @returns {editormd} 返回editormd的实例对象 - */ - - setMarkdown : function(md) { - this.cm.setValue(md || this.settings.markdown); - - return this; - }, - - /** - * 获取编辑器的markdown源文档 - * Set Editor.md markdown/CodeMirror value - * - * @returns {editormd} 返回editormd的实例对象 - */ - - getMarkdown : function() { - return this.cm.getValue(); - }, - - /** - * 获取编辑器的源文档 - * Get CodeMirror value - * - * @returns {editormd} 返回editormd的实例对象 - */ - - getValue : function() { - return this.cm.getValue(); - }, - - /** - * 设置编辑器的源文档 - * Set CodeMirror value - * - * @param {String} value set code/value/string/text - * @returns {editormd} 返回editormd的实例对象 - */ - - setValue : function(value) { - this.cm.setValue(value); - - return this; - }, - - /** - * 清空编辑器 - * Empty CodeMirror editor container - * - * @returns {editormd} 返回editormd的实例对象 - */ - - clear : function() { - this.cm.setValue(""); - - return this; - }, - - /** - * 获取解析后存放在Textarea的HTML源码 - * Get parsed html code from Textarea - * - * @returns {String} 返回HTML源码 - */ - - getHTML : function() { - if (!this.settings.saveHTMLToTextarea) - { - alert("Error: settings.saveHTMLToTextarea == false"); - - return false; - } - - return this.htmlTextarea.val(); - }, - - /** - * getHTML()的别名 - * getHTML (alias) - * - * @returns {String} Return html code 返回HTML源码 - */ - - getTextareaSavedHTML : function() { - return this.getHTML(); - }, - - /** - * 获取预览窗口的HTML源码 - * Get html from preview container - * - * @returns {editormd} 返回editormd的实例对象 - */ - - getPreviewedHTML : function() { - if (!this.settings.watch) - { - alert("Error: settings.watch == false"); - - return false; - } - - return this.previewContainer.html(); - }, - - /** - * 开启实时预览 - * Enable real-time watching - * - * @returns {editormd} 返回editormd的实例对象 - */ - - watch : function(callback) { - var settings = this.settings; - - if ($.inArray(settings.mode, ["gfm", "markdown"]) < 0) - { - return this; - } - - this.state.watching = settings.watch = true; - this.preview.show(); - - if (this.toolbar) - { - var watchIcon = settings.toolbarIconsClass.watch; - var unWatchIcon = settings.toolbarIconsClass.unwatch; - - var icon = this.toolbar.find(".fa[name=watch]"); - icon.parent().attr("title", settings.lang.toolbar.watch); - icon.removeClass(unWatchIcon).addClass(watchIcon); - } - - this.codeMirror.css("border-right", "1px solid #ddd").width(this.editor.width() / 2); - - timer = 0; - - this.save().resize(); - - if (!settings.onwatch) - { - settings.onwatch = callback || function() {}; - } - - $.proxy(settings.onwatch, this)(); - - return this; - }, - - /** - * 关闭实时预览 - * Disable real-time watching - * - * @returns {editormd} 返回editormd的实例对象 - */ - - unwatch : function(callback) { - var settings = this.settings; - this.state.watching = settings.watch = false; - this.preview.hide(); - - if (this.toolbar) - { - var watchIcon = settings.toolbarIconsClass.watch; - var unWatchIcon = settings.toolbarIconsClass.unwatch; - - var icon = this.toolbar.find(".fa[name=watch]"); - icon.parent().attr("title", settings.lang.toolbar.unwatch); - icon.removeClass(watchIcon).addClass(unWatchIcon); - } - - this.codeMirror.css("border-right", "none").width(this.editor.width()); - - this.resize(); - - if (!settings.onunwatch) - { - settings.onunwatch = callback || function() {}; - } - - $.proxy(settings.onunwatch, this)(); - - return this; - }, - - /** - * 显示编辑器 - * Show editor - * - * @param {Function} [callback=function()] 回调函数 - * @returns {editormd} 返回editormd的实例对象 - */ - - show : function(callback) { - callback = callback || function() {}; - - var _this = this; - this.editor.show(0, function() { - $.proxy(callback, _this)(); - }); - - return this; - }, - - /** - * 隐藏编辑器 - * Hide editor - * - * @param {Function} [callback=function()] 回调函数 - * @returns {editormd} 返回editormd的实例对象 - */ - - hide : function(callback) { - callback = callback || function() {}; - - var _this = this; - this.editor.hide(0, function() { - $.proxy(callback, _this)(); - }); - - return this; - }, - - /** - * 隐藏编辑器部分,只预览HTML - * Enter preview html state - * - * @returns {editormd} 返回editormd的实例对象 - */ - - previewing : function() { - - var _this = this; - var editor = this.editor; - var preview = this.preview; - var toolbar = this.toolbar; - var settings = this.settings; - var codeMirror = this.codeMirror; - - if ($.inArray(settings.mode, ["gfm", "markdown"]) < 0) { - return this; - } - - if (settings.toolbar && toolbar) { - toolbar.toggle(); - toolbar.find(".fa[name=preview]").toggleClass("active"); - } - - codeMirror.toggle(); - - var escHandle = function(event) { - if (event.shiftKey && event.keyCode === 27) { - _this.previewed(); - } - }; - - if (codeMirror.css("display") === "none") // 为了兼容Zepto,而不使用codeMirror.is(":hidden") - { - this.state.preview = true; - - if (this.state.fullscreen) { - preview.css("background", "#fff"); - } - - editor.find("." + this.classPrefix + "preview-close-btn").show().bind(editormd.mouseOrTouch("click", "touchend"), function(){ - _this.previewed(); - }); - - if (!settings.watch) - { - this.save(); - } - - preview.show().css({ - position : "static", - top : 0, - width : editor.width(), - height : (settings.autoHeight && !this.state.fullscreen) ? "auto" : editor.height() - }); - - if (this.state.loaded) - { - $.proxy(settings.onpreviewing, this)(); - } - - $(window).bind("keyup", escHandle); - } - else - { - $(window).unbind("keyup", escHandle); - this.previewed(); - } - }, - - /** - * 显示编辑器部分,退出只预览HTML - * Exit preview html state - * - * @returns {editormd} 返回editormd的实例对象 - */ - - previewed : function() { - - var editor = this.editor; - var preview = this.preview; - var toolbar = this.toolbar; - var settings = this.settings; - var previewCloseBtn = editor.find("." + this.classPrefix + "preview-close-btn"); - - this.state.preview = false; - - this.codeMirror.show(); - - if (settings.toolbar) { - toolbar.show(); - } - - preview[(settings.watch) ? "show" : "hide"](); - - previewCloseBtn.hide().unbind(editormd.mouseOrTouch("click", "touchend")); - - preview.css({ - background : null, - position : "absolute", - width : editor.width() / 2, - height : (settings.autoHeight && !this.state.fullscreen) ? "auto" : editor.height() - toolbar.height(), - top : (settings.toolbar) ? toolbar.height() : 0 - }); - - if (this.state.loaded) - { - $.proxy(settings.onpreviewed, this)(); - } - - return this; - }, - - /** - * 编辑器全屏显示 - * Fullscreen show - * - * @returns {editormd} 返回editormd的实例对象 - */ - - fullscreen : function() { - - var _this = this; - var state = this.state; - var editor = this.editor; - var preview = this.preview; - var toolbar = this.toolbar; - var settings = this.settings; - var fullscreenClass = this.classPrefix + "fullscreen"; - - if (toolbar) { - toolbar.find(".fa[name=fullscreen]").parent().toggleClass("active"); - } - - var escHandle = function(event) { - if (!event.shiftKey && event.keyCode === 27) - { - if (state.fullscreen) - { - _this.fullscreenExit(); - } - } - }; - - if (!editor.hasClass(fullscreenClass)) - { - state.fullscreen = true; - - $("html,body").css("overflow", "hidden"); - - editor.css({ - position : "fixed", - top : 0, - left : 0, - margin : 0, - border : "none", - width : $(window).width(), - height : $(window).height() - }).addClass(fullscreenClass); - - this.resize(); - - $.proxy(settings.onfullscreen, this)(); - - $(window).bind("keyup", escHandle); - } - else - { - $(window).unbind("keyup", escHandle); - this.fullscreenExit(); - } - - return this; - }, - - /** - * 编辑器退出全屏显示 - * Exit fullscreen state - * - * @returns {editormd} 返回editormd的实例对象 - */ - - fullscreenExit : function() { - - var editor = this.editor; - var settings = this.settings; - var toolbar = this.toolbar; - var fullscreenClass = this.classPrefix + "fullscreen"; - - this.state.fullscreen = false; - - if (toolbar) { - toolbar.find(".fa[name=fullscreen]").parent().removeClass("active"); - } - - $("html,body").css("overflow", ""); - - editor.css({ - position : "", - top : "", - left : "", - margin : "0 auto 15px", - width : editor.data("oldWidth"), - height : editor.data("oldHeight"), - border : "1px solid #ddd" - }).removeClass(fullscreenClass); - - this.resize(); - - $.proxy(settings.onfullscreenExit, this)(); - - return this; - }, - - /** - * 加载并执行插件 - * Load and execute the plugin - * - * @param {String} name plugin name / function name - * @param {String} path plugin load path - * @returns {editormd} 返回editormd的实例对象 - */ - - executePlugin : function(name, path) { - - var _this = this; - var cm = this.cm; - var settings = this.settings; - - path = settings.pluginPath + path; - - if (typeof define === "function") - { - if (typeof this[name] === "undefined") - { - alert("Error: " + name + " plugin is not found, you are not load this plugin."); - - return this; - } - - this[name](cm); - - return this; - } - - if ($.inArray(path, editormd.loadFiles.plugin) < 0) - { - editormd.loadPlugin(path, function() { - editormd.loadPlugins[name] = _this[name]; - _this[name](cm); - }); - } - else - { - $.proxy(editormd.loadPlugins[name], this)(cm); - } - - return this; - }, - - /** - * 搜索替换 - * Search & replace - * - * @param {String} command CodeMirror serach commands, "find, fintNext, fintPrev, clearSearch, replace, replaceAll" - * @returns {editormd} return this - */ - - search : function(command) { - var settings = this.settings; - - if (!settings.searchReplace) - { - alert("Error: settings.searchReplace == false"); - return this; - } - - if (!settings.readOnly) - { - this.cm.execCommand(command || "find"); - } - - return this; - }, - - searchReplace : function() { - this.search("replace"); - - return this; - }, - - searchReplaceAll : function() { - this.search("replaceAll"); - - return this; - } - }; - - editormd.fn.init.prototype = editormd.fn; - - /** - * 锁屏 - * lock screen when dialog opening - * - * @returns {void} - */ - - editormd.dialogLockScreen = function() { - var settings = this.settings || {dialogLockScreen : true}; - - if (settings.dialogLockScreen) - { - $("html,body").css("overflow", "hidden"); - } - }; - - /** - * 显示透明背景层 - * Display mask layer when dialog opening - * - * @param {Object} dialog dialog jQuery object - * @returns {void} - */ - - editormd.dialogShowMask = function(dialog) { - var editor = this.editor; - var settings = this.settings || {dialogShowMask : true}; - - dialog.css({ - top : ($(window).height() - dialog.height()) / 2 + "px", - left : ($(window).width() - dialog.width()) / 2 + "px" - }); - - if (settings.dialogShowMask) { - editor.children("." + this.classPrefix + "mask").css("z-index", parseInt(dialog.css("z-index")) - 1).show(); - } - }; - - editormd.toolbarHandlers = { - undo : function() { - this.cm.undo(); - }, - - redo : function() { - this.cm.redo(); - }, - - bold : function() { - var cm = this.cm; - var cursor = cm.getCursor(); - var selection = cm.getSelection(); - - cm.replaceSelection("**" + selection + "**"); - - if(selection === "") { - cm.setCursor(cursor.line, cursor.ch + 2); - } - }, - - del : function() { - var cm = this.cm; - var cursor = cm.getCursor(); - var selection = cm.getSelection(); - - cm.replaceSelection("~~" + selection + "~~"); - - if(selection === "") { - cm.setCursor(cursor.line, cursor.ch + 2); - } - }, - - italic : function() { - var cm = this.cm; - var cursor = cm.getCursor(); - var selection = cm.getSelection(); - - cm.replaceSelection("*" + selection + "*"); - - if(selection === "") { - cm.setCursor(cursor.line, cursor.ch + 1); - } - }, - - quote : function() { - var cm = this.cm; - var cursor = cm.getCursor(); - var selection = cm.getSelection(); - - cm.replaceSelection("> " + selection); - cm.setCursor(cursor.line, (selection === "") ? cursor.ch + 2 : cursor.ch + selection.length + 2); - }, - - ucfirst : function() { - var cm = this.cm; - var selection = cm.getSelection(); - var selections = cm.listSelections(); - - cm.replaceSelection(editormd.firstUpperCase(selection)); - cm.setSelections(selections); - }, - - ucwords : function() { - var cm = this.cm; - var selection = cm.getSelection(); - var selections = cm.listSelections(); - - cm.replaceSelection(editormd.wordsFirstUpperCase(selection)); - cm.setSelections(selections); - }, - - uppercase : function() { - var cm = this.cm; - var selection = cm.getSelection(); - var selections = cm.listSelections(); - - cm.replaceSelection(selection.toUpperCase()); - cm.setSelections(selections); - }, - - lowercase : function() { - var cm = this.cm; - var cursor = cm.getCursor(); - var selection = cm.getSelection(); - var selections = cm.listSelections(); - - cm.replaceSelection(selection.toLowerCase()); - cm.setSelections(selections); - }, - - h1 : function() { - var cm = this.cm; - var selection = cm.getSelection(); - - cm.replaceSelection("# " + selection); - }, - - h2 : function() { - var cm = this.cm; - var selection = cm.getSelection(); - - cm.replaceSelection("## " + selection); - }, - - h3 : function() { - var cm = this.cm; - var selection = cm.getSelection(); - - cm.replaceSelection("### " + selection); - }, - - h4 : function() { - var cm = this.cm; - var selection = cm.getSelection(); - - cm.replaceSelection("#### " + selection); - }, - - h5 : function() { - var cm = this.cm; - var selection = cm.getSelection(); - - cm.replaceSelection("##### " + selection); - }, - - h6 : function() { - var cm = this.cm; - var selection = cm.getSelection(); - - cm.replaceSelection("###### " + selection); - }, - - "list-ul" : function() { - var cm = this.cm; - var cursor = cm.getCursor(); - var selection = cm.getSelection(); - - if (selection === "") - { - cm.replaceSelection("- " + selection); - } - else - { - var selectionText = selection.split("\n"); - - for (var i = 0, len = selectionText.length; i < len; i++) - { - selectionText[i] = (selectionText[i] === "") ? "" : "- " + selectionText[i]; - } - - cm.replaceSelection(selectionText.join("\n")); - } - }, - - "list-ol" : function() { - var cm = this.cm; - var cursor = cm.getCursor(); - var selection = cm.getSelection(); - - if(selection === "") - { - cm.replaceSelection("1. " + selection); - } - else - { - var selectionText = selection.split("\n"); - - for (var i = 0, len = selectionText.length; i < len; i++) - { - selectionText[i] = (selectionText[i] === "") ? "" : (i+1) + ". " + selectionText[i]; - } - - cm.replaceSelection(selectionText.join("\n")); - } - }, - - hr : function() { - var cm = this.cm; - var cursor = cm.getCursor(); - var selection = cm.getSelection(); - - cm.replaceSelection("------------"); - }, - - tex : function() { - if (!this.settings.tex) - { - alert("settings.tex === false"); - return this; - } - - var cm = this.cm; - var cursor = cm.getCursor(); - var selection = cm.getSelection(); - - cm.replaceSelection("$$" + selection + "$$"); - - if(selection === "") { - cm.setCursor(cursor.line, cursor.ch + 2); - } - }, - - link : function() { - this.executePlugin("linkDialog", "link-dialog/link-dialog"); - }, - - "reference-link" : function() { - this.executePlugin("referenceLinkDialog", "reference-link-dialog/reference-link-dialog"); - }, - - pagebreak : function() { - if (!this.settings.pageBreak) - { - alert("settings.pageBreak === false"); - return this; - } - - var cm = this.cm; - var selection = cm.getSelection(); - - cm.replaceSelection("\r\n[========]\r\n"); - }, - - image : function() { - this.executePlugin("imageDialog", "image-dialog/image-dialog"); - }, - - code : function() { - var cm = this.cm; - var cursor = cm.getCursor(); - var selection = cm.getSelection(); - - cm.replaceSelection("`" + selection + "`"); - - if (selection === "") { - cm.setCursor(cursor.line, cursor.ch + 1); - } - }, - - "code-block" : function() { - this.executePlugin("codeBlockDialog", "code-block-dialog/code-block-dialog"); - }, - - "preformatted-text" : function() { - this.executePlugin("preformattedTextDialog", "preformatted-text-dialog/preformatted-text-dialog"); - }, - - table : function() { - this.executePlugin("tableDialog", "table-dialog/table-dialog"); - }, - - datetime : function() { - var cm = this.cm; - var selection = cm.getSelection(); - var date = new Date(); - var langName = this.settings.lang.name; - var datefmt = editormd.dateFormat() + " " + editormd.dateFormat((langName === "zh-cn" || langName === "zh-tw") ? "cn-week-day" : "week-day"); - - cm.replaceSelection(datefmt); - }, - - emoji : function() { - this.executePlugin("emojiDialog", "emoji-dialog/emoji-dialog"); - }, - - "html-entities" : function() { - this.executePlugin("htmlEntitiesDialog", "html-entities-dialog/html-entities-dialog"); - }, - - "goto-line" : function() { - this.executePlugin("gotoLineDialog", "goto-line-dialog/goto-line-dialog"); - }, - - watch : function() { - this[this.settings.watch ? "unwatch" : "watch"](); - }, - - preview : function() { - this.previewing(); - }, - - fullscreen : function() { - this.fullscreen(); - }, - - clear : function() { - this.clear(); - }, - - search : function() { - this.search(); - }, - - help : function() { - this.executePlugin("helpDialog", "help-dialog/help-dialog"); - }, - - info : function() { - this.showInfoDialog(); - } - }; - - editormd.keyMaps = { - "Ctrl-1" : "h1", - "Ctrl-2" : "h2", - "Ctrl-3" : "h3", - "Ctrl-4" : "h4", - "Ctrl-5" : "h5", - "Ctrl-6" : "h6", - "Ctrl-B" : "bold", // if this is string == editormd.toolbarHandlers.xxxx - "Ctrl-D" : "datetime", - - "Ctrl-E" : function() { // emoji - var cm = this.cm; - var cursor = cm.getCursor(); - var selection = cm.getSelection(); - - if (!this.settings.emoji) - { - alert("Error: settings.emoji == false"); - return ; - } - - cm.replaceSelection(":" + selection + ":"); - - if (selection === "") { - cm.setCursor(cursor.line, cursor.ch + 1); - } - }, - "Ctrl-Alt-G" : "goto-line", - "Ctrl-H" : "hr", - "Ctrl-I" : "italic", - "Ctrl-K" : "code", - - "Ctrl-L" : function() { - var cm = this.cm; - var cursor = cm.getCursor(); - var selection = cm.getSelection(); - - var title = (selection === "") ? "" : " \""+selection+"\""; - - cm.replaceSelection("[" + selection + "]("+title+")"); - - if (selection === "") { - cm.setCursor(cursor.line, cursor.ch + 1); - } - }, - "Ctrl-U" : "list-ul", - - "Shift-Ctrl-A" : function() { - var cm = this.cm; - var cursor = cm.getCursor(); - var selection = cm.getSelection(); - - if (!this.settings.atLink) - { - alert("Error: settings.atLink == false"); - return ; - } - - cm.replaceSelection("@" + selection); - - if (selection === "") { - cm.setCursor(cursor.line, cursor.ch + 1); - } - }, - - "Shift-Ctrl-C" : "code", - "Shift-Ctrl-Q" : "quote", - "Shift-Ctrl-S" : "del", - "Shift-Ctrl-K" : "tex", // KaTeX - - "Shift-Alt-C" : function() { - var cm = this.cm; - var cursor = cm.getCursor(); - var selection = cm.getSelection(); - - cm.replaceSelection(["```", selection, "```"].join("\n")); - - if (selection === "") { - cm.setCursor(cursor.line, cursor.ch + 3); - } - }, - - "Shift-Ctrl-Alt-C" : "code-block", - "Shift-Ctrl-H" : "html-entities", - "Shift-Alt-H" : "help", - "Shift-Ctrl-E" : "emoji", - "Shift-Ctrl-U" : "uppercase", - "Shift-Alt-U" : "ucwords", - "Shift-Ctrl-Alt-U" : "ucfirst", - "Shift-Alt-L" : "lowercase", - - "Shift-Ctrl-I" : function() { - var cm = this.cm; - var cursor = cm.getCursor(); - var selection = cm.getSelection(); - - var title = (selection === "") ? "" : " \""+selection+"\""; - - cm.replaceSelection(""); - - if (selection === "") { - cm.setCursor(cursor.line, cursor.ch + 4); - } - }, - - "Shift-Ctrl-Alt-I" : "image", - "Shift-Ctrl-L" : "link", - "Shift-Ctrl-O" : "list-ol", - "Shift-Ctrl-P" : "preformatted-text", - "Shift-Ctrl-T" : "table", - "Shift-Alt-P" : "pagebreak", - "F9" : "watch", - "F10" : "preview", - "F11" : "fullscreen", - }; - - /** - * 清除字符串两边的空格 - * Clear the space of strings both sides. - * - * @param {String} str string - * @returns {String} trimed string - */ - - var trim = function(str) { - return (!String.prototype.trim) ? str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "") : str.trim(); - }; - - editormd.trim = trim; - - /** - * 所有单词首字母大写 - * Words first to uppercase - * - * @param {String} str string - * @returns {String} string - */ - - var ucwords = function (str) { - return str.toLowerCase().replace(/\b(\w)|\s(\w)/g, function($1) { - return $1.toUpperCase(); - }); - }; - - editormd.ucwords = editormd.wordsFirstUpperCase = ucwords; - - /** - * 字符串首字母大写 - * Only string first char to uppercase - * - * @param {String} str string - * @returns {String} string - */ - - var firstUpperCase = function(str) { - return str.toLowerCase().replace(/\b(\w)/, function($1){ - return $1.toUpperCase(); - }); - }; - - var ucfirst = firstUpperCase; - - editormd.firstUpperCase = editormd.ucfirst = firstUpperCase; - - editormd.urls = { - atLinkBase : "https://github.com/" - }; - - editormd.regexs = { - atLink : /@(\w+)/g, - email : /(\w+)@(\w+)\.(\w+)\.?(\w+)?/g, - emailLink : /(mailto:)?([\w\.\_]+)@(\w+)\.(\w+)\.?(\w+)?/g, - emoji : /:([\w\+-]+):/g, - emojiDatetime : /(\d{2}:\d{2}:\d{2})/g, - twemoji : /:(tw-([\w]+)-?(\w+)?):/g, - fontAwesome : /:(fa-([\w]+)(-(\w+)){0,}):/g, - editormdLogo : /:(editormd-logo-?(\w+)?):/g, - pageBreak : /^\[[=]{8,}\]$/ - }; - - // Emoji graphics files url path - editormd.emoji = { - path : "http://www.emoji-cheat-sheet.com/graphics/emojis/", - ext : ".png" - }; - - // Twitter Emoji (Twemoji) graphics files url path - editormd.twemoji = { - path : "http://twemoji.maxcdn.com/36x36/", - ext : ".png" - }; - - /** - * 自定义marked的解析器 - * Custom Marked renderer rules - * - * @param {Array} markdownToC 传入用于接收TOC的数组 - * @returns {Renderer} markedRenderer 返回marked的Renderer自定义对象 - */ - - editormd.markedRenderer = function(markdownToC, options) { - var defaults = { - toc : true, // Table of contents - tocm : false, - tocStartLevel : 1, // Said from H1 to create ToC - pageBreak : true, - atLink : true, // for @link - emailLink : true, // for mail address auto link - taskList : false, // Enable Github Flavored Markdown task lists - emoji : false, // :emoji: , Support Twemoji, fontAwesome, Editor.md logo emojis. - tex : false, // TeX(LaTeX), based on KaTeX - flowChart : false, // flowChart.js only support IE9+ - sequenceDiagram : false, // sequenceDiagram.js only support IE9+ - }; - - var settings = $.extend(defaults, options || {}); - var marked = editormd.$marked; - var markedRenderer = new marked.Renderer(); - markdownToC = markdownToC || []; - - var regexs = editormd.regexs; - var atLinkReg = regexs.atLink; - var emojiReg = regexs.emoji; - var emailReg = regexs.email; - var emailLinkReg = regexs.emailLink; - var twemojiReg = regexs.twemoji; - var faIconReg = regexs.fontAwesome; - var editormdLogoReg = regexs.editormdLogo; - var pageBreakReg = regexs.pageBreak; - - markedRenderer.emoji = function(text) { - - text = text.replace(editormd.regexs.emojiDatetime, function($1) { - return $1.replace(/:/g, ":"); - }); - - var matchs = text.match(emojiReg); - - if (!matchs || !settings.emoji) { - return text; - } - - for (var i = 0, len = matchs.length; i < len; i++) - { - if (matchs[i] === ":+1:") { - matchs[i] = ":\\+1:"; - } - - text = text.replace(new RegExp(matchs[i]), function($1, $2){ - var faMatchs = $1.match(faIconReg); - var name = $1.replace(/:/g, ""); - - if (faMatchs) - { - for (var fa = 0, len1 = faMatchs.length; fa < len1; fa++) - { - var faName = faMatchs[fa].replace(/:/g, ""); - - return "<i class=\"fa " + faName + " fa-emoji\" title=\"" + faName.replace("fa-", "") + "\"></i>"; - } - } - else - { - var emdlogoMathcs = $1.match(editormdLogoReg); - var twemojiMatchs = $1.match(twemojiReg); - - if (emdlogoMathcs) - { - for (var x = 0, len2 = emdlogoMathcs.length; x < len2; x++) - { - var logoName = emdlogoMathcs[x].replace(/:/g, ""); - return "<i class=\"" + logoName + "\" title=\"Editor.md logo (" + logoName + ")\"></i>"; - } - } - else if (twemojiMatchs) - { - for (var t = 0, len3 = twemojiMatchs.length; t < len3; t++) - { - var twe = twemojiMatchs[t].replace(/:/g, "").replace("tw-", ""); - return "<img src=\"" + editormd.twemoji.path + twe + editormd.twemoji.ext + "\" title=\"twemoji-" + twe + "\" alt=\"twemoji-" + twe + "\" class=\"emoji twemoji\" />"; - } - } - else - { - var src = (name === "+1") ? "plus1" : name; - src = (src === "black_large_square") ? "black_square" : src; - - return "<img src=\"" + editormd.emoji.path + src + editormd.emoji.ext + "\" class=\"emoji\" title=\":" + name + ":\" alt=\":" + name + ":\" />"; - } - } - }); - } - - return text; - }; - - markedRenderer.atLink = function(text) { - - if (atLinkReg.test(text)) - { - if (settings.atLink) - { - text = text.replace(emailReg, function($1, $2, $3, $4) { - return $1.replace(/@/g, "_#_@_#_"); - }); - - text = text.replace(atLinkReg, function($1, $2) { - return "<a href=\"" + editormd.urls.atLinkBase + "" + $2 + "\" title=\"@" + $2 + "\" class=\"at-link\">" + $1 + "</a>"; - }).replace(/_#_@_#_/g, "@"); - } - - if (settings.emailLink) - { - text = text.replace(emailLinkReg, function($1, $2, $3, $4, $5) { - return (!$2 && $.inArray($5, "jpg|jpeg|png|gif|webp|ico|icon|pdf".split("|")) < 0) ? "<a href=\"mailto:" + $1 + "\">"+$1+"</a>" : $1; - }); - } - - return text; - } - - return text; - }; - - markedRenderer.link = function (href, title, text) { - - if (this.options.sanitize) { - try { - var prot = decodeURIComponent(unescape(href)).replace(/[^\w:]/g,"").toLowerCase(); - } catch(e) { - return ""; - } - - if (prot.indexOf("javascript:") === 0) { - return ""; - } - } - - var out = "<a href=\"" + href + "\""; - - if (atLinkReg.test(title) || atLinkReg.test(text)) - { - if (title) - { - out += " title=\"" + title.replace(/@/g, "@"); - } - - return out + "\">" + text.replace(/@/g, "@") + "</a>"; - } - - if (title) { - out += " title=\"" + title + "\""; - } - - out += ">" + text + "</a>"; - - return out; - }; - - markedRenderer.heading = function(text, level, raw) { - - var linkText = text; - var hasLinkReg = /\s*\<a\s*href\=\"(.*)\"\s*([^\>]*)\>(.*)\<\/a\>\s*/; - var getLinkTextReg = /\s*\<a\s*([^\>]+)\>([^\>]*)\<\/a\>\s*/g; - - if (hasLinkReg.test(text)) - { - var tempText = []; - text = text.split(/\<a\s*([^\>]+)\>([^\>]*)\<\/a\>/); - - for (var i = 0, len = text.length; i < len; i++) - { - tempText.push(text[i].replace(/\s*href\=\"(.*)\"\s*/g, "")); - } - - text = tempText.join(" "); - } - - text = trim(text); - - var escapedText = text.toLowerCase().replace(/[^\w]+/g, "-"); - var toc = { - text : text, - level : level, - slug : escapedText - }; - - var isChinese = /^[\u4e00-\u9fa5]+$/.test(text); - var id = (isChinese) ? escape(text).replace(/\%/g, "") : text.toLowerCase().replace(/[^\w]+/g, "-"); - - markdownToC.push(toc); - - var headingHTML = "<h" + level + " id=\"h"+ level + "-" + this.options.headerPrefix + id +"\">"; - - headingHTML += "<a name=\"" + text + "\" class=\"reference-link\"></a>"; - headingHTML += "<span class=\"header-link octicon octicon-link\"></span>"; - headingHTML += (hasLinkReg) ? this.atLink(this.emoji(linkText)) : this.atLink(this.emoji(text)); - headingHTML += "</h" + level + ">"; - - return headingHTML; - }; - - markedRenderer.pageBreak = function(text) { - if (pageBreakReg.test(text) && settings.pageBreak) - { - text = "<hr style=\"page-break-after:always;\" class=\"page-break editormd-page-break\" />"; - } - - return text; - }; - - markedRenderer.paragraph = function(text) { - var isTeXInline = /\$\$(.*)\$\$/g.test(text); - var isTeXLine = /^\$\$(.*)\$\$$/.test(text); - var isTeXAddClass = (isTeXLine) ? " class=\"" + editormd.classNames.tex + "\"" : ""; - var isToC = (settings.tocm) ? /^(\[TOC\]|\[TOCM\])$/.test(text) : /^\[TOC\]$/.test(text); - var isToCMenu = /^\[TOCM\]$/.test(text); - - if (!isTeXLine && isTeXInline) - { - text = text.replace(/(\$\$([^\$]*)\$\$)+/g, function($1, $2) { - return "<span class=\"" + editormd.classNames.tex + "\">" + $2.replace(/\$/g, "") + "</span>"; - }); - } - else - { - text = (isTeXLine) ? text.replace(/\$/g, "") : text; - } - - var tocHTML = "<div class=\"markdown-toc editormd-markdown-toc\">" + text + "</div>"; - - return (isToC) ? ( (isToCMenu) ? "<div class=\"editormd-toc-menu\">" + tocHTML + "</div><br/>" : tocHTML ) - : ( (pageBreakReg.test(text)) ? this.pageBreak(text) : "<p" + isTeXAddClass + ">" + this.atLink(this.emoji(text)) + "</p>\n" ); - }; - - markedRenderer.code = function (code, lang, escaped) { - - if (lang === "seq" || lang === "sequence") - { - return "<div class=\"sequence-diagram\">" + code + "</div>"; - } - else if ( lang === "flow") - { - return "<div class=\"flowchart\">" + code + "</div>"; - } - else - { - - return marked.Renderer.prototype.code.apply(this, arguments); - } - }; - - markedRenderer.tablecell = function(content, flags) { - var type = (flags.header) ? "th" : "td"; - var tag = (flags.align) ? "<" + type +" style=\"text-align:" + flags.align + "\">" : "<" + type + ">"; - - return tag + this.atLink(this.emoji(content)) + "</" + type + ">\n"; - }; - - markedRenderer.listitem = function(text) { - if (settings.taskList && /^\s*\[[x\s]\]\s*/.test(text)) - { - text = text.replace(/^\s*\[\s\]\s*/, "<input type=\"checkbox\" class=\"task-list-item-checkbox\" /> ") - .replace(/^\s*\[x\]\s*/, "<input type=\"checkbox\" class=\"task-list-item-checkbox\" checked disabled /> "); - - return "<li style=\"list-style: none;\">" + this.atLink(this.emoji(text)) + "</li>"; - } - else - { - return "<li>" + this.atLink(this.emoji(text)) + "</li>"; - } - }; - - return markedRenderer; - }; - - /** - * - * 生成TOC(Table of Contents) - * Creating ToC (Table of Contents) - * - * @param {Array} toc 从marked获取的TOC数组列表 - * @param {Element} container 插入TOC的容器元素 - * @param {Integer} startLevel Hx 起始层级 - * @returns {Object} tocContainer 返回ToC列表容器层的jQuery对象元素 - */ - - editormd.markdownToCRenderer = function(toc, container, tocDropdown, startLevel) { - - var html = ""; - var lastLevel = 0; - var classPrefix = this.classPrefix; - - startLevel = startLevel || 1; - - for (var i = 0, len = toc.length; i < len; i++) - { - var text = toc[i].text; - var level = toc[i].level; - - if (level < startLevel) { - continue; - } - - if (level > lastLevel) - { - html += ""; - } - else if (level < lastLevel) - { - html += (new Array(lastLevel - level + 2)).join("</ul></li>"); - } - else - { - html += "</ul></li>"; - } - - html += "<li><a class=\"toc-level-" + level + "\" href=\"#" + text + "\" level=\"" + level + "\">" + text + "</a><ul>"; - lastLevel = level; - } - - var tocContainer = container.find(".markdown-toc"); - - if (tocContainer.length < 1 && container.attr("previewContainer") === "false") - { - var tocHTML = "<div class=\"markdown-toc " + classPrefix + "markdown-toc\"></div>"; - - tocHTML = (tocDropdown) ? "<div class=\"" + classPrefix + "toc-menu\">" + tocHTML + "</div>" : tocHTML; - - container.html(tocHTML); - - tocContainer = container.find(".markdown-toc"); - } - - if (tocDropdown) - { - tocContainer.wrap("<div class=\"" + classPrefix + "toc-menu\"></div><br/>"); - } - - tocContainer.html("<ul class=\"markdown-toc-list\"></ul>").children(".markdown-toc-list").html(html.replace(/\r?\n?\<ul\>\<\/ul\>/g, "")); - - return tocContainer; - }; - - /** - * - * 生成TOC下拉菜单 - * Creating ToC dropdown menu - * - * @param {Object} container 插入TOC的容器jQuery对象元素 - * @param {String} tocTitle ToC title - * @returns {Object} return toc-menu object - */ - - editormd.tocDropdownMenu = function(container, tocTitle) { - - tocTitle = tocTitle || "Table of Contents"; - - var zindex = 400; - var tocMenus = container.find("." + this.classPrefix + "toc-menu"); - - tocMenus.each(function() { - var $this = $(this); - var toc = $this.children(".markdown-toc"); - var icon = "<i class=\"fa fa-angle-down\"></i>"; - var btn = "<a href=\"javascript:;\" class=\"toc-menu-btn\">" + icon + tocTitle + "</a>"; - var menu = toc.children("ul"); - var list = menu.find("li"); - - toc.append(btn); - - list.first().before("<li><h1>" + tocTitle + " " + icon + "</h1></li>"); - - $this.mouseover(function(){ - menu.show(); - - list.each(function(){ - var li = $(this); - var ul = li.children("ul"); - - if (ul.html() === "") - { - ul.remove(); - } - - if (ul.length > 0 && ul.html() !== "") - { - var firstA = li.children("a").first(); - - if (firstA.children(".fa").length < 1) - { - firstA.append( $(icon).css({ float:"right", paddingTop:"4px" }) ); - } - } - - li.mouseover(function(){ - ul.css("z-index", zindex).show(); - zindex += 1; - }).mouseleave(function(){ - ul.hide(); - }); - }); - }).mouseleave(function(){ - menu.hide(); - }); - }); - - return tocMenus; - }; - - /** - * 简单地过滤指定的HTML标签 - * Filter custom html tags - * - * @param {String} html 要过滤HTML - * @param {String} filters 要过滤的标签 - * @returns {String} html 返回过滤的HTML - */ - - editormd.filterHTMLTags = function(html, filters) { - - if (typeof html !== "string") { - html = new String(html); - } - - if (typeof filters !== "string") { - return html; - } - - var expression = filters.split("|"); - var filterTags = expression[0].split(","); - var attrs = expression[1]; - - for (var i = 0, len = filterTags.length; i < len; i++) - { - var tag = filterTags[i]; - - html = html.replace(new RegExp("\<\s*" + tag + "\s*([^\>]*)\>([^\>]*)\<\s*\/" + tag + "\s*\>", "igm"), ""); - } - - if (typeof attrs !== "undefined") - { - var htmlTagRegex = /\<(\w+)\s*([^\>]*)\>([^\>]*)\<\/(\w+)\>/ig; - - if (attrs === "*") - { - html = html.replace(htmlTagRegex, function($1, $2, $3, $4, $5) { - return "<" + $2 + ">" + $4 + "</" + $5 + ">"; - }); - } - else if (attrs === "on*") - { - html = html.replace(htmlTagRegex, function($1, $2, $3, $4, $5) { - var el = $("<" + $2 + ">" + $4 + "</" + $5 + ">"); - var _attrs = $($1)[0].attributes; - var $attrs = {}; - - $.each(_attrs, function(i, e) { - $attrs[e.nodeName] = e.nodeValue; - }); - - $.each($attrs, function(i) { - if (i.indexOf("on") === 0) { - delete $attrs[i]; - } - }); - - el.attr($attrs); - - return el[0].outerHTML; - }); - } - else - { - html = html.replace(htmlTagRegex, function($1, $2, $3, $4) { - var filterAttrs = attrs.split(","); - var el = $($1); - el.html($4); - - $.each(filterAttrs, function(i) { - el.attr(filterAttrs[i], null); - }); - - return el[0].outerHTML; - }); - } - } - - return html; - }; - - /** - * 将Markdown文档解析为HTML用于前台显示 - * Parse Markdown to HTML for Font-end preview. - * - * @param {String} id 用于显示HTML的对象ID - * @param {Object} [options={}] 配置选项,可选 - * @returns {Object} div 返回jQuery对象元素 - */ - - editormd.markdownToHTML = function(id, options) { - var defaults = { - gfm : true, - toc : true, - tocm : false, - tocStartLevel : 1, - tocTitle : "目录", - tocDropdown : false, - markdown : "", - htmlDecode : false, - autoLoadKaTeX : true, - pageBreak : true, - atLink : true, // for @link - emailLink : true, // for mail address auto link - tex : false, - taskList : false, // Github Flavored Markdown task lists - emoji : false, - flowChart : false, - sequenceDiagram : false, - previewCodeHighlight : true - }; - - editormd.$marked = marked; - - var div = $("#" + id); - var settings = div.settings = $.extend(true, defaults, options || {}); - var saveTo = div.find("textarea"); - - if (saveTo.length < 1) - { - div.append("<textarea></textarea>"); - saveTo = div.find("textarea"); - } - - var markdownDoc = (settings.markdown === "") ? saveTo.val() : settings.markdown; - var markdownToC = []; - - var rendererOptions = { - toc : settings.toc, - tocm : settings.tocm, - tocStartLevel : settings.tocStartLevel, - taskList : settings.taskList, - emoji : settings.emoji, - tex : settings.tex, - pageBreak : settings.pageBreak, - atLink : settings.atLink, // for @link - emailLink : settings.emailLink, // for mail address auto link - flowChart : settings.flowChart, - sequenceDiagram : settings.sequenceDiagram, - previewCodeHighlight : settings.previewCodeHighlight, - }; - - var markedOptions = { - renderer : editormd.markedRenderer(markdownToC, rendererOptions), - gfm : settings.gfm, - tables : true, - breaks : true, - pedantic : false, - sanitize : (settings.htmlDecode) ? false : true, // 是否忽略HTML标签,即是否开启HTML标签解析,为了安全性,默认不开启 - smartLists : true, - smartypants : true - }; - - markdownDoc = new String(markdownDoc); - markdownDoc = editormd.filterHTMLTags(markdownDoc, settings.htmlDecode); - - var markdownParsed = marked(markdownDoc, markedOptions); - - saveTo.val(markdownDoc); - - div.addClass("markdown-body " + this.classPrefix + "html-preview").append(markdownParsed); - - if (settings.toc) - { - div.tocContainer = this.markdownToCRenderer(markdownToC, div, settings.tocDropdown, settings.tocStartLevel); - - if (settings.tocDropdown || div.find("." + this.classPrefix + "toc-menu").length > 0) - { - this.tocDropdownMenu(div, settings.tocTitle); - } - } - - if (settings.previewCodeHighlight) - { - div.find("pre").addClass("prettyprint linenums"); - prettyPrint(); - } - - if (!editormd.isIE8) - { - if (settings.flowChart) { - div.find(".flowchart").flowChart(); - } - - if (settings.sequenceDiagram) { - div.find(".sequence-diagram").sequenceDiagram({theme: "simple"}); - } - } - - if (settings.tex) - { - var katexHandle = function() { - div.find("." + editormd.classNames.tex).each(function(){ - var tex = $(this); - katex.render(tex.html().replace(/</g, "<").replace(/>/g, ">"), tex[0]); - }); - }; - - if (settings.autoLoadKaTeX && !editormd.$katex && !editormd.kaTeXLoaded) - { - this.loadKaTeX(function() { - editormd.$katex = katex; - editormd.kaTeXLoaded = true; - katexHandle(); - }); - } - else - { - katexHandle(); - } - } - - div.getMarkdown = function() { - return saveTo.val(); - }; - - return div; - }; - - editormd.themes = [ - "default", "3024-day", "3024-night", - "ambiance", "ambiance-mobile", - "base16-dark", "base16-light", "blackboard", - "cobalt", - "eclipse", "elegant", "erlang-dark", - "lesser-dark", - "mbo", "mdn-like", "midnight", "monokai", - "neat", "neo", "night", - "paraiso-dark", "paraiso-light", "pastel-on-dark", - "rubyblue", - "solarized", - "the-matrix", "tomorrow-night-eighties", "twilight", - "vibrant-ink", - "xq-dark", "xq-light" - ]; - - editormd.loadPlugins = {}; - - editormd.loadFiles = { - js : [], - css : [], - plugin : [] - }; - - /** - * 动态加载Editor.md插件,但不立即执行 - * Load editor.md plugins - * - * @param {String} fileName 插件文件路径 - * @param {Function} [callback=function()] 加载成功后执行的回调函数 - * @param {String} [into="head"] 嵌入页面的位置 - */ - - editormd.loadPlugin = function(fileName, callback, into) { - callback = callback || function() {}; - - this.loadScript(fileName, function() { - editormd.loadFiles.plugin.push(fileName); - callback(); - }, into); - }; - - /** - * 动态加载CSS文件的方法 - * Load css file method - * - * @param {String} fileName CSS文件名 - * @param {Function} [callback=function()] 加载成功后执行的回调函数 - * @param {String} [into="head"] 嵌入页面的位置 - */ - - editormd.loadCSS = function(fileName, callback, into) { - into = into || "head"; - callback = callback || function() {}; - - var css = document.createElement("link"); - css.type = "text/css"; - css.rel = "stylesheet"; - css.onload = css.onreadystatechange = function() { - editormd.loadFiles.css.push(fileName); - callback(); - }; - - css.href = fileName + ".css"; - - if(into === "head") { - document.getElementsByTagName("head")[0].appendChild(css); - } else { - document.body.appendChild(css); - } - }; - - editormd.isIE = (navigator.appName == "Microsoft Internet Explorer"); - editormd.isIE8 = (editormd.isIE && navigator.appVersion.match(/8./i) == "8."); - - /** - * 动态加载JS文件的方法 - * Load javascript file method - * - * @param {String} fileName JS文件名 - * @param {Function} [callback=function()] 加载成功后执行的回调函数 - * @param {String} [into="head"] 嵌入页面的位置 - */ - - editormd.loadScript = function(fileName, callback, into) { - - into = into || "head"; - callback = callback || function() {}; - - var script = null; - script = document.createElement("script"); - script.id = fileName.replace(/[\./]+/g, "-"); - script.type = "text/javascript"; - script.src = fileName + ".js"; - - if (editormd.isIE8) - { - script.onreadystatechange = function() { - if(script.readyState) - { - if (script.readyState === "loaded" || script.readyState === "complete") - { - script.onreadystatechange = null; - editormd.loadFiles.js.push(fileName); - callback(); - } - } - }; - } - else - { - script.onload = function() { - editormd.loadFiles.js.push(fileName); - callback(); - }; - } - - if (into === "head") { - document.getElementsByTagName("head")[0].appendChild(script); - } else { - document.body.appendChild(script); - } - }; - - // 使用国外的CDN,加载速度有时会很慢,或者自定义URL - // You can custom KaTeX load url. - editormd.katexURL = { - css : "//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min", - js : "//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min" - }; - - editormd.kaTeXLoaded = false; - - /** - * 加载KaTeX文件 - * load KaTeX files - * - * @param {Function} [callback=function()] 加载成功后执行的回调函数 - */ - - editormd.loadKaTeX = function (callback) { - editormd.loadCSS(editormd.katexURL.css, function(){ - editormd.loadScript(editormd.katexURL.js, callback || function(){}); - }); - }; - - /** - * 锁屏 - * lock screen - * - * @param {Boolean} lock Boolean 布尔值,是否锁屏 - * @returns {void} - */ - - editormd.lockScreen = function(lock) { - $("html,body").css("overflow", (lock) ? "hidden" : ""); - }; - - /** - * 动态创建对话框 - * Creating custom dialogs - * - * @param {Object} options 配置项键值对 Key/Value - * @returns {dialog} 返回创建的dialog的jQuery实例对象 - */ - - editormd.createDialog = function(options) { - var defaults = { - name : "", - width : 420, - height: 240, - title : "", - drag : true, - closed : true, - content : "", - mask : true, - maskStyle : { - backgroundColor : "#fff", - opacity : 0.1 - }, - lockScreen : true, - footer : true, - buttons : false - }; - - options = $.extend(true, defaults, options); - - var editor = this.editor; - var classPrefix = editormd.classPrefix; - var guid = (new Date()).getTime(); - var dialogName = ( (options.name === "") ? classPrefix + "dialog-" + guid : options.name); - var mouseOrTouch = editormd.mouseOrTouch; - - var html = "<div class=\"" + classPrefix + "dialog " + dialogName + "\">"; - - if (options.title !== "") - { - html += "<div class=\"" + classPrefix + "dialog-header\"" + ( (options.drag) ? " style=\"cursor: move;\"" : "" ) + ">"; - html += "<strong class=\"" + classPrefix + "dialog-title\">" + options.title + "</strong>"; - html += "</div>"; - } - - if (options.closed) - { - html += "<a href=\"javascript:;\" class=\"fa fa-close " + classPrefix + "dialog-close\"></a>"; - } - - html += "<div class=\"" + classPrefix + "dialog-container\">" + options.content; - - if (options.footer || typeof options.footer === "string") - { - html += "<div class=\"" + classPrefix + "dialog-footer\">" + ( (typeof options.footer === "boolean") ? "" : options.footer) + "</div>"; - } - - html += "</div>"; - - html += "<div class=\"" + classPrefix + "dialog-mask " + classPrefix + "dialog-mask-bg\"></div>"; - html += "<div class=\"" + classPrefix + "dialog-mask " + classPrefix + "dialog-mask-con\"></div>"; - html += "</div>"; - - editor.append(html); - - var dialog = editor.find("." + dialogName); - - dialog.lockScreen = function(lock) { - if (options.lockScreen) - { - $("html,body").css("overflow", (lock) ? "hidden" : ""); - } - - return dialog; - }; - - dialog.showMask = function() { - if (options.mask) - { - editor.find("." + classPrefix + "mask").css(options.maskStyle).css("z-index", editormd.dialogZindex - 1).show(); - } - return dialog; - }; - - dialog.hideMask = function() { - if (options.mask) - { - editor.find("." + classPrefix + "mask").hide(); - } - - return dialog; - }; - - dialog.loading = function(show) { - var loading = dialog.find("." + classPrefix + "dialog-mask"); - loading[(show) ? "show" : "hide"](); - - return dialog; - }; - - dialog.lockScreen(true).showMask(); - - dialog.show().css({ - zIndex : editormd.dialogZindex, - border : (editormd.isIE8) ? "1px solid #ddd" : "", - width : (typeof options.width === "number") ? options.width + "px" : options.width, - height : (typeof options.height === "number") ? options.height + "px" : options.height - }); - - var dialogPosition = function(){ - dialog.css({ - top : ($(window).height() - dialog.height()) / 2 + "px", - left : ($(window).width() - dialog.width()) / 2 + "px" - }); - }; - - dialogPosition(); - - $(window).resize(dialogPosition); - - dialog.children("." + classPrefix + "dialog-close").bind(mouseOrTouch("click", "touchend"), function() { - dialog.hide().lockScreen(false).hideMask(); - }); - - if (typeof options.buttons === "object") - { - var footer = dialog.footer = dialog.find("." + classPrefix + "dialog-footer"); - - for (var key in options.buttons) - { - var btn = options.buttons[key]; - var btnClassName = classPrefix + key + "-btn"; - - footer.append("<button class=\"" + classPrefix + "btn " + btnClassName + "\">" + btn[0] + "</button>"); - btn[1] = $.proxy(btn[1], dialog); - footer.children("." + btnClassName).bind(mouseOrTouch("click", "touchend"), btn[1]); - } - } - - if (options.title !== "" && options.drag) - { - var posX, posY; - var dialogHeader = dialog.children("." + classPrefix + "dialog-header"); - - if (!options.mask) { - dialogHeader.bind(mouseOrTouch("click", "touchend"), function(){ - editormd.dialogZindex += 2; - dialog.css("z-index", editormd.dialogZindex); - }); - } - - dialogHeader.mousedown(function(e) { - e = e || window.event; //IE - posX = e.clientX - parseInt(dialog[0].style.left); - posY = e.clientY - parseInt(dialog[0].style.top); - - document.onmousemove = moveAction; - }); - - var userCanSelect = function (obj) { - obj.removeClass(classPrefix + "user-unselect").off("selectstart"); - }; - - var userUnselect = function (obj) { - obj.addClass(classPrefix + "user-unselect").on("selectstart", function(event) { // selectstart for IE - return false; - }); - }; - - var moveAction = function (e) { - e = e || window.event; //IE - - var left, top, nowLeft = parseInt(dialog[0].style.left), nowTop = parseInt(dialog[0].style.top); - - if( nowLeft >= 0 ) { - if( nowLeft + dialog.width() <= $(window).width()) { - left = e.clientX - posX; - } else { - left = $(window).width() - dialog.width(); - document.onmousemove = null; - } - } else { - left = 0; - document.onmousemove = null; - } - - if( nowTop >= 0 ) { - top = e.clientY - posY; - } else { - top = 0; - document.onmousemove = null; - } - - - document.onselectstart = function() { - return false; - }; - - userUnselect($("body")); - userUnselect(dialog); - dialog[0].style.left = left + "px"; - dialog[0].style.top = top + "px"; - }; - - document.onmouseup = function() { - userCanSelect($("body")); - userCanSelect(dialog); - - document.onselectstart = null; - document.onmousemove = null; - }; - - dialogHeader.touchDraggable = function() { - var offset = null; - var start = function(e) { - var orig = e.originalEvent; - var pos = $(this).parent().position(); - - offset = { - x : orig.changedTouches[0].pageX - pos.left, - y : orig.changedTouches[0].pageY - pos.top - }; - }; - - var move = function(e) { - e.preventDefault(); - var orig = e.originalEvent; - - $(this).parent().css({ - top : orig.changedTouches[0].pageY - offset.y, - left : orig.changedTouches[0].pageX - offset.x - }); - }; - - this.bind("touchstart", start).bind("touchmove", move); - }; - - dialogHeader.touchDraggable(); - } - - editormd.dialogZindex += 2; - - return dialog; - }; - - /** - * 鼠标和触摸事件的判断/选择方法 - * MouseEvent or TouchEvent type switch - * - * @param {String} [mouseEventType="click"] 供选择的鼠标事件 - * @param {String} [touchEventType="touchend"] 供选择的触摸事件 - * @returns {String} EventType 返回事件类型名称 - */ - - editormd.mouseOrTouch = function(mouseEventType, touchEventType) { - mouseEventType = mouseEventType || "click"; - touchEventType = touchEventType || "touchend"; - - var eventType = mouseEventType; - - try { - document.createEvent("TouchEvent"); - eventType = touchEventType; - } catch(e) {} - - return eventType; - }; - - /** - * 日期时间的格式化方法 - * Datetime format method - * - * @param {String} [format=""] 日期时间的格式,类似PHP的格式 - * @returns {String} datefmt 返回格式化后的日期时间字符串 - */ - - editormd.dateFormat = function(format) { - format = format || ""; - - var addZero = function(d) { - return (d < 10) ? "0" + d : d; - }; - - var date = new Date(); - var year = date.getFullYear(); - var year2 = year.toString().slice(2, 4); - var month = addZero(date.getMonth() + 1); - var day = addZero(date.getDate()); - var weekDay = date.getDay(); - var hour = addZero(date.getHours()); - var min = addZero(date.getMinutes()); - var second = addZero(date.getSeconds()); - var ms = addZero(date.getMilliseconds()); - var datefmt = ""; - - var ymd = year2 + "-" + month + "-" + day; - var fymd = year + "-" + month + "-" + day; - var hms = hour + ":" + min + ":" + second; - - switch (format) - { - case "UNIX Time" : - datefmt = date.getTime(); - break; - - case "UTC" : - datefmt = date.toUTCString(); - break; - - case "yy" : - datefmt = year2; - break; - - case "year" : - case "yyyy" : - datefmt = year; - break; - - case "month" : - case "mm" : - datefmt = month; - break; - - case "cn-week-day" : - case "cn-wd" : - var cnWeekDays = ["日", "一", "二", "三", "四", "五", "六"]; - datefmt = "星期" + cnWeekDays[weekDay]; - break; - - case "week-day" : - case "wd" : - var weekDays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; - datefmt = weekDays[weekDay]; - break; - - case "day" : - case "dd" : - datefmt = day; - break; - - case "hour" : - case "hh" : - datefmt = hour; - break; - - case "min" : - case "ii" : - datefmt = min; - break; - - case "second" : - case "ss" : - datefmt = second; - break; - - case "ms" : - datefmt = ms; - break; - - case "yy-mm-dd" : - datefmt = ymd; - break; - - case "yyyy-mm-dd" : - datefmt = fymd; - break; - - case "yyyy-mm-dd h:i:s ms" : - case "full + ms" : - datefmt = fymd + " " + hms + " " + ms; - break; - - case "full" : - case "yyyy-mm-dd h:i:s" : - default: - datefmt = fymd + " " + hms; - break; - } - - return datefmt; - }; - - return editormd; - -})); - -
-APL mode - -⍝ Conway's game of life - -⍝ This example was inspired by the impressive demo at -⍝ http://www.youtube.com/watch?v=a9xAKttWgP4 - -⍝ Create a matrix: -⍝ 0 1 1 -⍝ 1 1 0 -⍝ 0 1 0 -creature ← (3 3 ⍴ ⍳ 9) ∈ 1 2 3 4 7 ⍝ Original creature from demo -creature ← (3 3 ⍴ ⍳ 9) ∈ 1 3 6 7 8 ⍝ Glider - -⍝ Place the creature on a larger board, near the centre -board ← ¯1 ⊖ ¯2 ⌽ 5 7 ↑ creature - -⍝ A function to move from one generation to the next -life ← {∨/ 1 ⍵ ∧ 3 4 = ⊂+/ +⌿ 1 0 ¯1 ∘.⊖ 1 0 ¯1 ⌽¨ ⊂⍵} - -⍝ Compute n-th generation and format it as a -⍝ character matrix -gen ← {' #'[(life ⍣ ⍵) board]} - -⍝ Show first three generations -(gen 1) (gen 2) (gen 3) - - - - - Simple mode that tries to handle APL as well as it can. - It attempts to label functions/operators based upon - monadic/dyadic usage (but this is far from fully fleshed out). - This means there are meaningful classnames so hover states can - have popups etc. - - MIME types defined: text/apl (APL code) -
-Asterisk dialplan mode - -; extensions.conf - the Asterisk dial plan -; - -[general] -; -; If static is set to no, or omitted, then the pbx_config will rewrite -; this file when extensions are modified. Remember that all comments -; made in the file will be lost when that happens. -static=yes - -#include "/etc/asterisk/additional_general.conf - -[iaxprovider] -switch => IAX2/user:[key]@myserver/mycontext - -[dynamic] -#exec /usr/bin/dynamic-peers.pl - -[trunkint] -; -; International long distance through trunk -; -exten => _9011.,1,Macro(dundi-e164,${EXTEN:4}) -exten => _9011.,n,Dial(${GLOBAL(TRUNK)}/${FILTER(0-9,${EXTEN:${GLOBAL(TRUNKMSD)}})}) - -[local] -; -; Master context for local, toll-free, and iaxtel calls only -; -ignorepat => 9 -include => default - -[demo] -include => stdexten -; -; We start with what to do when a call first comes in. -; -exten => s,1,Wait(1) ; Wait a second, just for fun -same => n,Answer ; Answer the line -same => n,Set(TIMEOUT(digit)=5) ; Set Digit Timeout to 5 seconds -same => n,Set(TIMEOUT(response)=10) ; Set Response Timeout to 10 seconds -same => n(restart),BackGround(demo-congrats) ; Play a congratulatory message -same => n(instruct),BackGround(demo-instruct) ; Play some instructions -same => n,WaitExten ; Wait for an extension to be dialed. - -exten => 2,1,BackGround(demo-moreinfo) ; Give some more information. -exten => 2,n,Goto(s,instruct) - -exten => 3,1,Set(LANGUAGE()=fr) ; Set language to french -exten => 3,n,Goto(s,restart) ; Start with the congratulations - -exten => 1000,1,Goto(default,s,1) -; -; We also create an example user, 1234, who is on the console and has -; voicemail, etc. -; -exten => 1234,1,Playback(transfer,skip) ; "Please hold while..." - ; (but skip if channel is not up) -exten => 1234,n,Gosub(${EXTEN},stdexten(${GLOBAL(CONSOLE)})) -exten => 1234,n,Goto(default,s,1) ; exited Voicemail - -exten => 1235,1,Voicemail(1234,u) ; Right to voicemail - -exten => 1236,1,Dial(Console/dsp) ; Ring forever -exten => 1236,n,Voicemail(1234,b) ; Unless busy - -; -; # for when they're done with the demo -; -exten => #,1,Playback(demo-thanks) ; "Thanks for trying the demo" -exten => #,n,Hangup ; Hang them up. - -; -; A timeout and "invalid extension rule" -; -exten => t,1,Goto(#,1) ; If they take too long, give up -exten => i,1,Playback(invalid) ; "That's not valid, try again" - -; -; Create an extension, 500, for dialing the -; Asterisk demo. -; -exten => 500,1,Playback(demo-abouttotry); Let them know what's going on -exten => 500,n,Dial(IAX2/guest@pbx.digium.com/s@default) ; Call the Asterisk demo -exten => 500,n,Playback(demo-nogo) ; Couldn't connect to the demo site -exten => 500,n,Goto(s,6) ; Return to the start over message. - -; -; Create an extension, 600, for evaluating echo latency. -; -exten => 600,1,Playback(demo-echotest) ; Let them know what's going on -exten => 600,n,Echo ; Do the echo test -exten => 600,n,Playback(demo-echodone) ; Let them know it's over -exten => 600,n,Goto(s,6) ; Start over - -; -; You can use the Macro Page to intercom a individual user -exten => 76245,1,Macro(page,SIP/Grandstream1) -; or if your peernames are the same as extensions -exten => _7XXX,1,Macro(page,SIP/${EXTEN}) -; -; -; System Wide Page at extension 7999 -; -exten => 7999,1,Set(TIMEOUT(absolute)=60) -exten => 7999,2,Page(Local/Grandstream1@page&Local/Xlite1@page&Local/1234@page/n,d) - -; Give voicemail at extension 8500 -; -exten => 8500,1,VoicemailMain -exten => 8500,n,Goto(s,6) - - - - - MIME types defined: text/x-asterisk. - -
-C-like mode - - -/* C demo code */ - -#include -#include -#include -#include -#include -#include -#include - -typedef struct { - void* arg_socket; - zmq_msg_t* arg_msg; - char* arg_string; - unsigned long arg_len; - int arg_int, arg_command; - - int signal_fd; - int pad; - void* context; - sem_t sem; -} acl_zmq_context; - -#define p(X) (context->arg_##X) - -void* zmq_thread(void* context_pointer) { - acl_zmq_context* context = (acl_zmq_context*)context_pointer; - char ok = 'K', err = 'X'; - int res; - - while (1) { - while ((res = sem_wait(&context->sem)) == EINTR); - if (res) {write(context->signal_fd, &err, 1); goto cleanup;} - switch(p(command)) { - case 0: goto cleanup; - case 1: p(socket) = zmq_socket(context->context, p(int)); break; - case 2: p(int) = zmq_close(p(socket)); break; - case 3: p(int) = zmq_bind(p(socket), p(string)); break; - case 4: p(int) = zmq_connect(p(socket), p(string)); break; - case 5: p(int) = zmq_getsockopt(p(socket), p(int), (void*)p(string), &p(len)); break; - case 6: p(int) = zmq_setsockopt(p(socket), p(int), (void*)p(string), p(len)); break; - case 7: p(int) = zmq_send(p(socket), p(msg), p(int)); break; - case 8: p(int) = zmq_recv(p(socket), p(msg), p(int)); break; - case 9: p(int) = zmq_poll(p(socket), p(int), p(len)); break; - } - p(command) = errno; - write(context->signal_fd, &ok, 1); - } - cleanup: - close(context->signal_fd); - free(context_pointer); - return 0; -} - -void* zmq_thread_init(void* zmq_context, int signal_fd) { - acl_zmq_context* context = malloc(sizeof(acl_zmq_context)); - pthread_t thread; - - context->context = zmq_context; - context->signal_fd = signal_fd; - sem_init(&context->sem, 1, 0); - pthread_create(&thread, 0, &zmq_thread, context); - pthread_detach(thread); - return context; -} - - -C++ example - - -#include -#include "mystuff/util.h" - -namespace { -enum Enum { - VAL1, VAL2, VAL3 -}; - -char32_t unicode_string = U"\U0010FFFF"; -string raw_string = R"delim(anything -you -want)delim"; - -int Helper(const MyType& param) { - return 0; -} -} // namespace - -class ForwardDec; - -template -class Class : public BaseClass { - const MyType member_; - - public: - const MyType& Method() const { - return member_; - } - - void Method2(MyType* value); -} - -template -void Class::Method2(MyType* value) { - std::out << 1 >> method(); - value->Method3(member_); - member_ = value; -} - - -Objective-C example - - -/* -This is a longer comment -That spans two lines -*/ - -#import -@implementation YourAppDelegate - -// This is a one-line comment - -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ - char myString[] = "This is a C character array"; - int test = 5; - return YES; -} - - -Java example - - -import com.demo.util.MyType; -import com.demo.util.MyInterface; - -public enum Enum { - VAL1, VAL2, VAL3 -} - -public class Class implements MyInterface { - public static final MyType member; - - private class InnerClass { - public int zero() { - return 0; - } - } - - @Override - public MyType method() { - return member; - } - - public void method2(MyType value) { - method(); - value.method3(); - member = value; - } -} - - -Scala example - - -object FilterTest extends App { - def filter(xs: List[Int], threshold: Int) = { - def process(ys: List[Int]): List[Int] = - if (ys.isEmpty) ys - else if (ys.head < threshold) ys.head :: process(ys.tail) - else process(ys.tail) - process(xs) - } - println(filter(List(1, 9, 2, 8, 3, 7, 4), 5)) -} - - - - - Simple mode that tries to handle C-like languages as well as it - can. Takes two configuration parameters: keywords, an - object whose property names are the keywords in the language, - and useCPP, which determines whether C preprocessor - directives are recognized. - - MIME types defined: text/x-csrc - (C), text/x-c++src (C++), text/x-java - (Java), text/x-csharp (C#), - text/x-objectivec (Objective-C), - text/x-scala (Scala), text/x-vertex - and x-shader/x-fragment (shader programs). -
-Scala mode - - - - /* __ *\ - ** ________ ___ / / ___ Scala API ** - ** / __/ __// _ | / / / _ | (c) 2003-2011, LAMP/EPFL ** - ** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** - ** /____/\___/_/ |_/____/_/ | | ** - ** |/ ** - \* */ - - package scala.collection - - import generic._ - import mutable.{ Builder, ListBuffer } - import annotation.{tailrec, migration, bridge} - import annotation.unchecked.{ uncheckedVariance => uV } - import parallel.ParIterable - - /** A template trait for traversable collections of type `Traversable[A]`. - * - * $traversableInfo - * @define mutability - * @define traversableInfo - * This is a base trait of all kinds of $mutability Scala collections. It - * implements the behavior common to all collections, in terms of a method - * `foreach` with signature: - * {{{ - * def foreach[U](f: Elem => U): Unit - * }}} - * Collection classes mixing in this trait provide a concrete - * `foreach` method which traverses all the - * elements contained in the collection, applying a given function to each. - * They also need to provide a method `newBuilder` - * which creates a builder for collections of the same kind. - * - * A traversable class might or might not have two properties: strictness - * and orderedness. Neither is represented as a type. - * - * The instances of a strict collection class have all their elements - * computed before they can be used as values. By contrast, instances of - * a non-strict collection class may defer computation of some of their - * elements until after the instance is available as a value. - * A typical example of a non-strict collection class is a - * - * `scala.collection.immutable.Stream`. - * A more general class of examples are `TraversableViews`. - * - * If a collection is an instance of an ordered collection class, traversing - * its elements with `foreach` will always visit elements in the - * same order, even for different runs of the program. If the class is not - * ordered, `foreach` can visit elements in different orders for - * different runs (but it will keep the same order in the same run).' - * - * A typical example of a collection class which is not ordered is a - * `HashMap` of objects. The traversal order for hash maps will - * depend on the hash codes of its elements, and these hash codes might - * differ from one run to the next. By contrast, a `LinkedHashMap` - * is ordered because it's `foreach` method visits elements in the - * order they were inserted into the `HashMap`. - * - * @author Martin Odersky - * @version 2.8 - * @since 2.8 - * @tparam A the element type of the collection - * @tparam Repr the type of the actual collection containing the elements. - * - * @define Coll Traversable - * @define coll traversable collection - */ - trait TraversableLike[+A, +Repr] extends HasNewBuilder[A, Repr] - with FilterMonadic[A, Repr] - with TraversableOnce[A] - with GenTraversableLike[A, Repr] - with Parallelizable[A, ParIterable[A]] - { - self => - - import Traversable.breaks._ - - /** The type implementing this traversable */ - protected type Self = Repr - - /** The collection of type $coll underlying this `TraversableLike` object. - * By default this is implemented as the `TraversableLike` object itself, - * but this can be overridden. - */ - def repr: Repr = this.asInstanceOf[Repr] - - /** The underlying collection seen as an instance of `$Coll`. - * By default this is implemented as the current collection object itself, - * but this can be overridden. - */ - protected[this] def thisCollection: Traversable[A] = this.asInstanceOf[Traversable[A]] - - /** A conversion from collections of type `Repr` to `$Coll` objects. - * By default this is implemented as just a cast, but this can be overridden. - */ - protected[this] def toCollection(repr: Repr): Traversable[A] = repr.asInstanceOf[Traversable[A]] - - /** Creates a new builder for this collection type. - */ - protected[this] def newBuilder: Builder[A, Repr] - - protected[this] def parCombiner = ParIterable.newCombiner[A] - - /** Applies a function `f` to all elements of this $coll. - * - * Note: this method underlies the implementation of most other bulk operations. - * It's important to implement this method in an efficient way. - * - * - * @param f the function that is applied for its side-effect to every element. - * The result of function `f` is discarded. - * - * @tparam U the type parameter describing the result of function `f`. - * This result will always be ignored. Typically `U` is `Unit`, - * but this is not necessary. - * - * @usecase def foreach(f: A => Unit): Unit - */ - def foreach[U](f: A => U): Unit - - /** Tests whether this $coll is empty. - * - * @return `true` if the $coll contain no elements, `false` otherwise. - */ - def isEmpty: Boolean = { - var result = true - breakable { - for (x <- this) { - result = false - break - } - } - result - } - - /** Tests whether this $coll is known to have a finite size. - * All strict collections are known to have finite size. For a non-strict collection - * such as `Stream`, the predicate returns `true` if all elements have been computed. - * It returns `false` if the stream is not yet evaluated to the end. - * - * Note: many collection methods will not work on collections of infinite sizes. - * - * @return `true` if this collection is known to have finite size, `false` otherwise. - */ - def hasDefiniteSize = true - - def ++[B >: A, That](that: GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = { - val b = bf(repr) - if (that.isInstanceOf[IndexedSeqLike[_, _]]) b.sizeHint(this, that.seq.size) - b ++= thisCollection - b ++= that.seq - b.result - } - - @bridge - def ++[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = - ++(that: GenTraversableOnce[B])(bf) - - /** Concatenates this $coll with the elements of a traversable collection. - * It differs from ++ in that the right operand determines the type of the - * resulting collection rather than the left one. - * - * @param that the traversable to append. - * @tparam B the element type of the returned collection. - * @tparam That $thatinfo - * @param bf $bfinfo - * @return a new collection of type `That` which contains all elements - * of this $coll followed by all elements of `that`. - * - * @usecase def ++:[B](that: TraversableOnce[B]): $Coll[B] - * - * @return a new $coll which contains all elements of this $coll - * followed by all elements of `that`. - */ - def ++:[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = { - val b = bf(repr) - if (that.isInstanceOf[IndexedSeqLike[_, _]]) b.sizeHint(this, that.size) - b ++= that - b ++= thisCollection - b.result - } - - /** This overload exists because: for the implementation of ++: we should reuse - * that of ++ because many collections override it with more efficient versions. - * Since TraversableOnce has no '++' method, we have to implement that directly, - * but Traversable and down can use the overload. - */ - def ++:[B >: A, That](that: Traversable[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = - (that ++ seq)(breakOut) - - def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = { - val b = bf(repr) - b.sizeHint(this) - for (x <- this) b += f(x) - b.result - } - - def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = { - val b = bf(repr) - for (x <- this) b ++= f(x).seq - b.result - } - - /** Selects all elements of this $coll which satisfy a predicate. - * - * @param p the predicate used to test elements. - * @return a new $coll consisting of all elements of this $coll that satisfy the given - * predicate `p`. The order of the elements is preserved. - */ - def filter(p: A => Boolean): Repr = { - val b = newBuilder - for (x <- this) - if (p(x)) b += x - b.result - } - - /** Selects all elements of this $coll which do not satisfy a predicate. - * - * @param p the predicate used to test elements. - * @return a new $coll consisting of all elements of this $coll that do not satisfy the given - * predicate `p`. The order of the elements is preserved. - */ - def filterNot(p: A => Boolean): Repr = filter(!p(_)) - - def collect[B, That](pf: PartialFunction[A, B])(implicit bf: CanBuildFrom[Repr, B, That]): That = { - val b = bf(repr) - for (x <- this) if (pf.isDefinedAt(x)) b += pf(x) - b.result - } - - /** Builds a new collection by applying an option-valued function to all - * elements of this $coll on which the function is defined. - * - * @param f the option-valued function which filters and maps the $coll. - * @tparam B the element type of the returned collection. - * @tparam That $thatinfo - * @param bf $bfinfo - * @return a new collection of type `That` resulting from applying the option-valued function - * `f` to each element and collecting all defined results. - * The order of the elements is preserved. - * - * @usecase def filterMap[B](f: A => Option[B]): $Coll[B] - * - * @param pf the partial function which filters and maps the $coll. - * @return a new $coll resulting from applying the given option-valued function - * `f` to each element and collecting all defined results. - * The order of the elements is preserved. - def filterMap[B, That](f: A => Option[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = { - val b = bf(repr) - for (x <- this) - f(x) match { - case Some(y) => b += y - case _ => - } - b.result - } - */ - - /** Partitions this $coll in two ${coll}s according to a predicate. - * - * @param p the predicate on which to partition. - * @return a pair of ${coll}s: the first $coll consists of all elements that - * satisfy the predicate `p` and the second $coll consists of all elements - * that don't. The relative order of the elements in the resulting ${coll}s - * is the same as in the original $coll. - */ - def partition(p: A => Boolean): (Repr, Repr) = { - val l, r = newBuilder - for (x <- this) (if (p(x)) l else r) += x - (l.result, r.result) - } - - def groupBy[K](f: A => K): immutable.Map[K, Repr] = { - val m = mutable.Map.empty[K, Builder[A, Repr]] - for (elem <- this) { - val key = f(elem) - val bldr = m.getOrElseUpdate(key, newBuilder) - bldr += elem - } - val b = immutable.Map.newBuilder[K, Repr] - for ((k, v) <- m) - b += ((k, v.result)) - - b.result - } - - /** Tests whether a predicate holds for all elements of this $coll. - * - * $mayNotTerminateInf - * - * @param p the predicate used to test elements. - * @return `true` if the given predicate `p` holds for all elements - * of this $coll, otherwise `false`. - */ - def forall(p: A => Boolean): Boolean = { - var result = true - breakable { - for (x <- this) - if (!p(x)) { result = false; break } - } - result - } - - /** Tests whether a predicate holds for some of the elements of this $coll. - * - * $mayNotTerminateInf - * - * @param p the predicate used to test elements. - * @return `true` if the given predicate `p` holds for some of the - * elements of this $coll, otherwise `false`. - */ - def exists(p: A => Boolean): Boolean = { - var result = false - breakable { - for (x <- this) - if (p(x)) { result = true; break } - } - result - } - - /** Finds the first element of the $coll satisfying a predicate, if any. - * - * $mayNotTerminateInf - * $orderDependent - * - * @param p the predicate used to test elements. - * @return an option value containing the first element in the $coll - * that satisfies `p`, or `None` if none exists. - */ - def find(p: A => Boolean): Option[A] = { - var result: Option[A] = None - breakable { - for (x <- this) - if (p(x)) { result = Some(x); break } - } - result - } - - def scan[B >: A, That](z: B)(op: (B, B) => B)(implicit cbf: CanBuildFrom[Repr, B, That]): That = scanLeft(z)(op) - - def scanLeft[B, That](z: B)(op: (B, A) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = { - val b = bf(repr) - b.sizeHint(this, 1) - var acc = z - b += acc - for (x <- this) { acc = op(acc, x); b += acc } - b.result - } - - @migration(2, 9, - "This scanRight definition has changed in 2.9.\n" + - "The previous behavior can be reproduced with scanRight.reverse." - ) - def scanRight[B, That](z: B)(op: (A, B) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = { - var scanned = List(z) - var acc = z - for (x <- reversed) { - acc = op(x, acc) - scanned ::= acc - } - val b = bf(repr) - for (elem <- scanned) b += elem - b.result - } - - /** Selects the first element of this $coll. - * $orderDependent - * @return the first element of this $coll. - * @throws `NoSuchElementException` if the $coll is empty. - */ - def head: A = { - var result: () => A = () => throw new NoSuchElementException - breakable { - for (x <- this) { - result = () => x - break - } - } - result() - } - - /** Optionally selects the first element. - * $orderDependent - * @return the first element of this $coll if it is nonempty, `None` if it is empty. - */ - def headOption: Option[A] = if (isEmpty) None else Some(head) - - /** Selects all elements except the first. - * $orderDependent - * @return a $coll consisting of all elements of this $coll - * except the first one. - * @throws `UnsupportedOperationException` if the $coll is empty. - */ - override def tail: Repr = { - if (isEmpty) throw new UnsupportedOperationException("empty.tail") - drop(1) - } - - /** Selects the last element. - * $orderDependent - * @return The last element of this $coll. - * @throws NoSuchElementException If the $coll is empty. - */ - def last: A = { - var lst = head - for (x <- this) - lst = x - lst - } - - /** Optionally selects the last element. - * $orderDependent - * @return the last element of this $coll$ if it is nonempty, `None` if it is empty. - */ - def lastOption: Option[A] = if (isEmpty) None else Some(last) - - /** Selects all elements except the last. - * $orderDependent - * @return a $coll consisting of all elements of this $coll - * except the last one. - * @throws `UnsupportedOperationException` if the $coll is empty. - */ - def init: Repr = { - if (isEmpty) throw new UnsupportedOperationException("empty.init") - var lst = head - var follow = false - val b = newBuilder - b.sizeHint(this, -1) - for (x <- this.seq) { - if (follow) b += lst - else follow = true - lst = x - } - b.result - } - - def take(n: Int): Repr = slice(0, n) - - def drop(n: Int): Repr = - if (n <= 0) { - val b = newBuilder - b.sizeHint(this) - b ++= thisCollection result - } - else sliceWithKnownDelta(n, Int.MaxValue, -n) - - def slice(from: Int, until: Int): Repr = sliceWithKnownBound(math.max(from, 0), until) - - // Precondition: from >= 0, until > 0, builder already configured for building. - private[this] def sliceInternal(from: Int, until: Int, b: Builder[A, Repr]): Repr = { - var i = 0 - breakable { - for (x <- this.seq) { - if (i >= from) b += x - i += 1 - if (i >= until) break - } - } - b.result - } - // Precondition: from >= 0 - private[scala] def sliceWithKnownDelta(from: Int, until: Int, delta: Int): Repr = { - val b = newBuilder - if (until <= from) b.result - else { - b.sizeHint(this, delta) - sliceInternal(from, until, b) - } - } - // Precondition: from >= 0 - private[scala] def sliceWithKnownBound(from: Int, until: Int): Repr = { - val b = newBuilder - if (until <= from) b.result - else { - b.sizeHintBounded(until - from, this) - sliceInternal(from, until, b) - } - } - - def takeWhile(p: A => Boolean): Repr = { - val b = newBuilder - breakable { - for (x <- this) { - if (!p(x)) break - b += x - } - } - b.result - } - - def dropWhile(p: A => Boolean): Repr = { - val b = newBuilder - var go = false - for (x <- this) { - if (!p(x)) go = true - if (go) b += x - } - b.result - } - - def span(p: A => Boolean): (Repr, Repr) = { - val l, r = newBuilder - var toLeft = true - for (x <- this) { - toLeft = toLeft && p(x) - (if (toLeft) l else r) += x - } - (l.result, r.result) - } - - def splitAt(n: Int): (Repr, Repr) = { - val l, r = newBuilder - l.sizeHintBounded(n, this) - if (n >= 0) r.sizeHint(this, -n) - var i = 0 - for (x <- this) { - (if (i < n) l else r) += x - i += 1 - } - (l.result, r.result) - } - - /** Iterates over the tails of this $coll. The first value will be this - * $coll and the final one will be an empty $coll, with the intervening - * values the results of successive applications of `tail`. - * - * @return an iterator over all the tails of this $coll - * @example `List(1,2,3).tails = Iterator(List(1,2,3), List(2,3), List(3), Nil)` - */ - def tails: Iterator[Repr] = iterateUntilEmpty(_.tail) - - /** Iterates over the inits of this $coll. The first value will be this - * $coll and the final one will be an empty $coll, with the intervening - * values the results of successive applications of `init`. - * - * @return an iterator over all the inits of this $coll - * @example `List(1,2,3).inits = Iterator(List(1,2,3), List(1,2), List(1), Nil)` - */ - def inits: Iterator[Repr] = iterateUntilEmpty(_.init) - - /** Copies elements of this $coll to an array. - * Fills the given array `xs` with at most `len` elements of - * this $coll, starting at position `start`. - * Copying will stop once either the end of the current $coll is reached, - * or the end of the array is reached, or `len` elements have been copied. - * - * $willNotTerminateInf - * - * @param xs the array to fill. - * @param start the starting index. - * @param len the maximal number of elements to copy. - * @tparam B the type of the elements of the array. - * - * - * @usecase def copyToArray(xs: Array[A], start: Int, len: Int): Unit - */ - def copyToArray[B >: A](xs: Array[B], start: Int, len: Int) { - var i = start - val end = (start + len) min xs.length - breakable { - for (x <- this) { - if (i >= end) break - xs(i) = x - i += 1 - } - } - } - - def toTraversable: Traversable[A] = thisCollection - def toIterator: Iterator[A] = toStream.iterator - def toStream: Stream[A] = toBuffer.toStream - - /** Converts this $coll to a string. - * - * @return a string representation of this collection. By default this - * string consists of the `stringPrefix` of this $coll, - * followed by all elements separated by commas and enclosed in parentheses. - */ - override def toString = mkString(stringPrefix + "(", ", ", ")") - - /** Defines the prefix of this object's `toString` representation. - * - * @return a string representation which starts the result of `toString` - * applied to this $coll. By default the string prefix is the - * simple name of the collection class $coll. - */ - def stringPrefix : String = { - var string = repr.asInstanceOf[AnyRef].getClass.getName - val idx1 = string.lastIndexOf('.' : Int) - if (idx1 != -1) string = string.substring(idx1 + 1) - val idx2 = string.indexOf('$') - if (idx2 != -1) string = string.substring(0, idx2) - string - } - - /** Creates a non-strict view of this $coll. - * - * @return a non-strict view of this $coll. - */ - def view = new TraversableView[A, Repr] { - protected lazy val underlying = self.repr - override def foreach[U](f: A => U) = self foreach f - } - - /** Creates a non-strict view of a slice of this $coll. - * - * Note: the difference between `view` and `slice` is that `view` produces - * a view of the current $coll, whereas `slice` produces a new $coll. - * - * Note: `view(from, to)` is equivalent to `view.slice(from, to)` - * $orderDependent - * - * @param from the index of the first element of the view - * @param until the index of the element following the view - * @return a non-strict view of a slice of this $coll, starting at index `from` - * and extending up to (but not including) index `until`. - */ - def view(from: Int, until: Int): TraversableView[A, Repr] = view.slice(from, until) - - /** Creates a non-strict filter of this $coll. - * - * Note: the difference between `c filter p` and `c withFilter p` is that - * the former creates a new collection, whereas the latter only - * restricts the domain of subsequent `map`, `flatMap`, `foreach`, - * and `withFilter` operations. - * $orderDependent - * - * @param p the predicate used to test elements. - * @return an object of class `WithFilter`, which supports - * `map`, `flatMap`, `foreach`, and `withFilter` operations. - * All these operations apply to those elements of this $coll which - * satisfy the predicate `p`. - */ - def withFilter(p: A => Boolean): FilterMonadic[A, Repr] = new WithFilter(p) - - /** A class supporting filtered operations. Instances of this class are - * returned by method `withFilter`. - */ - class WithFilter(p: A => Boolean) extends FilterMonadic[A, Repr] { - - /** Builds a new collection by applying a function to all elements of the - * outer $coll containing this `WithFilter` instance that satisfy predicate `p`. - * - * @param f the function to apply to each element. - * @tparam B the element type of the returned collection. - * @tparam That $thatinfo - * @param bf $bfinfo - * @return a new collection of type `That` resulting from applying - * the given function `f` to each element of the outer $coll - * that satisfies predicate `p` and collecting the results. - * - * @usecase def map[B](f: A => B): $Coll[B] - * - * @return a new $coll resulting from applying the given function - * `f` to each element of the outer $coll that satisfies - * predicate `p` and collecting the results. - */ - def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = { - val b = bf(repr) - for (x <- self) - if (p(x)) b += f(x) - b.result - } - - /** Builds a new collection by applying a function to all elements of the - * outer $coll containing this `WithFilter` instance that satisfy - * predicate `p` and concatenating the results. - * - * @param f the function to apply to each element. - * @tparam B the element type of the returned collection. - * @tparam That $thatinfo - * @param bf $bfinfo - * @return a new collection of type `That` resulting from applying - * the given collection-valued function `f` to each element - * of the outer $coll that satisfies predicate `p` and - * concatenating the results. - * - * @usecase def flatMap[B](f: A => TraversableOnce[B]): $Coll[B] - * - * @return a new $coll resulting from applying the given collection-valued function - * `f` to each element of the outer $coll that satisfies predicate `p` and concatenating the results. - */ - def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = { - val b = bf(repr) - for (x <- self) - if (p(x)) b ++= f(x).seq - b.result - } - - /** Applies a function `f` to all elements of the outer $coll containing - * this `WithFilter` instance that satisfy predicate `p`. - * - * @param f the function that is applied for its side-effect to every element. - * The result of function `f` is discarded. - * - * @tparam U the type parameter describing the result of function `f`. - * This result will always be ignored. Typically `U` is `Unit`, - * but this is not necessary. - * - * @usecase def foreach(f: A => Unit): Unit - */ - def foreach[U](f: A => U): Unit = - for (x <- self) - if (p(x)) f(x) - - /** Further refines the filter for this $coll. - * - * @param q the predicate used to test elements. - * @return an object of class `WithFilter`, which supports - * `map`, `flatMap`, `foreach`, and `withFilter` operations. - * All these operations apply to those elements of this $coll which - * satisfy the predicate `q` in addition to the predicate `p`. - */ - def withFilter(q: A => Boolean): WithFilter = - new WithFilter(x => p(x) && q(x)) - } - - // A helper for tails and inits. - private def iterateUntilEmpty(f: Traversable[A @uV] => Traversable[A @uV]): Iterator[Repr] = { - val it = Iterator.iterate(thisCollection)(f) takeWhile (x => !x.isEmpty) - it ++ Iterator(Nil) map (newBuilder ++= _ result) - } - } - - - - - - -
-Clojure mode - -; Conway's Game of Life, based on the work of: -;; Laurent Petit https://gist.github.com/1200343 -;; Christophe Grand http://clj-me.cgrand.net/2011/08/19/conways-game-of-life - -(ns ^{:doc "Conway's Game of Life."} - game-of-life) - -;; Core game of life's algorithm functions - -(defn neighbours - "Given a cell's coordinates, returns the coordinates of its neighbours." - [[x y]] - (for [dx [-1 0 1] dy (if (zero? dx) [-1 1] [-1 0 1])] - [(+ dx x) (+ dy y)])) - -(defn step - "Given a set of living cells, computes the new set of living cells." - [cells] - (set (for [[cell n] (frequencies (mapcat neighbours cells)) - :when (or (= n 3) (and (= n 2) (cells cell)))] - cell))) - -;; Utility methods for displaying game on a text terminal - -(defn print-board - "Prints a board on *out*, representing a step in the game." - [board w h] - (doseq [x (range (inc w)) y (range (inc h))] - (if (= y 0) (print "\n")) - (print (if (board [x y]) "[X]" " . ")))) - -(defn display-grids - "Prints a squence of boards on *out*, representing several steps." - [grids w h] - (doseq [board grids] - (print-board board w h) - (print "\n"))) - -;; Launches an example board - -(def - ^{:doc "board represents the initial set of living cells"} - board #{[2 1] [2 2] [2 3]}) - -(display-grids (take 3 (iterate step board)) 5 5) - -;; Let's play with characters -(println \1 \a \# \\ - \" \( \newline - \} \" \space - \tab \return \backspace - \u1000 \uAaAa \u9F9F) - - - - - MIME types defined: text/x-clojure. - -
-COBOL mode - - Select Theme - default - ambiance - blackboard - cobalt - eclipse - elegant - erlang-dark - lesser-dark - midnight - monokai - neat - night - rubyblue - solarized dark - solarized light - twilight - vibrant-ink - xq-dark - xq-light - Select Font Size - 13px - 14px - 16px - 18px - 20px - 24px - 26px - 28px - 30px - 32px - 34px - 36px - -Read-only - -Insert Spaces on Tab - - - ----------1---------2---------3---------4---------5---------6---------7---------8 -12345678911234567892123456789312345678941234567895123456789612345678971234567898 -000010 IDENTIFICATION DIVISION. MODTGHERE -000020 PROGRAM-ID. SAMPLE. -000030 AUTHOR. TEST SAM. -000040 DATE-WRITTEN. 5 February 2013 -000041 -000042* A sample program just to show the form. -000043* The program copies its input to the output, -000044* and counts the number of records. -000045* At the end this number is printed. -000046 -000050 ENVIRONMENT DIVISION. -000060 INPUT-OUTPUT SECTION. -000070 FILE-CONTROL. -000080 SELECT STUDENT-FILE ASSIGN TO SYSIN -000090 ORGANIZATION IS LINE SEQUENTIAL. -000100 SELECT PRINT-FILE ASSIGN TO SYSOUT -000110 ORGANIZATION IS LINE SEQUENTIAL. -000120 -000130 DATA DIVISION. -000140 FILE SECTION. -000150 FD STUDENT-FILE -000160 RECORD CONTAINS 43 CHARACTERS -000170 DATA RECORD IS STUDENT-IN. -000180 01 STUDENT-IN PIC X(43). -000190 -000200 FD PRINT-FILE -000210 RECORD CONTAINS 80 CHARACTERS -000220 DATA RECORD IS PRINT-LINE. -000230 01 PRINT-LINE PIC X(80). -000240 -000250 WORKING-STORAGE SECTION. -000260 01 DATA-REMAINS-SWITCH PIC X(2) VALUE SPACES. -000261 01 RECORDS-WRITTEN PIC 99. -000270 -000280 01 DETAIL-LINE. -000290 05 FILLER PIC X(7) VALUE SPACES. -000300 05 RECORD-IMAGE PIC X(43). -000310 05 FILLER PIC X(30) VALUE SPACES. -000311 -000312 01 SUMMARY-LINE. -000313 05 FILLER PIC X(7) VALUE SPACES. -000314 05 TOTAL-READ PIC 99. -000315 05 FILLER PIC X VALUE SPACE. -000316 05 FILLER PIC X(17) -000317 VALUE 'Records were read'. -000318 05 FILLER PIC X(53) VALUE SPACES. -000319 -000320 PROCEDURE DIVISION. -000321 -000330 PREPARE-SENIOR-REPORT. -000340 OPEN INPUT STUDENT-FILE -000350 OUTPUT PRINT-FILE. -000351 MOVE ZERO TO RECORDS-WRITTEN. -000360 READ STUDENT-FILE -000370 AT END MOVE 'NO' TO DATA-REMAINS-SWITCH -000380 END-READ. -000390 PERFORM PROCESS-RECORDS -000410 UNTIL DATA-REMAINS-SWITCH = 'NO'. -000411 PERFORM PRINT-SUMMARY. -000420 CLOSE STUDENT-FILE -000430 PRINT-FILE. -000440 STOP RUN. -000450 -000460 PROCESS-RECORDS. -000470 MOVE STUDENT-IN TO RECORD-IMAGE. -000480 MOVE DETAIL-LINE TO PRINT-LINE. -000490 WRITE PRINT-LINE. -000500 ADD 1 TO RECORDS-WRITTEN. -000510 READ STUDENT-FILE -000520 AT END MOVE 'NO' TO DATA-REMAINS-SWITCH -000530 END-READ. -000540 -000550 PRINT-SUMMARY. -000560 MOVE RECORDS-WRITTEN TO TOTAL-READ. -000570 MOVE SUMMARY-LINE TO PRINT-LINE. -000571 WRITE PRINT-LINE. -000572 -000580 - - -
-CoffeeScript mode - -# CoffeeScript mode for CodeMirror -# Copyright (c) 2011 Jeff Pickhardt, released under -# the MIT License. -# -# Modified from the Python CodeMirror mode, which also is -# under the MIT License Copyright (c) 2010 Timothy Farrell. -# -# The following script, Underscore.coffee, is used to -# demonstrate CoffeeScript mode for CodeMirror. -# -# To download CoffeeScript mode for CodeMirror, go to: -# https://github.com/pickhardt/coffeescript-codemirror-mode - -# **Underscore.coffee -# (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.** -# Underscore is freely distributable under the terms of the -# [MIT license](http://en.wikipedia.org/wiki/MIT_License). -# Portions of Underscore are inspired by or borrowed from -# [Prototype.js](http://prototypejs.org/api), Oliver Steele's -# [Functional](http://osteele.com), and John Resig's -# [Micro-Templating](http://ejohn.org). -# For all details and documentation: -# http://documentcloud.github.com/underscore/ - - -# Baseline setup -# -------------- - -# Establish the root object, `window` in the browser, or `global` on the server. -root = this - - -# Save the previous value of the `_` variable. -previousUnderscore = root._ - -### Multiline - comment -### - -# Establish the object that gets thrown to break out of a loop iteration. -# `StopIteration` is SOP on Mozilla. -breaker = if typeof(StopIteration) is 'undefined' then '__break__' else StopIteration - - -#### Docco style single line comment (title) - - -# Helper function to escape **RegExp** contents, because JS doesn't have one. -escapeRegExp = (string) -> string.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1') - - -# Save bytes in the minified (but not gzipped) version: -ArrayProto = Array.prototype -ObjProto = Object.prototype - - -# Create quick reference variables for speed access to core prototypes. -slice = ArrayProto.slice -unshift = ArrayProto.unshift -toString = ObjProto.toString -hasOwnProperty = ObjProto.hasOwnProperty -propertyIsEnumerable = ObjProto.propertyIsEnumerable - - -# All **ECMA5** native implementations we hope to use are declared here. -nativeForEach = ArrayProto.forEach -nativeMap = ArrayProto.map -nativeReduce = ArrayProto.reduce -nativeReduceRight = ArrayProto.reduceRight -nativeFilter = ArrayProto.filter -nativeEvery = ArrayProto.every -nativeSome = ArrayProto.some -nativeIndexOf = ArrayProto.indexOf -nativeLastIndexOf = ArrayProto.lastIndexOf -nativeIsArray = Array.isArray -nativeKeys = Object.keys - - -# Create a safe reference to the Underscore object for use below. -_ = (obj) -> new wrapper(obj) - - -# Export the Underscore object for **CommonJS**. -if typeof(exports) != 'undefined' then exports._ = _ - - -# Export Underscore to global scope. -root._ = _ - - -# Current version. -_.VERSION = '1.1.0' - - -# Collection Functions -# -------------------- - -# The cornerstone, an **each** implementation. -# Handles objects implementing **forEach**, arrays, and raw objects. -_.each = (obj, iterator, context) -> - try - if nativeForEach and obj.forEach is nativeForEach - obj.forEach iterator, context - else if _.isNumber obj.length - iterator.call context, obj[i], i, obj for i in [0...obj.length] - else - iterator.call context, val, key, obj for own key, val of obj - catch e - throw e if e isnt breaker - obj - - -# Return the results of applying the iterator to each element. Use JavaScript -# 1.6's version of **map**, if possible. -_.map = (obj, iterator, context) -> - return obj.map(iterator, context) if nativeMap and obj.map is nativeMap - results = [] - _.each obj, (value, index, list) -> - results.push iterator.call context, value, index, list - results - - -# **Reduce** builds up a single result from a list of values. Also known as -# **inject**, or **foldl**. Uses JavaScript 1.8's version of **reduce**, if possible. -_.reduce = (obj, iterator, memo, context) -> - if nativeReduce and obj.reduce is nativeReduce - iterator = _.bind iterator, context if context - return obj.reduce iterator, memo - _.each obj, (value, index, list) -> - memo = iterator.call context, memo, value, index, list - memo - - -# The right-associative version of **reduce**, also known as **foldr**. Uses -# JavaScript 1.8's version of **reduceRight**, if available. -_.reduceRight = (obj, iterator, memo, context) -> - if nativeReduceRight and obj.reduceRight is nativeReduceRight - iterator = _.bind iterator, context if context - return obj.reduceRight iterator, memo - reversed = _.clone(_.toArray(obj)).reverse() - _.reduce reversed, iterator, memo, context - - -# Return the first value which passes a truth test. -_.detect = (obj, iterator, context) -> - result = null - _.each obj, (value, index, list) -> - if iterator.call context, value, index, list - result = value - _.breakLoop() - result - - -# Return all the elements that pass a truth test. Use JavaScript 1.6's -# **filter**, if it exists. -_.filter = (obj, iterator, context) -> - return obj.filter iterator, context if nativeFilter and obj.filter is nativeFilter - results = [] - _.each obj, (value, index, list) -> - results.push value if iterator.call context, value, index, list - results - - -# Return all the elements for which a truth test fails. -_.reject = (obj, iterator, context) -> - results = [] - _.each obj, (value, index, list) -> - results.push value if not iterator.call context, value, index, list - results - - -# Determine whether all of the elements match a truth test. Delegate to -# JavaScript 1.6's **every**, if it is present. -_.every = (obj, iterator, context) -> - iterator ||= _.identity - return obj.every iterator, context if nativeEvery and obj.every is nativeEvery - result = true - _.each obj, (value, index, list) -> - _.breakLoop() unless (result = result and iterator.call(context, value, index, list)) - result - - -# Determine if at least one element in the object matches a truth test. Use -# JavaScript 1.6's **some**, if it exists. -_.some = (obj, iterator, context) -> - iterator ||= _.identity - return obj.some iterator, context if nativeSome and obj.some is nativeSome - result = false - _.each obj, (value, index, list) -> - _.breakLoop() if (result = iterator.call(context, value, index, list)) - result - - -# Determine if a given value is included in the array or object, -# based on `===`. -_.include = (obj, target) -> - return _.indexOf(obj, target) isnt -1 if nativeIndexOf and obj.indexOf is nativeIndexOf - return true for own key, val of obj when val is target - false - - -# Invoke a method with arguments on every item in a collection. -_.invoke = (obj, method) -> - args = _.rest arguments, 2 - (if method then val[method] else val).apply(val, args) for val in obj - - -# Convenience version of a common use case of **map**: fetching a property. -_.pluck = (obj, key) -> - _.map(obj, (val) -> val[key]) - - -# Return the maximum item or (item-based computation). -_.max = (obj, iterator, context) -> - return Math.max.apply(Math, obj) if not iterator and _.isArray(obj) - result = computed: -Infinity - _.each obj, (value, index, list) -> - computed = if iterator then iterator.call(context, value, index, list) else value - computed >= result.computed and (result = {value: value, computed: computed}) - result.value - - -# Return the minimum element (or element-based computation). -_.min = (obj, iterator, context) -> - return Math.min.apply(Math, obj) if not iterator and _.isArray(obj) - result = computed: Infinity - _.each obj, (value, index, list) -> - computed = if iterator then iterator.call(context, value, index, list) else value - computed < result.computed and (result = {value: value, computed: computed}) - result.value - - -# Sort the object's values by a criterion produced by an iterator. -_.sortBy = (obj, iterator, context) -> - _.pluck(((_.map obj, (value, index, list) -> - {value: value, criteria: iterator.call(context, value, index, list)} - ).sort((left, right) -> - a = left.criteria; b = right.criteria - if a < b then -1 else if a > b then 1 else 0 - )), 'value') - - -# Use a comparator function to figure out at what index an object should -# be inserted so as to maintain order. Uses binary search. -_.sortedIndex = (array, obj, iterator) -> - iterator ||= _.identity - low = 0 - high = array.length - while low < high - mid = (low + high) >> 1 - if iterator(array[mid]) < iterator(obj) then low = mid + 1 else high = mid - low - - -# Convert anything iterable into a real, live array. -_.toArray = (iterable) -> - return [] if (!iterable) - return iterable.toArray() if (iterable.toArray) - return iterable if (_.isArray(iterable)) - return slice.call(iterable) if (_.isArguments(iterable)) - _.values(iterable) - - -# Return the number of elements in an object. -_.size = (obj) -> _.toArray(obj).length - - -# Array Functions -# --------------- - -# Get the first element of an array. Passing `n` will return the first N -# values in the array. Aliased as **head**. The `guard` check allows it to work -# with **map**. -_.first = (array, n, guard) -> - if n and not guard then slice.call(array, 0, n) else array[0] - - -# Returns everything but the first entry of the array. Aliased as **tail**. -# Especially useful on the arguments object. Passing an `index` will return -# the rest of the values in the array from that index onward. The `guard` -# check allows it to work with **map**. -_.rest = (array, index, guard) -> - slice.call(array, if _.isUndefined(index) or guard then 1 else index) - - -# Get the last element of an array. -_.last = (array) -> array[array.length - 1] - - -# Trim out all falsy values from an array. -_.compact = (array) -> item for item in array when item - - -# Return a completely flattened version of an array. -_.flatten = (array) -> - _.reduce array, (memo, value) -> - return memo.concat(_.flatten(value)) if _.isArray value - memo.push value - memo - , [] - - -# Return a version of the array that does not contain the specified value(s). -_.without = (array) -> - values = _.rest arguments - val for val in _.toArray(array) when not _.include values, val - - -# Produce a duplicate-free version of the array. If the array has already -# been sorted, you have the option of using a faster algorithm. -_.uniq = (array, isSorted) -> - memo = [] - for el, i in _.toArray array - memo.push el if i is 0 || (if isSorted is true then _.last(memo) isnt el else not _.include(memo, el)) - memo - - -# Produce an array that contains every item shared between all the -# passed-in arrays. -_.intersect = (array) -> - rest = _.rest arguments - _.select _.uniq(array), (item) -> - _.all rest, (other) -> - _.indexOf(other, item) >= 0 - - -# Zip together multiple lists into a single array -- elements that share -# an index go together. -_.zip = -> - length = _.max _.pluck arguments, 'length' - results = new Array length - for i in [0...length] - results[i] = _.pluck arguments, String i - results - - -# If the browser doesn't supply us with **indexOf** (I'm looking at you, MSIE), -# we need this function. Return the position of the first occurrence of an -# item in an array, or -1 if the item is not included in the array. -_.indexOf = (array, item) -> - return array.indexOf item if nativeIndexOf and array.indexOf is nativeIndexOf - i = 0; l = array.length - while l - i - if array[i] is item then return i else i++ - -1 - - -# Provide JavaScript 1.6's **lastIndexOf**, delegating to the native function, -# if possible. -_.lastIndexOf = (array, item) -> - return array.lastIndexOf(item) if nativeLastIndexOf and array.lastIndexOf is nativeLastIndexOf - i = array.length - while i - if array[i] is item then return i else i-- - -1 - - -# Generate an integer Array containing an arithmetic progression. A port of -# [the native Python **range** function](http://docs.python.org/library/functions.html#range). -_.range = (start, stop, step) -> - a = arguments - solo = a.length <= 1 - i = start = if solo then 0 else a[0] - stop = if solo then a[0] else a[1] - step = a[2] or 1 - len = Math.ceil((stop - start) / step) - return [] if len <= 0 - range = new Array len - idx = 0 - loop - return range if (if step > 0 then i - stop else stop - i) >= 0 - range[idx] = i - idx++ - i+= step - - -# Function Functions -# ------------------ - -# Create a function bound to a given object (assigning `this`, and arguments, -# optionally). Binding with arguments is also known as **curry**. -_.bind = (func, obj) -> - args = _.rest arguments, 2 - -> func.apply obj or root, args.concat arguments - - -# Bind all of an object's methods to that object. Useful for ensuring that -# all callbacks defined on an object belong to it. -_.bindAll = (obj) -> - funcs = if arguments.length > 1 then _.rest(arguments) else _.functions(obj) - _.each funcs, (f) -> obj[f] = _.bind obj[f], obj - obj - - -# Delays a function for the given number of milliseconds, and then calls -# it with the arguments supplied. -_.delay = (func, wait) -> - args = _.rest arguments, 2 - setTimeout((-> func.apply(func, args)), wait) - - -# Memoize an expensive function by storing its results. -_.memoize = (func, hasher) -> - memo = {} - hasher or= _.identity - -> - key = hasher.apply this, arguments - return memo[key] if key of memo - memo[key] = func.apply this, arguments - - -# Defers a function, scheduling it to run after the current call stack has -# cleared. -_.defer = (func) -> - _.delay.apply _, [func, 1].concat _.rest arguments - - -# Returns the first function passed as an argument to the second, -# allowing you to adjust arguments, run code before and after, and -# conditionally execute the original function. -_.wrap = (func, wrapper) -> - -> wrapper.apply wrapper, [func].concat arguments - - -# Returns a function that is the composition of a list of functions, each -# consuming the return value of the function that follows. -_.compose = -> - funcs = arguments - -> - args = arguments - for i in [funcs.length - 1..0] by -1 - args = [funcs[i].apply(this, args)] - args[0] - - -# Object Functions -# ---------------- - -# Retrieve the names of an object's properties. -_.keys = nativeKeys or (obj) -> - return _.range 0, obj.length if _.isArray(obj) - key for key, val of obj - - -# Retrieve the values of an object's properties. -_.values = (obj) -> - _.map obj, _.identity - - -# Return a sorted list of the function names available in Underscore. -_.functions = (obj) -> - _.filter(_.keys(obj), (key) -> _.isFunction(obj[key])).sort() - - -# Extend a given object with all of the properties in a source object. -_.extend = (obj) -> - for source in _.rest(arguments) - obj[key] = val for key, val of source - obj - - -# Create a (shallow-cloned) duplicate of an object. -_.clone = (obj) -> - return obj.slice 0 if _.isArray obj - _.extend {}, obj - - -# Invokes interceptor with the obj, and then returns obj. -# The primary purpose of this method is to "tap into" a method chain, -# in order to perform operations on intermediate results within - the chain. -_.tap = (obj, interceptor) -> - interceptor obj - obj - - -# Perform a deep comparison to check if two objects are equal. -_.isEqual = (a, b) -> - # Check object identity. - return true if a is b - # Different types? - atype = typeof(a); btype = typeof(b) - return false if atype isnt btype - # Basic equality test (watch out for coercions). - return true if `a == b` - # One is falsy and the other truthy. - return false if (!a and b) or (a and !b) - # One of them implements an `isEqual()`? - return a.isEqual(b) if a.isEqual - # Check dates' integer values. - return a.getTime() is b.getTime() if _.isDate(a) and _.isDate(b) - # Both are NaN? - return false if _.isNaN(a) and _.isNaN(b) - # Compare regular expressions. - if _.isRegExp(a) and _.isRegExp(b) - return a.source is b.source and - a.global is b.global and - a.ignoreCase is b.ignoreCase and - a.multiline is b.multiline - # If a is not an object by this point, we can't handle it. - return false if atype isnt 'object' - # Check for different array lengths before comparing contents. - return false if a.length and (a.length isnt b.length) - # Nothing else worked, deep compare the contents. - aKeys = _.keys(a); bKeys = _.keys(b) - # Different object sizes? - return false if aKeys.length isnt bKeys.length - # Recursive comparison of contents. - return false for key, val of a when !(key of b) or !_.isEqual(val, b[key]) - true - - -# Is a given array or object empty? -_.isEmpty = (obj) -> - return obj.length is 0 if _.isArray(obj) or _.isString(obj) - return false for own key of obj - true - - -# Is a given value a DOM element? -_.isElement = (obj) -> obj and obj.nodeType is 1 - - -# Is a given value an array? -_.isArray = nativeIsArray or (obj) -> !!(obj and obj.concat and obj.unshift and not obj.callee) - - -# Is a given variable an arguments object? -_.isArguments = (obj) -> obj and obj.callee - - -# Is the given value a function? -_.isFunction = (obj) -> !!(obj and obj.constructor and obj.call and obj.apply) - - -# Is the given value a string? -_.isString = (obj) -> !!(obj is '' or (obj and obj.charCodeAt and obj.substr)) - - -# Is a given value a number? -_.isNumber = (obj) -> (obj is +obj) or toString.call(obj) is '[object Number]' - - -# Is a given value a boolean? -_.isBoolean = (obj) -> obj is true or obj is false - - -# Is a given value a Date? -_.isDate = (obj) -> !!(obj and obj.getTimezoneOffset and obj.setUTCFullYear) - - -# Is the given value a regular expression? -_.isRegExp = (obj) -> !!(obj and obj.exec and (obj.ignoreCase or obj.ignoreCase is false)) - - -# Is the given value NaN -- this one is interesting. `NaN != NaN`, and -# `isNaN(undefined) == true`, so we make sure it's a number first. -_.isNaN = (obj) -> _.isNumber(obj) and window.isNaN(obj) - - -# Is a given value equal to null? -_.isNull = (obj) -> obj is null - - -# Is a given variable undefined? -_.isUndefined = (obj) -> typeof obj is 'undefined' - - -# Utility Functions -# ----------------- - -# Run Underscore.js in noConflict mode, returning the `_` variable to its -# previous owner. Returns a reference to the Underscore object. -_.noConflict = -> - root._ = previousUnderscore - this - - -# Keep the identity function around for default iterators. -_.identity = (value) -> value - - -# Run a function `n` times. -_.times = (n, iterator, context) -> - iterator.call context, i for i in [0...n] - - -# Break out of the middle of an iteration. -_.breakLoop = -> throw breaker - - -# Add your own custom functions to the Underscore object, ensuring that -# they're correctly added to the OOP wrapper as well. -_.mixin = (obj) -> - for name in _.functions(obj) - addToWrapper name, _[name] = obj[name] - - -# Generate a unique integer id (unique within the entire client session). -# Useful for temporary DOM ids. -idCounter = 0 -_.uniqueId = (prefix) -> - (prefix or '') + idCounter++ - - -# By default, Underscore uses **ERB**-style template delimiters, change the -# following template settings to use alternative delimiters. -_.templateSettings = { - start: '<%' - end: '%>' - interpolate: /<%=(.+?)%>/g -} - - -# JavaScript templating a-la **ERB**, pilfered from John Resig's -# *Secrets of the JavaScript Ninja*, page 83. -# Single-quote fix from Rick Strahl. -# With alterations for arbitrary delimiters, and to preserve whitespace. -_.template = (str, data) -> - c = _.templateSettings - endMatch = new RegExp("'(?=[^"+c.end.substr(0, 1)+"]*"+escapeRegExp(c.end)+")","g") - fn = new Function 'obj', - 'var p=[],print=function(){p.push.apply(p,arguments);};' + - 'with(obj||{}){p.push(\'' + - str.replace(/\r/g, '\\r') - .replace(/\n/g, '\\n') - .replace(/\t/g, '\\t') - .replace(endMatch,"���") - .split("'").join("\\'") - .split("���").join("'") - .replace(c.interpolate, "',$1,'") - .split(c.start).join("');") - .split(c.end).join("p.push('") + - "');}return p.join('');" - if data then fn(data) else fn - - -# Aliases -# ------- - -_.forEach = _.each -_.foldl = _.inject = _.reduce -_.foldr = _.reduceRight -_.select = _.filter -_.all = _.every -_.any = _.some -_.contains = _.include -_.head = _.first -_.tail = _.rest -_.methods = _.functions - - -# Setup the OOP Wrapper -# --------------------- - -# If Underscore is called as a function, it returns a wrapped object that -# can be used OO-style. This wrapper holds altered versions of all the -# underscore functions. Wrapped objects may be chained. -wrapper = (obj) -> - this._wrapped = obj - this - - -# Helper function to continue chaining intermediate results. -result = (obj, chain) -> - if chain then _(obj).chain() else obj - - -# A method to easily add functions to the OOP wrapper. -addToWrapper = (name, func) -> - wrapper.prototype[name] = -> - args = _.toArray arguments - unshift.call args, this._wrapped - result func.apply(_, args), this._chain - - -# Add all ofthe Underscore functions to the wrapper object. -_.mixin _ - - -# Add all mutator Array functions to the wrapper. -_.each ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], (name) -> - method = Array.prototype[name] - wrapper.prototype[name] = -> - method.apply(this._wrapped, arguments) - result(this._wrapped, this._chain) - - -# Add all accessor Array functions to the wrapper. -_.each ['concat', 'join', 'slice'], (name) -> - method = Array.prototype[name] - wrapper.prototype[name] = -> - result(method.apply(this._wrapped, arguments), this._chain) - - -# Start chaining a wrapped Underscore object. -wrapper::chain = -> - this._chain = true - this - - -# Extracts the result from a wrapped and chained object. -wrapper::value = -> this._wrapped - - - - MIME types defined: text/x-coffeescript. - - The CoffeeScript mode was written by Jeff Pickhardt. - -
-Common Lisp mode -(in-package :cl-postgres) - -;; These are used to synthesize reader and writer names for integer -;; reading/writing functions when the amount of bytes and the -;; signedness is known. Both the macro that creates the functions and -;; some macros that use them create names this way. -(eval-when (:compile-toplevel :load-toplevel :execute) - (defun integer-reader-name (bytes signed) - (intern (with-standard-io-syntax - (format nil "~a~a~a~a" '#:read- (if signed "" '#:u) '#:int bytes)))) - (defun integer-writer-name (bytes signed) - (intern (with-standard-io-syntax - (format nil "~a~a~a~a" '#:write- (if signed "" '#:u) '#:int bytes))))) - -(defmacro integer-reader (bytes) - "Create a function to read integers from a binary stream." - (let ((bits (* bytes 8))) - (labels ((return-form (signed) - (if signed - `(if (logbitp ,(1- bits) result) - (dpb result (byte ,(1- bits) 0) -1) - result) - `result)) - (generate-reader (signed) - `(defun ,(integer-reader-name bytes signed) (socket) - (declare (type stream socket) - #.*optimize*) - ,(if (= bytes 1) - `(let ((result (the (unsigned-byte 8) (read-byte socket)))) - (declare (type (unsigned-byte 8) result)) - ,(return-form signed)) - `(let ((result 0)) - (declare (type (unsigned-byte ,bits) result)) - ,@(loop :for byte :from (1- bytes) :downto 0 - :collect `(setf (ldb (byte 8 ,(* 8 byte)) result) - (the (unsigned-byte 8) (read-byte socket)))) - ,(return-form signed)))))) - `(progn -;; This causes weird errors on SBCL in some circumstances. Disabled for now. -;; (declaim (inline ,(integer-reader-name bytes t) -;; ,(integer-reader-name bytes nil))) - (declaim (ftype (function (t) (signed-byte ,bits)) - ,(integer-reader-name bytes t))) - ,(generate-reader t) - (declaim (ftype (function (t) (unsigned-byte ,bits)) - ,(integer-reader-name bytes nil))) - ,(generate-reader nil))))) - -(defmacro integer-writer (bytes) - "Create a function to write integers to a binary stream." - (let ((bits (* 8 bytes))) - `(progn - (declaim (inline ,(integer-writer-name bytes t) - ,(integer-writer-name bytes nil))) - (defun ,(integer-writer-name bytes nil) (socket value) - (declare (type stream socket) - (type (unsigned-byte ,bits) value) - #.*optimize*) - ,@(if (= bytes 1) - `((write-byte value socket)) - (loop :for byte :from (1- bytes) :downto 0 - :collect `(write-byte (ldb (byte 8 ,(* byte 8)) value) - socket))) - (values)) - (defun ,(integer-writer-name bytes t) (socket value) - (declare (type stream socket) - (type (signed-byte ,bits) value) - #.*optimize*) - ,@(if (= bytes 1) - `((write-byte (ldb (byte 8 0) value) socket)) - (loop :for byte :from (1- bytes) :downto 0 - :collect `(write-byte (ldb (byte 8 ,(* byte 8)) value) - socket))) - (values))))) - -;; All the instances of the above that we need. - -(integer-reader 1) -(integer-reader 2) -(integer-reader 4) -(integer-reader 8) - -(integer-writer 1) -(integer-writer 2) -(integer-writer 4) - -(defun write-bytes (socket bytes) - "Write a byte-array to a stream." - (declare (type stream socket) - (type (simple-array (unsigned-byte 8)) bytes) - #.*optimize*) - (write-sequence bytes socket)) - -(defun write-str (socket string) - "Write a null-terminated string to a stream \(encoding it when UTF-8 -support is enabled.)." - (declare (type stream socket) - (type string string) - #.*optimize*) - (enc-write-string string socket) - (write-uint1 socket 0)) - -(declaim (ftype (function (t unsigned-byte) - (simple-array (unsigned-byte 8) (*))) - read-bytes)) -(defun read-bytes (socket length) - "Read a byte array of the given length from a stream." - (declare (type stream socket) - (type fixnum length) - #.*optimize*) - (let ((result (make-array length :element-type '(unsigned-byte 8)))) - (read-sequence result socket) - result)) - -(declaim (ftype (function (t) string) read-str)) -(defun read-str (socket) - "Read a null-terminated string from a stream. Takes care of encoding -when UTF-8 support is enabled." - (declare (type stream socket) - #.*optimize*) - (enc-read-string socket :null-terminated t)) - -(defun skip-bytes (socket length) - "Skip a given number of bytes in a binary stream." - (declare (type stream socket) - (type (unsigned-byte 32) length) - #.*optimize*) - (dotimes (i length) - (read-byte socket))) - -(defun skip-str (socket) - "Skip a null-terminated string." - (declare (type stream socket) - #.*optimize*) - (loop :for char :of-type fixnum = (read-byte socket) - :until (zerop char))) - -(defun ensure-socket-is-closed (socket &key abort) - (when (open-stream-p socket) - (handler-case - (close socket :abort abort) - (error (error) - (warn "Ignoring the error which happened while trying to close PostgreSQL socket: ~A" error))))) - - - - MIME types defined: text/x-common-lisp. - -
-CSS mode - -/* Some example CSS */ - -@import url("something.css"); - -body { - margin: 0; - padding: 3em 6em; - font-family: tahoma, arial, sans-serif; - color: #000; -} - -#navigation a { - font-weight: bold; - text-decoration: none !important; -} - -h1 { - font-size: 2.5em; -} - -h2 { - font-size: 1.7em; -} - -h1:before, h2:before { - content: "::"; -} - -code { - font-family: courier, monospace; - font-size: 80%; - color: #418A8A; -} - - - - MIME types defined: text/css, text/x-scss (demo), text/x-less (demo). - - Parsing/Highlighting Tests: normal, verbose. - -
-LESS mode -@media screen and (device-aspect-ratio: 16/9) { … } -@media screen and (device-aspect-ratio: 1280/720) { … } -@media screen and (device-aspect-ratio: 2560/1440) { … } - -html:lang(fr-be) - -tr:nth-child(2n+1) /* represents every odd row of an HTML table */ - -img:nth-of-type(2n+1) { float: right; } -img:nth-of-type(2n) { float: left; } - -body > h2:not(:first-of-type):not(:last-of-type) - -html|*:not(:link):not(:visited) -*|*:not(:hover) -p::first-line { text-transform: uppercase } - -@namespace foo url(http://www.example.com); -foo|h1 { color: blue } /* first rule */ - -span[hello="Ocean"][goodbye="Land"] - -E[foo]{ - padding:65px; -} - -input[type="search"]::-webkit-search-decoration, -input[type="search"]::-webkit-search-cancel-button { - -webkit-appearance: none; // Inner-padding issues in Chrome OSX, Safari 5 -} -button::-moz-focus-inner, -input::-moz-focus-inner { // Inner padding and border oddities in FF3/4 - padding: 0; - border: 0; -} -.btn { - // reset here as of 2.0.3 due to Recess property order - border-color: #ccc; - border-color: rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25); -} -fieldset span button, fieldset span input[type="file"] { - font-size:12px; - font-family:Arial, Helvetica, sans-serif; -} - -.rounded-corners (@radius: 5px) { - border-radius: @radius; - -webkit-border-radius: @radius; - -moz-border-radius: @radius; -} - -@import url("something.css"); - -@light-blue: hsl(190, 50%, 65%); - -#menu { - position: absolute; - width: 100%; - z-index: 3; - clear: both; - display: block; - background-color: @blue; - height: 42px; - border-top: 2px solid lighten(@alpha-blue, 20%); - border-bottom: 2px solid darken(@alpha-blue, 25%); - .box-shadow(0, 1px, 8px, 0.6); - -moz-box-shadow: 0 0 0 #000; // Because firefox sucks. - - &.docked { - background-color: hsla(210, 60%, 40%, 0.4); - } - &:hover { - background-color: @blue; - } - - #dropdown { - margin: 0 0 0 117px; - padding: 0; - padding-top: 5px; - display: none; - width: 190px; - border-top: 2px solid @medium; - color: @highlight; - border: 2px solid darken(@medium, 25%); - border-left-color: darken(@medium, 15%); - border-right-color: darken(@medium, 15%); - border-top-width: 0; - background-color: darken(@medium, 10%); - ul { - padding: 0px; - } - li { - font-size: 14px; - display: block; - text-align: left; - padding: 0; - border: 0; - a { - display: block; - padding: 0px 15px; - text-decoration: none; - color: white; - &:hover { - background-color: darken(@medium, 15%); - text-decoration: none; - } - } - } - .border-radius(5px, bottom); - .box-shadow(0, 6px, 8px, 0.5); - } -} - - - - The LESS mode is a sub-mode of the CSS mode (defined in css.js. - - Parsing/Highlighting Tests: normal, verbose. -
-SCSS mode - -/* Some example SCSS */ - -@import "compass/css3"; -$variable: #333; - -$blue: #3bbfce; -$margin: 16px; - -.content-navigation { - #nested { - background-color: black; - } - border-color: $blue; - color: - darken($blue, 9%); -} - -.border { - padding: $margin / 2; - margin: $margin / 2; - border-color: $blue; -} - -@mixin table-base { - th { - text-align: center; - font-weight: bold; - } - td, th {padding: 2px} -} - -table.hl { - margin: 2em 0; - td.ln { - text-align: right; - } -} - -li { - font: { - family: serif; - weight: bold; - size: 1.2em; - } -} - -@mixin left($dist) { - float: left; - margin-left: $dist; -} - -#data { - @include left(10px); - @include table-base; -} - -.source { - @include flow-into(target); - border: 10px solid green; - margin: 20px; - width: 200px; } - -.new-container { - @include flow-from(target); - border: 10px solid red; - margin: 20px; - width: 200px; } - -body { - margin: 0; - padding: 3em 6em; - font-family: tahoma, arial, sans-serif; - color: #000; -} - -@mixin yellow() { - background: yellow; -} - -.big { - font-size: 14px; -} - -.nested { - @include border-radius(3px); - @extend .big; - p { - background: whitesmoke; - a { - color: red; - } - } -} - -#navigation a { - font-weight: bold; - text-decoration: none !important; -} - -h1 { - font-size: 2.5em; -} - -h2 { - font-size: 1.7em; -} - -h1:before, h2:before { - content: "::"; -} - -code { - font-family: courier, monospace; - font-size: 80%; - color: #418A8A; -} - - - - The SCSS mode is a sub-mode of the CSS mode (defined in css.js. - - Parsing/Highlighting Tests: normal, verbose. - -
-Cypher Mode for CodeMirror - - // Cypher Mode for CodeMirror, using the neo theme -MATCH (joe { name: 'Joe' })-[:knows*2..2]-(friend_of_friend) -WHERE NOT (joe)-[:knows]-(friend_of_friend) -RETURN friend_of_friend.name, COUNT(*) -ORDER BY COUNT(*) DESC , friend_of_friend.name - - - MIME types defined: - application/x-cypher-query - - - -
-D mode - -/* D demo code // copied from phobos/sd/metastrings.d */ -// Written in the D programming language. - -/** -Templates with which to do compile-time manipulation of strings. - -Macros: - WIKI = Phobos/StdMetastrings - -Copyright: Copyright Digital Mars 2007 - 2009. -License: Boost License 1.0. -Authors: $(WEB digitalmars.com, Walter Bright), - Don Clugston -Source: $(PHOBOSSRC std/_metastrings.d) -*/ -/* - Copyright Digital Mars 2007 - 2009. -Distributed under the Boost Software License, Version 1.0. - (See accompanying file LICENSE_1_0.txt or copy at - http://www.boost.org/LICENSE_1_0.txt) - */ -module std.metastrings; - -/** -Formats constants into a string at compile time. Analogous to $(XREF -string,format). - -Parameters: - -A = tuple of constants, which can be strings, characters, or integral - values. - -Formats: - * The formats supported are %s for strings, and %% - * for the % character. -Example: ---- -import std.metastrings; -import std.stdio; - -void main() -{ - string s = Format!("Arg %s = %s", "foo", 27); - writefln(s); // "Arg foo = 27" -} - * --- - */ - -template Format(A...) -{ - static if (A.length == 0) - enum Format = ""; - else static if (is(typeof(A[0]) : const(char)[])) - enum Format = FormatString!(A[0], A[1..$]); - else - enum Format = toStringNow!(A[0]) ~ Format!(A[1..$]); -} - -template FormatString(const(char)[] F, A...) -{ - static if (F.length == 0) - enum FormatString = Format!(A); - else static if (F.length == 1) - enum FormatString = F[0] ~ Format!(A); - else static if (F[0..2] == "%s") - enum FormatString - = toStringNow!(A[0]) ~ FormatString!(F[2..$],A[1..$]); - else static if (F[0..2] == "%%") - enum FormatString = "%" ~ FormatString!(F[2..$],A); - else - { - static assert(F[0] != '%', "unrecognized format %" ~ F[1]); - enum FormatString = F[0] ~ FormatString!(F[1..$],A); - } -} - -unittest -{ - auto s = Format!("hel%slo", "world", -138, 'c', true); - assert(s == "helworldlo-138ctrue", "[" ~ s ~ "]"); -} - -/** - * Convert constant argument to a string. - */ - -template toStringNow(ulong v) -{ - static if (v < 10) - enum toStringNow = "" ~ cast(char)(v + '0'); - else - enum toStringNow = toStringNow!(v / 10) ~ toStringNow!(v % 10); -} - -unittest -{ - static assert(toStringNow!(1uL << 62) == "4611686018427387904"); -} - -/// ditto -template toStringNow(long v) -{ - static if (v < 0) - enum toStringNow = "-" ~ toStringNow!(cast(ulong) -v); - else - enum toStringNow = toStringNow!(cast(ulong) v); -} - -unittest -{ - static assert(toStringNow!(0x100000000) == "4294967296"); - static assert(toStringNow!(-138L) == "-138"); -} - -/// ditto -template toStringNow(uint U) -{ - enum toStringNow = toStringNow!(cast(ulong)U); -} - -/// ditto -template toStringNow(int I) -{ - enum toStringNow = toStringNow!(cast(long)I); -} - -/// ditto -template toStringNow(bool B) -{ - enum toStringNow = B ? "true" : "false"; -} - -/// ditto -template toStringNow(string S) -{ - enum toStringNow = S; -} - -/// ditto -template toStringNow(char C) -{ - enum toStringNow = "" ~ C; -} - - -/******** - * Parse unsigned integer literal from the start of string s. - * returns: - * .value = the integer literal as a string, - * .rest = the string following the integer literal - * Otherwise: - * .value = null, - * .rest = s - */ - -template parseUinteger(const(char)[] s) -{ - static if (s.length == 0) - { - enum value = ""; - enum rest = ""; - } - else static if (s[0] >= '0' && s[0] <= '9') - { - enum value = s[0] ~ parseUinteger!(s[1..$]).value; - enum rest = parseUinteger!(s[1..$]).rest; - } - else - { - enum value = ""; - enum rest = s; - } -} - -/******** -Parse integer literal optionally preceded by $(D '-') from the start -of string $(D s). - -Returns: - .value = the integer literal as a string, - .rest = the string following the integer literal - -Otherwise: - .value = null, - .rest = s -*/ - -template parseInteger(const(char)[] s) -{ - static if (s.length == 0) - { - enum value = ""; - enum rest = ""; - } - else static if (s[0] >= '0' && s[0] <= '9') - { - enum value = s[0] ~ parseUinteger!(s[1..$]).value; - enum rest = parseUinteger!(s[1..$]).rest; - } - else static if (s.length >= 2 && - s[0] == '-' && s[1] >= '0' && s[1] <= '9') - { - enum value = s[0..2] ~ parseUinteger!(s[2..$]).value; - enum rest = parseUinteger!(s[2..$]).rest; - } - else - { - enum value = ""; - enum rest = s; - } -} - -unittest -{ - assert(parseUinteger!("1234abc").value == "1234"); - assert(parseUinteger!("1234abc").rest == "abc"); - assert(parseInteger!("-1234abc").value == "-1234"); - assert(parseInteger!("-1234abc").rest == "abc"); -} - -/** -Deprecated aliases held for backward compatibility. -*/ -deprecated alias toStringNow ToString; -/// Ditto -deprecated alias parseUinteger ParseUinteger; -/// Ditto -deprecated alias parseUinteger ParseInteger; - - - - - - Simple mode that handle D-Syntax (DLang Homepage). - - MIME types defined: text/x-d - . -
-Dart mode - - -import 'dart:math' show Random; - -void main() { - print(new Die(n: 12).roll()); -} - -// Define a class. -class Die { - // Define a class variable. - static Random shaker = new Random(); - - // Define instance variables. - int sides, value; - - // Define a method using shorthand syntax. - String toString() => '$value'; - - // Define a constructor. - Die({int n: 6}) { - if (4 <= n && n <= 20) { - sides = n; - } else { - // Support for errors and exceptions. - throw new ArgumentError(/* */); - } - } - - // Define an instance method. - int roll() { - return value = shaker.nextInt(sides) + 1; - } -} - - - - - -
-Diff mode - -diff --git a/index.html b/index.html -index c1d9156..7764744 100644 ---- a/index.html -+++ b/index.html -@@ -95,7 +95,8 @@ StringStream.prototype = { - -