diff --git a/build.dev.js b/build.dev.js index 4017223..e72453b 100644 --- a/build.dev.js +++ b/build.dev.js @@ -19,7 +19,12 @@ const prefixer = postcss().use( ) const jsOpt = { presets: ['es2015'], - plugins: ['transform-es2015-modules-amd'] + plugins: [ + 'transform-es2015-modules-amd', + 'transform-decorators-legacy', + 'transform-class-properties', + 'transform-object-rest-spread' + ] } const cssOpt = { includePaths: ['src/css/'], diff --git a/build.prod.js b/build.prod.js index 8f79a3a..334caa7 100644 --- a/build.prod.js +++ b/build.prod.js @@ -18,7 +18,12 @@ const prefixer = postcss().use( ) const jsOpt = { presets: ['es2015', 'minify'], - plugins: ['transform-es2015-modules-amd'] + plugins: [ + 'transform-es2015-modules-amd', + 'transform-decorators-legacy', + 'transform-class-properties', + 'transform-object-rest-spread' + ] } const cssOpt = { includePaths: ['src/css/'], diff --git a/package-lock.json b/package-lock.json index 2b5f5fc..e90d0ea 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,5 +1,5 @@ { - "name": "doui-yua", + "name": "doui-anot", "version": "0.0.1", "lockfileVersion": 1, "requires": true, @@ -463,6 +463,47 @@ "babel-helper-is-void-0": "0.2.0" } }, + "babel-plugin-syntax-class-properties": { + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/babel-plugin-syntax-class-properties/-/babel-plugin-syntax-class-properties-6.13.0.tgz", + "integrity": "sha1-1+sjt5oxf4VDlixQW4J8fWysJ94=", + "dev": true + }, + "babel-plugin-syntax-decorators": { + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/babel-plugin-syntax-decorators/-/babel-plugin-syntax-decorators-6.13.0.tgz", + "integrity": "sha1-MSVjtNvePMgGzuPkFszurd0RrAs=", + "dev": true + }, + "babel-plugin-syntax-object-rest-spread": { + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/babel-plugin-syntax-object-rest-spread/-/babel-plugin-syntax-object-rest-spread-6.13.0.tgz", + "integrity": "sha1-/WU28rzhODb/o6VFjEkDpZe7O/U=", + "dev": true + }, + "babel-plugin-transform-class-properties": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-class-properties/-/babel-plugin-transform-class-properties-6.24.1.tgz", + "integrity": "sha1-anl2PqYdM9NvN7YRqp3vgagbRqw=", + "dev": true, + "requires": { + "babel-helper-function-name": "6.24.1", + "babel-plugin-syntax-class-properties": "6.13.0", + "babel-runtime": "6.26.0", + "babel-template": "6.26.0" + } + }, + "babel-plugin-transform-decorators-legacy": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-decorators-legacy/-/babel-plugin-transform-decorators-legacy-1.3.4.tgz", + "integrity": "sha1-dBtY9sW86eYCfgiC2cmU8E82aSU=", + "dev": true, + "requires": { + "babel-plugin-syntax-decorators": "6.13.0", + "babel-runtime": "6.26.0", + "babel-template": "6.26.0" + } + }, "babel-plugin-transform-es2015-arrow-functions": { "version": "6.22.0", "resolved": "https://registry.npmjs.org/babel-plugin-transform-es2015-arrow-functions/-/babel-plugin-transform-es2015-arrow-functions-6.22.0.tgz", @@ -721,6 +762,16 @@ "integrity": "sha512-bPbUhkeN2Nc0KH0/A19GwQGj8w+CvdJzyu8t59VoEDgsNMQ9Bopzi5DrVkrSsVjbYUaZpzq/DYLrH+wD5K2Tig==", "dev": true }, + "babel-plugin-transform-object-rest-spread": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-object-rest-spread/-/babel-plugin-transform-object-rest-spread-6.26.0.tgz", + "integrity": "sha1-DzZpLVD+9rfi1LOsFHgTepY7ewY=", + "dev": true, + "requires": { + "babel-plugin-syntax-object-rest-spread": "6.13.0", + "babel-runtime": "6.26.0" + } + }, "babel-plugin-transform-property-literals": { "version": "6.8.5", "resolved": "https://registry.npmjs.org/babel-plugin-transform-property-literals/-/babel-plugin-transform-property-literals-6.8.5.tgz", diff --git a/package.json b/package.json index 8aaf582..66403d5 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "name": "doui-yua", + "name": "doui-anot", "version": "0.0.1", "description": "基于Anot框架的doUI组件库。支持IE10+,及现代浏览器。", "main": "index.js", @@ -13,13 +13,16 @@ }, "keywords": [ "doui", - "yua" + "Anot" ], "author": "yutent", "license": "MIT", "devDependencies": { "autoprefixer": "^7.2.5", "babel-core": "^6.26.0", + "babel-plugin-transform-class-properties": "^6.24.1", + "babel-plugin-transform-decorators-legacy": "^1.3.4", + "babel-plugin-transform-object-rest-spread": "^6.26.0", "babel-preset-es2015": "^6.24.1", "babel-preset-minify": "^0.2.0", "chalk": "^2.3.0", diff --git a/src/font/ui-font.eot b/src/font/ui-font.eot index b4d3763..fb01476 100644 Binary files a/src/font/ui-font.eot and b/src/font/ui-font.eot differ diff --git a/src/font/ui-font.js b/src/font/ui-font.js index 7dc9667..95f34ca 100644 --- a/src/font/ui-font.js +++ b/src/font/ui-font.js @@ -1 +1 @@ -(function(window){var svgSprite='';var script=function(){var scripts=document.getElementsByTagName("script");return scripts[scripts.length-1]}();var shouldInjectCss=script.getAttribute("data-injectcss");var ready=function(fn){if(document.addEventListener){if(~["complete","loaded","interactive"].indexOf(document.readyState)){setTimeout(fn,0)}else{var loadFn=function(){document.removeEventListener("DOMContentLoaded",loadFn,false);fn()};document.addEventListener("DOMContentLoaded",loadFn,false)}}else if(document.attachEvent){IEContentLoaded(window,fn)}function IEContentLoaded(w,fn){var d=w.document,done=false,init=function(){if(!done){done=true;fn()}};var polling=function(){try{d.documentElement.doScroll("left")}catch(e){setTimeout(polling,50);return}init()};polling();d.onreadystatechange=function(){if(d.readyState=="complete"){d.onreadystatechange=null;init()}}}};var before=function(el,target){target.parentNode.insertBefore(el,target)};var prepend=function(el,target){if(target.firstChild){before(el,target.firstChild)}else{target.appendChild(el)}};function appendSvg(){var div,svg;div=document.createElement("div");div.innerHTML=svgSprite;svgSprite=null;svg=div.getElementsByTagName("svg")[0];if(svg){svg.setAttribute("aria-hidden","true");svg.style.position="absolute";svg.style.width=0;svg.style.height=0;svg.style.overflow="hidden";prepend(svg,document.body)}}if(shouldInjectCss&&!window.__iconfont__svg__cssinject__){window.__iconfont__svg__cssinject__=true;try{document.write("")}catch(e){console&&console.log(e)}}ready(appendSvg)})(window) \ No newline at end of file +(function(window){var svgSprite='';var script=function(){var scripts=document.getElementsByTagName("script");return scripts[scripts.length-1]}();var shouldInjectCss=script.getAttribute("data-injectcss");var ready=function(fn){if(document.addEventListener){if(~["complete","loaded","interactive"].indexOf(document.readyState)){setTimeout(fn,0)}else{var loadFn=function(){document.removeEventListener("DOMContentLoaded",loadFn,false);fn()};document.addEventListener("DOMContentLoaded",loadFn,false)}}else if(document.attachEvent){IEContentLoaded(window,fn)}function IEContentLoaded(w,fn){var d=w.document,done=false,init=function(){if(!done){done=true;fn()}};var polling=function(){try{d.documentElement.doScroll("left")}catch(e){setTimeout(polling,50);return}init()};polling();d.onreadystatechange=function(){if(d.readyState=="complete"){d.onreadystatechange=null;init()}}}};var before=function(el,target){target.parentNode.insertBefore(el,target)};var prepend=function(el,target){if(target.firstChild){before(el,target.firstChild)}else{target.appendChild(el)}};function appendSvg(){var div,svg;div=document.createElement("div");div.innerHTML=svgSprite;svgSprite=null;svg=div.getElementsByTagName("svg")[0];if(svg){svg.setAttribute("aria-hidden","true");svg.style.position="absolute";svg.style.width=0;svg.style.height=0;svg.style.overflow="hidden";prepend(svg,document.body)}}if(shouldInjectCss&&!window.__iconfont__svg__cssinject__){window.__iconfont__svg__cssinject__=true;try{document.write("")}catch(e){console&&console.log(e)}}ready(appendSvg)})(window) \ No newline at end of file diff --git a/src/font/ui-font.ttf b/src/font/ui-font.ttf index 8568230..70e12c1 100644 Binary files a/src/font/ui-font.ttf and b/src/font/ui-font.ttf differ diff --git a/src/js/anot.shim.js b/src/js/anot.shim.js index d4baa6e..d9cf270 100644 --- a/src/js/anot.shim.js +++ b/src/js/anot.shim.js @@ -3297,11 +3297,12 @@ if (/^:/.test(attr.name)) { var name = attr.name.match(rmsAttr)[1] var value = null - if (!name || Anot.directives[name]) { + if (!name || Anot.directives[name] || events[name]) { return } try { value = parseExpr(attr.value, vmodels, {}).apply(0, vmodels) + value = toJson(value) elem.removeAttribute(attr.name) if (!value) { return @@ -4092,7 +4093,7 @@ elem.addEventListener(type, callback, false) var old = binding.rollback binding.rollback = function() { - elem.anotStter = null + elem.anotSetter = null Anot.unbind(elem, type, callback) old && old() } @@ -4196,7 +4197,7 @@ elem.msFocus = false }) } - elem.anotStter = updateVModel //#765 + elem.anotSetter = updateVModel //#765 watchValueInTimer(function() { if (root.contains(elem)) { if (!elem.msFocus) { @@ -4346,8 +4347,8 @@ function newSetter(value) { // jshint ignore:line setters[this.tagName].call(this, value) - if (!this.msFocus && this.anotStter) { - this.anotStter() + if (!this.msFocus && this.anotSetter) { + this.anotSetter() } } var inputProto = HTMLInputElement.prototype diff --git a/src/js/datepicker/style.scss b/src/js/datepicker/style.scss index 53863d9..ddc45d3 100644 --- a/src/js/datepicker/style.scss +++ b/src/js/datepicker/style.scss @@ -42,16 +42,16 @@ &:active {font-weight:bold; &::before {animation:ripple .3s cubic-bezier(0.23, 1, 0.32, 1);} } - &::after {content:"\e652";} + &::after {content:"\e692";} &.prev-month {left:35px; - &::after {content:"\e659"} + &::after {content:"\e67c"} } &.next-month {left:auto; right:35px; - &::after {content:"\e658"} + &::after {content:"\e66e"} } &.next-year {left:auto; right:0; - &::after {content:"\e653"} + &::after {content:"\e694"} } } diff --git a/src/js/drag/index.js b/src/js/drag/index.js new file mode 100644 index 0000000..60c355e --- /dev/null +++ b/src/js/drag/index.js @@ -0,0 +1,219 @@ +/** + * + * @authors yutent (yutent@doui.cc) + * @date 2017-03-29 18:39:35 + * + */ + +'use strict' + +function getBindingCallback(elem, name, vmodels) { + var callback = elem.getAttribute(name) + if (callback) { + for (var i = 0, vm; (vm = vmodels[i++]); ) { + if (vm.hasOwnProperty(callback) && typeof vm[callback] === 'function') { + return vm[callback] + } + } + } +} +Anot.ui.drag = '1.0.0' +// 元素拖动 +Anot.directive('drag', { + priority: 1500, + init: function(binding) { + binding.expr = '"' + binding.expr + '"' + Anot(binding.element).css('cursor', 'move') + + //取得拖动的3种状态回调 + //按下,且拖拽之前 + binding.beforedrag = getBindingCallback( + binding.element, + 'data-beforedrag', + binding.vmodels + ) + //拖拽过程 + binding.dragging = getBindingCallback( + binding.element, + 'data-dragging', + binding.vmodels + ) + // 拖拽结束,且释放鼠标 + binding.dragged = getBindingCallback( + binding.element, + 'data-dragged', + binding.vmodels + ) + + //默认允许溢出可视区 + binding.overflow = true + + //方向,x轴, y轴, xy轴 + binding.axis = 'xy' + if (!!binding.element.dataset.axis) { + binding.axis = binding.element.dataset.axis + delete binding.element.dataset.axis + } + + //默认不限制拖拽区域 + binding.limit = false + if (!!binding.element.dataset.limit) { + binding.limit = binding.element.dataset.limit + //这里,只要不为空,除parent外,其他值都默认为window, 故"可溢出"为false + binding.overflow = false + delete binding.element.dataset.limit + } + + delete binding.element.dataset.beforedrag + delete binding.element.dataset.dragging + delete binding.element.dataset.dragged + }, + update: function(val) { + var _this = this, + target = val ? this.element.parentNode : this.element, + $drag = Anot(this.element), + $doc = Anot(document), + $target = null, + parentElem = null + + // val值不为空时, 获取真正的拖动元素 + // 仅从父级上找 + while (val && target) { + if (target.classList.contains(val) || target.id === val) { + break + } else { + target = target.parentNode + } + } + $target = Anot(target) + // 限制范围为parent时,获取父级元素 + if (this.limit === 'parent') { + parentElem = target.parentNode + } + + var dx, dy, mx, my, ox, oy, fox, foy, tw, th, ww, wh, bst, bsl + $drag.bind('mousedown', function(ev) { + var gcs = getComputedStyle(target), + cst = gcs.transform.replace(/matrix\((.*)\)/, '$1'), + offset = $target.offset() + + cst = cst !== 'none' ? cst.split(', ') : [1, 0, 0, 1, 0, 0] + cst[4] -= 0 + cst[5] -= 0 + + //记录初始的transform位移 + dx = cst[4] + dy = cst[5] + + //滚动条的偏移 + bst = $doc.scrollTop() + bsl = $doc.scrollLeft() + + // 计算元素的offset值, 需要修正 + ox = offset.left - dx - bsl + oy = offset.top - dy - bst + + mx = ev.pageX //按下鼠标的的坐标值 + my = ev.pageY //按下鼠标的的坐标值 + + // 在按下时才获取窗口大小, 是为了防止人为的改变窗口大小,导致计算不准备 + // 同时减少不必要的事件监听(页面上可能会很多可拖动元素) + ww = window.innerWidth + wh = window.innerHeight + + // 同样,在点击之后获取元素的宽高,可保证获取到的是真实的值 + tw = target.clientWidth + th = target.clientHeight + + //拖拽前回调 + if (_this.beforedrag) { + var result = _this.beforedrag.call(_this.vmodels, target, ox, oy) + if (result === false) { + return + } + } + + //限制区域, 4个值依次是: 上, 下, 左, 右 + var limit = [0, wh - th, 0, ww - tw] + + if (_this.limit === 'parent') { + var pgcs = getComputedStyle(parentElem), + pcst = pgcs.transform.replace(/matrix\((.*)\)/, '$1'), + poffset = Anot(parentElem).offset() + + pcst = pcst !== 'none' ? pcst.split(', ') : [1, 0, 0, 1, 0, 0] + + var pox = poffset.left - pcst[4] - bsl, + poy = poffset.top - pcst[5] - bst + + limit = [ + poy, + poy + parentElem.clientHeight - th, + pox, + pox + parentElem.clientWidth - tw + ] + } + + var mvfn = $doc.bind('mousemove', function(ev) { + //坐标轴限制 + if (_this.axis !== 'y') { + cst[4] = ev.pageX - mx + dx + } + if (_this.axis !== 'x') { + cst[5] = ev.pageY - my + dy + } + + ;(fox = ox + cst[4]), //修正的offset + (foy = oy + cst[5]) //修正的offset + + //如果不允许溢出可视区 + if (!_this.overflow) { + if (_this.axis !== 'y') { + if (fox <= limit[2]) { + fox = limit[2] + //修正矩阵 + cst[4] = fox - ox + } + if (fox >= limit[3]) { + fox = limit[3] + //修正矩阵 + cst[4] = fox - ox + } + } + + if (_this.axis !== 'x') { + if (foy <= limit[0]) { + foy = limit[0] + //修正矩阵 + cst[5] = foy - oy + } + if (foy >= limit[1]) { + foy = limit[1] + //修正矩阵 + cst[5] = foy - oy + } + } + } + + $target.css({ + transform: 'matrix(' + cst.join(', ') + ')' + }) + + //拖拽过程的回调 + if (_this.dragging) { + _this.dragging.call(_this.vmodels, target, fox, foy) + } + // 防止拖动到边缘时导致页面滚动 + ev.preventDefault() + }), + upfn = $doc.bind('mouseup', function(ev) { + $doc.unbind('mousemove', mvfn) + $doc.unbind('mouseup', upfn) + //结束回调 + if (_this.dragged) { + _this.dragged.call(_this.vmodels, target, fox, foy) + } + }) + }) + } +}) diff --git a/src/js/drag/main.js b/src/js/drag/main.js deleted file mode 100644 index 5d4a5ca..0000000 --- a/src/js/drag/main.js +++ /dev/null @@ -1,216 +0,0 @@ -/** - * - * @authors yutent (yutent@doui.cc) - * @date 2017-03-29 18:39:35 - * - */ - -"use strict"; - -define(['yua'], function(){ - - function getBindingCallback(elem, name, vmodels) { - var callback = elem.getAttribute(name) - if (callback) { - for (var i = 0, vm; vm = vmodels[i++]; ) { - if (vm.hasOwnProperty(callback) && typeof vm[callback] === "function") { - return vm[callback] - } - } - } - } - yua.ui.drag = '1.0.0' - // 元素拖动 - yua.directive('drag', { - priority: 1500, - init: function(binding){ - binding.expr = '"' + binding.expr + '"' - yua(binding.element).css('cursor', 'move') - - //取得拖动的3种状态回调 - //按下,且拖拽之前 - binding.beforedrag = getBindingCallback(binding.element, 'data-beforedrag', binding.vmodels) - //拖拽过程 - binding.dragging = getBindingCallback(binding.element, 'data-dragging', binding.vmodels) - // 拖拽结束,且释放鼠标 - binding.dragged = getBindingCallback(binding.element, 'data-dragged', binding.vmodels) - - //默认允许溢出可视区 - binding.overflow = true - - //方向,x轴, y轴, xy轴 - binding.axis = 'xy' - if(!!binding.element.dataset.axis){ - binding.axis = binding.element.dataset.axis - delete binding.element.dataset.axis - } - - //默认不限制拖拽区域 - binding.limit = false - if(!!binding.element.dataset.limit) { - binding.limit = binding.element.dataset.limit - //这里,只要不为空,除parent外,其他值都默认为window, 故"可溢出"为false - binding.overflow = false - delete binding.element.dataset.limit - } - - delete binding.element.dataset.beforedrag - delete binding.element.dataset.dragging - delete binding.element.dataset.dragged - }, - update: function(val){ - var _this = this, - target = val ? this.element.parentNode : this.element, - $drag = yua(this.element), - $doc = yua(document), - $target = null, - parentElem = null; - - // val值不为空时, 获取真正的拖动元素 - // 仅从父级上找 - while(val && target){ - if(target.classList.contains(val) || target.id === val){ - break - }else{ - target = target.parentNode - } - } - $target = yua(target); - // 限制范围为parent时,获取父级元素 - if(this.limit === 'parent'){ - parentElem = target.parentNode - } - - - var dx,dy,mx,my,ox,oy,fox,foy,tw,th,ww,wh,bst,bsl; - $drag.bind('mousedown', function(ev){ - var gcs = getComputedStyle(target), - cst = gcs.transform.replace(/matrix\((.*)\)/, '$1'), - offset = $target.offset(); - - cst = cst !== 'none' ? cst.split(', ') : [1,0,0,1,0,0] - cst[4] -= 0 - cst[5] -= 0 - - //记录初始的transform位移 - dx = cst[4] - dy = cst[5] - - //滚动条的偏移 - bst = $doc.scrollTop() - bsl = $doc.scrollLeft() - - // 计算元素的offset值, 需要修正 - ox = offset.left - dx - bsl - oy = offset.top - dy - bst - - mx = ev.pageX //按下鼠标的的坐标值 - my = ev.pageY //按下鼠标的的坐标值 - - // 在按下时才获取窗口大小, 是为了防止人为的改变窗口大小,导致计算不准备 - // 同时减少不必要的事件监听(页面上可能会很多可拖动元素) - ww = window.innerWidth; - wh = window.innerHeight; - - // 同样,在点击之后获取元素的宽高,可保证获取到的是真实的值 - tw = target.clientWidth; - th = target.clientHeight; - - //拖拽前回调 - if(_this.beforedrag){ - var result = _this.beforedrag.call(_this.vmodels, target, ox, oy) - if(result === false){ - return - } - } - - //限制区域, 4个值依次是: 上, 下, 左, 右 - var limit = [0, wh - th, 0, ww - tw] - - if(_this.limit === 'parent') { - var pgcs = getComputedStyle(parentElem), - pcst = pgcs.transform.replace(/matrix\((.*)\)/, '$1'), - poffset = yua(parentElem).offset(); - - pcst = pcst !== 'none' ? pcst.split(', ') : [1,0,0,1,0,0] - - var pox = poffset.left - pcst[4] - bsl, - poy = poffset.top - pcst[5] - bst; - - limit = [poy, poy + parentElem.clientHeight - th, pox, pox + parentElem.clientWidth - tw] - } - - var mvfn = $doc.bind('mousemove', function(ev){ - - //坐标轴限制 - if(_this.axis !== 'y'){ - cst[4] = ev.pageX - mx + dx - } - if(_this.axis !== 'x'){ - cst[5] = ev.pageY - my + dy - } - - - fox = ox + cst[4], //修正的offset - foy = oy + cst[5]; //修正的offset - - - //如果不允许溢出可视区 - if(!_this.overflow){ - if(_this.axis !== 'y'){ - if(fox <= limit[2]) { - fox = limit[2] - //修正矩阵 - cst[4] = fox - ox - } - if(fox >= limit[3]){ - fox = limit[3] - //修正矩阵 - cst[4] = fox - ox - } - } - - if(_this.axis !== 'x'){ - if(foy <= limit[0]) { - foy = limit[0] - //修正矩阵 - cst[5] = foy - oy - } - if(foy >= limit[1]){ - foy = limit[1] - //修正矩阵 - cst[5] = foy - oy - } - } - - } - - $target.css({ - transform: 'matrix(' + cst.join(', ') + ')' - }) - - //拖拽过程的回调 - if(_this.dragging){ - _this.dragging.call(_this.vmodels, target, fox, foy) - } - // 防止拖动到边缘时导致页面滚动 - ev.preventDefault() - }), - upfn = $doc.bind('mouseup', function(ev){ - $doc.unbind('mousemove', mvfn) - $doc.unbind('mouseup', upfn) - //结束回调 - if(_this.dragged){ - _this.dragged.call(_this.vmodels, target, fox, foy) - } - }); - - }) - - } - }) - - - - -}) diff --git a/src/js/layer/base.js b/src/js/layer/base.js index c1608a5..29cc150 100644 --- a/src/js/layer/base.js +++ b/src/js/layer/base.js @@ -1,243 +1,257 @@ /** - * + * * @authors yutent (yutent@doui.cc) * @date 2016-09-21 01:36:29 * */ -"use strict"; +'use strict' +import 'drag/index' +import './skin/def.scss' -define(['yua', 'lib/drag/main', 'css!./skin/def'], function(yua){ +Anot.ui.layer = '1.0.0-base' +let layerDom = {} +let layerObj = {} +let unique = null //储存当前打开的1/2/3类型的弹窗 +let lid = 0 +let defconf = { + type: 1, // 弹窗类型 + skin: 'def', //默认主题 + icon: 1, //图标类型 + background: '#fff', + mask: true, //遮罩 + maskClose: false, //遮罩点击关闭弹窗 + radius: '0px', //弹窗圆角半径 + area: ['auto', 'auto'], + title: '提示', //弹窗主标题(在工具栏上的) + menubar: true, //是否显示菜单栏 + content: '', // 弹窗的内容 + fixed: false, //是否固定不可拖拽 + offset: null, //弹窗出来时的坐标, 为数组,可有4个值,依次是 上右下左 + btns: ['确定', '取消'] //弹窗的2个按钮的文字 +} +const uuid = function() { + return 'layer-' + ++lid +} +const close = function(id) { + if (typeof id !== 'string' && typeof id !== 'number') { + return Anot.error('要关闭的layer实例不存在') + } + if (/^\$wrap\-/.test(id) || layerObj['$wrap-' + id]) { + try { + id = (layerObj['$wrap-' + id] ? '$wrap-' : '') + id + //未显示过,忽略 + if (!layerObj[id].show) { + return + } + layerObj[id].parentElem.replaceChild(layerObj[id].wrap, layerDom[id][0]) + layerObj[id].wrap.style.display = 'none' + layerObj[id].show = false + } catch (err) {} + } else { + try { + // document.body.removeChild(layerDom[id][1]) + document.body.removeChild(layerDom[id][0]) + unique = null + } catch (err) {} - if(window.layer){ - return window.layer + delete layerDom[id] + delete Anot.vmodels[id] + } +} + +const reapeat = function(str, num) { + var idx = 0, + result = '' + while (idx < num) { + result += str + idx++ + } + return result +} +const fixOffset = function(val) { + if (!val && val !== 0) { + return 'auto' + } else { + return val + } +} +const __layer__ = function(conf) { + if (conf) { + let { yes, no, success } = conf + delete conf.yes + delete conf.no + delete conf.success + + this.construct({ + state: { ...conf }, + props: { yes, no, success } + }) + .append() + .show() + } +} + +const _layer = { + alert: function(msg, conf) { + if (typeof conf === 'function') { + conf = { methods: { yes: conf, no: conf } } + } else if (typeof conf === 'object') { + conf = conf + } else { + conf = {} + } + conf.icon = 5 + conf.content = msg + conf.fixed = true + return _layer.open(conf) + }, + confirm: function(msg, yescb, nocb) { + var conf = {} + if (typeof yescb === 'function') { + conf = { yes: yescb } + } else if (typeof yescb === 'object') { + conf = yescb + } + conf.type = 2 + conf.icon = 0 + conf.content = msg + if (typeof nocb === 'function') { + conf.no = nocb + } + conf.fixed = true + return _layer.open(conf) + }, + msg: function(msg, conf) { + if (typeof conf !== 'object') { + var tmp = conf + conf = { timeout: 2500 } + if (typeof tmp === 'number') { + conf.icon = tmp + } } - yua.ui.layer = '1.0.0-base' - var layerDom = {}, - layerObj = {}, - unique = null, //储存当前打开的1/2/3类型的弹窗 - lid = 0, - defconf = { - type: 1, // 弹窗类型 - skin: 'def', //默认主题 - icon: 1, //图标类型 - background: '#fff', - shade: true, //遮罩 - shadeClose: false, //遮罩点击关闭弹窗 - radius: '0px', //弹窗圆角半径 - area: ['auto', 'auto'], - title: '提示', //弹窗主标题(在工具栏上的) - menubar: true, //是否显示菜单栏 - content: '', // 弹窗的内容 - fixed: false, //是否固定不可拖拽 - offset: null, //弹窗出来时的坐标, 为数组,可有4个值,依次是 上右下左 - btns: ['确定', '取消'], //弹窗的2个按钮的文字 - yes: yua.noop, //确定按钮对应的回调 - no: yua.noop, //取消按钮对应的回调 - success: null //弹窗初始化完成时的回调 - }, - uuid = function(){ - return 'layer-' + (++lid) - }, - close = function(id){ - if(typeof id !== 'string' && typeof id !== 'number'){ - return yua.error('要关闭的layer实例不存在') - } - if(/^\$wrap\-/.test(id) || layerObj['$wrap-' + id]){ + if (!conf.hasOwnProperty('timeout')) { + conf.timeout = 2500 + } - try { - id = (layerObj['$wrap-' + id] ? '$wrap-' : '') + id; - //未显示过,忽略 - if(!layerObj[id].show){ - return - } - layerObj[id].parentElem.replaceChild(layerObj[id].wrap, layerDom[id][1]) - layerObj[id].wrap.style.display = 'none' - layerObj[id].show = false + conf.specialMode = true //特殊模式 + conf.content = '

' + msg + '

' + conf.type = 7 + conf.fixed = true + conf.shade = false + conf.menubar = false + conf.radius = '5px' + return _layer.open(conf) + }, + loading: function(style, time, cb) { + style = style >>> 0 - }catch(err){} - }else{ - try { - document.body.removeChild(layerDom[id][1]) - document.body.removeChild(layerDom[id][0]) - unique = null - }catch(err){} + if (typeof time === 'function') { + cb = time + time = 0 + } else { + time = time >>> 0 + if (typeof cb !== 'function') { + cb = Anot.noop + } + } + return _layer.open({ + type: 6, + load: style, + yes: cb, + timeout: time, + menubar: false, + background: 'none', + fixed: true + }) + }, + tips: function(msg, elem, conf) { + if (!(elem instanceof HTMLElement)) { + return Anot.error('tips类型必须指定一个目标容器') + } + if (typeof conf !== 'object') { + var tmp = conf + conf = { timeout: 2500 } + if (typeof tmp === 'number') { + conf.icon = tmp + } + } + if (!conf.hasOwnProperty('timeout')) { + conf.timeout = 2500 + } + if (!conf.background) { + conf.background = 'rgba(0,0,0,.5)' + } + if (!conf.color) { + conf.color = '#fff' + } + conf.$elem = elem + conf.content = msg + conf.type = 5 + conf.icon = 0 + conf.fixed = true + conf.shade = false + conf.menubar = false + return _layer.open(conf) + }, + prompt: function(msg, yescb) { + if (typeof yescb !== 'function') { + return console.error( + 'argument [callback] requires a function, but ' + + typeof yescb + + ' given' + ) + } + var conf = { + type: 3, + prompt: '', + title: msg, + content: + '', + fixed: true, + yes: yescb + } + return _layer.open(conf) + }, + use: function(skin, callback) { + require(['css!./skin/' + skin], callback) + }, + close: close, + open: function(conf) { + if (typeof conf === 'string') { + /*conf = '$wrap-' + conf + if (!layerObj[conf]) { + throw new Error('layer实例不存在') + } else { + //只能显示一个实例 + if (layerObj[conf].show) { + return conf + } + layerObj[conf].show = true - delete layerDom[id] - delete yua.vmodels[id] - } - }, - reapeat = function(str, num){ - var idx = 0, - result = '' - while(idx < num){ - result += str - idx++ - } - return result - }, - fixOffset = function (val){ - if(!val && val !== 0){ - return 'auto' - }else{ - return val - } - }, - __constructor = function(conf){ - if(conf){ - this.ready(conf).append().show() - } - }, - __layer = { - alert: function(msg, conf){ - if(typeof conf === 'function'){ - conf = {yes: conf, no: conf} - }else if(typeof conf === 'object'){ - conf = conf - }else{ - conf = {} - } - conf.icon = 5 - conf.content = msg - return __layer.open(conf) - }, - confirm: function(msg, yescb, nocb){ - var conf = {} - if(typeof yescb === 'function'){ - conf = {yes: yescb} - }else if(typeof yescb === 'object'){ - conf = yescb - } - conf.type = 2 - conf.icon = 0 - conf.content = msg - if(typeof nocb === 'function'){ - conf.no = nocb - } - return __layer.open(conf) - }, - msg: function(msg, conf){ - if(typeof conf !== 'object'){ - var tmp = conf - conf = {timeout: 2500} - if(typeof tmp === 'number'){ - conf.icon = tmp - } - } + if (!Anot.vmodels[conf]) { + Anot(layerObj[conf].obj.init) + } - if(!conf.hasOwnProperty('timeout')){ - conf.timeout = 2500 - } + layerObj[conf].parentElem.appendChild(layerDom[conf][1]) + layerDom[conf][1] + .querySelector('.detail') + .appendChild(layerObj[conf].wrap) + layerObj[conf].wrap.style.display = '' + // Anot.scan(layerDom[conf][1]) + layerObj[conf].obj.show() + return conf + }*/ + } else { + return new __layer__(conf).init.$id + } + }, + version: Anot.ui.layer +} - conf.specialMode = true;//特殊模式 - conf.content = '

' + msg + '

' - conf.type = 7 - conf.fixed = true - conf.shade = false - conf.menubar = false - conf.radius = '5px' - return __layer.open(conf) - }, - loading: function(style, time, cb){ - style = style >>> 0 - - if(typeof time === 'function'){ - cb = time; - time = 0 - } else{ - time = time >>> 0 - if(typeof cb !== 'function'){ - cb = yua.noop - } - } - return __layer.open({type: 6, load: style, yes: cb, timeout: time, menubar: false, background: 'none', fixed: true}) - }, - tips: function(msg, elem, conf){ - if(!(elem instanceof HTMLElement)){ - return yua.error('tips类型必须指定一个目标容器') - } - if(typeof conf !== 'object'){ - var tmp = conf - conf = {timeout: 2500} - if(typeof tmp === 'number'){ - conf.icon = tmp - } - } - if(!conf.hasOwnProperty('timeout')){ - conf.timeout = 2500 - } - if(!conf.background){ - conf.background = 'rgba(0,0,0,.5)' - } - if(!conf.color){ - conf.color = '#fff' - } - conf.$elem = elem - conf.content = msg - conf.type = 5; - conf.icon = 0; - conf.fixed = true; - conf.shade = false; - conf.menubar = false; - return __layer.open(conf) - }, - prompt: function(msg, yescb){ - if(typeof yescb !== 'function'){ - return console.error('argument [callback] requires a function, but ' + (typeof yescb) + ' given') - } - var conf = { - type: 3, - prompt: '', - title: msg, - content: '', - yes: function(id){ - if(!yua.vmodels[id].prompt){ - return - } - yescb(id, yua.vmodels[id].prompt) - } - } - return __layer.open(conf) - }, - use: function(skin, callback){ - require(['css!./skin/' + skin], callback) - }, - close: close, - open: function(conf){ - if(typeof conf === 'string'){ - conf = '$wrap-' + conf - if(!layerObj[conf]){ - throw new Error('layer实例不存在') - }else{ - //只能显示一个实例 - if(layerObj[conf].show){ - return conf - } - layerObj[conf].show = true - - if(!yua.vmodels[conf]){ - yua(layerObj[conf].obj.init) - } - - layerObj[conf].parentElem.appendChild(layerDom[conf][1]) - layerDom[conf][1].querySelector('.detail').appendChild(layerObj[conf].wrap) - layerObj[conf].wrap.style.display = '' - yua.scan(layerDom[conf][1]) - layerObj[conf].obj.show() - return conf - } - }else{ - return new __constructor(conf).init.$id - } - }, - version: yua.ui.layer - }; - - - defconf.yes = defconf.no = close - /*type: { // 弹窗类型对应的id值 +/*type: { // 弹窗类型对应的id值 1: 'alert', 2: 'confirm', 3: 'prompt', @@ -246,364 +260,423 @@ define(['yua', 'lib/drag/main', 'css!./skin/def'], function(yua){ 6: 'loading', 7: 'msg', }*/ - __constructor.prototype = { - dot: { //loading的子元素数量 - 1: 0, - 2: 0, - 3: 5, - 4: 5, - 5: 9 +__layer__.prototype = { + dot: { + //loading的子元素数量 + 1: 0, + 2: 0, + 3: 5, + 4: 5, + 5: 9 + }, + timeout: null, + construct: function(conf) { + let _id = conf.$id || uuid() + this.init = { + $id: _id, + state: { + ...defconf, + ...conf.state + }, + props: conf.props, + methods: { + onMaskClick: function() { + if (this.type < 4) { + this.$refs.layer.classList.add('scale') + setTimeout(() => { + this.$refs.layer.classList.remove('scale') + }, 100) + } }, - timeout: null, - create: function(){ - var layBox = document.createElement('div'), - coverBox = document.createElement('div'); - - coverBox.className = 'do-layer-cover type-' + this.init.type - // 允许点击遮罩关闭弹层时, 添加控制器 - if(this.init.shadeClose){ - coverBox.setAttribute(':controller', this.cInit.$id) - coverBox.setAttribute(':click', 'close(\'' + this.init.$id + '\')') + handleConfirm: function() { + if (this.type === 3) { + if (!this.prompt) { + return } - - layBox.className = 'do-layer skin-' - + this.init.skin - + (this.init.type === 5 && ' active' || '') - + ' type-' - + ((!this.init.specialMode && this.init.type === 7) ? 'unspecial' : this.init.type); - - //暂时隐藏,避免修正定位时,能看到闪一下 - layBox.style.visibility = 'hidden' - layBox.style.borderRadius = this.init.radius - - layBox.setAttribute(':controller', this.init.$id) - - //没有菜单栏, 且未禁止拖拽,则加上可拖拽属性 - if(!this.init.menubar && !this.init.fixed){ - layBox.setAttribute(':drag', '') - layBox.setAttribute('data-limit', 'window') - } - - //弹窗的宽高 - var boxcss = '' - if(this.init.area[0] !== 'auto'){ - boxcss += 'width: ' + this.init.area[0] + ';' - } - if(this.init.area[1] !== 'auto'){ - boxcss += 'height: ' + this.init.area[1] + ';' - } - - layBox.innerHTML = this.getMenubar() - + '
' - + this.getCont() - + '
' - + this.getBtns() - + (this.init.type === 5 && '' || '') - delete this.init.wrap - return [this.init.shade ? coverBox : null, layBox] + } + if (typeof this.props.yes === 'function') { + this.props.yes.call(this, this.prompt, this.$id) + } else { + this.close() + } }, - getCont: function(){ - if(this.init.type === 6){ - return this.getLoading(this.init.load) - }else{ - return this.getIcon() - + '
' - } + handleCancel: function() { + if (typeof this.props.no === 'function') { + this.props.no.call(this, this.$id) + } else { + this.close() + } }, - getLoading: function(style){ - return '
' - + '' - + reapeat('', this.dot[style]) - + '' - + '
' + close: function() { + close(this.$id) }, - //获取窗口导航条 - getMenubar: function(){ - var html = '' - if(this.init.menubar){ - html += '
' - + '
' - } - return html - }, - //获取窗口内容的图标 - getIcon: function(){ - if(this.init.icon < 0){ - return '' - } - if(this.init.type < 4 || this.init.type === 5 || this.init.specialMode){ - return '' - } - return '' - }, - // 获取窗口按钮 - getBtns: function(){ - if(this.init.type > 3){ - return '' - }else{ - var html = '
'; - if(this.init.type > 1){ - html += '' - + '' - }else{ - html += '' - } - html += '
' - - return html - } - }, - append: function(){ - //如果有已经打开的弹窗,则关闭 - if(unique){ - __layer.close(unique) - } - if(this.init.type < 4){ - unique = this.init.$id - } - layerDom[this.init.$id] = this.create() - if(layerDom[this.init.$id][0]){ - document.body.appendChild(layerDom[this.init.$id][0]) - //仅在允许点击遮罩时,初始化控制器,减少资源消耗 - if(this.init.shadeClose){ - yua(this.cInit) - yua.scan(layerDom[this.init.$id][0]) - } - } - - document.body.appendChild(layerDom[this.init.$id][1]) - yua(this.init) - yua.scan(layerDom[this.init.$id][1]) - return this - }, - show: function(){ - var _this = this; - - setTimeout(function(){ - var style = {visibility: '', background: _this.init.background}, - css = getComputedStyle(layerDom[_this.init.$id][1]); - - if(_this.init.type === 5){ - style.color = _this.init.color - - var $elem = yua(_this.init.$elem), - ew = $elem.innerWidth(), - ol = $elem.offset().left - document.body.scrollLeft, - ot = $elem.offset().top - document.body.scrollTop; - - style.left = ol + (ew * 0.7) - style.top = ot - parseInt(css.height) - 8 - - }else{ - if(_this.init.offset){ - style.top = fixOffset(_this.init.offset[0]) - style.right = fixOffset(_this.init.offset[1]) - style.bottom = fixOffset(_this.init.offset[2]) - style.left = fixOffset(_this.init.offset[3]) - //左右都为auto时,改为居中 - if(style.left === 'auto' && style.right === 'auto'){ - style.left = '50%' - style.marginLeft = -parseInt(css.width) / 2; - } - //上下都为auto时,同样改为居中 - if(style.top === 'auto' && style.bottom === 'auto'){ - style.top = '50%' - style.marginTop = -parseInt(css.height) / 2; - } - }else{ - style = yua.mix(style, { - marginLeft: -parseInt(css.width) / 2, - marginTop: -parseInt(css.height) / 2, - }) - } - } - - yua(layerDom[_this.init.$id][1]).css(style) - - }, 4) - - - if(this.init.success && typeof this.init.success === 'function'){ - //弹窗成功的回调 - this.init.success(this.init.$id) - } - // loading类型,回调需要自动触发 - if(this.init.type > 3) { - //大于0自动触发超时关闭 - if(this.init.timeout > 0){ - clearTimeout(this.timeout) - this.timeout = setTimeout(function(){ - - clearTimeout(_this.timeout) - __layer.close(_this.init.$id) - - // 为loading类型时,自动关闭同时触发回调 - if(_this.init.type === 6){ - _this.init.yes(_this.init.$id) - } - - }, this.init.timeout) - - } else if(this.init.type === 6) { - // loading类型, 非自动关闭时, 主动触发回调 - this.init.yes(this.init.$id) - } - - } - - }, - ready: function(conf){ - this.init = yua.mix({}, defconf, conf) - if(!this.init.$id){ - this.init.$id = uuid(); - } - if(this.init.icon > 17){ - this.init.icon = 17 - } - //base版没有iframe类型 - if(this.init.type === 4){ - this.icon.type = 7 - } - this.cInit = { - $id: this.init.$id + '-c', - close: this.init.shadeClose ? close : yua.noop - }; - return this + cancelBubble: function(ev) { + ev.cancelBubble = true } + }, + mounted: function() { + if (typeof this.success === 'function') { + this.success(_id) + } + } } + if (this.init.state.icon > 9) { + this.init.state.icon = 9 + } + //base版没有iframe类型 + if (this.init.state.type === 4) { + this.icon.state.type = 7 + } + console.log(this.init) + return this + }, + create: function() { + let { state, $id } = this.init + let outerBox = document.createElement('div') + let layBox = document.createElement('div') - yua.directive('layer', { - priority: 1400, - init: function(binding){ - if(!binding.param || binding.param !== 'tips'){ - - binding.param = '' //去掉param,保证之后的逻辑处理正常 - // 去掉:layer属性,避免二次扫描 - binding.element.removeAttribute(binding.name) - binding.element.style.display = 'none' - } - }, - update: function(val){ - if(!val){ - return yua.error(':layer指令格式不正确或无效属性. [' + this.name + '="' + this.expr + '"]') - } + outerBox.setAttribute('anot', $id) + outerBox.setAttribute(':click', 'onMaskClick') - var _this = this, - init = Object.assign({}, this.element.dataset); + outerBox.classList.add('do-layer') + if (state.mask) { + outerBox.classList.add('mask') + } - if(init.hasOwnProperty('area')){ - init.area = init.area.split(',') - } - if(init.hasOwnProperty('offset')){ - init.offset = init.offset.split(',') - } - if(init.hasOwnProperty('btns')){ - init.btns = init.btns.split(',') - } - - if(!this.param){ - init.wrap = true - init.type = 7; - init.$id = '$wrap-' + val; - if(!init.hasOwnProperty('menubar')){ - init.menubar = false; - } + layBox.classList.add('layer-box') + layBox.classList.add('skin-' + state.skin) + if (state.type === 5) { + layBox.classList.add('active') + } + if (state.specialMode && state.type === 7) { + layBox.classList.add('type-unspecial') + } else { + layBox.classList.add('type-' + state.type) + } - var tmp = new __constructor().ready(init); - - //去掉data-*属性 - for(var i in this.element.dataset){ - delete this.element.dataset[i] - } + layBox.setAttribute('ref', 'layer') + layBox.setAttribute(':click', 'cancelBubble') - layerObj[tmp.init.$id] = {obj: tmp, parentElem: this.element.parentNode, wrap: this.element, show: false}; - layerDom[tmp.init.$id] = tmp.create(); - }else if(this.param === 'tips'){ - var $elem = yua(this.element), - ew = $elem.innerWidth(), - ol = $elem.offset().left - document.body.scrollLeft, - ot = $elem.offset().top - document.body.scrollTop, - tipsBox = document.createElement('div'), - tipsArrow = document.createElement('i'), - tipsCont = document.createElement('div'); + //暂时隐藏,避免修正定位时,能看到闪一下 + layBox.style.cssText = + 'visibility:hidden; border-radius:' + state.radius + 'px' + //没有菜单栏, 且未禁止拖拽,则加上可拖拽属性 + if (!state.menubar && !state.fixed) { + layBox.setAttribute(':drag', '') + layBox.setAttribute('data-limit', 'window') + } - tipsBox.className = 'do-layer skin-' + (init.skin || 'def') + ' type-5' - tipsBox.style.left = ol + (ew * 0.7) + 'px' - if(init.background){ - tipsBox.style.background = init.background - tipsArrow.style.borderTopColor = init.background - } - if(init.color){ - tipsBox.style.color = init.color - } - tipsCont.className = 'layer-content' - tipsCont.textContent = val - tipsArrow.className = 'arrow' - tipsBox.appendChild(tipsCont) - tipsBox.appendChild(tipsArrow) + //弹窗的宽高 + var boxcss = '' + if (state.area[0] !== 'auto') { + boxcss += 'width: ' + state.area[0] + ';' + } + if (state.area[1] !== 'auto') { + boxcss += 'height: ' + state.area[1] + ';' + } + let arrow = '' + if (state.type === 5) { + arrow += `` + } + layBox.innerHTML = ` + ${this.getMenubar()} +
+ ${this.getCont()} +
+ ${this.getCtrl()} + ${arrow} + ` + delete state.wrap + outerBox.appendChild(layBox) + return [outerBox, layBox] + }, + getCont: function() { + let { state, $id } = this.init + if (state.type === 6) { + return this.getLoading(state.load) + } else { + return ` + ${this.getIcon()} +
+ ` + } + }, + getLoading: function(style) { + return ` +
+ + ${repeat('', this.dot[style])} + +
+ ` + }, + //获取窗口导航条 + getMenubar: function() { + let { state, $id } = this.init + let html = '' + if (state.menubar) { + html = ` +
+
+ ` + } + return html + }, + //获取窗口内容的图标 + getIcon: function() { + let { state, $id } = this.init + if (state.type < 4 || state.type === 5 || state.specialMode) { + return `` + } + return '' + }, + // 获取窗口按钮 + getCtrl: function() { + let { state, $id } = this.init + if (state.type > 3) { + return '' + } else { + let html = '' + let btns = ` + + ` + if (state.type > 1) { + btns = + ` + + ` + btns + } + html = ` +
+ ${btns} +
+ ` + return html + } + }, + append: function() { + let { state, $id } = this.init + //如果有已经打开的弹窗,则关闭 + if (unique) { + _layer.close(unique) + } + if (state.type < 4) { + unique = $id + } + layerDom[$id] = this.create() - yua(document).bind('scroll', function(){ - ol = $elem.offset().left - document.body.scrollLeft; - ot = $elem.offset().top - document.body.scrollTop; + delete state.specialMode + // if (layerDom[this.init.$id][0]) { + // document.body.appendChild(layerDom[this.init.$id][0]) + // //仅在允许点击遮罩时,初始化控制器,减少资源消耗 + // if (this.init.shadeClose) { + // Anot(this.cInit) + // // Anot.scan(layerDom[this.init.$id][0]) + // } + // } - tipsBox.style.left = ol + (ew * 0.7) + 'px' - tipsBox.style.top = (ot - tipsBox.offsetHeight - 8) + 'px' - }) + document.body.appendChild(layerDom[$id][0]) + this.vm = Anot(this.init) + // Anot.scan(layerDom[this.init.$id][1]) + return this + }, + show: function() { + let { state, $id } = this.init + var _this = this - $elem.bind('mouseenter', function(ev){ - _this.element.parentNode.appendChild(tipsBox) - clearTimeout(_this.showTime) - clearTimeout(_this.hideTime) - _this.showTime = setTimeout(function(){ - tipsBox.style.top = (ot - tipsBox.offsetHeight - 8) + 'px' - tipsBox.classList.add('active') - - }, 4) - - }) - $elem.bind('mouseleave', function(){ - _this.hideTime = setTimeout(function(){ - clearTimeout(_this.hideTime) - try{ - _this.element.parentNode.removeChild(tipsBox) - }catch(err){} - }, 150) - }) - } + setTimeout(function() { + var style = { visibility: '', background: state.background } + let css = getComputedStyle(layerDom[$id][1]) + + if (state.type === 5) { + style.color = state.color + + let $elem = Anot(_this.init.$elem) + let ew = $elem.innerWidth() + let ol = $elem.offset().left - document.body.scrollLeft + let ot = $elem.offset().top - document.body.scrollTop + + style.left = ol + ew * 0.7 + style.top = ot - parseInt(css.height) - 8 + } else { + if (state.offset) { + style.top = fixOffset(state.offset[0]) + style.right = fixOffset(state.offset[1]) + style.bottom = fixOffset(state.offset[2]) + style.left = fixOffset(state.offset[3]) + //左右都为auto时,改为居中 + if (style.left === 'auto' && style.right === 'auto') { + style.left = '50%' + style.marginLeft = -parseInt(css.width) / 2 + } + //上下都为auto时,同样改为居中 + if (style.top === 'auto' && style.bottom === 'auto') { + style.top = '50%' + style.marginTop = -parseInt(css.height) / 2 + } + } else { + style = Anot.mix(style, { + marginLeft: -parseInt(css.width) / 2, + marginTop: -parseInt(css.height) / 2 + }) } - }) + } + Anot(layerDom[_this.init.$id][1]).css(style) + }, 4) + // if (this.init.success && typeof this.init.success === 'function') { + // //弹窗成功的回调 + // this.init.success(this.init.$id) + // } + // loading类型,回调需要自动触发 + if (state.type > 3) { + //大于0自动触发超时关闭 + if (state.timeout > 0) { + clearTimeout(this.timeout) + this.timeout = setTimeout(function() { + clearTimeout(_this.timeout) + _layer.close($id) - window.layer = __layer + // 为loading类型时,自动关闭同时触发回调 + if (state.type === 6) { + _this.vm.yes($id) + } + }, state.timeout) + } else if (statetype === 6) { + // loading类型, 非自动关闭时, 主动触发回调 + this.vm.yes($id) + } + } + } +} - return __layer +Anot.directive('layer', { + priority: 1400, + init: function(binding) { + if (!binding.param || binding.param !== 'tips') { + binding.param = '' //去掉param,保证之后的逻辑处理正常 + // 去掉:layer属性,避免二次扫描 + binding.element.removeAttribute(binding.name) + binding.element.style.display = 'none' + } + }, + update: function(val) { + if (!val) { + return Anot.error( + ':layer指令格式不正确或无效属性. [' + + this.name + + '="' + + this.expr + + '"]' + ) + } -}) \ No newline at end of file + var _this = this, + init = Object.assign({}, this.element.dataset) + + if (init.hasOwnProperty('area')) { + init.area = init.area.split(',') + } + if (init.hasOwnProperty('offset')) { + init.offset = init.offset.split(',') + } + if (init.hasOwnProperty('btns')) { + init.btns = init.btns.split(',') + } + + if (!this.param) { + init.wrap = true + init.type = 7 + init.$id = '$wrap-' + val + if (!init.hasOwnProperty('menubar')) { + init.menubar = false + } + + var tmp = new __layer__().construct(init) + + //去掉data-*属性 + for (var i in this.element.dataset) { + delete this.element.dataset[i] + } + + layerObj[tmp.init.$id] = { + obj: tmp, + parentElem: this.element.parentNode, + wrap: this.element, + show: false + } + layerDom[tmp.init.$id] = tmp.create() + } else if (this.param === 'tips') { + var $elem = Anot(this.element), + ew = $elem.innerWidth(), + ol = $elem.offset().left - document.body.scrollLeft, + ot = $elem.offset().top - document.body.scrollTop, + tipsBox = document.createElement('div'), + tipsArrow = document.createElement('i'), + tipsCont = document.createElement('div') + + tipsBox.className = 'do-layer skin-' + (init.skin || 'def') + ' type-5' + tipsBox.style.left = ol + ew * 0.7 + 'px' + if (init.background) { + tipsBox.style.background = init.background + tipsArrow.style.borderTopColor = init.background + } + if (init.color) { + tipsBox.style.color = init.color + } + tipsCont.className = 'layer-content' + tipsCont.textContent = val + tipsArrow.className = 'arrow' + tipsBox.appendChild(tipsCont) + tipsBox.appendChild(tipsArrow) + + Anot(document).bind('scroll', function() { + ol = $elem.offset().left - document.body.scrollLeft + ot = $elem.offset().top - document.body.scrollTop + + tipsBox.style.left = ol + ew * 0.7 + 'px' + tipsBox.style.top = ot - tipsBox.offsetHeight - 8 + 'px' + }) + + $elem.bind('mouseenter', function(ev) { + _this.element.parentNode.appendChild(tipsBox) + clearTimeout(_this.showTime) + clearTimeout(_this.hideTime) + _this.showTime = setTimeout(function() { + tipsBox.style.top = ot - tipsBox.offsetHeight - 8 + 'px' + tipsBox.classList.add('active') + }, 4) + }) + $elem.bind('mouseleave', function() { + _this.hideTime = setTimeout(function() { + clearTimeout(_this.hideTime) + try { + _this.element.parentNode.removeChild(tipsBox) + } catch (err) {} + }, 150) + }) + } + } +}) + +window.layer = _layer + +export default _layer diff --git a/src/js/layer/full.js b/src/js/layer/full.js deleted file mode 100644 index 480e185..0000000 --- a/src/js/layer/full.js +++ /dev/null @@ -1,578 +0,0 @@ -/** - * - * @authors yutent (yutent@doui.cc) - * @date 2016-09-21 01:36:29 - * - */ - -"use strict"; - - -define(['yua', 'lib/drag', 'css!./skin/def'], function(yua){ - - - var layerDom = {}, - layerObj = {}, - unique = null, //储存当前打开的1/2/3类型的弹窗 - lid = 0, - defconf = { - type: 1, // 弹窗类型 - skin: 'def', //默认主题 - icon: 1, //图标类型 - background: '#fff', - shade: true, //遮罩 - shadeClose: false, //遮罩点击关闭弹窗 - radius: '0px', //弹窗圆角半径 - area: ['auto', 'auto'], - title: '', //弹窗主标题(在工具栏上的) - menubar: true, //是否显示菜单栏 - content: '', // 弹窗的内容 - fixed: false, //是否固定不可拖拽 - offset: null, //弹窗出来时的坐标, 为数组,可有4个值,依次是 上右下左 - btns: ['确定', '取消'], //弹窗的2个按钮的文字 - yes: close, //确定按钮对应的回调 - no: close, //取消按钮对应的回调 - success: null //弹窗初始化完成时的回调 - }; - - function uuid(){ - return 'layer-' + (++lid) - } - - - function close(id){ - if(typeof id !== 'string' && typeof id !== 'number'){ - return console.error(new Error('要关闭的layer实例不存在')) - } - if(/^\$wrap\-/.test(id) || layerObj['$wrap-' + id]){ - - try { - id = (layerObj['$wrap-' + id] ? '$wrap-' : '') + id; - //未显示过,忽略 - if(!layerObj[id].show){ - return - } - layerObj[id].parentElem.replaceChild(layerObj[id].wrap, layerDom[id][1]) - unique = null - }catch(err){} - }else{ - try { - document.body.removeChild(layerDom[id][1]) - document.body.removeChild(layerDom[id][0]) - unique = null - }catch(err){} - - delete layerDom[id] - delete yua.vmodels[id] - } - - } - - function reapeat(str, num){ - var idx = 0, - result = '' - while(idx < num){ - result += str - idx++ - } - return result - } - - function fixOffset(val){ - if(!val && val !== 0){ - return 'auto' - }else{ - return val - } - } - - var __constructor = function(conf){ - if(conf){ - this.ready(conf).append().show() - } - }, - __layer = { - alert: function(msg, conf){ - if(typeof conf === 'function'){ - conf = {yes: conf} - }else if(typeof conf === 'object'){ - conf = conf - }else{ - conf = {} - } - conf.icon = 6 - conf.content = msg - return __layer.open(conf) - }, - confirm: function(msg, conf){ - if(typeof conf === 'function'){ - conf = {yes: conf} - }else if(typeof conf === 'object'){ - conf = conf - }else{ - conf = {} - } - conf.type = 2 - conf.icon = 8 - conf.content = msg - return __layer.open(conf) - }, - msg: function(msg, conf){ - if(typeof conf !== 'object'){ - var tmp = conf - conf = {timeout: 2500} - if(typeof tmp === 'number'){ - conf.icon = tmp - } - } - - if(!conf.hasOwnProperty('timeout')){ - conf.timeout = 2500 - } - - conf.specialMode = true;//特殊模式 - conf.content = '

' + msg + '

' - conf.type = 7 - conf.fixed = true - conf.shade = false - conf.menubar = false - conf.radius = '5px' - return __layer.open(conf) - }, - loading: function(style, time, cb){ - style = style >>> 0 - - if(typeof time === 'function'){ - cb = time; - time = 0 - } else{ - time = time >>> 0 - if(typeof cb !== 'function'){ - cb = yua.noop - } - } - return __layer.open({type: 6, load: style, yes: cb, timeout: time, menubar: false, background: 'none', fixed: true}) - }, - tips: function(msg, elem, conf){ - if(!(elem instanceof HTMLElement)){ - return console.error(new Error('tips类型必须指定一个目标容器')) - } - if(typeof conf !== 'object'){ - var tmp = conf - conf = {timeout: 2500} - if(typeof tmp === 'number'){ - conf.icon = tmp - } - } - if(!conf.hasOwnProperty('timeout')){ - conf.timeout = 2500 - } - if(!conf.background){ - conf.background = 'rgba(0,0,0,.5)' - } - if(!conf.color){ - conf.color = '#fff' - } - conf.$elem = elem - conf.content = msg - conf.type = 5; - conf.icon = 0; - conf.fixed = true; - conf.shade = false; - conf.menubar = false; - return __layer.open(conf) - }, - prompt: function(msg, callback){ - if(typeof callback !== 'function'){ - return console.error('argument [callback] requires a function, but ' + (typeof callback) + ' given') - } - var conf = { - type: 3, - icon: 7, - prompt: '', - title: msg, - content: '', - yes: function(id){ - callback(id, yua.vmodels[id].prompt) - } - } - return __layer.open(conf) - }, - use: function(skin, callback){ - require(['css!./skin/' + skin], callback) - }, - close: close, - open: function(conf){ - if(typeof conf === 'string'){ - conf = '$wrap-' + conf - if(!layerObj[conf]){ - throw new Error('layer实例不存在') - }else{ - //只能显示一个实例 - if(layerObj[conf].show){ - return - } - layerObj[conf].show = true - - if(!yua.vmodels[conf]){ - yua.define(layerObj[conf].obj.init) - } - - yua.scan(layerDom[conf][1]) - layerObj[conf].obj.show() - - layerObj[conf].parentElem.appendChild(layerDom[conf][1]) - layerObj[conf].parentElem.replaceChild(layerDom[conf][1], layerObj[conf].wrap) - } - }else{ - return new __constructor(conf).init.$id - } - }, - version: '0.0.1-base' - }; - - /*type: { // 弹窗类型对应的id值 - 1: 'alert', - 2: 'confirm', - 3: 'prompt', - 4: 'iframe', - 5: 'tips', - 6: 'loading', - 7: 'msg', - }*/ - __constructor.prototype = { - dot: { //loading的子元素数量 - 0: 4, - 1: 9, - 2: 2, - 3: 3, - 4: 2, - 5: 5, - 6: 5, - 7: 5 - }, - timeout: null, - create: function(){ - var layBox = document.createElement('div'), - coverBox = document.createElement('div'); - - coverBox.className = 'do-layer-cover type-' + this.init.type - // 允许点击遮罩关闭弹层时, 添加控制器 - if(this.init.shadeClose){ - coverBox.setAttribute(':controller', this.cInit.$id) - coverBox.setAttribute(':click', 'close(\'' + this.init.$id + '\')') - } - - layBox.className = 'do-layer skin-' - + this.init.skin - + (this.init.type === 5 && ' active' || '') - + ' type-' - + ((!this.init.specialMode && this.init.type === 7) ? 'unspecial' : this.init.type); - - //暂时隐藏,避免修正定位时,能看到闪一下 - layBox.style.visibility = 'hidden' - layBox.style.borderRadius = this.init.radius - - layBox.setAttribute(':controller', this.init.$id) - - //没有菜单栏, 且未禁止拖拽,则加上可拖拽属性 - if(!this.init.menubar && !this.init.fixed){ - layBox.setAttribute(':drag', '') - layBox.setAttribute('data-limit', 'window') - } - - //弹窗的宽高 - var boxcss = '' - if(this.init.area[0] !== 'auto'){ - boxcss += 'width: ' + this.init.area[0] + ';' - } - if(this.init.area[1] !== 'auto'){ - boxcss += 'height: ' + this.init.area[1] + ';' - } - - layBox.innerHTML = this.getMenubar() - + '
' - + this.getCont() - + '
' - + this.getBtns() - + (this.init.type === 5 && '' || '') - - return [this.init.shade ? coverBox : null, layBox] - }, - getCont: function(){ - if(this.init.type === 6){ - return this.getLoading(this.init.load) - }else{ - return this.getIcon() - + '
' - } - }, - getLoading: function(style){ - return '
' - + '' - + reapeat('', this.dot[style]) - + '' - + '
' - }, - //获取窗口导航条 - getMenubar: function(){ - var html = '' - if(this.init.menubar){ - html += '
' - + '
' - } - return html - }, - //获取窗口内容的图标 - getIcon: function(){ - if(this.init.icon === 0){ - return '' - } - if(this.init.type < 4 || this.init.type === 5 || this.init.specialMode){ - return '' - } - return '' - }, - // 获取窗口按钮 - getBtns: function(){ - if(this.init.type > 3){ - return '' - }else{ - var html = '
'; - if(this.init.type > 1){ - html += '' - + '' - }else{ - html += '' - } - html += '
' - - return html - } - }, - append: function(){ - //如果有已经打开的弹窗,则关闭 - if(unique){ - __layer.close(unique) - } - if(this.init.type < 4){ - unique = this.init.$id - } - layerDom[this.init.$id] = this.create() - if(layerDom[this.init.$id][0]){ - document.body.appendChild(layerDom[this.init.$id][0]) - //仅在允许点击遮罩时,初始化控制器,减少资源消耗 - if(this.init.shadeClose){ - yua.define(this.cInit) - yua.scan(layerDom[this.init.$id][0]) - } - } - - document.body.appendChild(layerDom[this.init.$id][1]) - yua.define(this.init) - yua.scan(layerDom[this.init.$id][1]) - return this - }, - show: function(){ - var _this = this; - - setTimeout(function(){ - var style = {visibility: '', background: _this.init.background}, - css = getComputedStyle(layerDom[_this.init.$id][1]); - - if(_this.init.type === 5){ - style.color = _this.init.color - - var $elem = yua(_this.init.$elem), - ew = $elem.innerWidth(), - ol = $elem.offset().left - document.body.scrollLeft, - ot = $elem.offset().top - document.body.scrollTop; - - style.left = ol + (ew * 0.7) - style.top = ot - parseInt(css.height) - 8 - - }else{ - if(_this.init.offset){ - style.top = fixOffset(_this.init.offset[0]) - style.right = fixOffset(_this.init.offset[1]) - style.bottom = fixOffset(_this.init.offset[2]) - style.left = fixOffset(_this.init.offset[3]) - }else{ - style = yua.mix(style, { - marginLeft: -parseInt(css.width) / 2, - marginTop: -parseInt(css.height) / 2, - }) - } - } - - yua(layerDom[_this.init.$id][1]).css(style) - - }, 4) - - - if(this.init.success && typeof this.init.success === 'function'){ - //弹窗成功的回调 - this.init.success(this.init.$id) - } - // loading类型,回调需要自动触发 - if(this.init.type > 3) { - //大于0自动触发超时关闭 - if(this.init.timeout > 0){ - clearTimeout(this.timeout) - this.timeout = setTimeout(function(){ - - clearTimeout(_this.timeout) - __layer.close(_this.init.$id) - - // 为loading类型时,自动关闭同时触发回调 - if(_this.init.type === 6){ - _this.init.yes(_this.init.$id) - } - - }, this.init.timeout) - - } else if(this.init.type === 6) { - // loading类型, 非自动关闭时, 主动触发回调 - this.init.yes(this.init.$id) - } - - } - - }, - ready: function(conf){ - this.init = yua.mix({}, defconf, conf) - if(!this.init.$id){ - this.init.$id = uuid(); - } - if(this.init.icon > 17){ - this.icon.icon = 17 - } - //base版没有iframe类型 - if(this.init.type === 4){ - this.icon.type = 7 - } - this.cInit = { - $id: this.init.$id + '-c', - close: this.init.shadeClose ? close : yua.noop - }; - return this - } - } - - - yua.directive('layer', { - priority: 1400, - init: function(binding){ - if(!binding.param){ - binding.element.style.display = 'none' - } - }, - update: function(val){ - if(!val){ - return console.error(new Error(':layer指令格式不正确或无效属性. [' + this.name + '="' + this.expr) + '"]') - } - - var _this = this, - init = Object.assign({}, this.element.dataset); - - if(!this.param){ - init.type = 7; - init.$id = '$wrap-' + val; - if(!init.hasOwnProperty('menubar')){ - init.menubar = false; - } - - var tmp = new __constructor().ready(init); - - tmp.init.content = this.element.cloneNode(true); - - layerObj[tmp.init.$id] = {obj: tmp, parentElem: this.element.parentNode, wrap: this.element, show: false}; - layerDom[tmp.init.$id] = tmp.create(); - }else if(this.param === 'tips'){ - var $elem = yua(this.element), - ew = $elem.innerWidth(), - ol = $elem.offset().left - document.body.scrollLeft, - ot = $elem.offset().top - document.body.scrollTop, - tipsBox = document.createElement('div'), - tipsArrow = document.createElement('i'), - tipsCont = document.createElement('div'); - - - tipsBox.className = 'do-layer skin-def type-5' - tipsBox.style.left = ol + (ew * 0.7) + 'px' - if(init.background){ - tipsBox.style.background = init.background - tipsArrow.style.borderTopColor = init.background - } - if(init.color){ - tipsBox.style.color = init.color - } - tipsCont.className = 'layer-content' - tipsCont.textContent = val - tipsArrow.className = 'arrow' - tipsBox.appendChild(tipsCont) - tipsBox.appendChild(tipsArrow) - - - - yua(document).bind('scroll', function(){ - ol = $elem.offset().left - document.body.scrollLeft; - ot = $elem.offset().top - document.body.scrollTop; - - tipsBox.style.left = ol + (ew * 0.7) + 'px' - tipsBox.style.top = (ot - tipsBox.offsetHeight - 8) + 'px' - }) - - $elem.bind('mouseenter', function(ev){ - _this.element.parentNode.appendChild(tipsBox) - clearTimeout(_this.showTime) - clearTimeout(_this.hideTime) - _this.showTime = setTimeout(function(){ - tipsBox.style.top = (ot - tipsBox.offsetHeight - 8) + 'px' - tipsBox.classList.add('active') - - }, 4) - - }) - $elem.bind('mouseleave', function(){ - _this.hideTime = setTimeout(function(){ - clearTimeout(_this.hideTime) - try{ - _this.element.parentNode.removeChild(tipsBox) - }catch(err){} - }, 150) - }) - } - } - }) - - - - if(!window.layer) - window.layer = __layer - - - return __layer - -}) \ No newline at end of file diff --git a/src/js/layer/mobile.js b/src/js/layer/mobile.js deleted file mode 100644 index 480e185..0000000 --- a/src/js/layer/mobile.js +++ /dev/null @@ -1,578 +0,0 @@ -/** - * - * @authors yutent (yutent@doui.cc) - * @date 2016-09-21 01:36:29 - * - */ - -"use strict"; - - -define(['yua', 'lib/drag', 'css!./skin/def'], function(yua){ - - - var layerDom = {}, - layerObj = {}, - unique = null, //储存当前打开的1/2/3类型的弹窗 - lid = 0, - defconf = { - type: 1, // 弹窗类型 - skin: 'def', //默认主题 - icon: 1, //图标类型 - background: '#fff', - shade: true, //遮罩 - shadeClose: false, //遮罩点击关闭弹窗 - radius: '0px', //弹窗圆角半径 - area: ['auto', 'auto'], - title: '', //弹窗主标题(在工具栏上的) - menubar: true, //是否显示菜单栏 - content: '', // 弹窗的内容 - fixed: false, //是否固定不可拖拽 - offset: null, //弹窗出来时的坐标, 为数组,可有4个值,依次是 上右下左 - btns: ['确定', '取消'], //弹窗的2个按钮的文字 - yes: close, //确定按钮对应的回调 - no: close, //取消按钮对应的回调 - success: null //弹窗初始化完成时的回调 - }; - - function uuid(){ - return 'layer-' + (++lid) - } - - - function close(id){ - if(typeof id !== 'string' && typeof id !== 'number'){ - return console.error(new Error('要关闭的layer实例不存在')) - } - if(/^\$wrap\-/.test(id) || layerObj['$wrap-' + id]){ - - try { - id = (layerObj['$wrap-' + id] ? '$wrap-' : '') + id; - //未显示过,忽略 - if(!layerObj[id].show){ - return - } - layerObj[id].parentElem.replaceChild(layerObj[id].wrap, layerDom[id][1]) - unique = null - }catch(err){} - }else{ - try { - document.body.removeChild(layerDom[id][1]) - document.body.removeChild(layerDom[id][0]) - unique = null - }catch(err){} - - delete layerDom[id] - delete yua.vmodels[id] - } - - } - - function reapeat(str, num){ - var idx = 0, - result = '' - while(idx < num){ - result += str - idx++ - } - return result - } - - function fixOffset(val){ - if(!val && val !== 0){ - return 'auto' - }else{ - return val - } - } - - var __constructor = function(conf){ - if(conf){ - this.ready(conf).append().show() - } - }, - __layer = { - alert: function(msg, conf){ - if(typeof conf === 'function'){ - conf = {yes: conf} - }else if(typeof conf === 'object'){ - conf = conf - }else{ - conf = {} - } - conf.icon = 6 - conf.content = msg - return __layer.open(conf) - }, - confirm: function(msg, conf){ - if(typeof conf === 'function'){ - conf = {yes: conf} - }else if(typeof conf === 'object'){ - conf = conf - }else{ - conf = {} - } - conf.type = 2 - conf.icon = 8 - conf.content = msg - return __layer.open(conf) - }, - msg: function(msg, conf){ - if(typeof conf !== 'object'){ - var tmp = conf - conf = {timeout: 2500} - if(typeof tmp === 'number'){ - conf.icon = tmp - } - } - - if(!conf.hasOwnProperty('timeout')){ - conf.timeout = 2500 - } - - conf.specialMode = true;//特殊模式 - conf.content = '

' + msg + '

' - conf.type = 7 - conf.fixed = true - conf.shade = false - conf.menubar = false - conf.radius = '5px' - return __layer.open(conf) - }, - loading: function(style, time, cb){ - style = style >>> 0 - - if(typeof time === 'function'){ - cb = time; - time = 0 - } else{ - time = time >>> 0 - if(typeof cb !== 'function'){ - cb = yua.noop - } - } - return __layer.open({type: 6, load: style, yes: cb, timeout: time, menubar: false, background: 'none', fixed: true}) - }, - tips: function(msg, elem, conf){ - if(!(elem instanceof HTMLElement)){ - return console.error(new Error('tips类型必须指定一个目标容器')) - } - if(typeof conf !== 'object'){ - var tmp = conf - conf = {timeout: 2500} - if(typeof tmp === 'number'){ - conf.icon = tmp - } - } - if(!conf.hasOwnProperty('timeout')){ - conf.timeout = 2500 - } - if(!conf.background){ - conf.background = 'rgba(0,0,0,.5)' - } - if(!conf.color){ - conf.color = '#fff' - } - conf.$elem = elem - conf.content = msg - conf.type = 5; - conf.icon = 0; - conf.fixed = true; - conf.shade = false; - conf.menubar = false; - return __layer.open(conf) - }, - prompt: function(msg, callback){ - if(typeof callback !== 'function'){ - return console.error('argument [callback] requires a function, but ' + (typeof callback) + ' given') - } - var conf = { - type: 3, - icon: 7, - prompt: '', - title: msg, - content: '', - yes: function(id){ - callback(id, yua.vmodels[id].prompt) - } - } - return __layer.open(conf) - }, - use: function(skin, callback){ - require(['css!./skin/' + skin], callback) - }, - close: close, - open: function(conf){ - if(typeof conf === 'string'){ - conf = '$wrap-' + conf - if(!layerObj[conf]){ - throw new Error('layer实例不存在') - }else{ - //只能显示一个实例 - if(layerObj[conf].show){ - return - } - layerObj[conf].show = true - - if(!yua.vmodels[conf]){ - yua.define(layerObj[conf].obj.init) - } - - yua.scan(layerDom[conf][1]) - layerObj[conf].obj.show() - - layerObj[conf].parentElem.appendChild(layerDom[conf][1]) - layerObj[conf].parentElem.replaceChild(layerDom[conf][1], layerObj[conf].wrap) - } - }else{ - return new __constructor(conf).init.$id - } - }, - version: '0.0.1-base' - }; - - /*type: { // 弹窗类型对应的id值 - 1: 'alert', - 2: 'confirm', - 3: 'prompt', - 4: 'iframe', - 5: 'tips', - 6: 'loading', - 7: 'msg', - }*/ - __constructor.prototype = { - dot: { //loading的子元素数量 - 0: 4, - 1: 9, - 2: 2, - 3: 3, - 4: 2, - 5: 5, - 6: 5, - 7: 5 - }, - timeout: null, - create: function(){ - var layBox = document.createElement('div'), - coverBox = document.createElement('div'); - - coverBox.className = 'do-layer-cover type-' + this.init.type - // 允许点击遮罩关闭弹层时, 添加控制器 - if(this.init.shadeClose){ - coverBox.setAttribute(':controller', this.cInit.$id) - coverBox.setAttribute(':click', 'close(\'' + this.init.$id + '\')') - } - - layBox.className = 'do-layer skin-' - + this.init.skin - + (this.init.type === 5 && ' active' || '') - + ' type-' - + ((!this.init.specialMode && this.init.type === 7) ? 'unspecial' : this.init.type); - - //暂时隐藏,避免修正定位时,能看到闪一下 - layBox.style.visibility = 'hidden' - layBox.style.borderRadius = this.init.radius - - layBox.setAttribute(':controller', this.init.$id) - - //没有菜单栏, 且未禁止拖拽,则加上可拖拽属性 - if(!this.init.menubar && !this.init.fixed){ - layBox.setAttribute(':drag', '') - layBox.setAttribute('data-limit', 'window') - } - - //弹窗的宽高 - var boxcss = '' - if(this.init.area[0] !== 'auto'){ - boxcss += 'width: ' + this.init.area[0] + ';' - } - if(this.init.area[1] !== 'auto'){ - boxcss += 'height: ' + this.init.area[1] + ';' - } - - layBox.innerHTML = this.getMenubar() - + '
' - + this.getCont() - + '
' - + this.getBtns() - + (this.init.type === 5 && '' || '') - - return [this.init.shade ? coverBox : null, layBox] - }, - getCont: function(){ - if(this.init.type === 6){ - return this.getLoading(this.init.load) - }else{ - return this.getIcon() - + '
' - } - }, - getLoading: function(style){ - return '
' - + '' - + reapeat('', this.dot[style]) - + '' - + '
' - }, - //获取窗口导航条 - getMenubar: function(){ - var html = '' - if(this.init.menubar){ - html += '
' - + '
' - } - return html - }, - //获取窗口内容的图标 - getIcon: function(){ - if(this.init.icon === 0){ - return '' - } - if(this.init.type < 4 || this.init.type === 5 || this.init.specialMode){ - return '' - } - return '' - }, - // 获取窗口按钮 - getBtns: function(){ - if(this.init.type > 3){ - return '' - }else{ - var html = '
'; - if(this.init.type > 1){ - html += '' - + '' - }else{ - html += '' - } - html += '
' - - return html - } - }, - append: function(){ - //如果有已经打开的弹窗,则关闭 - if(unique){ - __layer.close(unique) - } - if(this.init.type < 4){ - unique = this.init.$id - } - layerDom[this.init.$id] = this.create() - if(layerDom[this.init.$id][0]){ - document.body.appendChild(layerDom[this.init.$id][0]) - //仅在允许点击遮罩时,初始化控制器,减少资源消耗 - if(this.init.shadeClose){ - yua.define(this.cInit) - yua.scan(layerDom[this.init.$id][0]) - } - } - - document.body.appendChild(layerDom[this.init.$id][1]) - yua.define(this.init) - yua.scan(layerDom[this.init.$id][1]) - return this - }, - show: function(){ - var _this = this; - - setTimeout(function(){ - var style = {visibility: '', background: _this.init.background}, - css = getComputedStyle(layerDom[_this.init.$id][1]); - - if(_this.init.type === 5){ - style.color = _this.init.color - - var $elem = yua(_this.init.$elem), - ew = $elem.innerWidth(), - ol = $elem.offset().left - document.body.scrollLeft, - ot = $elem.offset().top - document.body.scrollTop; - - style.left = ol + (ew * 0.7) - style.top = ot - parseInt(css.height) - 8 - - }else{ - if(_this.init.offset){ - style.top = fixOffset(_this.init.offset[0]) - style.right = fixOffset(_this.init.offset[1]) - style.bottom = fixOffset(_this.init.offset[2]) - style.left = fixOffset(_this.init.offset[3]) - }else{ - style = yua.mix(style, { - marginLeft: -parseInt(css.width) / 2, - marginTop: -parseInt(css.height) / 2, - }) - } - } - - yua(layerDom[_this.init.$id][1]).css(style) - - }, 4) - - - if(this.init.success && typeof this.init.success === 'function'){ - //弹窗成功的回调 - this.init.success(this.init.$id) - } - // loading类型,回调需要自动触发 - if(this.init.type > 3) { - //大于0自动触发超时关闭 - if(this.init.timeout > 0){ - clearTimeout(this.timeout) - this.timeout = setTimeout(function(){ - - clearTimeout(_this.timeout) - __layer.close(_this.init.$id) - - // 为loading类型时,自动关闭同时触发回调 - if(_this.init.type === 6){ - _this.init.yes(_this.init.$id) - } - - }, this.init.timeout) - - } else if(this.init.type === 6) { - // loading类型, 非自动关闭时, 主动触发回调 - this.init.yes(this.init.$id) - } - - } - - }, - ready: function(conf){ - this.init = yua.mix({}, defconf, conf) - if(!this.init.$id){ - this.init.$id = uuid(); - } - if(this.init.icon > 17){ - this.icon.icon = 17 - } - //base版没有iframe类型 - if(this.init.type === 4){ - this.icon.type = 7 - } - this.cInit = { - $id: this.init.$id + '-c', - close: this.init.shadeClose ? close : yua.noop - }; - return this - } - } - - - yua.directive('layer', { - priority: 1400, - init: function(binding){ - if(!binding.param){ - binding.element.style.display = 'none' - } - }, - update: function(val){ - if(!val){ - return console.error(new Error(':layer指令格式不正确或无效属性. [' + this.name + '="' + this.expr) + '"]') - } - - var _this = this, - init = Object.assign({}, this.element.dataset); - - if(!this.param){ - init.type = 7; - init.$id = '$wrap-' + val; - if(!init.hasOwnProperty('menubar')){ - init.menubar = false; - } - - var tmp = new __constructor().ready(init); - - tmp.init.content = this.element.cloneNode(true); - - layerObj[tmp.init.$id] = {obj: tmp, parentElem: this.element.parentNode, wrap: this.element, show: false}; - layerDom[tmp.init.$id] = tmp.create(); - }else if(this.param === 'tips'){ - var $elem = yua(this.element), - ew = $elem.innerWidth(), - ol = $elem.offset().left - document.body.scrollLeft, - ot = $elem.offset().top - document.body.scrollTop, - tipsBox = document.createElement('div'), - tipsArrow = document.createElement('i'), - tipsCont = document.createElement('div'); - - - tipsBox.className = 'do-layer skin-def type-5' - tipsBox.style.left = ol + (ew * 0.7) + 'px' - if(init.background){ - tipsBox.style.background = init.background - tipsArrow.style.borderTopColor = init.background - } - if(init.color){ - tipsBox.style.color = init.color - } - tipsCont.className = 'layer-content' - tipsCont.textContent = val - tipsArrow.className = 'arrow' - tipsBox.appendChild(tipsCont) - tipsBox.appendChild(tipsArrow) - - - - yua(document).bind('scroll', function(){ - ol = $elem.offset().left - document.body.scrollLeft; - ot = $elem.offset().top - document.body.scrollTop; - - tipsBox.style.left = ol + (ew * 0.7) + 'px' - tipsBox.style.top = (ot - tipsBox.offsetHeight - 8) + 'px' - }) - - $elem.bind('mouseenter', function(ev){ - _this.element.parentNode.appendChild(tipsBox) - clearTimeout(_this.showTime) - clearTimeout(_this.hideTime) - _this.showTime = setTimeout(function(){ - tipsBox.style.top = (ot - tipsBox.offsetHeight - 8) + 'px' - tipsBox.classList.add('active') - - }, 4) - - }) - $elem.bind('mouseleave', function(){ - _this.hideTime = setTimeout(function(){ - clearTimeout(_this.hideTime) - try{ - _this.element.parentNode.removeChild(tipsBox) - }catch(err){} - }, 150) - }) - } - } - }) - - - - if(!window.layer) - window.layer = __layer - - - return __layer - -}) \ No newline at end of file diff --git a/src/js/layer/skin/def.scss b/src/js/layer/skin/def.scss index 5a02b77..e2d705b 100644 --- a/src/js/layer/skin/def.scss +++ b/src/js/layer/skin/def.scss @@ -6,22 +6,28 @@ * @version $Id$ */ -@import "../../../../css/var.scss"; +@import "var.scss"; -.do-layer {position:fixed;left:50%;top:50%;z-index:65535;width:auto;height:auto; +.do-layer {width:auto;height:auto; - a {text-decoration:none;} + &.mask {position:fixed;z-index:65534;left:0;top:0;width:100%;height:100%;background:rgba(0,0,0,.3);} + + a {text-decoration:none;} + + .layer-box {position:absolute;left:50%;top:50%;z-index:65535; + + &.scale {transform:scale(1.02);transition:transform .1s linear;} /* 默认皮肤 */ - &.skin-def {color:#666;font-size:14px;box-shadow:0 0 10px rgba(0,0,0,.3); + &.skin-def {padding:15px 10px;border-radius:3px;color:#666;font-size:14px;box-shadow:0 5px 20px rgba(0,0,0,.3); - .icon-0::before {content:"\e62e";color:nth($cr, 1);} // question + .icon-0::before {content:"\e674";color:nth($cr, 1);} // question .icon-1::before {content:"\e610";color:nth($ct, 1);} // get .icon-2::before {content:"\e6f8";color:nth($cb, 1);} // happy .icon-3::before {content:"\e6fd";color:nth($co, 1);} // sad .icon-4::before {content:"\e6f6";color:nth($co, 1);} // warn - .icon-5::before {content:"\e630";color:nth($ct, 1);} // face + .icon-5::before {content:"\e673";color:nth($ct, 1);} // face .icon-6::before {content:"\e636";color:nth($cgr, 1);} // time .icon-7::before {content:"\e623";color:nth($co, 1);} // star .icon-8::before {content:"\e604";color:nth($cr, 1);} // mute @@ -29,25 +35,13 @@ /* 弹层标题栏 */ - .layer-title {width:100%;height:43px;padding:0 8px;line-height:43px;background:#f5f5f5;font-size:16px;color:nth($cgr, 1);} - - .action-min, - .action-close {position:absolute;display:block;top:12px;width:20px;height:20px;line-height:20px;font-size:14px;text-align:center;cursor:pointer;color:nth($cgr, 2); - - &:hover {color:nth($ct, 1);} - } - .action-min {right:40px; - &::before {content:"\e634"} - } - .action-close {right:10px; - &::before {content:"\e687"} - } + .layer-title {width:100%;height:43px;padding:0 10px;line-height:43px;font-size:16px;color:nth($cgr, 1);} /* 弹层主体内容 */ .layer-content {position:relative;width:100%;height:auto;min-height:50px;padding:10px; .msg-icon {position:absolute;left:10px;top:10px;width:50px;height:auto;line-height:40px;font-size:35px;text-align:center;} - .detail {width:auto;height:100%;margin:auto auto auto 60px;padding:5px 15px;word-break:break-all;word-wrap: break-word; + .detail {width:auto;height:100%;margin:auto auto auto 50px;padding:5px 15px;word-break:break-all;word-wrap: break-word; .prompt-value {width: 230px;height: 30px;padding: 0 8px;border: 1px solid #ddd;border-radius: 3px; @@ -62,30 +56,34 @@ /* 弹层按钮部分 */ - .layer-btns {width:100%;height:40px;padding:0 5px;line-height:30px;font-size:14px;color:#454545;text-align:right; + .layer-ctrl {width:100%;height:40px;padding:5px 0;line-height:30px;font-size:14px;color:#454545;text-align:right; - a {display:inline-block;width:auto;min-width:60px;height:30px;margin:0 5px;padding:0 10px;color:nth($cgr, 1);text-align:center;background:nth($cp, 1);@include ts(); - - &:hover {background:nth($cp, 2)} - &:active {background:nth($cp, 3)} - } + a {overflow:hidden;position:relative;display:inline-block;width:auto;min-width:60px;height:30px;margin-left:5px;padding:0 10px;color:nth($ct, 1);text-align:center; + + &::before {position:absolute;left:-50%;top:-50%;z-index:-1;display:block;width:200%;height:200%;border-radius:50%;background:nth($cp, 2); content:"";opacity:0;transform: scale(0, .0); transition:opacity 1.3s cubic-bezier(0.23, 1, 0.32, 1),transform 1.3s cubic-bezier(0.23, 1, 0.32, 1);} + + &:hover { + &::before {opacity:1;transform:scale(1, .8);} + } + &:active {background:nth($cp, 1)} } + } } /* ;alert/confirm/prompt 3类弹层 */ &.type-1, &.type-2, - &.type-3 {max-width:600px;min-width:230px;} + &.type-3 {max-width:600px;min-width:300px;} /* tips类弹层(type 5) */ &.type-5 {visibility:hidden;min-width:75px;max-width:600px;line-height:1.5;color:#fff;background:rgba(0,0,0,.5);opacity:0;box-shadow:none;-webkit-transition:opacity .3s ease-in-out;-moz-transition:opacity .3s ease-in-out;transition:opacity .3s ease-in-out; - &.active {visibility:visible;opacity:1;} - i.arrow {position:absolute;left:5px;bottom:-14px;width:0;height:0;border:6px solid transparent;border-top:8px solid rgba(0,0,0,.5);content: ""} + &.active {visibility:visible;opacity:1;} + i.arrow {position:absolute;left:5px;bottom:-14px;width:0;height:0;border:6px solid transparent;border-top:8px solid rgba(0,0,0,.5);content: ""} - .layer-content .detail {margin:0;padding:0} + .layer-content .detail {margin:0;padding:0} } @@ -178,9 +176,15 @@ &:active {z-index:65536;} + + + } + + + } -.do-layer-cover {position:fixed;left:0;top:0;z-index:65534;width:100%;height:100%;background:rgba(255,255,255,.05); +.do-layer-cover { &.type-6 {background:rgba(0,0,0,.3);} } diff --git a/src/js/marked/index.js b/src/js/marked/index.js new file mode 100644 index 0000000..f00ebbb --- /dev/null +++ b/src/js/marked/index.js @@ -0,0 +1,1379 @@ +/** + * marked - a markdown parser + * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed) + * https://github.com/chjj/marked + */ + +import './theme.scss' +/** + * Block-Level Grammar + */ + +var block = { + newline: /^\n+/, + code: /^( {4}[^\n]+\n*)+/, + fences: noop, + hr: /^( *[-*_]){3,} *(?:\n+|$)/, + heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/, + nptable: noop, + lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/, + blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/, + mark: /^ *;;;([\!]?) ([^\n]+)/, + task: /^ *- *\[([ x]?)\] *([^\n]*)/, + list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/, + html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/, + def: /^ *\[([^\]]+)\]: *]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/, + table: noop, + paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/, + text: /^[^\n]+/ +} + +block.bullet = /(?:[*+-]|\d+\.)/ +block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/ +block.item = replace(block.item, 'gm')(/bull/g, block.bullet)() + +block.list = replace(block.list)(/bull/g, block.bullet)( + 'hr', + '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))' +)('def', '\\n+(?=' + block.def.source + ')')() + +block.blockquote = replace(block.blockquote)('def', block.def)() + +block._tag = + '(?!(?:' + + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code' + + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo' + + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b' + +block.html = replace(block.html)('comment', //)( + 'closed', + /<(tag)[\s\S]+?<\/\1>/ +)('closing', /])*?>/)(/tag/g, block._tag)() + +block.paragraph = replace(block.paragraph)('hr', block.hr)( + 'heading', + block.heading +)('lheading', block.lheading)('blockquote', block.blockquote)( + 'tag', + '<' + block._tag +)('def', block.def)() + +/** + * Normal Block Grammar + */ + +block.normal = merge({}, block) + +/** + * GFM Block Grammar + */ + +block.gfm = merge({}, block.normal, { + fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/, + paragraph: /^/, + heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/ +}) + +block.gfm.paragraph = replace(block.paragraph)( + '(?!', + '(?!' + + block.gfm.fences.source.replace('\\1', '\\2') + + '|' + + block.list.source.replace('\\1', '\\3') + + '|' +)() + +/** + * GFM + Tables Block Grammar + */ + +block.tables = merge({}, block.gfm, { + nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/, + table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/ +}) + +/** + * Block Lexer + */ + +function Lexer(options) { + this.tokens = [] + this.tokens.links = {} + this.options = options || marked.defaults + this.rules = block.normal + + if (this.options.gfm) { + if (this.options.tables) { + this.rules = block.tables + } else { + this.rules = block.gfm + } + } +} + +/** + * Expose Block Rules + */ + +Lexer.rules = block + +/** + * Static Lex Method + */ + +Lexer.lex = function(src, options) { + var lexer = new Lexer(options) + return lexer.lex(src) +} + +/** + * Preprocessing + */ + +Lexer.prototype.lex = function(src) { + src = src + .replace(/\r\n|\r/g, '\n') + .replace(/\t/g, ' ') + .replace(/\u00a0/g, ' ') + .replace(/\u2424/g, '\n') + + return this.token(src, true) +} + +/** + * Lexing + */ + +Lexer.prototype.token = function(src, top, bq) { + var src = src.replace(/^ +$/gm, ''), + next, + loose, + cap, + bull, + b, + item, + space, + i, + l + + while (src) { + // newline + if ((cap = this.rules.newline.exec(src))) { + src = src.substring(cap[0].length) + if (cap[0].length > 1) { + this.tokens.push({ + type: 'space' + }) + } + } + + // code + if ((cap = this.rules.code.exec(src))) { + src = src.substring(cap[0].length) + cap = cap[0].replace(/^ {4}/gm, '') + this.tokens.push({ + type: 'code', + text: !this.options.pedantic ? cap.replace(/\n+$/, '') : cap + }) + continue + } + + // fences (gfm) + if ((cap = this.rules.fences.exec(src))) { + src = src.substring(cap[0].length) + this.tokens.push({ + type: 'code', + lang: cap[2], + text: cap[3] || '' + }) + continue + } + + // heading + if ((cap = this.rules.heading.exec(src))) { + src = src.substring(cap[0].length) + this.tokens.push({ + type: 'heading', + depth: cap[1].length, + text: cap[2] + }) + continue + } + + // table no leading pipe (gfm) + if (top && (cap = this.rules.nptable.exec(src))) { + src = src.substring(cap[0].length) + + item = { + type: 'table', + header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */), + align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), + cells: cap[3].replace(/\n$/, '').split('\n') + } + + for (i = 0; i < item.align.length; i++) { + if (/^ *-+: *$/.test(item.align[i])) { + item.align[i] = 'right' + } else if (/^ *:-+: *$/.test(item.align[i])) { + item.align[i] = 'center' + } else if (/^ *:-+ *$/.test(item.align[i])) { + item.align[i] = 'left' + } else { + item.align[i] = null + } + } + + for (i = 0; i < item.cells.length; i++) { + item.cells[i] = item.cells[i].split(/ *\| */) + } + + this.tokens.push(item) + + continue + } + + // lheading + if ((cap = this.rules.lheading.exec(src))) { + src = src.substring(cap[0].length) + this.tokens.push({ + type: 'heading', + depth: cap[2] === '=' ? 1 : 2, + text: cap[1] + }) + continue + } + + // hr + if ((cap = this.rules.hr.exec(src))) { + src = src.substring(cap[0].length) + this.tokens.push({ + type: 'hr' + }) + continue + } + + // blockquote + if ((cap = this.rules.blockquote.exec(src))) { + src = src.substring(cap[0].length) + + this.tokens.push({ + type: 'blockquote_start' + }) + + cap = cap[0].replace(/^ *> ?/gm, '') + + // Pass `top` to keep the current + // "toplevel" state. This is exactly + // how markdown.pl works. + this.token(cap, top, true) + + this.tokens.push({ + type: 'blockquote_end' + }) + + continue + } + + // mark + if ((cap = this.rules.mark.exec(src))) { + src = src.substring(cap[0].length) + + this.tokens.push({ + type: 'mark', + mark: cap[1] === '!', + text: cap[2] + }) + /* var sign = cap[2] === '!' + cap = cap[0].replace(/^ *;;;[\!]? ?/gm, ''); + + this.token(cap, top, true); + + this.tokens.push({ + type: 'mark_end', + mark: sign + });*/ + + continue + } + + if ((cap = this.rules.task.exec(src))) { + src = src.substring(cap[0].length) + + this.tokens.push({ + type: 'task', + mark: cap[1] === 'x', + text: cap[2] + }) + + continue + } + + // list + if ((cap = this.rules.list.exec(src))) { + src = src.substring(cap[0].length) + bull = cap[2] + + this.tokens.push({ + type: 'list_start', + ordered: bull.length > 1 + }) + + // Get each top-level item. + cap = cap[0].match(this.rules.item) + + next = false + l = cap.length + i = 0 + + for (; i < l; i++) { + item = cap[i] + + // Remove the list item's bullet + // so it is seen as the next token. + space = item.length + item = item.replace(/^ *([*+-]|\d+\.) +/, '') + + // Outdent whatever the + // list item contains. Hacky. + if (~item.indexOf('\n ')) { + space -= item.length + item = !this.options.pedantic + ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '') + : item.replace(/^ {1,4}/gm, '') + } + + // Determine whether the next list item belongs here. + // Backpedal if it does not belong in this list. + if (this.options.smartLists && i !== l - 1) { + b = block.bullet.exec(cap[i + 1])[0] + if (bull !== b && !(bull.length > 1 && b.length > 1)) { + src = cap.slice(i + 1).join('\n') + src + i = l - 1 + } + } + + // Determine whether item is loose or not. + // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/ + // for discount behavior. + loose = next || /\n\n(?!\s*$)/.test(item) + if (i !== l - 1) { + next = item.charAt(item.length - 1) === '\n' + if (!loose) loose = next + } + + this.tokens.push({ + type: loose ? 'loose_item_start' : 'list_item_start' + }) + + // Recurse. + this.token(item, false, bq) + + this.tokens.push({ + type: 'list_item_end' + }) + } + + this.tokens.push({ + type: 'list_end' + }) + + continue + } + + // html + if ((cap = this.rules.html.exec(src))) { + src = src.substring(cap[0].length) + this.tokens.push({ + type: this.options.sanitize ? 'paragraph' : 'html', + pre: + !this.options.sanitizer && + (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'), + text: cap[0] + }) + continue + } + + // def + if (!bq && top && (cap = this.rules.def.exec(src))) { + src = src.substring(cap[0].length) + this.tokens.links[cap[1].toLowerCase()] = { + href: cap[2], + title: cap[3] + } + continue + } + + // table (gfm) + if (top && (cap = this.rules.table.exec(src))) { + src = src.substring(cap[0].length) + + item = { + type: 'table', + header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */), + align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), + cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n') + } + + for (i = 0; i < item.align.length; i++) { + if (/^ *-+: *$/.test(item.align[i])) { + item.align[i] = 'right' + } else if (/^ *:-+: *$/.test(item.align[i])) { + item.align[i] = 'center' + } else if (/^ *:-+ *$/.test(item.align[i])) { + item.align[i] = 'left' + } else { + item.align[i] = null + } + } + + for (i = 0; i < item.cells.length; i++) { + item.cells[i] = item.cells[i] + .replace(/^ *\| *| *\| *$/g, '') + .split(/ *\| */) + } + + this.tokens.push(item) + + continue + } + + // top-level paragraph + if (top && (cap = this.rules.paragraph.exec(src))) { + src = src.substring(cap[0].length) + this.tokens.push({ + type: 'paragraph', + text: + cap[1].charAt(cap[1].length - 1) === '\n' + ? cap[1].slice(0, -1) + : cap[1] + }) + continue + } + + // text + if ((cap = this.rules.text.exec(src))) { + // Top-level should never reach here. + src = src.substring(cap[0].length) + this.tokens.push({ + type: 'text', + text: cap[0] + }) + continue + } + + if (src) { + throw new Error('Infinite loop on byte: ' + src.charCodeAt(0)) + } + } + + return this.tokens +} + +/** + * Inline-Level Grammar + */ + +var inline = { + escape: /^\\([\\`*{}\[\]()#+\-.!_>])/, + autolink: /^<([^ >]+(@|:\/)[^ >]+)>/, + url: noop, + tag: /^|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/, + link: /^!?\[(inside)\]\(href\)/, + reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/, + nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/, + strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/, + em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/, + code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/, + br: /^ {2,}\n(?!\s*$)/, + del: noop, + text: /^[\s\S]+?(?=[\\?(?:\s+['"]([\s\S]*?)['"])?\s*/ + +inline.link = replace(inline.link)('inside', inline._inside)( + 'href', + inline._href +)() + +inline.reflink = replace(inline.reflink)('inside', inline._inside)() + +/** + * Normal Inline Grammar + */ + +inline.normal = merge({}, inline) + +/** + * Pedantic Inline Grammar + */ + +inline.pedantic = merge({}, inline.normal, { + strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/, + em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/ +}) + +/** + * GFM Inline Grammar + */ + +inline.gfm = merge({}, inline.normal, { + escape: replace(inline.escape)('])', '~|])')(), + url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/, + del: /^~~(?=\S)([\s\S]*?\S)~~/, + text: replace(inline.text)(']|', '~]|')('|', '|https?://|')() +}) + +/** + * GFM + Line Breaks Inline Grammar + */ + +inline.breaks = merge({}, inline.gfm, { + br: replace(inline.br)('{2,}', '*')(), + text: replace(inline.gfm.text)('{2,}', '*')() +}) + +/** + * Inline Lexer & Compiler + */ + +function InlineLexer(links, options) { + this.options = options || marked.defaults + this.links = links + this.rules = inline.normal + this.renderer = this.options.renderer || new Renderer() + this.renderer.options = this.options + + if (!this.links) { + throw new Error('Tokens array requires a `links` property.') + } + + if (this.options.gfm) { + if (this.options.breaks) { + this.rules = inline.breaks + } else { + this.rules = inline.gfm + } + } else if (this.options.pedantic) { + this.rules = inline.pedantic + } +} + +/** + * Expose Inline Rules + */ + +InlineLexer.rules = inline + +/** + * Static Lexing/Compiling Method + */ + +InlineLexer.output = function(src, links, options) { + var inline = new InlineLexer(links, options) + return inline.output(src) +} + +/** + * Lexing/Compiling + */ + +InlineLexer.prototype.output = function(src) { + var out = '', + link, + text, + href, + cap + + while (src) { + // escape + if ((cap = this.rules.escape.exec(src))) { + src = src.substring(cap[0].length) + out += cap[1] + continue + } + + // autolink + if ((cap = this.rules.autolink.exec(src))) { + src = src.substring(cap[0].length) + if (cap[2] === '@') { + text = + cap[1].charAt(6) === ':' + ? this.mangle(cap[1].substring(7)) + : this.mangle(cap[1]) + href = this.mangle('mailto:') + text + } else { + text = escape(cap[1]) + href = text + } + out += this.renderer.link(href, null, text) + continue + } + + // url (gfm) + if (!this.inLink && (cap = this.rules.url.exec(src))) { + src = src.substring(cap[0].length) + text = escape(cap[1]) + href = text + out += this.renderer.link(href, null, text) + continue + } + + // tag + if ((cap = this.rules.tag.exec(src))) { + if (!this.inLink && /^/i.test(cap[0])) { + this.inLink = false + } + src = src.substring(cap[0].length) + out += this.options.sanitize + ? this.options.sanitizer + ? this.options.sanitizer(cap[0]) + : escape(cap[0]) + : cap[0] + continue + } + + // link + if ((cap = this.rules.link.exec(src))) { + src = src.substring(cap[0].length) + this.inLink = true + out += this.outputLink(cap, { + href: cap[2], + title: cap[3] + }) + this.inLink = false + continue + } + + // reflink, nolink + if ( + (cap = this.rules.reflink.exec(src)) || + (cap = this.rules.nolink.exec(src)) + ) { + src = src.substring(cap[0].length) + link = (cap[2] || cap[1]).replace(/\s+/g, ' ') + link = this.links[link.toLowerCase()] + if (!link || !link.href) { + out += cap[0].charAt(0) + src = cap[0].substring(1) + src + continue + } + this.inLink = true + out += this.outputLink(cap, link) + this.inLink = false + continue + } + + // strong + if ((cap = this.rules.strong.exec(src))) { + src = src.substring(cap[0].length) + out += this.renderer.strong(this.output(cap[2] || cap[1])) + continue + } + + // em + if ((cap = this.rules.em.exec(src))) { + src = src.substring(cap[0].length) + out += this.renderer.em(this.output(cap[2] || cap[1])) + continue + } + + // code + if ((cap = this.rules.code.exec(src))) { + src = src.substring(cap[0].length) + out += this.renderer.codespan(escape(cap[2], true)) + continue + } + + // br + if ((cap = this.rules.br.exec(src))) { + src = src.substring(cap[0].length) + out += this.renderer.br() + continue + } + + // del (gfm) + if ((cap = this.rules.del.exec(src))) { + src = src.substring(cap[0].length) + out += this.renderer.del(this.output(cap[1])) + continue + } + + // text + if ((cap = this.rules.text.exec(src))) { + src = src.substring(cap[0].length) + out += this.renderer.text(escape(this.smartypants(cap[0]))) + continue + } + + if (src) { + throw new Error('Infinite loop on byte: ' + src.charCodeAt(0)) + } + } + + return out +} + +/** + * Compile Link + */ + +InlineLexer.prototype.outputLink = function(cap, link) { + var href = escape(link.href), + title = link.title ? escape(link.title) : null + + return cap[0].charAt(0) !== '!' + ? this.renderer.link(href, title, this.output(cap[1])) + : this.renderer.image(href, title, escape(cap[1])) +} + +/** + * Smartypants Transformations + */ + +InlineLexer.prototype.smartypants = function(text) { + if (!this.options.smartypants) return text + return ( + text + // em-dashes + .replace(/---/g, '\u2014') + // en-dashes + .replace(/--/g, '\u2013') + // opening singles + .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018') + // closing singles & apostrophes + .replace(/'/g, '\u2019') + // opening doubles + .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c') + // closing doubles + .replace(/"/g, '\u201d') + // ellipses + .replace(/\.{3}/g, '\u2026') + ) +} + +/** + * Mangle Links + */ + +InlineLexer.prototype.mangle = function(text) { + if (!this.options.mangle) return text + var out = '', + l = text.length, + i = 0, + ch + + for (; i < l; i++) { + ch = text.charCodeAt(i) + if (Math.random() > 0.5) { + ch = 'x' + ch.toString(16) + } + out += '&#' + ch + ';' + } + + return out +} + +/** + * Renderer + */ + +function Renderer(options) { + this.options = options || {} +} + +Renderer.prototype.code = function(code, lang, escaped) { + code = code + .replace(/<script([^&]*?)>/g, '') + .replace(/<\/script>/g, '') + if (this.options.highlight) { + var out = this.options.highlight(code, lang) + if (out != null && out !== code) { + escaped = true + code = out + } + } + + //转义特殊字符 + code = escaped ? code : escape(code, true) + lang = this.options.langPrefix + escape(lang, true) + + var codes = code.split('\n'), + ln = codes.length, + idx = 0, + output = '', + multiCom = false + + while (idx++ < ln) { + //处理多行注释 + if (!multiCom) { + if ( + /^\s*?$/.test(codes[idx - 1]) + ) { + multiCom = true + codes[idx - 1] += '' + } + } else { + if (!/<\/span>$/.test(codes[idx - 1])) { + codes[idx - 1] = + '' + codes[idx - 1] + '' + } else { + codes[idx - 1] = '' + codes[idx - 1] + multiCom = false + } + } + + output += '' + codes[idx - 1] + '\n' //加\n为了避免空行时无法显示 + } + + return '
' + output + '
' +} + +Renderer.prototype.blockquote = function(quote) { + return '
\n' + quote + '
\n' +} +Renderer.prototype.mark = function(mark, t) { + return ( + '
\n' + + mark + + '
\n' + ) +} + +Renderer.prototype.task = function(task, t) { + task = t ? '' + task + '' : task + return ( + '
\n' + ) +} + +Renderer.prototype.html = function(html) { + return html +} + +Renderer.prototype.heading = function(text, level, raw) { + raw = text.replace(/<[^>]+>|<\/[^>]+>/g, '') + return ( + '
' + + text + + '\n' + ) +} + +Renderer.prototype.hr = function() { + return this.options.xhtml ? '
\n' : '
\n' +} + +Renderer.prototype.list = function(body, ordered) { + var type = ordered ? 'ol' : 'ul' + return '<' + type + '>\n' + body + '\n' +} + +Renderer.prototype.listitem = function(text) { + return '
  • ' + text + '
  • \n' +} + +Renderer.prototype.paragraph = function(text) { + return '

    ' + text + '

    \n' +} + +Renderer.prototype.table = function(header, body) { + return ( + '\n' + + '\n' + + header + + '\n' + + '\n' + + body + + '\n' + + '
    \n' + ) +} + +Renderer.prototype.tablerow = function(content) { + return '\n' + content + '\n' +} + +Renderer.prototype.tablecell = function(content, flags) { + var type = flags.header ? 'th' : 'td' + var tag = flags.align + ? '<' + type + ' style="text-align:' + flags.align + '">' + : '<' + type + '>' + return tag + content + '\n' +} + +// span level renderer +Renderer.prototype.strong = function(text) { + return '' + text + '' +} + +Renderer.prototype.em = function(text) { + return '' + text + '' +} + +Renderer.prototype.codespan = function(txt) { + txt = txt.replace(/&/g, '&') + return '' + txt + '' +} + +Renderer.prototype.br = function() { + return this.options.xhtml ? '
    ' : '
    ' +} + +Renderer.prototype.del = function(text) { + return '' + text + '' +} + +Renderer.prototype.link = function(href, attr, text) { + if (this.options.sanitize) { + try { + var prot = decodeURIComponent(unescape(href)) + .replace(/[^\w:]/g, '') + .toLowerCase() + } catch (e) { + return '' + } + if ( + prot.indexOf('javascript:') === 0 || + prot.indexOf('vbscript:') === 0 || + prot.indexOf('data:') === 0 + ) { + return '' + } + } + var out = ' 1) { + return tmp[0] + '="' + tmp[1] + '"' + } else { + return 'title="' + tmp[0] + '"' + } + }) + out += attr.join(' ') + } + out += '>' + text + '' + + return out +} + +Renderer.prototype.image = function(href, title, text) { + var out = '' + text + '' : '>' + return out +} + +Renderer.prototype.text = function(text) { + return text +} + +/** + * Parsing & Compiling + */ + +function Parser(options) { + this.tokens = [] + this.token = null + this.options = options || marked.defaults + this.options.renderer = this.options.renderer || new Renderer() + this.renderer = this.options.renderer + this.renderer.options = this.options +} + +/** + * Static Parse Method + */ + +Parser.parse = function(src, options, renderer) { + var parser = new Parser(options, renderer) + return parser.parse(src) +} + +/** + * Parse Loop + */ + +Parser.prototype.parse = function(src) { + this.inline = new InlineLexer(src.links, this.options, this.renderer) + this.tokens = src.reverse() + + var out = '' + while (this.next()) { + out += this.tok() + } + + return out +} + +/** + * Next Token + */ + +Parser.prototype.next = function() { + return (this.token = this.tokens.pop()) +} + +/** + * Preview Next Token + */ + +Parser.prototype.peek = function() { + return this.tokens[this.tokens.length - 1] || 0 +} + +/** + * Parse Text Tokens + */ + +Parser.prototype.parseText = function() { + var body = this.token.text + + while (this.peek().type === 'text') { + body += '\n' + this.next().text + } + + return this.inline.output(body) +} + +/** + * Parse Current Token + */ + +Parser.prototype.tok = function() { + switch (this.token.type) { + case 'space': { + return '' + } + case 'hr': { + return this.renderer.hr() + } + case 'heading': { + return this.renderer.heading( + this.inline.output(this.token.text), + this.token.depth, + this.token.text + ) + } + case 'code': { + return this.renderer.code( + this.token.text, + this.token.lang || 'other', + this.token.escaped + ) + } + case 'table': { + var header = '', + body = '', + i, + row, + cell, + flags, + j + + // header + cell = '' + for (i = 0; i < this.token.header.length; i++) { + flags = { header: true, align: this.token.align[i] } + cell += this.renderer.tablecell( + this.inline.output(this.token.header[i]), + { header: true, align: this.token.align[i] } + ) + } + header += this.renderer.tablerow(cell) + + for (i = 0; i < this.token.cells.length; i++) { + row = this.token.cells[i] + + cell = '' + for (j = 0; j < row.length; j++) { + cell += this.renderer.tablecell(this.inline.output(row[j]), { + header: false, + align: this.token.align[j] + }) + } + + body += this.renderer.tablerow(cell) + } + return this.renderer.table(header, body) + } + case 'blockquote_start': { + var body = '' + + while (this.next().type !== 'blockquote_end') { + body += this.tok() + } + + return this.renderer.blockquote(body) + } + case 'mark': { + return this.renderer.mark(this.token.text, this.token.mark) + } + case 'task': { + return this.renderer.task(this.token.text, this.token.mark) + } + case 'list_start': { + var body = '', + ordered = this.token.ordered + + while (this.next().type !== 'list_end') { + body += this.tok() + } + + return this.renderer.list(body, ordered) + } + case 'list_item_start': { + var body = '' + + while (this.next().type !== 'list_item_end') { + body += this.token.type === 'text' ? this.parseText() : this.tok() + } + + return this.renderer.listitem(body) + } + case 'loose_item_start': { + var body = '' + + while (this.next().type !== 'list_item_end') { + body += this.tok() + } + + return this.renderer.listitem(body) + } + case 'html': { + var html = + !this.token.pre && !this.options.pedantic + ? this.inline.output(this.token.text) + : this.token.text + return this.renderer.html(html) + } + case 'paragraph': { + return this.renderer.paragraph(this.inline.output(this.token.text)) + } + case 'text': { + return this.renderer.paragraph(this.parseText()) + } + } +} + +/** + * Helpers + */ + +function escape(html, encode) { + return html + .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, ''') +} + +function unescape(html) { + // explicitly match decimal, hex, and named HTML entities + return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function( + _, + n + ) { + n = n.toLowerCase() + if (n === 'colon') return ':' + if (n.charAt(0) === '#') { + return n.charAt(1) === 'x' + ? String.fromCharCode(parseInt(n.substring(2), 16)) + : String.fromCharCode(+n.substring(1)) + } + return '' + }) +} + +function replace(regex, opt) { + regex = regex.source + opt = opt || '' + return function self(name, val) { + if (!name) return new RegExp(regex, opt) + val = val.source || val + val = val.replace(/(^|[^\[])\^/g, '$1') + regex = regex.replace(name, val) + return self + } +} + +function noop() {} +noop.exec = noop + +function merge(obj) { + var i = 1, + target, + key + + for (; i < arguments.length; i++) { + target = arguments[i] + for (key in target) { + if (Object.prototype.hasOwnProperty.call(target, key)) { + obj[key] = target[key] + } + } + } + + return obj +} + +/** + * Marked + */ + +function marked(src, opt, callback) { + if (callback || typeof opt === 'function') { + if (!callback) { + callback = opt + opt = null + } + + opt = merge({}, marked.defaults, opt || {}) + + var highlight = opt.highlight, + tokens, + pending, + i = 0 + + try { + tokens = Lexer.lex(src, opt) + } catch (e) { + return callback(e) + } + + pending = tokens.length + + var done = function(err) { + if (err) { + opt.highlight = highlight + return callback(err) + } + + var out + + try { + out = Parser.parse(tokens, opt) + } catch (e) { + err = e + } + + opt.highlight = highlight + + return err ? callback(err) : callback(null, out) + } + + if (!highlight || highlight.length < 3) { + return done() + } + + delete opt.highlight + + if (!pending) return done() + + for (; i < tokens.length; i++) { + ;(function(token) { + if (token.type !== 'code') { + return --pending || done() + } + return highlight(token.text, token.lang, function(err, code) { + if (err) return done(err) + if (code == null || code === token.text) { + return --pending || done() + } + token.text = code + token.escaped = true + --pending || done() + }) + })(tokens[i]) + } + + return + } + try { + if (opt) opt = merge({}, marked.defaults, opt) + return Parser.parse(Lexer.lex(src, opt), opt) + } catch (e) { + e.message += '\nPlease report this to https://github.com/chjj/marked.' + if ((opt || marked.defaults).silent) { + return ( + '

    An error occured:

    ' +
    +        escape(e.message + '', true) +
    +        '
    ' + ) + } + throw e + } +} + +/** + * Options + */ + +marked.options = marked.setOptions = function(opt) { + merge(marked.defaults, opt) + return marked +} +if (window.Anot) { + Anot.ui.marked = '1.0.0' +} + +marked.defaults = { + gfm: true, + tables: true, + breaks: true, + pedantic: false, + sanitize: false, + sanitizer: null, + mangle: true, + smartLists: false, + silent: false, + highlight: null, + langPrefix: 'lang-', + smartypants: false, + headerPrefix: '', + renderer: new Renderer(), + xhtml: false +} + +/** + * Expose + */ + +marked.Parser = Parser +marked.parser = Parser.parse + +marked.Renderer = Renderer + +marked.Lexer = Lexer +marked.lexer = Lexer.lex + +marked.InlineLexer = InlineLexer +marked.inlineLexer = InlineLexer.output + +marked.parse = marked + +window.marked = marked + +export default marked diff --git a/src/js/marked/main.js b/src/js/marked/main.js deleted file mode 100644 index 69d11a1..0000000 --- a/src/js/marked/main.js +++ /dev/null @@ -1,1377 +0,0 @@ -/** - * marked - a markdown parser - * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed) - * https://github.com/chjj/marked - */ - -;(function() { - -/** - * Block-Level Grammar - */ - -var block = { - newline: /^\n+/, - code: /^( {4}[^\n]+\n*)+/, - fences: noop, - hr: /^( *[-*_]){3,} *(?:\n+|$)/, - heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/, - nptable: noop, - lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/, - blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/, - mark: /^ *;;;([\!]?) ([^\n]+)/, - task: /^ *- *\[([ x]?)\] *([^\n]*)/, - list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/, - html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/, - def: /^ *\[([^\]]+)\]: *]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/, - table: noop, - paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/, - text: /^[^\n]+/ -}; - -block.bullet = /(?:[*+-]|\d+\.)/; -block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/; -block.item = replace(block.item, 'gm') - (/bull/g, block.bullet) - (); - -block.list = replace(block.list) - (/bull/g, block.bullet) - ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))') - ('def', '\\n+(?=' + block.def.source + ')') - (); - -block.blockquote = replace(block.blockquote) - ('def', block.def) - (); - - -block._tag = '(?!(?:' - + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code' - + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo' - + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b'; - -block.html = replace(block.html) - ('comment', //) - ('closed', /<(tag)[\s\S]+?<\/\1>/) - ('closing', /])*?>/) - (/tag/g, block._tag) - (); - -block.paragraph = replace(block.paragraph) - ('hr', block.hr) - ('heading', block.heading) - ('lheading', block.lheading) - ('blockquote', block.blockquote) - ('tag', '<' + block._tag) - ('def', block.def) - (); - -/** - * Normal Block Grammar - */ - -block.normal = merge({}, block); - -/** - * GFM Block Grammar - */ - -block.gfm = merge({}, block.normal, { - fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/, - paragraph: /^/, - heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/ -}); - -block.gfm.paragraph = replace(block.paragraph) - ('(?!', '(?!' - + block.gfm.fences.source.replace('\\1', '\\2') + '|' - + block.list.source.replace('\\1', '\\3') + '|') - (); - -/** - * GFM + Tables Block Grammar - */ - -block.tables = merge({}, block.gfm, { - nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/, - table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/ -}); - -/** - * Block Lexer - */ - -function Lexer(options) { - this.tokens = []; - this.tokens.links = {}; - this.options = options || marked.defaults; - this.rules = block.normal; - - if (this.options.gfm) { - if (this.options.tables) { - this.rules = block.tables; - } else { - this.rules = block.gfm; - } - } -} - -/** - * Expose Block Rules - */ - -Lexer.rules = block; - -/** - * Static Lex Method - */ - -Lexer.lex = function(src, options) { - var lexer = new Lexer(options); - return lexer.lex(src); -}; - -/** - * Preprocessing - */ - -Lexer.prototype.lex = function(src) { - src = src - .replace(/\r\n|\r/g, '\n') - .replace(/\t/g, ' ') - .replace(/\u00a0/g, ' ') - .replace(/\u2424/g, '\n'); - - return this.token(src, true); -}; - -/** - * Lexing - */ - -Lexer.prototype.token = function(src, top, bq) { - var src = src.replace(/^ +$/gm, '') - , next - , loose - , cap - , bull - , b - , item - , space - , i - , l; - - while (src) { - // newline - if (cap = this.rules.newline.exec(src)) { - src = src.substring(cap[0].length); - if (cap[0].length > 1) { - this.tokens.push({ - type: 'space' - }); - } - } - - // code - if (cap = this.rules.code.exec(src)) { - src = src.substring(cap[0].length); - cap = cap[0].replace(/^ {4}/gm, ''); - this.tokens.push({ - type: 'code', - text: !this.options.pedantic - ? cap.replace(/\n+$/, '') - : cap - }); - continue; - } - - // fences (gfm) - if (cap = this.rules.fences.exec(src)) { - src = src.substring(cap[0].length); - this.tokens.push({ - type: 'code', - lang: cap[2], - text: cap[3] || '' - }); - continue; - } - - // heading - if (cap = this.rules.heading.exec(src)) { - src = src.substring(cap[0].length); - this.tokens.push({ - type: 'heading', - depth: cap[1].length, - text: cap[2] - }); - continue; - } - - // table no leading pipe (gfm) - if (top && (cap = this.rules.nptable.exec(src))) { - src = src.substring(cap[0].length); - - item = { - type: 'table', - header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */), - align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), - cells: cap[3].replace(/\n$/, '').split('\n') - }; - - for (i = 0; i < item.align.length; i++) { - if (/^ *-+: *$/.test(item.align[i])) { - item.align[i] = 'right'; - } else if (/^ *:-+: *$/.test(item.align[i])) { - item.align[i] = 'center'; - } else if (/^ *:-+ *$/.test(item.align[i])) { - item.align[i] = 'left'; - } else { - item.align[i] = null; - } - } - - for (i = 0; i < item.cells.length; i++) { - item.cells[i] = item.cells[i].split(/ *\| */); - } - - this.tokens.push(item); - - continue; - } - - // lheading - if (cap = this.rules.lheading.exec(src)) { - src = src.substring(cap[0].length); - this.tokens.push({ - type: 'heading', - depth: cap[2] === '=' ? 1 : 2, - text: cap[1] - }); - continue; - } - - // hr - if (cap = this.rules.hr.exec(src)) { - src = src.substring(cap[0].length); - this.tokens.push({ - type: 'hr' - }); - continue; - } - - // blockquote - if (cap = this.rules.blockquote.exec(src)) { - src = src.substring(cap[0].length); - - this.tokens.push({ - type: 'blockquote_start' - }); - - cap = cap[0].replace(/^ *> ?/gm, ''); - - // Pass `top` to keep the current - // "toplevel" state. This is exactly - // how markdown.pl works. - this.token(cap, top, true); - - this.tokens.push({ - type: 'blockquote_end' - }); - - continue; - } - - // mark - if (cap = this.rules.mark.exec(src)) { - src = src.substring(cap[0].length); - - this.tokens.push({ - type: 'mark', - mark: cap[1] === '!', - text: cap[2] - }); -/* var sign = cap[2] === '!' - cap = cap[0].replace(/^ *;;;[\!]? ?/gm, ''); - - this.token(cap, top, true); - - this.tokens.push({ - type: 'mark_end', - mark: sign - });*/ - - continue; - } - - if (cap = this.rules.task.exec(src)) { - src = src.substring(cap[0].length); - - this.tokens.push({ - type: 'task', - mark: cap[1] === 'x', - text: cap[2] - }); - - continue; - } - - // list - if (cap = this.rules.list.exec(src)) { - src = src.substring(cap[0].length); - bull = cap[2]; - - this.tokens.push({ - type: 'list_start', - ordered: bull.length > 1 - }); - - // Get each top-level item. - cap = cap[0].match(this.rules.item); - - next = false; - l = cap.length; - i = 0; - - for (; i < l; i++) { - item = cap[i]; - - // Remove the list item's bullet - // so it is seen as the next token. - space = item.length; - item = item.replace(/^ *([*+-]|\d+\.) +/, ''); - - // Outdent whatever the - // list item contains. Hacky. - if (~item.indexOf('\n ')) { - space -= item.length; - item = !this.options.pedantic - ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '') - : item.replace(/^ {1,4}/gm, ''); - } - - // Determine whether the next list item belongs here. - // Backpedal if it does not belong in this list. - if (this.options.smartLists && i !== l - 1) { - b = block.bullet.exec(cap[i + 1])[0]; - if (bull !== b && !(bull.length > 1 && b.length > 1)) { - src = cap.slice(i + 1).join('\n') + src; - i = l - 1; - } - } - - // Determine whether item is loose or not. - // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/ - // for discount behavior. - loose = next || /\n\n(?!\s*$)/.test(item); - if (i !== l - 1) { - next = item.charAt(item.length - 1) === '\n'; - if (!loose) loose = next; - } - - this.tokens.push({ - type: loose - ? 'loose_item_start' - : 'list_item_start' - }); - - // Recurse. - this.token(item, false, bq); - - this.tokens.push({ - type: 'list_item_end' - }); - } - - this.tokens.push({ - type: 'list_end' - }); - - continue; - } - - // html - if (cap = this.rules.html.exec(src)) { - src = src.substring(cap[0].length); - this.tokens.push({ - type: this.options.sanitize - ? 'paragraph' - : 'html', - pre: !this.options.sanitizer - && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'), - text: cap[0] - }); - continue; - } - - // def - if ((!bq && top) && (cap = this.rules.def.exec(src))) { - src = src.substring(cap[0].length); - this.tokens.links[cap[1].toLowerCase()] = { - href: cap[2], - title: cap[3] - }; - continue; - } - - // table (gfm) - if (top && (cap = this.rules.table.exec(src))) { - src = src.substring(cap[0].length); - - item = { - type: 'table', - header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */), - align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), - cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n') - }; - - for (i = 0; i < item.align.length; i++) { - if (/^ *-+: *$/.test(item.align[i])) { - item.align[i] = 'right'; - } else if (/^ *:-+: *$/.test(item.align[i])) { - item.align[i] = 'center'; - } else if (/^ *:-+ *$/.test(item.align[i])) { - item.align[i] = 'left'; - } else { - item.align[i] = null; - } - } - - for (i = 0; i < item.cells.length; i++) { - item.cells[i] = item.cells[i] - .replace(/^ *\| *| *\| *$/g, '') - .split(/ *\| */); - } - - this.tokens.push(item); - - continue; - } - - // top-level paragraph - if (top && (cap = this.rules.paragraph.exec(src))) { - src = src.substring(cap[0].length); - this.tokens.push({ - type: 'paragraph', - text: cap[1].charAt(cap[1].length - 1) === '\n' - ? cap[1].slice(0, -1) - : cap[1] - }); - continue; - } - - // text - if (cap = this.rules.text.exec(src)) { - // Top-level should never reach here. - src = src.substring(cap[0].length); - this.tokens.push({ - type: 'text', - text: cap[0] - }); - continue; - } - - if (src) { - throw new - Error('Infinite loop on byte: ' + src.charCodeAt(0)); - } - } - - return this.tokens; -}; - -/** - * Inline-Level Grammar - */ - -var inline = { - escape: /^\\([\\`*{}\[\]()#+\-.!_>])/, - autolink: /^<([^ >]+(@|:\/)[^ >]+)>/, - url: noop, - tag: /^|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/, - link: /^!?\[(inside)\]\(href\)/, - reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/, - nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/, - strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/, - em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/, - code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/, - br: /^ {2,}\n(?!\s*$)/, - del: noop, - text: /^[\s\S]+?(?=[\\?(?:\s+['"]([\s\S]*?)['"])?\s*/; - -inline.link = replace(inline.link) - ('inside', inline._inside) - ('href', inline._href) - (); - -inline.reflink = replace(inline.reflink) - ('inside', inline._inside) - (); - -/** - * Normal Inline Grammar - */ - -inline.normal = merge({}, inline); - -/** - * Pedantic Inline Grammar - */ - -inline.pedantic = merge({}, inline.normal, { - strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/, - em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/ -}); - -/** - * GFM Inline Grammar - */ - -inline.gfm = merge({}, inline.normal, { - escape: replace(inline.escape)('])', '~|])')(), - url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/, - del: /^~~(?=\S)([\s\S]*?\S)~~/, - text: replace(inline.text) - (']|', '~]|') - ('|', '|https?://|') - () -}); - -/** - * GFM + Line Breaks Inline Grammar - */ - -inline.breaks = merge({}, inline.gfm, { - br: replace(inline.br)('{2,}', '*')(), - text: replace(inline.gfm.text)('{2,}', '*')() -}); - -/** - * Inline Lexer & Compiler - */ - -function InlineLexer(links, options) { - this.options = options || marked.defaults; - this.links = links; - this.rules = inline.normal; - this.renderer = this.options.renderer || new Renderer; - this.renderer.options = this.options; - - if (!this.links) { - throw new - Error('Tokens array requires a `links` property.'); - } - - if (this.options.gfm) { - if (this.options.breaks) { - this.rules = inline.breaks; - } else { - this.rules = inline.gfm; - } - } else if (this.options.pedantic) { - this.rules = inline.pedantic; - } -} - -/** - * Expose Inline Rules - */ - -InlineLexer.rules = inline; - -/** - * Static Lexing/Compiling Method - */ - -InlineLexer.output = function(src, links, options) { - var inline = new InlineLexer(links, options); - return inline.output(src); -}; - -/** - * Lexing/Compiling - */ - -InlineLexer.prototype.output = function(src) { - var out = '' - , link - , text - , href - , cap; - - while (src) { - // escape - if (cap = this.rules.escape.exec(src)) { - src = src.substring(cap[0].length); - out += cap[1]; - continue; - } - - // autolink - if (cap = this.rules.autolink.exec(src)) { - src = src.substring(cap[0].length); - if (cap[2] === '@') { - text = cap[1].charAt(6) === ':' - ? this.mangle(cap[1].substring(7)) - : this.mangle(cap[1]); - href = this.mangle('mailto:') + text; - } else { - text = escape(cap[1]); - href = text; - } - out += this.renderer.link(href, null, text); - continue; - } - - // url (gfm) - if (!this.inLink && (cap = this.rules.url.exec(src))) { - src = src.substring(cap[0].length); - text = escape(cap[1]); - href = text; - out += this.renderer.link(href, null, text); - continue; - } - - // tag - if (cap = this.rules.tag.exec(src)) { - if (!this.inLink && /^/i.test(cap[0])) { - this.inLink = false; - } - src = src.substring(cap[0].length); - out += this.options.sanitize - ? this.options.sanitizer - ? this.options.sanitizer(cap[0]) - : escape(cap[0]) - : cap[0] - continue; - } - - // link - if (cap = this.rules.link.exec(src)) { - src = src.substring(cap[0].length); - this.inLink = true; - out += this.outputLink(cap, { - href: cap[2], - title: cap[3] - }); - this.inLink = false; - continue; - } - - // reflink, nolink - if ((cap = this.rules.reflink.exec(src)) - || (cap = this.rules.nolink.exec(src))) { - src = src.substring(cap[0].length); - link = (cap[2] || cap[1]).replace(/\s+/g, ' '); - link = this.links[link.toLowerCase()]; - if (!link || !link.href) { - out += cap[0].charAt(0); - src = cap[0].substring(1) + src; - continue; - } - this.inLink = true; - out += this.outputLink(cap, link); - this.inLink = false; - continue; - } - - // strong - if (cap = this.rules.strong.exec(src)) { - src = src.substring(cap[0].length); - out += this.renderer.strong(this.output(cap[2] || cap[1])); - continue; - } - - // em - if (cap = this.rules.em.exec(src)) { - src = src.substring(cap[0].length); - out += this.renderer.em(this.output(cap[2] || cap[1])); - continue; - } - - // code - if (cap = this.rules.code.exec(src)) { - src = src.substring(cap[0].length); - out += this.renderer.codespan(escape(cap[2], true)); - continue; - } - - // br - if (cap = this.rules.br.exec(src)) { - src = src.substring(cap[0].length); - out += this.renderer.br(); - continue; - } - - // del (gfm) - if (cap = this.rules.del.exec(src)) { - src = src.substring(cap[0].length); - out += this.renderer.del(this.output(cap[1])); - continue; - } - - // text - if (cap = this.rules.text.exec(src)) { - src = src.substring(cap[0].length); - out += this.renderer.text(escape(this.smartypants(cap[0]))); - continue; - } - - if (src) { - throw new - Error('Infinite loop on byte: ' + src.charCodeAt(0)); - } - } - - return out; -}; - -/** - * Compile Link - */ - -InlineLexer.prototype.outputLink = function(cap, link) { - var href = escape(link.href) - , title = link.title ? escape(link.title) : null; - - return cap[0].charAt(0) !== '!' - ? this.renderer.link(href, title, this.output(cap[1])) - : this.renderer.image(href, title, escape(cap[1])); -}; - -/** - * Smartypants Transformations - */ - -InlineLexer.prototype.smartypants = function(text) { - if (!this.options.smartypants) return text; - return text - // em-dashes - .replace(/---/g, '\u2014') - // en-dashes - .replace(/--/g, '\u2013') - // opening singles - .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018') - // closing singles & apostrophes - .replace(/'/g, '\u2019') - // opening doubles - .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c') - // closing doubles - .replace(/"/g, '\u201d') - // ellipses - .replace(/\.{3}/g, '\u2026'); -}; - -/** - * Mangle Links - */ - -InlineLexer.prototype.mangle = function(text) { - if (!this.options.mangle) return text; - var out = '' - , l = text.length - , i = 0 - , ch; - - for (; i < l; i++) { - ch = text.charCodeAt(i); - if (Math.random() > 0.5) { - ch = 'x' + ch.toString(16); - } - out += '&#' + ch + ';'; - } - - return out; -}; - -/** - * Renderer - */ - -function Renderer(options) { - this.options = options || {}; -} - -Renderer.prototype.code = function(code, lang, escaped) { - code = code.replace(/<script([^&]*?)>/g, '') - .replace(/<\/script>/g, '') - if (this.options.highlight) { - var out = this.options.highlight(code, lang); - if (out != null && out !== code) { - escaped = true; - code = out; - } - } - - //转义特殊字符 - code = escaped ? code : escape(code, true); - lang = this.options.langPrefix + escape(lang, true) - - var codes = code.split('\n'), - ln = codes.length, - idx = 0, - output = '', - multiCom = false; - - while(idx++ < ln){ - //处理多行注释 - if(!multiCom){ - if(/^\s*?$/.test(codes[idx - 1])){ - multiCom = true; - codes[idx - 1] += '' - } - } else { - if(!/<\/span>$/.test(codes[idx - 1])){ - codes[idx - 1] = '' + codes[idx - 1] + '' - }else{ - codes[idx - 1] = '' + codes[idx - 1] - multiCom = false; - } - } - - output += '' - + codes[idx - 1] - + '\n' //加\n为了避免空行时无法显示 - } - - return '
    '
    -        + output
    -        + '
    '; -}; - -Renderer.prototype.blockquote = function(quote) { - return '
    \n' + quote + '
    \n'; -}; -Renderer.prototype.mark = function(mark, t) { - return '
    \n' + mark + '
    \n'; -}; - -Renderer.prototype.task = function(task, t) { - task = t ? ('' + task + '') : task - return '
    \n'; -}; - -Renderer.prototype.html = function(html) { - return html; -}; - -Renderer.prototype.heading = function(text, level, raw) { - raw = text.replace(/<[^>]+>|<\/[^>]+>/g, '') - return '
    ' - + text - + '\n'; -}; - -Renderer.prototype.hr = function() { - return this.options.xhtml ? '
    \n' : '
    \n'; -}; - -Renderer.prototype.list = function(body, ordered) { - var type = ordered ? 'ol' : 'ul'; - return '<' + type + '>\n' + body + '\n'; -}; - -Renderer.prototype.listitem = function(text) { - return '
  • ' + text + '
  • \n'; -}; - -Renderer.prototype.paragraph = function(text) { - return '

    ' + text + '

    \n'; -}; - -Renderer.prototype.table = function(header, body) { - return '\n' - + '\n' - + header - + '\n' - + '\n' - + body - + '\n' - + '
    \n'; -}; - -Renderer.prototype.tablerow = function(content) { - return '\n' + content + '\n'; -}; - -Renderer.prototype.tablecell = function(content, flags) { - var type = flags.header ? 'th' : 'td'; - var tag = flags.align - ? '<' + type + ' style="text-align:' + flags.align + '">' - : '<' + type + '>'; - return tag + content + '\n'; -}; - -// span level renderer -Renderer.prototype.strong = function(text) { - return '' + text + ''; -}; - -Renderer.prototype.em = function(text) { - return '' + text + ''; -}; - -Renderer.prototype.codespan = function(txt) { - txt = txt.replace(/&/g, '&') - return '' + txt + ''; -}; - -Renderer.prototype.br = function() { - return this.options.xhtml ? '
    ' : '
    '; -}; - -Renderer.prototype.del = function(text) { - return '' + text + ''; -}; - -Renderer.prototype.link = function(href, attr, text) { - - if (this.options.sanitize) { - try { - var prot = decodeURIComponent(unescape(href)) - .replace(/[^\w:]/g, '') - .toLowerCase(); - } catch (e) { - return ''; - } - if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) { - return ''; - } - } - var out = ' 1){ - return tmp[0] + '="' + tmp[1] +'"' - }else{ - return 'title="' + tmp[0] +'"' - } - }) - out += attr.join(' '); - } - out += '>' + text + ''; - - return out; -}; - -Renderer.prototype.image = function(href, title, text) { - var out = '' + text + '' : '>'; - return out; -}; - -Renderer.prototype.text = function(text) { - return text; -}; - -/** - * Parsing & Compiling - */ - -function Parser(options) { - this.tokens = []; - this.token = null; - this.options = options || marked.defaults; - this.options.renderer = this.options.renderer || new Renderer; - this.renderer = this.options.renderer; - this.renderer.options = this.options; -} - -/** - * Static Parse Method - */ - -Parser.parse = function(src, options, renderer) { - var parser = new Parser(options, renderer); - return parser.parse(src); -}; - -/** - * Parse Loop - */ - -Parser.prototype.parse = function(src) { - this.inline = new InlineLexer(src.links, this.options, this.renderer); - this.tokens = src.reverse(); - - var out = ''; - while (this.next()) { - out += this.tok(); - } - - return out; -}; - -/** - * Next Token - */ - -Parser.prototype.next = function() { - return this.token = this.tokens.pop(); -}; - -/** - * Preview Next Token - */ - -Parser.prototype.peek = function() { - return this.tokens[this.tokens.length - 1] || 0; -}; - -/** - * Parse Text Tokens - */ - -Parser.prototype.parseText = function() { - var body = this.token.text; - - while (this.peek().type === 'text') { - body += '\n' + this.next().text; - } - - return this.inline.output(body); -}; - -/** - * Parse Current Token - */ - -Parser.prototype.tok = function() { - switch (this.token.type) { - case 'space': { - return ''; - } - case 'hr': { - return this.renderer.hr(); - } - case 'heading': { - return this.renderer.heading( - this.inline.output(this.token.text), - this.token.depth, - this.token.text); - } - case 'code': { - return this.renderer.code(this.token.text, - this.token.lang || 'other', - this.token.escaped); - } - case 'table': { - var header = '' - , body = '' - , i - , row - , cell - , flags - , j; - - // header - cell = ''; - for (i = 0; i < this.token.header.length; i++) { - flags = { header: true, align: this.token.align[i] }; - cell += this.renderer.tablecell( - this.inline.output(this.token.header[i]), - { header: true, align: this.token.align[i] } - ); - } - header += this.renderer.tablerow(cell); - - for (i = 0; i < this.token.cells.length; i++) { - row = this.token.cells[i]; - - cell = ''; - for (j = 0; j < row.length; j++) { - cell += this.renderer.tablecell( - this.inline.output(row[j]), - { header: false, align: this.token.align[j] } - ); - } - - body += this.renderer.tablerow(cell); - } - return this.renderer.table(header, body); - } - case 'blockquote_start': { - var body = ''; - - while (this.next().type !== 'blockquote_end') { - body += this.tok(); - } - - return this.renderer.blockquote(body); - } - case 'mark': { - return this.renderer.mark(this.token.text, this.token.mark); - } - case 'task': { - return this.renderer.task(this.token.text, this.token.mark) - } - case 'list_start': { - var body = '' - , ordered = this.token.ordered; - - while (this.next().type !== 'list_end') { - body += this.tok(); - } - - return this.renderer.list(body, ordered); - } - case 'list_item_start': { - var body = ''; - - while (this.next().type !== 'list_item_end') { - body += this.token.type === 'text' - ? this.parseText() - : this.tok(); - } - - return this.renderer.listitem(body); - } - case 'loose_item_start': { - var body = ''; - - while (this.next().type !== 'list_item_end') { - body += this.tok(); - } - - return this.renderer.listitem(body); - } - case 'html': { - var html = !this.token.pre && !this.options.pedantic - ? this.inline.output(this.token.text) - : this.token.text; - return this.renderer.html(html); - } - case 'paragraph': { - return this.renderer.paragraph(this.inline.output(this.token.text)); - } - case 'text': { - return this.renderer.paragraph(this.parseText()); - } - } -}; - -/** - * Helpers - */ - -function escape(html, encode) { - return (html) - .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"') - .replace(/'/g, '''); -} - -function unescape(html) { - // explicitly match decimal, hex, and named HTML entities - return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(_, n) { - n = n.toLowerCase(); - if (n === 'colon') return ':'; - if (n.charAt(0) === '#') { - return n.charAt(1) === 'x' - ? String.fromCharCode(parseInt(n.substring(2), 16)) - : String.fromCharCode(+n.substring(1)); - } - return ''; - }); -} - -function replace(regex, opt) { - regex = regex.source; - opt = opt || ''; - return function self(name, val) { - if (!name) return new RegExp(regex, opt); - val = val.source || val; - val = val.replace(/(^|[^\[])\^/g, '$1'); - regex = regex.replace(name, val); - return self; - }; -} - -function noop() {} -noop.exec = noop; - -function merge(obj) { - var i = 1 - , target - , key; - - for (; i < arguments.length; i++) { - target = arguments[i]; - for (key in target) { - if (Object.prototype.hasOwnProperty.call(target, key)) { - obj[key] = target[key]; - } - } - } - - return obj; -} - - -/** - * Marked - */ - -function marked(src, opt, callback) { - if (callback || typeof opt === 'function') { - if (!callback) { - callback = opt; - opt = null; - } - - opt = merge({}, marked.defaults, opt || {}); - - var highlight = opt.highlight - , tokens - , pending - , i = 0; - - try { - tokens = Lexer.lex(src, opt) - } catch (e) { - return callback(e); - } - - pending = tokens.length; - - var done = function(err) { - if (err) { - opt.highlight = highlight; - return callback(err); - } - - var out; - - try { - out = Parser.parse(tokens, opt); - } catch (e) { - err = e; - } - - opt.highlight = highlight; - - return err - ? callback(err) - : callback(null, out); - }; - - if (!highlight || highlight.length < 3) { - return done(); - } - - delete opt.highlight; - - if (!pending) return done(); - - for (; i < tokens.length; i++) { - (function(token) { - if (token.type !== 'code') { - return --pending || done(); - } - return highlight(token.text, token.lang, function(err, code) { - if (err) return done(err); - if (code == null || code === token.text) { - return --pending || done(); - } - token.text = code; - token.escaped = true; - --pending || done(); - }); - })(tokens[i]); - } - - return; - } - try { - if (opt) opt = merge({}, marked.defaults, opt); - return Parser.parse(Lexer.lex(src, opt), opt); - } catch (e) { - e.message += '\nPlease report this to https://github.com/chjj/marked.'; - if ((opt || marked.defaults).silent) { - return '

    An error occured:

    '
    -                + escape(e.message + '', true)
    -                + '
    '; - } - throw e; - } -} - -/** - * Options - */ - -marked.options = -marked.setOptions = function(opt) { - merge(marked.defaults, opt); - return marked; -}; -if (window.yua) {yua.ui.marked = '1.0.0'} - -marked.defaults = { - gfm: true, - tables: true, - breaks: true, - pedantic: false, - sanitize: false, - sanitizer: null, - mangle: true, - smartLists: false, - silent: false, - highlight: null, - langPrefix: 'lang-', - smartypants: false, - headerPrefix: '', - renderer: new Renderer, - xhtml: false -}; - -/** - * Expose - */ - -marked.Parser = Parser; -marked.parser = Parser.parse; - -marked.Renderer = Renderer; - -marked.Lexer = Lexer; -marked.lexer = Lexer.lex; - -marked.InlineLexer = InlineLexer; -marked.inlineLexer = InlineLexer.output; - -marked.parse = marked; - -this.marked = marked; -if (typeof module !== 'undefined' && typeof exports === 'object') { - module.exports = marked; -} else if (typeof define === 'function' && define.amd) { - define(['css!./theme'], function() { return marked; }); -} - -}).call(function() { - return this || (typeof window !== 'undefined' ? window : global); -}()); diff --git a/src/js/meditor/addon/base.js b/src/js/meditor/addon/base.js index f53baec..128a1cd 100644 --- a/src/js/meditor/addon/base.js +++ b/src/js/meditor/addon/base.js @@ -1,363 +1,407 @@ /** - * + * * @authors yutent (yutent@doui.cc) * @date 2017-04-17 21:41:48 * */ -"use strict"; +'use strict' +import 'layer/base' -define(['lib/layer/base'], function(){ +function objArr(num) { + var arr = [] + while (num > 0) { + arr.push({ v: 0 }) + num-- + } + return arr +} +function trim(str, sign) { + return str.replace(new RegExp('^' + sign + '|' + sign + '$', 'g'), '') +} +function getOrderArr(len) { + var arr = [], + i = 0 + while (i < len) { + arr.push(i++) + } + return arr +} +const addon = { + h1: function(elem, vm) { + var offset = Anot(elem).offset(), + wrap = ME.selection(vm.$editor, true) || '在此输入文本', + h1ID = layer.open({ + type: 7, + menubar: false, + shadeClose: true, + fixed: true, + $insert: function(level) { + wrap = wrap.replace(/^#{1,6} /, '') + wrap = ME.repeat('#', level) + ' ' + wrap + ME.insert(vm.$editor, wrap, true) + layer.close(h1ID) + }, + offset: [ + offset.top + 37 - ME.doc.scrollTop(), + 'auto', + 'auto', + offset.left - ME.doc.scrollLeft() + ], + content: + '' + }) + }, + quote: function(elem, vm) { + var wrap = ME.selection(vm.$editor) || '在此输入文本' + wrap = '> ' + wrap - function objArr(num){ - var arr = [] - while(num > 0){ - arr.push({v: 0}) - num-- + ME.insert(vm.$editor, wrap, true) + }, + bold: function(elem, vm) { + var wrap = ME.selection(vm.$editor) || '在此输入文本', + wraped = trim(wrap, '\\*\\*') + + wrap = wrap === wraped ? '**' + wrap + '**' : wraped + + ME.insert(vm.$editor, wrap, true) + }, + italic: function(elem, vm) { + var wrap = ME.selection(vm.$editor) || '在此输入文本', + wraped = trim(wrap, '_') + + wrap = wrap === wraped ? '_' + wrap + '_' : wraped + + ME.insert(vm.$editor, wrap, true) + }, + through: function(elem, vm) { + var wrap = ME.selection(vm.$editor) || '在此输入文本', + wraped = trim(wrap, '~~') + + wrap = wrap === wraped ? '~~' + wrap + '~~' : wraped + + ME.insert(vm.$editor, wrap, true) + }, + unordered: function(elem, vm) { + var wrap = ME.selection(vm.$editor) || '在此输入文本' + wrap = '* ' + wrap + + ME.insert(vm.$editor, wrap, false) + }, + ordered: function(elem, vm) { + var wrap = ME.selection(vm.$editor) || '在此输入文本' + wrap = '1. ' + wrap + + ME.insert(vm.$editor, wrap, false) + }, + hr: function(elem, vm) { + ME.insert(vm.$editor, '\n\n---\n\n', false) + }, + link: function(elem, vm) { + var offset = Anot(elem).offset(), + wrap = ME.selection(vm.$editor) || '', + layid = layer.open({ + type: 7, + menubar: false, + shadeClose: true, + fixed: true, + link: '', + linkName: wrap, + linkTarget: 1, + $confirm: function() { + var lvm = Anot.vmodels[layid] + if (!lvm.link || !lvm.linkName) { + return layer.alert('链接文字和地址不能为空') + } + var val = + '[' + + lvm.linkName + + '](' + + lvm.link + + (lvm.linkTarget === 1 ? ' "target=_blank"' : '') + + ')' + ME.insert(vm.$editor, val, false) + layer.close(layid) + }, + offset: [ + offset.top + 37 - ME.doc.scrollTop(), + 'auto', + 'auto', + offset.left - ME.doc.scrollLeft() + ], + content: + '
    ' + + '
    链接文字' + + '' + + '
    ' + + '
    链接地址' + + '' + + '
    ' + + '
    ' + + '' + + '' + + '
    ' + + '
    ' + + '确定' + + '
    ' + + '
    ' + }) + }, + time: function(elem, vm) { + ME.insert(vm.$editor, new Date().format(), false) + }, + face: function(elem, vm) { + var offset = Anot(elem).offset(), + faceid = 0, + layid = layer.open({ + type: 7, + title: '插入表情', + fixed: true, + shadeClose: true, + arr: getOrderArr(36), + offset: [ + offset.top + 37 - ME.doc.scrollTop(), + 'auto', + 'auto', + offset.left - ME.doc.scrollLeft() + ], + content: + '', + $insert: function(src) { + ME.insert(vm.$editor, '![](' + src + ')', false) + layer.close(layid) } - return arr - } - function trim(str, sign){ - return str.replace(new RegExp('^' + sign + '|' + sign + '$', 'g'), '') - } - function getOrderArr(len){ - var arr = [], i = 0; - while(i < len){ - arr.push(i++) - } - return arr - } - ME.addon = { - h1: function(elem, vm){ - var offset = yua(elem).offset(), - wrap = ME.selection(vm.$editor, true) || '在此输入文本', - h1ID = layer.open({ - type: 7, - menubar: false, - shadeClose: true, - fixed: true, - $insert: function(level){ - wrap = wrap.replace(/^#{1,6} /, '') - wrap = ME.repeat('#', level) + ' ' + wrap - ME.insert(vm.$editor, wrap, true) - layer.close(h1ID) - }, - offset: [offset.top + 37 - ME.doc.scrollTop(), 'auto', 'auto', offset.left - ME.doc.scrollLeft()], - content: '' - }) - }, - quote: function(elem, vm){ - var wrap = ME.selection(vm.$editor) || '在此输入文本' - wrap = '> ' + wrap - - ME.insert(vm.$editor, wrap, true) - }, - bold: function(elem, vm){ - var wrap = ME.selection(vm.$editor) || '在此输入文本', - wraped = trim(wrap, '\\*\\*') - - wrap = wrap === wraped ? ('**' + wrap + '**') : wraped - - ME.insert(vm.$editor, wrap, true) - }, - italic: function(elem, vm){ - var wrap = ME.selection(vm.$editor) || '在此输入文本', - wraped = trim(wrap, '_') - - wrap = wrap === wraped ? ('_' + wrap + '_') : wraped - - ME.insert(vm.$editor, wrap, true) - }, - through: function(elem, vm){ - var wrap = ME.selection(vm.$editor) || '在此输入文本', - wraped = trim(wrap, '~~') - - wrap = wrap === wraped ? ('~~' + wrap + '~~') : wraped - - ME.insert(vm.$editor, wrap, true) - }, - unordered: function(elem, vm){ - var wrap = ME.selection(vm.$editor) || '在此输入文本' - wrap = '* ' + wrap - - ME.insert(vm.$editor, wrap, false) - }, - ordered: function(elem, vm){ - var wrap = ME.selection(vm.$editor) || '在此输入文本' - wrap = '1. ' + wrap - - ME.insert(vm.$editor, wrap, false) - }, - hr: function(elem, vm){ - ME.insert(vm.$editor, '\n\n---\n\n', false) - }, - link: function(elem, vm){ - var offset = yua(elem).offset(), - wrap = ME.selection(vm.$editor) || '', - layid = layer.open({ - type: 7, - menubar: false, - shadeClose: true, - fixed: true, - link: '', - linkName: wrap, - linkTarget: 1, - $confirm: function(){ - var lvm = yua.vmodels[layid] - if(!lvm.link || !lvm.linkName){ - return layer.alert('链接文字和地址不能为空') - } - var val = '[' + lvm.linkName + '](' - + lvm.link - + (lvm.linkTarget === 1 ? ' "target=_blank"' : '') - + ')' - ME.insert(vm.$editor, val, false) - layer.close(layid) - }, - offset: [offset.top + 37 - ME.doc.scrollTop(), 'auto', 'auto', offset.left - ME.doc.scrollLeft()], - content: '
    ' - + '
    链接文字' - + '' - + '
    ' - + '
    链接地址' - + '' - + '
    ' - + '
    ' - + '' - + '' - + '
    ' - + '
    ' - + '确定' - + '
    ' - + '
    ' - }) - }, - time: function(elem, vm){ - ME.insert(vm.$editor, new Date().format(), false) - }, - face: function(elem, vm){ - var offset = yua(elem).offset(), - faceid = 0, - layid = layer.open({ - type: 7, - title: '插入表情', - fixed: true, - shadeClose: true, - arr: getOrderArr(36), - offset: [offset.top + 37 - ME.doc.scrollTop(), 'auto', 'auto', offset.left - ME.doc.scrollLeft()], - content: '', - $insert: function(src){ - ME.insert(vm.$editor, '![](' + src + ')', false) - layer.close(layid) - } - }) - }, - table: function(elem, vm){ - var offset = yua(elem).offset(); - layer.open({ - type: 7, - title: '0行 x 0列', - fixed: true, - shadeClose: true, - offset: [offset.top + 37 - ME.doc.scrollTop(), 'auto', 'auto', offset.left - ME.doc.scrollLeft()], - matrix: objArr(10).map(function(){return objArr(10)}), - content: '', - success: function(id){ - var tb = document.querySelector('.do-meditor-table'), - _this = yua.vmodels[id], - lastx,lasty; - yua(tb).bind('mousemove', function(ev){ - if(ev.target.nodeName === 'SPAN'){ - var x = ev.target.dataset.x - 0, - y = ev.target.dataset.y - 0; - if(x === lastx && y === lasty){ - return - } - lastx = x; - lasty = y; - _this.title = (y + 1) + '行 x ' + (x + 1) + '列' - for(var i = 0; i <= 9; i++){ - for(var j = 0; j <= 9; j++){ - _this.matrix[i][j].v = (i <= y && j <= x) ? 1 : 0 - } - } - } - }) - yua(tb).bind('mouseleave', function(ev){ - lastx = -1; - lasty = -1; - _this.title = '0行 x 0列' - for(var i = 0; i <= 9; i++){ - for(var j = 0; j <= 9; j++){ - _this.matrix[i][j].v = 0 - } - } - }) - yua(tb).bind('click', function(ev){ - if(ev.target.nodeName === 'SPAN'){ - var x = ev.target.dataset.x - 0 + 1, - y = ev.target.dataset.y - 0 + 1; - - var val = '\n\n' + ME.repeat('| 表头 ', x) + '|\n' - + ME.repeat('| -- ', x) + '|\n' - + ME.repeat(ME.repeat('| ', x) + '|\n', y) - ME.insert(vm.$editor, val, false) - layer.close(id) - } - }) - } - }) - }, - image: function(elem, vm){ - var offset = yua(elem).offset(), - wrap = ME.selection(vm.$editor) || '', - layid = layer.open({ - type: 7, - menubar: false, - shadeClose: true, - fixed: true, - img: '', - imgAlt: wrap, - $confirm: function(){ - var lvm = yua.vmodels[layid] - if(!lvm.img || !lvm.imgAlt){ - return layer.alert('图片描述和图片地址不能为空') - } - var val = '![' + lvm.imgAlt + '](' + lvm.img + ')' - - ME.insert(vm.$editor, val, false) - layer.close(layid) - }, - offset: [offset.top + 37 - ME.doc.scrollTop(), 'auto', 'auto', offset.left - ME.doc.scrollLeft()], - content: '
    ' - + '
    图片描述' - + '' - + '
    ' - + '
    图片地址' - + '' - + '
    ' - + '
    ' - + '确定' - + '
    ' - + '
    ' - }) - }, - file: function(elem, vm){ - this.link(elem, vm, false) - }, - inlinecode: function(elem, vm){ - var wrap = ME.selection(vm.$editor) || '在此输入文本', - wraped = trim(wrap, '`'); - - wrap = wrap === wraped ? ('`' + wrap + '`') : wraped - ME.insert(vm.$editor, wrap, true) - }, - blockcode: function(elem, vm){ - var layid = layer.open({ - type: 7, - title: '添加代码块', - $lang: [ - {id: 'asp'}, - {id: 'actionscript', name: 'ActionScript(3.0)/Flash/Flex'}, - {id: 'bash', name: 'Bash/Shell/Bat'}, - {id: 'css'}, - {id: 'c', name: 'C'}, - {id: 'cpp', name: 'C++'}, - {id: 'csharp', name: 'C#'}, - {id: 'coffeescript', name: 'CoffeeScript'}, - {id: 'd', name: 'D'}, - {id: 'dart'}, - {id: 'delphi', name: 'Delphi/Pascal'}, - {id: 'erlang'}, - {id: 'go', name: 'Golang'}, - {id: 'html'}, - {id: 'java'}, - {id: 'javascript'}, - {id: 'json'}, - {id: 'lua'}, - {id: 'less'}, - {id: 'markdown'}, - {id: 'nginx'}, - {id: 'objective-c'}, - {id: 'php'}, - {id: 'perl'}, - {id: 'python'}, - {id: 'r', name: 'R'}, - {id: 'ruby'}, - {id: 'sql'}, - {id: 'sass', name: 'SASS/SCSS'}, - {id: 'swift'}, - {id: 'typescript'}, - {id: 'xml'}, - {id: 'yaml'}, - {id: 'other', name: '其他语言'}, - ], - lang: 'javascript', - code: '', - $confirm: function(){ - var lvm = yua.vmodels[layid] - var val = '\n```' + lvm.lang + '\n' + (lvm.code || '//在此输入代码') + '\n```\n' - - ME.insert(vm.$editor, val, false) - layer.close(layid) - }, - content: '
    ' - + '
    语言类型' - + '' - + '
    ' - + '
    ' - + '' - + '
    ' - + '
    ' - + '确定' - + '
    ' - + '
    ' - }) - }, - preview: function(elem, vm){ - vm.preview = !vm.preview - if(vm.preview){ - vm.htmlTxt = vm.$htmlTxt + }) + }, + table: function(elem, vm) { + var offset = Anot(elem).offset() + layer.open({ + type: 7, + title: '0行 x 0列', + fixed: true, + shadeClose: true, + offset: [ + offset.top + 37 - ME.doc.scrollTop(), + 'auto', + 'auto', + offset.left - ME.doc.scrollLeft() + ], + matrix: objArr(10).map(function() { + return objArr(10) + }), + content: + '', + success: function(id) { + var tb = document.querySelector('.do-meditor-table'), + _this = Anot.vmodels[id], + lastx, + lasty + Anot(tb).bind('mousemove', function(ev) { + if (ev.target.nodeName === 'SPAN') { + var x = ev.target.dataset.x - 0, + y = ev.target.dataset.y - 0 + if (x === lastx && y === lasty) { + return } - }, - fullscreen: function(elem, vm){ - vm.fullscreen = !vm.fullscreen - vm.$onFullscreen(vm.fullscreen) - }, - about: function(elem){ - var offset = yua(elem).offset() - layer.open({ - type: 7, - title: '关于编辑器', - offset: [offset.top + 37 - ME.doc.scrollTop()], - content: '
    ' - + '
    '
    -                    + ' __  __ _____    _ _ _\n'             
    -                    + '|  \\/  | ____|__| (_) |_ ___  _ __\n' 
    -                    + '| |\\/| |  _| / _` | | __/ _ \\| \'__|\n'
    -                    + '| |  | | |__| (_| | | || (_) | |\n'   
    -                    + '|_|  |_|_____\\__,_|_|\\__\\___/|_|    ' 
    -                    + 'v' + ME.version + '
    ' - + '

    开源在线Markdown编辑器

    ' - + '

    https://doui.cc/product/meditor

    ' - + '

    Copyright © 2017 Yutent, The MIT License.

    ' - + '
    ' - }) - } + lastx = x + lasty = y + _this.title = y + 1 + '行 x ' + (x + 1) + '列' + for (var i = 0; i <= 9; i++) { + for (var j = 0; j <= 9; j++) { + _this.matrix[i][j].v = i <= y && j <= x ? 1 : 0 + } + } + } + }) + Anot(tb).bind('mouseleave', function(ev) { + lastx = -1 + lasty = -1 + _this.title = '0行 x 0列' + for (var i = 0; i <= 9; i++) { + for (var j = 0; j <= 9; j++) { + _this.matrix[i][j].v = 0 + } + } + }) + Anot(tb).bind('click', function(ev) { + if (ev.target.nodeName === 'SPAN') { + var x = ev.target.dataset.x - 0 + 1, + y = ev.target.dataset.y - 0 + 1 + var val = + '\n\n' + + ME.repeat('| 表头 ', x) + + '|\n' + + ME.repeat('| -- ', x) + + '|\n' + + ME.repeat(ME.repeat('| ', x) + '|\n', y) + ME.insert(vm.$editor, val, false) + layer.close(id) + } + }) + } + }) + }, + image: function(elem, vm) { + var offset = Anot(elem).offset(), + wrap = ME.selection(vm.$editor) || '', + layid = layer.open({ + type: 7, + menubar: false, + shadeClose: true, + fixed: true, + img: '', + imgAlt: wrap, + $confirm: function() { + var lvm = Anot.vmodels[layid] + if (!lvm.img || !lvm.imgAlt) { + return layer.alert('图片描述和图片地址不能为空') + } + var val = '![' + lvm.imgAlt + '](' + lvm.img + ')' + + ME.insert(vm.$editor, val, false) + layer.close(layid) + }, + offset: [ + offset.top + 37 - ME.doc.scrollTop(), + 'auto', + 'auto', + offset.left - ME.doc.scrollLeft() + ], + content: + '
    ' + + '
    图片描述' + + '' + + '
    ' + + '
    图片地址' + + '' + + '
    ' + + '
    ' + + '确定' + + '
    ' + + '
    ' + }) + }, + file: function(elem, vm) { + this.link(elem, vm, false) + }, + inlinecode: function(elem, vm) { + var wrap = ME.selection(vm.$editor) || '在此输入文本', + wraped = trim(wrap, '`') + + wrap = wrap === wraped ? '`' + wrap + '`' : wraped + ME.insert(vm.$editor, wrap, true) + }, + blockcode: function(elem, vm) { + var layid = layer.open({ + type: 7, + title: '添加代码块', + $lang: [ + { id: 'asp' }, + { id: 'actionscript', name: 'ActionScript(3.0)/Flash/Flex' }, + { id: 'bash', name: 'Bash/Shell/Bat' }, + { id: 'css' }, + { id: 'c', name: 'C' }, + { id: 'cpp', name: 'C++' }, + { id: 'csharp', name: 'C#' }, + { id: 'coffeescript', name: 'CoffeeScript' }, + { id: 'd', name: 'D' }, + { id: 'dart' }, + { id: 'delphi', name: 'Delphi/Pascal' }, + { id: 'erlang' }, + { id: 'go', name: 'Golang' }, + { id: 'html' }, + { id: 'java' }, + { id: 'javascript' }, + { id: 'json' }, + { id: 'lua' }, + { id: 'less' }, + { id: 'markdown' }, + { id: 'nginx' }, + { id: 'objective-c' }, + { id: 'php' }, + { id: 'perl' }, + { id: 'python' }, + { id: 'r', name: 'R' }, + { id: 'ruby' }, + { id: 'sql' }, + { id: 'sass', name: 'SASS/SCSS' }, + { id: 'swift' }, + { id: 'typescript' }, + { id: 'xml' }, + { id: 'yaml' }, + { id: 'other', name: '其他语言' } + ], + lang: 'javascript', + code: '', + $confirm: function() { + var lvm = Anot.vmodels[layid] + var val = + '\n```' + lvm.lang + '\n' + (lvm.code || '//在此输入代码') + '\n```\n' + + ME.insert(vm.$editor, val, false) + layer.close(layid) + }, + content: + '
    ' + + '
    语言类型' + + '' + + '
    ' + + '
    ' + + '' + + '
    ' + + '
    ' + + '确定' + + '
    ' + + '
    ' + }) + }, + preview: function(elem, vm) { + vm.preview = !vm.preview + if (vm.preview) { + vm.htmlTxt = vm.$htmlTxt } - -}) \ No newline at end of file + }, + fullscreen: function(elem, vm) { + vm.fullscreen = !vm.fullscreen + vm.$onFullscreen(vm.fullscreen) + }, + about: function(elem) { + var offset = Anot(elem).offset() + layer.open({ + type: 7, + title: '关于编辑器', + offset: [offset.top + 37 - ME.doc.scrollTop()], + content: + '
    ' + + '
    ' +
    +        ' __  __ _____    _ _ _\n' +
    +        '|  \\/  | ____|__| (_) |_ ___  _ __\n' +
    +        "| |\\/| |  _| / _` | | __/ _ \\| '__|\n" +
    +        '| |  | | |__| (_| | | || (_) | |\n' +
    +        '|_|  |_|_____\\__,_|_|\\__\\___/|_|    ' +
    +        'v' +
    +        ME.version +
    +        '
    ' + + '

    开源在线Markdown编辑器

    ' + + '

    https://doui.cc/product/meditor

    ' + + '

    Copyright © 2017 Yutent, The MIT License.

    ' + + '
    ' + }) + } +} + +export default addon diff --git a/src/js/meditor/index.js b/src/js/meditor/index.js new file mode 100644 index 0000000..911b6e8 --- /dev/null +++ b/src/js/meditor/index.js @@ -0,0 +1,470 @@ +/** + * + * @authors yutent (yutent@doui.cc) + * @date 2017-04-17 16:37:12 + * + */ + +'use strict' + +import 'prism/base' +import 'marked/index' +import addon from './addon/base' +import './skin/main.scss' + +marked.setOptions({ + highlight: function(code, lang) { + return Prism.highlight(code, Prism.languages[lang]) + } +}) +var editorVM = [] +Anot.ui.meditor = '1.0.0' +//存放编辑器公共静态资源 +window.ME = { + version: Anot.ui.meditor, + toolbar: { + //工具栏title + pipe: '', + h1: '标题', + quote: '引用文本', + bold: '粗体', + italic: '斜体', + through: '删除线', + unordered: '无序列表', + ordered: '有序列表', + link: '超链接', + hr: '横线', + time: '插入当前时间', + face: '表情', + table: '插入表格', + image: '插入图片', + file: '插入附件', + inlinecode: '行内代码', + blockcode: '代码块', + preview: '预览', + fullscreen: '全屏', + about: '关于编辑器' + }, + addon, //已有插件 + //往文本框中插入内容 + insert: function(dom, val, isSelect) { + if (document.selection) { + dom.focus() + var range = document.selection.createRange() + range.text = val + dom.focus() + range.moveStart('character', -1) + } else if (dom.selectionStart || dom.selectionStart === 0) { + var startPos = dom.selectionStart, + endPos = dom.selectionEnd, + scrollTop = dom.scrollTop + + dom.value = + dom.value.slice(0, startPos) + + val + + dom.value.slice(endPos, dom.value.length) + + dom.selectionStart = isSelect ? startPos : startPos + val.length + dom.selectionEnd = startPos + val.length + dom.scrollTop = scrollTop + dom.focus() + } else { + dom.value += val + dom.focus() + } + }, + /** + * [selection 获取选中的文本] + * @param {[type]} dom [要操作的元素] + * @param {[type]} line [是否强制选取整行] + */ + selection: function(dom, line) { + if (document.selection) { + return document.selection.createRange().text + } else { + var startPos = dom.selectionStart, + endPos = dom.selectionEnd + + if (endPos) { + //强制选择整行 + if (line) { + startPos = dom.value.slice(0, startPos).lastIndexOf('\n') + + var tmpEnd = dom.value.slice(endPos).indexOf('\n') + tmpEnd = tmpEnd < 0 ? 0 : tmpEnd + + startPos += 1 //把\n加上 + endPos += tmpEnd + + dom.selectionStart = startPos + dom.selectionEnd = endPos + } + } else { + //强制选择整行 + if (line) { + endPos = dom.value.indexOf('\n') + endPos = endPos < 0 ? dom.value.length : endPos + dom.selectionEnd = endPos + } + } + return dom.value.slice(startPos, endPos) + } + }, + repeat: function(str, num) { + if (String.prototype.repeat) { + return str.repeat(num) + } else { + var result = '' + while (num > 0) { + result += str + num-- + } + return result + } + }, + get: function(id) { + if (id === void 0) { + id = editorVM.length - 1 + } + var vm = editorVM[id] + if (vm) { + return { + id: vm.$id, + getVal: function() { + return vm.plainTxt.trim() + }, + getHtml: function() { + return vm.$htmlTxt + }, + setVal: function(txt) { + vm.plainTxt = txt || '' + }, + show: function() { + vm.editorVisible = true + }, + hide: function() { + vm.editorVisible = false + } + } + } + return null + }, + doc: Anot(document) +} +//获取真实的引用路径,避免因为不同的目录结构导致加载失败的情况 +for (var i in Anot.modules) { + if (/meditor/.test(i)) { + ME.path = i.slice(0, i.lastIndexOf('/')) + break + } +} +var elems = { + p: function(str, attr, inner) { + return inner ? '\n' + inner + '\n' : '' + }, + br: '\n', + 'h([1-6])': function(str, level, attr, inner) { + var h = ME.repeat('#', level) + return '\n' + h + ' ' + inner + '\n' + }, + hr: '\n\n___\n\n', + a: function(str, attr, inner) { + var href = attr.match(attrExp('href')), + title = attr.match(attrExp('title')), + tar = attr.match(attrExp('target')) + + href = (href && href[1]) || '' + title = (title && title[1]) || '' + tar = (tar && tar[1]) || '_self' + + href = href === 'javascript:void(0);' ? 'javascript:;' : href + + return ( + '[' + + (inner || href) + + '](' + + href + + ' "title=' + + title + + ';target=' + + tar + + '")' + ) + }, + em: function(str, attr, inner) { + return (inner && '_' + inner + '_') || '' + }, + strong: function(str, attr, inner) { + return (inner && '**' + inner + '**') || '' + }, + code: function(str, attr, inner) { + return (inner && '`' + inner + '`') || '' + }, + pre: function(str, attr, inner) { + return '\n\n```\n' + inner + '\n```\n' + }, + blockquote: function(str, attr, inner) { + return '> ' + inner.trim() + }, + img: function(str, attr, inner) { + var src = attr.match(attrExp('src')), + alt = attr.match(attrExp('alt')) + + src = (src && src[1]) || '' + alt = (alt && alt[1]) || '' + + return '![' + alt + '](' + src + ')' + } +} + +function attrExp(field) { + return new RegExp(field + '\\s?=\\s?["\']?([^"\']*)["\']?', 'i') +} +function tagExp(tag, open) { + var exp = '' + if (['br', 'hr', 'img'].indexOf(tag) > -1) { + exp = '<' + tag + '([^>]*)\\/?>' + } else { + exp = '<' + tag + '([^>]*)>([\\s\\S]*?)<\\/' + tag + '>' + } + return new RegExp(exp, 'gi') +} +function html2md(str) { + try { + str = decodeURIComponent(str) + } catch (err) {} + str = str.replace(/\t/g, ' ').replace(/]*>/, '') + + for (var i in elems) { + var cb = elems[i], + exp = tagExp(i) + + if (i === 'blockquote') { + while (str.match(exp)) { + str = str.replace(exp, cb) + } + } else { + str = str.replace(exp, cb) + } + + if (i === 'em') { + exp = tagExp('i') + str = str.replace(exp, cb) + } + if (i === 'strong') { + exp = tagExp('b') + str = str.replace(exp, cb) + } + } + var liExp = /<(ul|ol)[^>]*>(?:(?!/gi + while (str.match(liExp)) { + str = str.replace(liExp, function(match) { + match = match.replace(/<(ul|ol)[^>]*>([\s\S]*?)<\/\1>/gi, function( + m, + t, + inner + ) { + var li = inner.split('') + li.pop() + + for (var i = 0, len = li.length; i < len; i++) { + var pre = t === 'ol' ? i + 1 + '. ' : '* ' + li[i] = + pre + + li[i] + .replace(/\s*]*>([\s\S]*)/i, function(m, n) { + n = n.trim().replace(/\n/g, '\n ') + return n + }) + .replace(/<[\/]?[\w]*[^>]*>/g, '') + } + return li.join('\n') + }) + return '\n' + match.trim() + }) + } + str = str + .replace(/<[\/]?[\w]*[^>]*>/g, '') + .replace(/```([\w\W]*)```/g, function(str, inner) { + inner = inner + .replace(/&/g, '&') + .replace(/</g, '<') + .replace(/>/g, '>') + return '```' + inner + '```' + }) + return str +} + +var defaultToolbar = [ + 'h1', + 'quote', + '|', + 'bold', + 'italic', + 'through', + '|', + 'unordered', + 'ordered', + '|', + 'hr', + 'link', + 'time', + 'face', + '|', + 'table', + 'image', + 'file', + 'inlinecode', + 'blockcode', + '|', + 'preview', + 'fullscreen', + '|', + 'about' + ], + extraAddons = [] + +function tool(name) { + name = (name + '').trim().toLowerCase() + name = '|' === name ? 'pipe' : name + return ( + '' + ) +} + +Anot.component('meditor', { + render: function() { + var toolbar = (this.toolbar || defaultToolbar) + .map(function(it) { + return tool(it) + }) + .join('') + delete this.toolbar + return ( + '
    ' + + '
    {toolbar}
    ' + + '' + + '' + + '
    ' + ).replace(/\{toolbar\}/g, toolbar) + }, + + construct: function(base, opt, attr) { + Anot.mix(base, opt, attr) + if (base.$addons && Array.isArray(base.$addons)) { + extraAddons = base.$addons.map(function(name) { + return ME.path + '/addon/' + name + }) + delete base.$addons + } + if (base.hasOwnProperty('$show')) { + base.editorVisible = base.$show + delete base.$show + } + return base + }, + componentWillMount: function(vm) {}, + componentDidMount: function(vm, elem) { + console.log(this) + // vm.$editor = elem.children[1] + + // editorVM.push(vm) + // //自动加载额外的插件 + // require(extraAddons, function() { + // var args = Array.prototype.slice.call(arguments, 0) + // args.forEach(function(addon) { + // addon && addon(vm) + // }) + // }) + + // Anot(vm.$editor).bind('keydown', function(ev) { + // var wrap = ME.selection(vm.$editor) || '', + // select = !!wrap + // //tab键改为插入2个空格,阻止默认事件,防止焦点失去 + // if (ev.keyCode === 9) { + // wrap = wrap + // .split('\n') + // .map(function(it) { + // return ev.shiftKey ? it.replace(/^\s\s/, '') : ' ' + it + // }) + // .join('\n') + // ME.insert(this, wrap, select) + // ev.preventDefault() + // } + // //修复按退格键删除选中文本时,选中的状态不更新的bug + // if (ev.keyCode === 8) { + // if (select) { + // ME.insert(this, '', select) + // ev.preventDefault() + // } + // } + // }) + // //编辑器成功加载的回调 + // vm.$onSuccess(ME.get(), vm) + }, + watch: { + plainTxt: function(val) { + this.$compile() + //只有开启实时预览,才会赋值给htmlTxt + if (this.preview) { + this.htmlTxt = this.$htmlTxt + } + this.$onUpdate(this.plainTxt, vm.$htmlTxt) + } + }, + state: { + disabled: false, //禁用编辑器 + fullscreen: false, //是否全屏 + preview: false, //是否显示预览 + $editor: null, //编辑器元素 + editorVisible: true, + $htmlTxt: '', //临时储存html文本 + htmlTxt: '', //用于预览渲染 + plainTxt: '', //纯md文本 + $safelyCompile: true + }, + methods: { + onToolClick: function(name, ev) { + if (ME.addon[name]) { + ME.addon[name].call(ME, ev.target, this) + } else { + console.log('%c没有对应的插件%c[%s]', 'color:#f00;', '', name) + } + }, + $onSuccess: Anot.noop, + $onUpdate: Anot.noop, + $onFullscreen: Anot.noop, + $paste: function(ev) { + ev.preventDefault() + var txt = ev.clipboardData.getData('text/plain').trim(), + html = ev.clipboardData.getData('text/html').trim() + + html = html2md(html) + + if (html) { + ME.insert(this, html) + } else if (txt) { + ME.insert(this, txt) + } + this.plainTxt = this.value + }, + compile: function() { + var txt = this.plainTxt.trim() + + if (this.$safelyCompile) { + txt = txt + .replace(/]*?)>/g, '<script$1>') + .replace(/<\/script>/g, '</script>') + } + //只解析,不渲染 + this.$htmlTxt = marked(txt) + } + } +}) diff --git a/src/js/meditor/main.js b/src/js/meditor/main.js deleted file mode 100644 index 33789c5..0000000 --- a/src/js/meditor/main.js +++ /dev/null @@ -1,440 +0,0 @@ -/** - * - * @authors yutent (yutent@doui.cc) - * @date 2017-04-17 16:37:12 - * - */ - -"use strict"; - - -define([ - 'yua', - 'lib/prism/base', - 'lib/marked/main', - 'css!./skin/main', -], function(yua){ - - marked.setOptions({ - highlight: function(code, lang){ - return Prism.highlight(code, Prism.languages[lang]) - } - }) - - var editorVM = [] - yua.ui.meditor = '1.0.0' - //存放编辑器公共静态资源 - window.ME = { - version: yua.ui.meditor, - toolbar: { //工具栏title - pipe: '', - h1: '标题', - quote: '引用文本', - bold: '粗体', - italic: '斜体', - through: '删除线', - unordered: '无序列表', - ordered: '有序列表', - link: '超链接', - hr: '横线', - time: '插入当前时间', - face: '表情', - table: '插入表格', - image: '插入图片', - file: '插入附件', - inlinecode: '行内代码', - blockcode: '代码块', - preview: '预览', - fullscreen: '全屏', - about: '关于编辑器', - }, - addon: {}, //已有插件 - //往文本框中插入内容 - insert: function(dom, val, isSelect){ - if(document.selection){ - dom.focus() - var range = document.selection.createRange() - range.text = val - dom.focus() - range.moveStart('character', -1) - - }else if(dom.selectionStart || dom.selectionStart === 0) { - var startPos = dom.selectionStart, - endPos = dom.selectionEnd, - scrollTop = dom.scrollTop; - - dom.value = dom.value.slice(0, startPos) - + val - + dom.value.slice(endPos, dom.value.length); - - dom.selectionStart = isSelect ? startPos : (startPos + val.length) - dom.selectionEnd = startPos + val.length - dom.scrollTop = scrollTop - dom.focus() - }else{ - dom.value += val; - dom.focus() - } - }, - /** - * [selection 获取选中的文本] - * @param {[type]} dom [要操作的元素] - * @param {[type]} line [是否强制选取整行] - */ - selection: function(dom, line){ - if(document.selection){ - return document.selection.createRange().text - }else{ - - var startPos = dom.selectionStart, - endPos = dom.selectionEnd; - - if(endPos){ - //强制选择整行 - if(line) { - startPos = dom.value.slice(0, startPos).lastIndexOf('\n'); - - var tmpEnd = dom.value.slice(endPos).indexOf('\n'); - tmpEnd = tmpEnd < 0 ? 0 : tmpEnd - - startPos += 1 //把\n加上 - endPos += tmpEnd; - - dom.selectionStart = startPos - dom.selectionEnd = endPos - } - }else{ - //强制选择整行 - if(line) { - endPos = dom.value.indexOf('\n') - endPos = endPos < 0 ? dom.value.length : endPos - dom.selectionEnd = endPos - } - } - return dom.value.slice(startPos, endPos) - } - }, - repeat: function(str, num){ - if(String.prototype.repeat){ - return str.repeat(num) - }else{ - var result = '' - while(num > 0){ - result += str; - num-- - } - return result - } - }, - get: function(id){ - if(id === void 0){ - id = editorVM.length - 1 - } - var vm = editorVM[id] - if(vm){ - return { - id: vm.$id, - getVal: function(){ - return vm.plainTxt.trim() - }, - getHtml: function(){ - return vm.$htmlTxt - }, - setVal: function(txt){ - vm.plainTxt = txt || '' - }, - show: function(){ - vm.editorVisible = true - }, - hide: function(){ - vm.editorVisible = false - } - } - } - return null - }, - doc: yua(document) - } - //获取真实的引用路径,避免因为不同的目录结构导致加载失败的情况 - for(var i in yua.modules){ - if(/meditor/.test(i)) { - ME.path = i.slice(0, i.lastIndexOf('/')) - break; - } - } - var elems = { - p: function(str, attr, inner){ - return inner ? ('\n' + inner + '\n') : '' - }, - br: '\n', - 'h([1-6])': function(str, level, attr, inner){ - var h = ME.repeat('#', level) - return '\n' + h + ' ' + inner + '\n' - }, - hr: '\n\n___\n\n', - a: function(str, attr, inner){ - var href = attr.match(attrExp('href')), - title = attr.match(attrExp('title')), - tar = attr.match(attrExp('target')); - - href = href && href[1] || '' - title = title && title[1] || '' - tar = tar && tar[1] || '_self' - - href = href === 'javascript:void(0);' ? 'javascript:;' : href - - return '[' + (inner || href) + '](' + href + ' "title=' + title + ';target=' + tar + '")' - }, - em: function(str, attr, inner){ - return inner && ('_' + inner + '_') || '' - }, - strong: function(str, attr, inner){ - return inner && ('**' + inner + '**') || '' - }, - code: function(str, attr, inner){ - return inner && ('`' + inner + '`') || '' - }, - pre: function(str, attr, inner){ - - return '\n\n```\n' + inner + '\n```\n' - }, - blockquote: function(str, attr, inner){ - return '> ' + inner.trim() - }, - img: function(str, attr, inner){ - var src = attr.match(attrExp('src')), - alt = attr.match(attrExp('alt')); - - src = src && src[1] || '' - alt = alt && alt[1] || '' - - return '![' + alt + '](' + src + ')' - } - } - - function attrExp(field){ - return new RegExp(field + '\\s?=\\s?["\']?([^"\']*)["\']?', 'i') - } - function tagExp(tag, open){ - var exp = '' - if(['br', 'hr', 'img'].indexOf(tag) > -1){ - exp = '<' + tag + '([^>]*)\\/?>' - }else{ - exp = '<' + tag + '([^>]*)>([\\s\\S]*?)<\\/' + tag + '>' - } - return new RegExp(exp, 'gi') - } - function html2md(str){ - try{ - str = decodeURIComponent(str) - }catch(err){} - str = str.replace(/\t/g, ' ').replace(/]*>/, '') - - for(var i in elems){ - var cb = elems[i], - exp = tagExp(i); - - if(i === 'blockquote'){ - while(str.match(exp)){ - str = str.replace(exp, cb) - } - }else{ - str = str.replace(exp, cb) - } - - if(i === 'em'){ - exp = tagExp('i') - str = str.replace(exp, cb) - } - if(i === 'strong'){ - exp = tagExp('b') - str = str.replace(exp, cb) - } - } - var liExp = /<(ul|ol)[^>]*>(?:(?!/gi - while(str.match(liExp)) { - str = str.replace(liExp, function(match){ - match = match.replace(/<(ul|ol)[^>]*>([\s\S]*?)<\/\1>/gi, function(m, t, inner){ - var li = inner.split('') - li.pop() - - for(var i = 0,len = li.length; i < len; i++){ - var pre = t === 'ol' ? ((i + 1) + '. ') : '* ' - li[i] = pre + li[i].replace(/\s*]*>([\s\S]*)/i, function(m, n){ - n = n.trim() - .replace(/\n/g, '\n ') - return n - }).replace(/<[\/]?[\w]*[^>]*>/g, '') - } - return li.join('\n') - }) - return '\n' + match.trim() - }) - } - str = str.replace(/<[\/]?[\w]*[^>]*>/g, '') - .replace(/```([\w\W]*)```/g, function(str, inner){ - inner = inner.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>') - return '```' + inner + '```' - }) - return str - } - - require([ - ME.path + '/addon/base' - ], function(){ - - - var defaultToolbar = ['h1', 'quote', '|', - 'bold', 'italic', 'through', '|', - 'unordered', 'ordered', '|', - 'hr', 'link', 'time', 'face', '|', - 'table','image', 'file','inlinecode', 'blockcode','|', - 'preview', 'fullscreen', '|', - 'about' - ], - extraAddons = []; - - - function tool(name){ - name = (name + '').trim().toLowerCase() - name = '|' === name ? 'pipe' : name - return '' - } - - - - yua.component('meditor', { - $template: '
    ' - + '
    {toolbar}
    ' - + '' - + '' - + '
    ', - $$template: function(txt){ - - var toolbar = (this.toolbar || defaultToolbar).map(function(it){ - return tool(it) - }).join('') - - delete this.toolbar - return txt.replace(/\{uuid\}/g, this.$id).replace(/\{toolbar\}/g, toolbar) - }, - $construct: function(base, opt, attr){ - yua.mix(base, opt, attr) - if(base.$addons && Array.isArray(base.$addons)){ - extraAddons = base.$addons.map(function(name){ - return ME.path + '/addon/' + name - }) - delete base.$addons - } - if(base.hasOwnProperty('$show')){ - base.editorVisible = base.$show - delete base.$show - } - return base - }, - $init: function(vm){ - vm.$watch('plainTxt', function(val){ - vm.$compile() - //只有开启实时预览,才会赋值给htmlTxt - if(vm.preview){ - vm.htmlTxt = vm.$htmlTxt - } - vm.$onUpdate(vm.plainTxt, vm.$htmlTxt) - }) - - vm.$onToolbarClick = function(name){ - if(ME.addon[name]){ - ME.addon[name].call(ME.addon, this, vm) - }else{ - console.log('%c没有对应的插件%c[%s]', 'color:#f00;', '',name) - } - } - - vm.$paste = function(ev){ - ev.preventDefault() - var txt = ev.clipboardData.getData('text/plain').trim(), - html = ev.clipboardData.getData('text/html').trim(); - - html = html2md(html) - - if(html){ - ME.insert(this, html) - }else if(txt) { - ME.insert(this, txt) - } - vm.plainTxt = this.value - } - }, - $ready: function(vm, elem){ - - vm.$editor = elem.children[1] - - editorVM.push(vm) - //自动加载额外的插件 - require(extraAddons, function(){ - var args = Array.prototype.slice.call(arguments, 0) - args.forEach(function(addon){ - addon && addon(vm) - }) - }) - - yua(vm.$editor).bind('keydown', function(ev){ - - var wrap = ME.selection(vm.$editor) || '', - select = !!wrap; - //tab键改为插入2个空格,阻止默认事件,防止焦点失去 - if(ev.keyCode === 9){ - wrap = wrap.split('\n').map(function(it){ - return ev.shiftKey ? it.replace(/^\s\s/, '') : ' ' + it - }).join('\n') - ME.insert(this, wrap, select) - ev.preventDefault() - } - //修复按退格键删除选中文本时,选中的状态不更新的bug - if(ev.keyCode === 8){ - if(select){ - ME.insert(this, '', select) - ev.preventDefault() - } - } - - }) - //编辑器成功加载的回调 - vm.$onSuccess(ME.get(), vm) - }, - $paste: yua.noop, - $compile: function(){ - var txt = this.plainTxt.trim() - - if(this.$safelyCompile){ - txt = txt.replace(/]*?)>/g, '<script$1>') - .replace(/<\/script>/g, '</script>') - } - //只解析,不渲染 - this.$htmlTxt = marked(txt) - }, - $onToolbarClick: yua.noop, - $onSuccess: yua.noop, - $onUpdate: yua.noop, - $onFullscreen: yua.noop, - $safelyCompile: true, - disabled: false, //禁用编辑器 - fullscreen: false, //是否全屏 - preview: false, //是否显示预览 - $editor: null, //编辑器元素 - editorVisible: true, - $htmlTxt: '', //临时储存html文本 - htmlTxt: '', //用于预览渲染 - plainTxt: '' //纯md文本 - - - }) - - - - }) - -}) diff --git a/src/js/meditor/skin/main.scss b/src/js/meditor/skin/main.scss index 995be3a..a4f566e 100644 --- a/src/js/meditor/skin/main.scss +++ b/src/js/meditor/skin/main.scss @@ -6,15 +6,15 @@ * */ -@import "../../../../css/var.scss"; +@import "var.scss"; .do-meditor {position:relative;width:100%;height:100%;min-height:180px;padding-top:43px;border:1px solid #ddd;background:#fff;color:#666; - ::-webkit-scrollbar {width:5px;height:5px;background:#ebeeec;} - ::-webkit-scrollbar:hover {background:rgba(0,0,0,.05);} - ::-webkit-scrollbar-button {display:none;} - ::-webkit-scrollbar-thumb {background:nth($ct, 1);} - ::-webkit-scrollbar-thumb:hover {background:nth($ct, 3);} + ::-webkit-scrollbar {width:5px;height:5px;background:#ebeeec;} + ::-webkit-scrollbar:hover {background:rgba(0,0,0,.05);} + ::-webkit-scrollbar-button {display:none;} + ::-webkit-scrollbar-thumb {background:nth($ct, 1);} + ::-webkit-scrollbar-thumb:hover {background:nth($ct, 3);} } .do-meditor-font {font-family:"PingFang SC","Helvetica Neue","Hiragino Sans GB","Segoe UI","Microsoft YaHei",sans-serif;} @@ -32,104 +32,104 @@ /*表格模块*/ .do-meditor-table {width:270px;height:270px;padding:10px; - li {width:100%;height:25px; - span {float:left;width:25px;height:25px;border:2px solid #fff;background:#f2f2f2;} - span.active {background:rgba(4,151,137,.2);} - } + li {width:100%;height:25px; + span {float:left;width:25px;height:25px;border:2px solid #fff;background:#f2f2f2;} + span.active {background:rgba(4,151,137,.2);} + } } /*表情模块*/ .do-meditor-face {float:left;;width:241px;height:241px;margin:10px;border-top:1px solid #e2e2e2;border-left:1px solid #e2e2e2; - li {float:left;width:40px;height:40px;padding:8px;border:1px solid #e2e2e2;border-top:0;border-left:0} - li img {width:100%;@include ts();} - li:hover img {-webkit-transform:scale(3);-moz-transform:scale(3);-ms-transform:scale(3);transform:scale(3);} + li {float:left;width:40px;height:40px;padding:8px;border:1px solid #e2e2e2;border-top:0;border-left:0} + li img {width:100%;@include ts();} + li:hover img {-webkit-transform:scale(3);-moz-transform:scale(3);-ms-transform:scale(3);transform:scale(3);} } /*段落模块*/ .do-meditor-h1 {width:150px;height:auto;padding:5px 0; - li {width:100%;height:auto;padding:0 10px;line-height:1.5;font-size:18px;cursor:default;} - li:hover {background:#f2f2f2;} - li::before {font-family:"ui font" !important;-webkit-font-smoothing: antialiased;-webkit-text-stroke-width: 0.2px;-moz-osx-font-smoothing: grayscale;} - li.h1 {font-size:23px;} - li.h2 {font-size:21px;} - li.h1::before {content:"\e62b "} - li.h2::before {content:"\e625 "} - li.h3::before {content:"\e626 "} - li.h4::before {content:"\e629 "} - li.h5::before {content:"\e62a "} - li.h6::before {content:"\e624 "} + li {width:100%;height:auto;padding:0 10px;line-height:1.5;font-size:18px;cursor:default;} + li:hover {background:#f2f2f2;} + li::before {font-family:"ui font" !important;-webkit-font-smoothing: antialiased;-webkit-text-stroke-width: 0.2px;-moz-osx-font-smoothing: grayscale;} + li.h1 {font-size:23px;} + li.h2 {font-size:21px;} + li.h1::before {content:"\e62b "} + li.h2::before {content:"\e625 "} + li.h3::before {content:"\e626 "} + li.h4::before {content:"\e629 "} + li.h5::before {content:"\e62a "} + li.h6::before {content:"\e624 "} } /*通用输入模块, 链接/图片插入/文件插入/代码块插入*/ .do-meditor-common {width:360px;height:auto;padding:15px 20px; - section {width:100%;height: 35px;margin:10px 0;line-height:35px; + section {width:100%;height: 35px;margin:10px 0;line-height:35px; - &.input {line-height:33px;border:1px solid #e9e9e9;} - .label {float: left;width:30%;text-align:center;background:#f7f7f7;} - label {float: left;width:50%;} - .txt {float: left;width:70%;height:33px;padding:0 8px;border:0;border-left:1px solid #e9e9e9;background:#fff;color:#666;} - .submit {float:right;width:30%;height:35px;background:#ddd;color:#666;text-align:center;} - } + &.input {line-height:33px;border:1px solid #e9e9e9;} + .label {float: left;width:30%;text-align:center;background:#f7f7f7;} + label {float: left;width:50%;} + .txt {float: left;width:70%;height:33px;padding:0 8px;border:0;border-left:1px solid #e9e9e9;background:#fff;color:#666;} + .submit {float:right;width:30%;height:35px;background:#ddd;color:#666;text-align:center;} + } } .do-meditor-codeblock {width:780px;height:auto;padding:15px 20px;background:#fafafa; - section {display:block;width:100%;height:auto;margin:10px 0;line-height:35px; - - .label {float: left;width:80px;} - select {float:left;width:200px;height:35px;padding:0 30px 0 10px;border:0;border-bottom:1px solid #e7e7e7;background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAMCAMAAABV0m3JAAAADFBMVEUAAAD///+Pj4+JiYkxcGihAAAABHRSTlMAABBwqVQF9wAAADNJREFUeNqlzjEOACAMw8DQ/v/PSE5FFhaEx5usdekBuzRVH0RtCqJYELUFrVjQigX/5jdvzgDh9izlMQAAAABJRU5ErkJggg==) no-repeat right 8px;color:nth($cgr, 1);outline:none;-webkit-appearance:none;-moz-appearance: none;@include ts; - - &::-ms-expand {display:none;} + section {display:block;width:100%;height:auto;margin:10px 0;line-height:35px; + + .label {float: left;width:80px;} + select {float:left;width:200px;height:35px;padding:0 30px 0 10px;border:0;border-bottom:1px solid #e7e7e7;background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAMCAMAAABV0m3JAAAADFBMVEUAAAD///+Pj4+JiYkxcGihAAAABHRSTlMAABBwqVQF9wAAADNJREFUeNqlzjEOACAMw8DQ/v/PSE5FFhaEx5usdekBuzRVH0RtCqJYELUFrVjQigX/5jdvzgDh9izlMQAAAABJRU5ErkJggg==) no-repeat right 8px;color:nth($cgr, 1);outline:none;-webkit-appearance:none;-moz-appearance: none;@include ts; + + &::-ms-expand {display:none;} - &:focus {border-color:nth($ct, 1);} - } - textarea {width:100%;height:300px;padding:5px 10px;border:1px solid #ddd;background:#fff;resize:none;outline:none;} - .submit {float:right;width:80px;height:35px;background:#ddd;color:#666;text-align:center;} + &:focus {border-color:nth($ct, 1);} } + textarea {width:100%;height:300px;padding:5px 10px;border:1px solid #ddd;background:#fff;resize:none;outline:none;} + .submit {float:right;width:80px;height:35px;background:#ddd;color:#666;text-align:center;} + } } .do-meditor { - .tool-bar {overflow:hidden;position:absolute;top:0;left:0;z-index:99;width:100%;height:43px;padding:5px 10px;border-bottom:1px solid #ddd;background:#f5f5f5;color:#666; + .tool-bar {overflow:hidden;position:absolute;top:0;left:0;z-index:99;width:100%;height:43px;padding:5px 10px;border-bottom:1px solid #ddd;background:#f5f5f5;color:#666; - span {display:inline-block;width:30px;height:32px;line-height:32px;text-align:center;font-size:20px;} - span:hover {background:#e5e5e5;} - .icon-pipe {width:20px;} - .icon-pipe:hover {background:none;} - .icon-pipe::before {content:"\e62c"} - .icon-h1::before {content:"\e62b"} - .icon-bold::before {content:"\e62f"} - .icon-italic::before {content:"\e639"} - .icon-through::before {content:"\e619"} - .icon-link::before {content:"\e61c"} - .icon-inlinecode::before {content:"\e63a"} - .icon-blockcode::before {content:"\e632"} - .icon-quote::before {content:"\e61b"} - .icon-hr::before {content:"\e614"} - .icon-time::before {content:"\e636"} - .icon-face::before {content:"\e630"} - .icon-image::before {content:"\e637"} - .icon-file::before {content:"\e618"} - .icon-preview::before {content:"\e61f"} - .icon-fullscreen::before {content:"\e621"} - .icon-table::before {content:"\e617"} - .icon-ordered::before {content:"\e638"} - .icon-unordered::before {content:"\e633"} - .icon-about::before {content:"\e700"} - } + span {display:inline-block;width:32px;height:32px;line-height:32px;text-align:center;font-size:28px;} + span:hover {background:#e5e5e5;} + .icon-pipe {width:20px;color:nth($cp, 3)} + .icon-pipe:hover {background:none;} + .icon-pipe::before {content:"\e677"} + .icon-h1::before {content:"\e65c"} + .icon-bold::before {content:"\e66c"} + .icon-italic::before {content:"\e670"} + .icon-through::before {content:"\e66d"} + .icon-link::before {content:"\e667"} + .icon-inlinecode::before {content:"\e67a"} + .icon-blockcode::before {content:"\e67b"} + .icon-quote::before {content:"\e66a"} + .icon-hr::before {content:"\e676"} + .icon-time::before {content:"\e675"} + .icon-face::before {content:"\e673"} + .icon-image::before {content:"\e682"} + .icon-file::before {content:"\e66b"} + .icon-preview::before {content:"\e67d"} + .icon-fullscreen::before {content:"\e67e"} + .icon-table::before {content:"\e65a"} + .icon-ordered::before {content:"\e664"} + .icon-unordered::before {content:"\e663"} + .icon-about::before {content:"\e672"} + } - .editor-body{overflow:hidden;overflow-y:auto;float:left;width:100%;height:100%;padding:5px 5px 50px;border:0;outline:none;resize:none;color:#666;background:#fff;} - .md-preview {float:right;overflow:hidden;overflow-y:auto;display:block;width:50%;height:100%;padding:10px 10px 50px;line-height:2;border-left:1px solid #ddd;color:#666;font-size:14px;background:#fff;} + .editor-body{overflow:hidden;overflow-y:auto;float:left;width:100%;height:100%;padding:5px 5px 50px;border:0;outline:none;resize:none;color:#666;background:#fff;} + .md-preview {float:right;overflow:hidden;overflow-y:auto;display:block;width:50%;height:100%;padding:10px 10px 50px;line-height:2;border-left:1px solid #ddd;color:#666;font-size:14px;background:#fff;} - /*全屏模式*/ - &.fullscreen {position:fixed;left:0;top:0;z-index:999;} + /*全屏模式*/ + &.fullscreen {position:fixed;left:0;top:0;z-index:999;} - &.preview .editor-body {width:50%} + &.preview .editor-body {width:50%} } \ No newline at end of file diff --git a/src/js/pager/main.scss b/src/js/pager/main.scss index 37bac16..f5c68be 100644 --- a/src/js/pager/main.scss +++ b/src/js/pager/main.scss @@ -22,10 +22,10 @@ .button,.page {display:inline-block;border:0;color: nth($cgr, 1);text-decoration:none;cursor:pointer;vertical-align:top;font-size:14px;font-weight:100; - &.home::after {content:"\e652";font-size:18px;} - &.prev::after {content:"\e659";font-size:18px;} - &.next::after {content:"\e658";font-size:18px;} - &.end::after {content:"\e653";font-size:18px;} + &.home::after {content:"\e691";font-size:18px;} + &.prev::after {content:"\e67c";font-size:18px;} + &.next::after {content:"\e66e";font-size:18px;} + &.end::after {content:"\e693";font-size:18px;} } diff --git a/src/js/prism/base.js b/src/js/prism/base.js index eedc4ac..0ef809a 100644 --- a/src/js/prism/base.js +++ b/src/js/prism/base.js @@ -1,800 +1,867 @@ /** - * + * * @authors yutent (yutent@doui.cc) * @date 2017-08-02 21:50:34 * @version $Id$ */ -define(['css!./highlight'], function() { - - var _self = window; - - var Prism = (function() { - - // Private helper vars - var lang = /\blang(?:uage)?-(\w+)\b/i; - var uniqueId = 0; - - var _ = _self.Prism = { - manual: _self.Prism && _self.Prism.manual, - util: { - encode: function(tokens) { - if (tokens instanceof Token) { - return new Token(tokens.type, _.util.encode(tokens.content), tokens.alias); - } else if (_.util.type(tokens) === 'Array') { - return tokens.map(_.util.encode); - } else { - return tokens.replace(/&/g, '&').replace(/ text.length) { - // Something went terribly wrong, ABORT, ABORT! - break tokenloop; - } - - if (str instanceof Token) { - continue; - } - - pattern.lastIndex = 0; - - var match = pattern.exec(str), - delNum = 1; - - // Greedy patterns can override/remove up to two previously matched tokens - if (!match && greedy && i != strarr.length - 1) { - pattern.lastIndex = pos; - match = pattern.exec(text); - if (!match) { - break; - } - - var from = match.index + (lookbehind ? match[1].length : 0), - to = match.index + match[0].length, - k = i, - p = pos; - - for (var len = strarr.length; k < len && p < to; ++k) { - p += strarr[k].length; - // Move the index i to the element in strarr that is closest to from - if (from >= p) { - ++i; - pos = p; - } - } - - if (strarr[i] instanceof Token || strarr[k - 1].greedy) { - continue; - } - - // Number of tokens to delete and replace with the new match - delNum = k - i; - str = text.slice(pos, p); - match.index -= pos; - } - - if (!match) { - continue; - } - - if (lookbehind) { - lookbehindLength = match[1].length; - } - - var from = match.index + lookbehindLength, - match = match[0].slice(lookbehindLength), - to = from + match.length, - before = str.slice(0, from), - after = str.slice(to); - - var args = [i, delNum]; - - if (before) { - args.push(before); - } - - var wrapped = new Token(token, inside ? _.tokenize(match, inside) : match, alias, match, greedy); - - args.push(wrapped); - - if (after) { - args.push(after); - } - - Array.prototype.splice.apply(strarr, args); - } - } - } - - return strarr; - }, - - hooks: { - all: {}, - - add: function(name, callback) { - var hooks = _.hooks.all; - - hooks[name] = hooks[name] || []; - - hooks[name].push(callback); - }, - - run: function(name, env) { - var callbacks = _.hooks.all[name]; - - if (!callbacks || !callbacks.length) { - return; - } - - for (var i = 0, callback; callback = callbacks[i++];) { - callback(env); - } - } +import './highlight.scss' + +var _self = window + +var Prism = (function() { + // Private helper vars + var lang = /\blang(?:uage)?-(\w+)\b/i + var uniqueId = 0 + + var _ = (_self.Prism = { + manual: _self.Prism && _self.Prism.manual, + util: { + encode: function(tokens) { + if (tokens instanceof Token) { + return new Token( + tokens.type, + _.util.encode(tokens.content), + tokens.alias + ) + } else if (_.util.type(tokens) === 'Array') { + return tokens.map(_.util.encode) + } else { + return tokens + .replace(/&/g, '&') + .replace(/' + env.content + ''; - - }; - - if (!_self.document) { - if (!_self.addEventListener) { - // in Node.js - return _self.Prism; - } - // In worker - _self.addEventListener('message', function(evt) { - var message = JSON.parse(evt.data), - lang = message.language, - code = message.code, - immediateClose = message.immediateClose; - - _self.postMessage(_.highlight(code, _.languages[lang], lang)); - if (immediateClose) { - _self.close(); - } - }, false); - - return _self.Prism; + return clone + case 'Array': + // Check for existence for IE8 + return ( + o.map && + o.map(function(v) { + return _.util.clone(v) + }) + ) } - //Get current script and highlight - var script = document.currentScript || [].slice.call(document.getElementsByTagName("script")).pop(); + return o + } + }, - if (script) { - _.filename = script.src; + languages: { + extend: function(id, redef) { + var lang = _.util.clone(_.languages[id]) - if (document.addEventListener && !_.manual && !script.hasAttribute('data-manual')) { - if (document.readyState !== "loading") { - if (window.requestAnimationFrame) { - window.requestAnimationFrame(_.highlightAll); - } else { - window.setTimeout(_.highlightAll, 16); - } - } else { - document.addEventListener('DOMContentLoaded', _.highlightAll); + for (var key in redef) { + lang[key] = redef[key] + } + + return lang + }, + insertBefore: function(inside, before, insert, root) { + root = root || _.languages + var grammar = root[inside] + + if (arguments.length == 2) { + insert = arguments[1] + + for (var newToken in insert) { + if (insert.hasOwnProperty(newToken)) { + grammar[newToken] = insert[newToken] + } + } + + return grammar + } + + var ret = {} + + for (var token in grammar) { + if (grammar.hasOwnProperty(token)) { + if (token == before) { + for (var newToken in insert) { + if (insert.hasOwnProperty(newToken)) { + ret[newToken] = insert[newToken] } + } } + + ret[token] = grammar[token] + } } - return _self.Prism; + // Update references in other language definitions + _.languages.DFS(_.languages, function(key, value) { + if (value === root[inside] && key != inside) { + this[key] = ret + } + }) - })(); + return (root[inside] = ret) + }, + // Traverse a language definition with Depth First Search + DFS: function(o, callback, type, visited) { + visited = visited || {} + for (var i in o) { + if (o.hasOwnProperty(i)) { + callback.call(o, i, o[i], type || i) - Prism.languages.markup = { - 'smartyx': //, - 'comment': //, - 'prolog': /<\?[\w\W]+?\?>/, - 'doctype': //i, - 'cdata': //i, - 'tag': { - pattern: /<\/?(?!\d)[^\s>\/=$<]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\\1|\\?(?!\1)[\w\W])*\1|[^\s'">=]+))?)*\s*\/?>/i, - inside: { - 'tag': { - pattern: /^<\/?[^\s>\/]+/i, - inside: { - 'punctuation': /^<\/?/, - 'namespace': /^[^\s>\/:]+:/ - } - }, - 'attr-value': { - pattern: /=(?:('|")[\w\W]*?(\1)|[^\s>]+)/i, - inside: { - 'punctuation': /[=>"']/ - } - }, - 'punctuation': /\/?>/, - 'attr-name': { - pattern: /[^\s>\/]+/, - inside: { - 'namespace': /^[^\s>\/:]+:/ - } + if ( + _.util.type(o[i]) === 'Object' && + !visited[_.util.objId(o[i])] + ) { + visited[_.util.objId(o[i])] = true + _.languages.DFS(o[i], callback, null, visited) + } else if ( + _.util.type(o[i]) === 'Array' && + !visited[_.util.objId(o[i])] + ) { + visited[_.util.objId(o[i])] = true + _.languages.DFS(o[i], callback, i, visited) + } + } + } + } + }, + plugins: {}, + + highlightAll: function(async, callback) { + var env = { + callback: callback, + selector: + 'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code' + } + + _.hooks.run('before-highlightall', env) + + var elements = env.elements || document.querySelectorAll(env.selector) + + for (var i = 0, element; (element = elements[i++]); ) { + _.highlightElement(element, async === true, env.callback) + } + }, + + highlightElement: function(element, async, callback) { + // Find language + var language, + grammar, + parent = element + + while (parent && !lang.test(parent.className)) { + parent = parent.parentNode + } + + if (parent) { + language = (parent.className.match(lang) || [, ''])[1].toLowerCase() + grammar = _.languages[language] + } + + // Set language on the element, if not present + element.className = + element.className.replace(lang, '').replace(/\s+/g, ' ') + + ' language-' + + language + + // Set language on the parent, for styling + parent = element.parentNode + + if (/pre/i.test(parent.nodeName)) { + parent.className = + parent.className.replace(lang, '').replace(/\s+/g, ' ') + + ' language-' + + language + } + + var code = element.textContent + + var env = { + element: element, + language: language, + grammar: grammar, + code: code + } + + _.hooks.run('before-sanity-check', env) + + if (!env.code || !env.grammar) { + if (env.code) { + env.element.textContent = env.code + } + _.hooks.run('complete', env) + return + } + + _.hooks.run('before-highlight', env) + + if (async && _self.Worker) { + var worker = new Worker(_.filename) + + worker.onmessage = function(evt) { + env.highlightedCode = evt.data + + _.hooks.run('before-insert', env) + + env.element.innerHTML = env.highlightedCode + + callback && callback.call(env.element) + _.hooks.run('after-highlight', env) + _.hooks.run('complete', env) + } + + worker.postMessage( + JSON.stringify({ + language: env.language, + code: env.code, + immediateClose: true + }) + ) + } else { + env.highlightedCode = _.highlight(env.code, env.grammar, env.language) + + _.hooks.run('before-insert', env) + + env.element.innerHTML = env.highlightedCode + + callback && callback.call(element) + + _.hooks.run('after-highlight', env) + _.hooks.run('complete', env) + } + }, + + highlight: function(text, grammar, language) { + var tokens = _.tokenize(text, grammar || Prism.languages.other) + return Token.stringify(_.util.encode(tokens), language) + }, + + tokenize: function(text, grammar, language) { + var Token = _.Token + + var strarr = [text] + + var rest = grammar.rest + + if (rest) { + for (var token in rest) { + grammar[token] = rest[token] + } + + delete grammar.rest + } + + tokenloop: for (var token in grammar) { + if (!grammar.hasOwnProperty(token) || !grammar[token]) { + continue + } + + var patterns = grammar[token] + patterns = _.util.type(patterns) === 'Array' ? patterns : [patterns] + + for (var j = 0; j < patterns.length; ++j) { + var pattern = patterns[j], + inside = pattern.inside, + lookbehind = !!pattern.lookbehind, + greedy = !!pattern.greedy, + lookbehindLength = 0, + alias = pattern.alias + + if (greedy && !pattern.pattern.global) { + // Without the global flag, lastIndex won't work + var flags = pattern.pattern.toString().match(/[imuy]*$/)[0] + pattern.pattern = RegExp(pattern.pattern.source, flags + 'g') + } + + pattern = pattern.pattern || pattern + + // Don’t cache length as it changes during the loop + for ( + var i = 0, pos = 0; + i < strarr.length; + pos += strarr[i].length, ++i + ) { + var str = strarr[i] + + if (strarr.length > text.length) { + // Something went terribly wrong, ABORT, ABORT! + break tokenloop + } + + if (str instanceof Token) { + continue + } + + pattern.lastIndex = 0 + + var match = pattern.exec(str), + delNum = 1 + + // Greedy patterns can override/remove up to two previously matched tokens + if (!match && greedy && i != strarr.length - 1) { + pattern.lastIndex = pos + match = pattern.exec(text) + if (!match) { + break + } + + var from = match.index + (lookbehind ? match[1].length : 0), + to = match.index + match[0].length, + k = i, + p = pos + + for (var len = strarr.length; k < len && p < to; ++k) { + p += strarr[k].length + // Move the index i to the element in strarr that is closest to from + if (from >= p) { + ++i + pos = p } + } + if (strarr[i] instanceof Token || strarr[k - 1].greedy) { + continue + } + + // Number of tokens to delete and replace with the new match + delNum = k - i + str = text.slice(pos, p) + match.index -= pos } - }, - 'entity': /&#?[\da-z]{1,8};/i - }; - // Plugin to make entity title show the real entity, idea by Roman Komarov - Prism.hooks.add('wrap', function(env) { + if (!match) { + continue + } - if (env.type === 'entity') { - env.attributes['title'] = env.content.replace(/&/, '&'); + if (lookbehind) { + lookbehindLength = match[1].length + } + + var from = match.index + lookbehindLength, + match = match[0].slice(lookbehindLength), + to = from + match.length, + before = str.slice(0, from), + after = str.slice(to) + + var args = [i, delNum] + + if (before) { + args.push(before) + } + + var wrapped = new Token( + token, + inside ? _.tokenize(match, inside) : match, + alias, + match, + greedy + ) + + args.push(wrapped) + + if (after) { + args.push(after) + } + + Array.prototype.splice.apply(strarr, args) + } } - }); + } - Prism.languages.xml = Prism.languages.markup; - Prism.languages.html = Prism.languages.markup; - Prism.languages.mathml = Prism.languages.markup; - Prism.languages.svg = Prism.languages.markup; + return strarr + }, - Prism.languages.css = { - 'comment': /\/\*[\w\W]*?\*\//, - 'atrule': { - pattern: /@[\w-]+?.*?(;|(?=\s*\{))/i, - inside: { - 'rule': /@[\w-]+/ - // See rest below - } - }, - 'url': /url\((?:(["'])(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1|.*?)\)/i, - 'selector': /[^\{\}\s][^\{\};]*?(?=\s*\{)/, - 'string': { - pattern: /("|')(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1/, - greedy: true - }, - 'property': /(\b|\B)[\w-]+(?=\s*:)/i, - 'important': /\B!important\b/i, - 'function': /[-a-z0-9]+(?=\()/i, - 'punctuation': /[(){};:]/ - }; + hooks: { + all: {}, - Prism.languages.css['atrule'].inside.rest = Prism.util.clone(Prism.languages.css); + add: function(name, callback) { + var hooks = _.hooks.all - if (Prism.languages.markup) { - Prism.languages.insertBefore('markup', 'tag', { - 'style': { - pattern: /()[\w\W]*?(?=<\/style>)/i, - lookbehind: true, - inside: Prism.languages.css, - alias: 'language-css' - } - }); + hooks[name] = hooks[name] || [] - Prism.languages.insertBefore('inside', 'attr-value', { - 'style-attr': { - pattern: /\s*style=("|').*?\1/i, - inside: { - 'attr-name': { - pattern: /^\s*style/i, - inside: Prism.languages.markup.tag.inside - }, - 'punctuation': /^\s*=\s*['"]|['"]\s*$/, - 'attr-value': { - pattern: /.+/i, - inside: Prism.languages.css - } - }, - alias: 'language-css' - } - }, Prism.languages.markup.tag); - }; - Prism.languages.clike = { - 'comment': [{ - pattern: /(^|[^\\])\/\*[\w\W]*?\*\//, - lookbehind: true - }, { - pattern: /(^|[^\\:])\/\/.*/, - lookbehind: true - }], - 'string': { - pattern: /(["'])(\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/, - greedy: true - }, - 'class-name': { - pattern: /((?:\b(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/i, - lookbehind: true, - inside: { - punctuation: /(\.|\\)/ - } - }, - 'keyword': /\b(if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/, - 'boolean': /\b(true|false)\b/, - 'function': /[a-z0-9_]+(?=\()/i, - 'number': /\b-?(?:0x[\da-f]+|\d*\.?\d+(?:e[+-]?\d+)?)\b/i, - 'operator': /--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*|\/|~|\^|%/, - 'punctuation': /[{}[\];(),.:]/ - }; + hooks[name].push(callback) + }, - Prism.languages.javascript = Prism.languages.extend('clike', { - 'build-in': /\b(Object|Array|console|Function|String|Global|window|Buffer|Audio|Video|Date|Math|process|EventEmitter|__dirname|__filename|module|export|exports|import|require|Promise)\b/, - 'params': /(\(.*?\)|[A-Za-z$_][0-9A-Za-z$_]*)\s*=>/, - 'keyword': /\b(as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|var|void|while|with|yield)\b/, - 'number': /\b-?(0x[\dA-Fa-f]+|0b[01]+|0o[0-7]+|\d*\.?\d+([Ee][+-]?\d+)?|NaN|Infinity)\b/, - // Allow for all non-ASCII characters (See http://stackoverflow.com/a/2008444) - 'function': /[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*(?=\()/i, - 'operator': /--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*\*?|\/|~|\^|%|\.{3}/, + run: function(name, env) { + var callbacks = _.hooks.all[name] - }); - - Prism.languages.insertBefore('javascript', 'keyword', { - 'regex': { - pattern: /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\\\r\n])+\/[gimyu]{0,5}(?=\s*($|[\r\n,.;})]))/, - lookbehind: true, - greedy: true + if (!callbacks || !callbacks.length) { + return } - }); - Prism.languages.insertBefore('javascript', 'string', { - 'template-string': { - pattern: /`(?:\\\\|\\?[^\\])*?`/, - greedy: true, - inside: { - 'interpolation': { - pattern: /\$\{[^}]+\}/, - inside: { - 'interpolation-punctuation': { - pattern: /^\$\{|\}$/, - alias: 'punctuation' - }, - rest: Prism.languages.javascript - } - }, - 'string': /[\s\S]+/ - } + for (var i = 0, callback; (callback = callbacks[i++]); ) { + callback(env) } - }); + } + } + }) - if (Prism.languages.markup) { - Prism.languages.insertBefore('markup', 'tag', { - 'script': { - pattern: /()[\w\W]*?(?=<\/script>)/i, - lookbehind: true, - inside: Prism.languages.javascript, - alias: 'language-javascript' - } - }); + var Token = (_.Token = function(type, content, alias, matchedStr, greedy) { + this.type = type + this.content = content + this.alias = alias + // Copy of the full string this token was created from + this.length = (matchedStr || '').length | 0 + this.greedy = !!greedy + }) + + Token.stringify = function(o, language, parent) { + if (typeof o == 'string') { + return o } - Prism.languages.js = Prism.languages.javascript; - (function(Prism) { - var insideString = { - variable: [ - // Arithmetic Environment - { - pattern: /\$?\(\([\w\W]+?\)\)/, - inside: { - // If there is a $ sign at the beginning highlight $(( and )) as variable - variable: [{ - pattern: /(^\$\(\([\w\W]+)\)\)/, - lookbehind: true - }, - /^\$\(\(/, - ], - number: /\b-?(?:0x[\dA-Fa-f]+|\d*\.?\d+(?:[Ee]-?\d+)?)\b/, - // Operators according to https://www.gnu.org/software/bash/manual/bashref.html#Shell-Arithmetic - operator: /--?|-=|\+\+?|\+=|!=?|~|\*\*?|\*=|\/=?|%=?|<<=?|>>=?|<=?|>=?|==?|&&?|&=|\^=?|\|\|?|\|=|\?|:/, - // If there is no $ sign at the beginning highlight (( and )) as punctuation - punctuation: /\(\(?|\)\)?|,|;/ - } - }, - // Command Substitution - { - pattern: /\$\([^)]+\)|`[^`]+`/, - inside: { - variable: /^\$\(|^`|\)$|`$/ - } - }, - /\$(?:[a-z0-9_#\?\*!@]+|\{[^}]+\})/i - ], - }; + if (_.util.type(o) === 'Array') { + return o + .map(function(element) { + return Token.stringify(element, language, o) + }) + .join('') + } - Prism.languages.bash = { - 'important': { - pattern: /^#!\s*\/bin\/bash|^#!\s*\/bin\/sh/ - }, - 'comment': { - pattern: /(^|[^"{\\])#.*/, - lookbehind: true - }, - 'string': [ - //Support for Here-Documents https://en.wikipedia.org/wiki/Here_document - { - pattern: /((?:^|[^<])<<\s*)(?:"|')?(\w+?)(?:"|')?\s*\r?\n(?:[\s\S])*?\r?\n\2/g, - lookbehind: true, - greedy: true, - inside: insideString - }, { - pattern: /(["'])(?:\\\\|\\?[^\\])*?\1/g, - greedy: true, - inside: insideString - } - ], - 'variable': insideString.variable, - // Originally based on http://ss64.com/bash/ - 'function': { - pattern: /(^|\s|;|\||&)(?:alias|apropos|apt-get|aptitude|aspell|awk|basename|bash|bc|bg|builtin|bzip2|cal|cat|cd|cfdisk|chgrp|chmod|chown|chroot|chkconfig|cksum|clear|cmp|comm|command|cp|cron|crontab|csplit|cut|date|dc|dd|ddrescue|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|du|egrep|eject|enable|env|ethtool|eval|exec|expand|expect|export|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|getopts|git|grep|groupadd|groupdel|groupmod|groups|gzip|hash|head|help|hg|history|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|jobs|join|kill|killall|less|link|ln|locate|logname|logout|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|make|man|mkdir|mkfifo|mkisofs|mknod|more|most|mount|mtools|mtr|mv|mmv|nano|netstat|nice|nl|nohup|notify-send|npm|nslookup|open|op|passwd|paste|pathchk|ping|pkill|popd|pr|printcap|printenv|printf|ps|pushd|pv|pwd|quota|quotacheck|quotactl|ram|rar|rcp|read|readarray|readonly|reboot|rename|renice|remsync|rev|rm|rmdir|rsync|screen|scp|sdiff|sed|seq|service|sftp|shift|shopt|shutdown|sleep|slocate|sort|source|split|ssh|stat|strace|su|sudo|sum|suspend|sync|tail|tar|tee|test|time|timeout|times|touch|top|traceroute|trap|tr|tsort|tty|type|ulimit|umask|umount|unalias|uname|unexpand|uniq|units|unrar|unshar|uptime|useradd|userdel|usermod|users|uuencode|uudecode|v|vdir|vi|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yes|zip)(?=$|\s|;|\||&)/, - lookbehind: true - }, - 'keyword': { - pattern: /(^|\s|;|\||&)(?:let|:|\.|if|then|else|elif|fi|for|break|continue|while|in|case|function|select|do|done|until|echo|exit|return|set|declare)(?=$|\s|;|\||&)/, - lookbehind: true - }, - 'boolean': { - pattern: /(^|\s|;|\||&)(?:true|false)(?=$|\s|;|\||&)/, - lookbehind: true - }, - 'operator': /&&?|\|\|?|==?|!=?|<<>|<=?|>=?|=~/, - 'punctuation': /\$?\(\(?|\)\)?|\.\.|[{}[\];]/ - }; + var env = { + type: o.type, + content: Token.stringify(o.content, language, parent), + tag: 'span', + classes: ['c-' + o.type], + attributes: {}, + language: language, + parent: parent + } - var inside = insideString.variable[1].inside; - inside['function'] = Prism.languages.bash['function']; - inside.keyword = Prism.languages.bash.keyword; - inside.boolean = Prism.languages.bash.boolean; - inside.operator = Prism.languages.bash.operator; - inside.punctuation = Prism.languages.bash.punctuation; - })(Prism); + if (o.alias) { + var aliases = _.util.type(o.alias) === 'Array' ? o.alias : [o.alias] + Array.prototype.push.apply(env.classes, aliases) + } - Prism.languages.nginx = Prism.languages.extend('clike', { - 'comment': { - pattern: /(^|[^"{\\])#.*/, - lookbehind: true - }, - 'keyword': /\b(?:CONTENT_|DOCUMENT_|GATEWAY_|HTTP_|HTTPS|if_not_empty|PATH_|QUERY_|REDIRECT_|REMOTE_|REQUEST_|SCGI|SCRIPT_|SERVER_|http|server|events|location|include|accept_mutex|accept_mutex_delay|access_log|add_after_body|add_before_body|add_header|addition_types|aio|alias|allow|ancient_browser|ancient_browser_value|auth|auth_basic|auth_basic_user_file|auth_http|auth_http_header|auth_http_timeout|autoindex|autoindex_exact_size|autoindex_localtime|break|charset|charset_map|charset_types|chunked_transfer_encoding|client_body_buffer_size|client_body_in_file_only|client_body_in_single_buffer|client_body_temp_path|client_body_timeout|client_header_buffer_size|client_header_timeout|client_max_body_size|connection_pool_size|create_full_put_path|daemon|dav_access|dav_methods|debug_connection|debug_points|default_type|deny|devpoll_changes|devpoll_events|directio|directio_alignment|disable_symlinks|empty_gif|env|epoll_events|error_log|error_page|expires|fastcgi_buffer_size|fastcgi_buffers|fastcgi_busy_buffers_size|fastcgi_cache|fastcgi_cache_bypass|fastcgi_cache_key|fastcgi_cache_lock|fastcgi_cache_lock_timeout|fastcgi_cache_methods|fastcgi_cache_min_uses|fastcgi_cache_path|fastcgi_cache_purge|fastcgi_cache_use_stale|fastcgi_cache_valid|fastcgi_connect_timeout|fastcgi_hide_header|fastcgi_ignore_client_abort|fastcgi_ignore_headers|fastcgi_index|fastcgi_intercept_errors|fastcgi_keep_conn|fastcgi_max_temp_file_size|fastcgi_next_upstream|fastcgi_no_cache|fastcgi_param|fastcgi_pass|fastcgi_pass_header|fastcgi_read_timeout|fastcgi_redirect_errors|fastcgi_send_timeout|fastcgi_split_path_info|fastcgi_store|fastcgi_store_access|fastcgi_temp_file_write_size|fastcgi_temp_path|flv|geo|geoip_city|geoip_country|google_perftools_profiles|gzip|gzip_buffers|gzip_comp_level|gzip_disable|gzip_http_version|gzip_min_length|gzip_proxied|gzip_static|gzip_types|gzip_vary|if|if_modified_since|ignore_invalid_headers|image_filter|image_filter_buffer|image_filter_jpeg_quality|image_filter_sharpen|image_filter_transparency|imap_capabilities|imap_client_buffer|include|index|internal|ip_hash|keepalive|keepalive_disable|keepalive_requests|keepalive_timeout|kqueue_changes|kqueue_events|large_client_header_buffers|limit_conn|limit_conn_log_level|limit_conn_zone|limit_except|limit_rate|limit_rate_after|limit_req|limit_req_log_level|limit_req_zone|limit_zone|lingering_close|lingering_time|lingering_timeout|listen|location|lock_file|log_format|log_format_combined|log_not_found|log_subrequest|map|map_hash_bucket_size|map_hash_max_size|master_process|max_ranges|memcached_buffer_size|memcached_connect_timeout|memcached_next_upstream|memcached_pass|memcached_read_timeout|memcached_send_timeout|merge_slashes|min_delete_depth|modern_browser|modern_browser_value|mp4|mp4_buffer_size|mp4_max_buffer_size|msie_padding|msie_refresh|multi_accept|open_file_cache|open_file_cache_errors|open_file_cache_min_uses|open_file_cache_valid|open_log_file_cache|optimize_server_names|override_charset|pcre_jit|perl|perl_modules|perl_require|perl_set|pid|pop3_auth|pop3_capabilities|port_in_redirect|post_action|postpone_output|protocol|proxy|proxy_buffer|proxy_buffer_size|proxy_buffering|proxy_buffers|proxy_busy_buffers_size|proxy_cache|proxy_cache_bypass|proxy_cache_key|proxy_cache_lock|proxy_cache_lock_timeout|proxy_cache_methods|proxy_cache_min_uses|proxy_cache_path|proxy_cache_use_stale|proxy_cache_valid|proxy_connect_timeout|proxy_cookie_domain|proxy_cookie_path|proxy_headers_hash_bucket_size|proxy_headers_hash_max_size|proxy_hide_header|proxy_http_version|proxy_ignore_client_abort|proxy_ignore_headers|proxy_intercept_errors|proxy_max_temp_file_size|proxy_method|proxy_next_upstream|proxy_no_cache|proxy_pass|proxy_pass_error_message|proxy_pass_header|proxy_pass_request_body|proxy_pass_request_headers|proxy_read_timeout|proxy_redirect|proxy_redirect_errors|proxy_send_lowat|proxy_send_timeout|proxy_set_body|proxy_set_header|proxy_ssl_session_reuse|proxy_store|proxy_store_access|proxy_temp_file_write_size|proxy_temp_path|proxy_timeout|proxy_upstream_fail_timeout|proxy_upstream_max_fails|random_index|read_ahead|real_ip_header|recursive_error_pages|request_pool_size|reset_timedout_connection|resolver|resolver_timeout|return|rewrite|root|rtsig_overflow_events|rtsig_overflow_test|rtsig_overflow_threshold|rtsig_signo|satisfy|satisfy_any|secure_link_secret|send_lowat|send_timeout|sendfile|sendfile_max_chunk|server|server_name|server_name_in_redirect|server_names_hash_bucket_size|server_names_hash_max_size|server_tokens|set|set_real_ip_from|smtp_auth|smtp_capabilities|so_keepalive|source_charset|split_clients|ssi|ssi_silent_errors|ssi_types|ssi_value_length|ssl|ssl_certificate|ssl_certificate_key|ssl_ciphers|ssl_client_certificate|ssl_crl|ssl_dhparam|ssl_engine|ssl_prefer_server_ciphers|ssl_protocols|ssl_session_cache|ssl_session_timeout|ssl_verify_client|ssl_verify_depth|starttls|stub_status|sub_filter|sub_filter_once|sub_filter_types|tcp_nodelay|tcp_nopush|timeout|timer_resolution|try_files|types|types_hash_bucket_size|types_hash_max_size|underscores_in_headers|uninitialized_variable_warn|upstream|use|user|userid|userid_domain|userid_expires|userid_name|userid_p3p|userid_path|userid_service|valid_referers|variables_hash_bucket_size|variables_hash_max_size|worker_connections|worker_cpu_affinity|worker_priority|worker_processes|worker_rlimit_core|worker_rlimit_nofile|worker_rlimit_sigpending|working_directory|xclient|xml_entities|xslt_entities|xslt_stylesheet|xslt_types)\b/i, - }); + _.hooks.run('wrap', env) - Prism.languages.insertBefore('nginx', 'keyword', { - 'variable': /\$[a-z_]+/i - }); - Prism.languages.yaml = { - 'scalar': { - pattern: /([\-:]\s*(![^\s]+)?[ \t]*[|>])[ \t]*(?:((?:\r?\n|\r)[ \t]+)[^\r\n]+(?:\3[^\r\n]+)*)/, - lookbehind: true, - alias: 'string' - }, - 'comment': /#.*/, - 'key': { - pattern: /(\s*(?:^|[:\-,[{\r\n?])[ \t]*(![^\s]+)?[ \t]*)[^\r\n{[\]},#\s]+?(?=\s*:\s)/, - lookbehind: true, - alias: 'atrule' - }, - 'directive': { - pattern: /(^[ \t]*)%.+/m, - lookbehind: true, - alias: 'important' - }, - 'datetime': { - pattern: /([:\-,[{]\s*(![^\s]+)?[ \t]*)(\d{4}-\d\d?-\d\d?([tT]|[ \t]+)\d\d?:\d{2}:\d{2}(\.\d*)?[ \t]*(Z|[-+]\d\d?(:\d{2})?)?|\d{4}-\d{2}-\d{2}|\d\d?:\d{2}(:\d{2}(\.\d*)?)?)(?=[ \t]*($|,|]|}))/m, - lookbehind: true, - alias: 'number' - }, - 'boolean': { - pattern: /([:\-,[{]\s*(![^\s]+)?[ \t]*)(true|false)[ \t]*(?=$|,|]|})/im, - lookbehind: true, - alias: 'important' - }, - 'null': { - pattern: /([:\-,[{]\s*(![^\s]+)?[ \t]*)(null|~)[ \t]*(?=$|,|]|})/im, - lookbehind: true, - alias: 'important' - }, - 'string': { - pattern: /([:\-,[{]\s*(![^\s]+)?[ \t]*)("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')(?=[ \t]*($|,|]|}))/m, - lookbehind: true, - greedy: true - }, - 'number': { - pattern: /([:\-,[{]\s*(![^\s]+)?[ \t]*)[+\-]?(0x[\da-f]+|0o[0-7]+|(\d+\.?\d*|\.?\d+)(e[\+\-]?\d+)?|\.inf|\.nan)[ \t]*(?=$|,|]|})/im, - lookbehind: true - }, - 'tag': /![^\s]+/, - 'important': /[&*][\w]+/, - 'punctuation': /---|[:[\]{}\-,|>?]|\.\.\./ - }; - Prism.languages.other = {} + var attributes = Object.keys(env.attributes) + .map(function(name) { + return ( + name + + '="' + + (env.attributes[name] || '').replace(/"/g, '"') + + '"' + ) + }) + .join(' ') - window.Prism = Prism - return Prism -}) \ No newline at end of file + return ( + '<' + + env.tag + + ' class="' + + env.classes.join(' ') + + '"' + + (attributes ? ' ' + attributes : '') + + '>' + + env.content + + '' + ) + } + + if (!_self.document) { + if (!_self.addEventListener) { + // in Node.js + return _self.Prism + } + // In worker + _self.addEventListener( + 'message', + function(evt) { + var message = JSON.parse(evt.data), + lang = message.language, + code = message.code, + immediateClose = message.immediateClose + + _self.postMessage(_.highlight(code, _.languages[lang], lang)) + if (immediateClose) { + _self.close() + } + }, + false + ) + + return _self.Prism + } + + //Get current script and highlight + var script = + document.currentScript || + [].slice.call(document.getElementsByTagName('script')).pop() + + if (script) { + _.filename = script.src + + if ( + document.addEventListener && + !_.manual && + !script.hasAttribute('data-manual') + ) { + if (document.readyState !== 'loading') { + if (window.requestAnimationFrame) { + window.requestAnimationFrame(_.highlightAll) + } else { + window.setTimeout(_.highlightAll, 16) + } + } else { + document.addEventListener('DOMContentLoaded', _.highlightAll) + } + } + } + + return _self.Prism +})() + +Prism.languages.markup = { + smartyx: //, + comment: //, + prolog: /<\?[\w\W]+?\?>/, + doctype: //i, + cdata: //i, + tag: { + pattern: /<\/?(?!\d)[^\s>\/=$<]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\\1|\\?(?!\1)[\w\W])*\1|[^\s'">=]+))?)*\s*\/?>/i, + inside: { + tag: { + pattern: /^<\/?[^\s>\/]+/i, + inside: { + punctuation: /^<\/?/, + namespace: /^[^\s>\/:]+:/ + } + }, + 'attr-value': { + pattern: /=(?:('|")[\w\W]*?(\1)|[^\s>]+)/i, + inside: { + punctuation: /[=>"']/ + } + }, + punctuation: /\/?>/, + 'attr-name': { + pattern: /[^\s>\/]+/, + inside: { + namespace: /^[^\s>\/:]+:/ + } + } + } + }, + entity: /&#?[\da-z]{1,8};/i +} + +// Plugin to make entity title show the real entity, idea by Roman Komarov +Prism.hooks.add('wrap', function(env) { + if (env.type === 'entity') { + env.attributes['title'] = env.content.replace(/&/, '&') + } +}) + +Prism.languages.xml = Prism.languages.markup +Prism.languages.html = Prism.languages.markup +Prism.languages.mathml = Prism.languages.markup +Prism.languages.svg = Prism.languages.markup + +Prism.languages.css = { + comment: /\/\*[\w\W]*?\*\//, + atrule: { + pattern: /@[\w-]+?.*?(;|(?=\s*\{))/i, + inside: { + rule: /@[\w-]+/ + // See rest below + } + }, + url: /url\((?:(["'])(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1|.*?)\)/i, + selector: /[^\{\}\s][^\{\};]*?(?=\s*\{)/, + string: { + pattern: /("|')(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1/, + greedy: true + }, + property: /(\b|\B)[\w-]+(?=\s*:)/i, + important: /\B!important\b/i, + function: /[-a-z0-9]+(?=\()/i, + punctuation: /[(){};:]/ +} + +Prism.languages.css['atrule'].inside.rest = Prism.util.clone( + Prism.languages.css +) + +if (Prism.languages.markup) { + Prism.languages.insertBefore('markup', 'tag', { + style: { + pattern: /()[\w\W]*?(?=<\/style>)/i, + lookbehind: true, + inside: Prism.languages.css, + alias: 'language-css' + } + }) + + Prism.languages.insertBefore( + 'inside', + 'attr-value', + { + 'style-attr': { + pattern: /\s*style=("|').*?\1/i, + inside: { + 'attr-name': { + pattern: /^\s*style/i, + inside: Prism.languages.markup.tag.inside + }, + punctuation: /^\s*=\s*['"]|['"]\s*$/, + 'attr-value': { + pattern: /.+/i, + inside: Prism.languages.css + } + }, + alias: 'language-css' + } + }, + Prism.languages.markup.tag + ) +} +Prism.languages.clike = { + comment: [ + { + pattern: /(^|[^\\])\/\*[\w\W]*?\*\//, + lookbehind: true + }, + { + pattern: /(^|[^\\:])\/\/.*/, + lookbehind: true + } + ], + string: { + pattern: /(["'])(\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/, + greedy: true + }, + 'class-name': { + pattern: /((?:\b(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/i, + lookbehind: true, + inside: { + punctuation: /(\.|\\)/ + } + }, + keyword: /\b(if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/, + boolean: /\b(true|false)\b/, + function: /[a-z0-9_]+(?=\()/i, + number: /\b-?(?:0x[\da-f]+|\d*\.?\d+(?:e[+-]?\d+)?)\b/i, + operator: /--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*|\/|~|\^|%/, + punctuation: /[{}[\];(),.:]/ +} + +Prism.languages.javascript = Prism.languages.extend('clike', { + 'build-in': /\b(Object|Array|console|Function|String|Global|window|Buffer|Audio|Video|Date|Math|process|EventEmitter|__dirname|__filename|module|export|exports|import|require|Promise)\b/, + params: /(\(.*?\)|[A-Za-z$_][0-9A-Za-z$_]*)\s*=>/, + keyword: /\b(as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|var|void|while|with|yield)\b/, + number: /\b-?(0x[\dA-Fa-f]+|0b[01]+|0o[0-7]+|\d*\.?\d+([Ee][+-]?\d+)?|NaN|Infinity)\b/, + // Allow for all non-ASCII characters (See http://stackoverflow.com/a/2008444) + function: /[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*(?=\()/i, + operator: /--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*\*?|\/|~|\^|%|\.{3}/ +}) + +Prism.languages.insertBefore('javascript', 'keyword', { + regex: { + pattern: /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\\\r\n])+\/[gimyu]{0,5}(?=\s*($|[\r\n,.;})]))/, + lookbehind: true, + greedy: true + } +}) + +Prism.languages.insertBefore('javascript', 'string', { + 'template-string': { + pattern: /`(?:\\\\|\\?[^\\])*?`/, + greedy: true, + inside: { + interpolation: { + pattern: /\$\{[^}]+\}/, + inside: { + 'interpolation-punctuation': { + pattern: /^\$\{|\}$/, + alias: 'punctuation' + }, + rest: Prism.languages.javascript + } + }, + string: /[\s\S]+/ + } + } +}) + +if (Prism.languages.markup) { + Prism.languages.insertBefore('markup', 'tag', { + script: { + pattern: /()[\w\W]*?(?=<\/script>)/i, + lookbehind: true, + inside: Prism.languages.javascript, + alias: 'language-javascript' + } + }) +} + +Prism.languages.js = Prism.languages.javascript +;(function(Prism) { + var insideString = { + variable: [ + // Arithmetic Environment + { + pattern: /\$?\(\([\w\W]+?\)\)/, + inside: { + // If there is a $ sign at the beginning highlight $(( and )) as variable + variable: [ + { + pattern: /(^\$\(\([\w\W]+)\)\)/, + lookbehind: true + }, + /^\$\(\(/ + ], + number: /\b-?(?:0x[\dA-Fa-f]+|\d*\.?\d+(?:[Ee]-?\d+)?)\b/, + // Operators according to https://www.gnu.org/software/bash/manual/bashref.html#Shell-Arithmetic + operator: /--?|-=|\+\+?|\+=|!=?|~|\*\*?|\*=|\/=?|%=?|<<=?|>>=?|<=?|>=?|==?|&&?|&=|\^=?|\|\|?|\|=|\?|:/, + // If there is no $ sign at the beginning highlight (( and )) as punctuation + punctuation: /\(\(?|\)\)?|,|;/ + } + }, + // Command Substitution + { + pattern: /\$\([^)]+\)|`[^`]+`/, + inside: { + variable: /^\$\(|^`|\)$|`$/ + } + }, + /\$(?:[a-z0-9_#\?\*!@]+|\{[^}]+\})/i + ] + } + + Prism.languages.bash = { + important: { + pattern: /^#!\s*\/bin\/bash|^#!\s*\/bin\/sh/ + }, + comment: { + pattern: /(^|[^"{\\])#.*/, + lookbehind: true + }, + string: [ + //Support for Here-Documents https://en.wikipedia.org/wiki/Here_document + { + pattern: /((?:^|[^<])<<\s*)(?:"|')?(\w+?)(?:"|')?\s*\r?\n(?:[\s\S])*?\r?\n\2/g, + lookbehind: true, + greedy: true, + inside: insideString + }, + { + pattern: /(["'])(?:\\\\|\\?[^\\])*?\1/g, + greedy: true, + inside: insideString + } + ], + variable: insideString.variable, + // Originally based on http://ss64.com/bash/ + function: { + pattern: /(^|\s|;|\||&)(?:alias|apropos|apt-get|aptitude|aspell|awk|basename|bash|bc|bg|builtin|bzip2|cal|cat|cd|cfdisk|chgrp|chmod|chown|chroot|chkconfig|cksum|clear|cmp|comm|command|cp|cron|crontab|csplit|cut|date|dc|dd|ddrescue|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|du|egrep|eject|enable|env|ethtool|eval|exec|expand|expect|export|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|getopts|git|grep|groupadd|groupdel|groupmod|groups|gzip|hash|head|help|hg|history|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|jobs|join|kill|killall|less|link|ln|locate|logname|logout|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|make|man|mkdir|mkfifo|mkisofs|mknod|more|most|mount|mtools|mtr|mv|mmv|nano|netstat|nice|nl|nohup|notify-send|npm|nslookup|open|op|passwd|paste|pathchk|ping|pkill|popd|pr|printcap|printenv|printf|ps|pushd|pv|pwd|quota|quotacheck|quotactl|ram|rar|rcp|read|readarray|readonly|reboot|rename|renice|remsync|rev|rm|rmdir|rsync|screen|scp|sdiff|sed|seq|service|sftp|shift|shopt|shutdown|sleep|slocate|sort|source|split|ssh|stat|strace|su|sudo|sum|suspend|sync|tail|tar|tee|test|time|timeout|times|touch|top|traceroute|trap|tr|tsort|tty|type|ulimit|umask|umount|unalias|uname|unexpand|uniq|units|unrar|unshar|uptime|useradd|userdel|usermod|users|uuencode|uudecode|v|vdir|vi|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yes|zip)(?=$|\s|;|\||&)/, + lookbehind: true + }, + keyword: { + pattern: /(^|\s|;|\||&)(?:let|:|\.|if|then|else|elif|fi|for|break|continue|while|in|case|function|select|do|done|until|echo|exit|return|set|declare)(?=$|\s|;|\||&)/, + lookbehind: true + }, + boolean: { + pattern: /(^|\s|;|\||&)(?:true|false)(?=$|\s|;|\||&)/, + lookbehind: true + }, + operator: /&&?|\|\|?|==?|!=?|<<>|<=?|>=?|=~/, + punctuation: /\$?\(\(?|\)\)?|\.\.|[{}[\];]/ + } + + var inside = insideString.variable[1].inside + inside['function'] = Prism.languages.bash['function'] + inside.keyword = Prism.languages.bash.keyword + inside.boolean = Prism.languages.bash.boolean + inside.operator = Prism.languages.bash.operator + inside.punctuation = Prism.languages.bash.punctuation +})(Prism) + +Prism.languages.nginx = Prism.languages.extend('clike', { + comment: { + pattern: /(^|[^"{\\])#.*/, + lookbehind: true + }, + keyword: /\b(?:CONTENT_|DOCUMENT_|GATEWAY_|HTTP_|HTTPS|if_not_empty|PATH_|QUERY_|REDIRECT_|REMOTE_|REQUEST_|SCGI|SCRIPT_|SERVER_|http|server|events|location|include|accept_mutex|accept_mutex_delay|access_log|add_after_body|add_before_body|add_header|addition_types|aio|alias|allow|ancient_browser|ancient_browser_value|auth|auth_basic|auth_basic_user_file|auth_http|auth_http_header|auth_http_timeout|autoindex|autoindex_exact_size|autoindex_localtime|break|charset|charset_map|charset_types|chunked_transfer_encoding|client_body_buffer_size|client_body_in_file_only|client_body_in_single_buffer|client_body_temp_path|client_body_timeout|client_header_buffer_size|client_header_timeout|client_max_body_size|connection_pool_size|create_full_put_path|daemon|dav_access|dav_methods|debug_connection|debug_points|default_type|deny|devpoll_changes|devpoll_events|directio|directio_alignment|disable_symlinks|empty_gif|env|epoll_events|error_log|error_page|expires|fastcgi_buffer_size|fastcgi_buffers|fastcgi_busy_buffers_size|fastcgi_cache|fastcgi_cache_bypass|fastcgi_cache_key|fastcgi_cache_lock|fastcgi_cache_lock_timeout|fastcgi_cache_methods|fastcgi_cache_min_uses|fastcgi_cache_path|fastcgi_cache_purge|fastcgi_cache_use_stale|fastcgi_cache_valid|fastcgi_connect_timeout|fastcgi_hide_header|fastcgi_ignore_client_abort|fastcgi_ignore_headers|fastcgi_index|fastcgi_intercept_errors|fastcgi_keep_conn|fastcgi_max_temp_file_size|fastcgi_next_upstream|fastcgi_no_cache|fastcgi_param|fastcgi_pass|fastcgi_pass_header|fastcgi_read_timeout|fastcgi_redirect_errors|fastcgi_send_timeout|fastcgi_split_path_info|fastcgi_store|fastcgi_store_access|fastcgi_temp_file_write_size|fastcgi_temp_path|flv|geo|geoip_city|geoip_country|google_perftools_profiles|gzip|gzip_buffers|gzip_comp_level|gzip_disable|gzip_http_version|gzip_min_length|gzip_proxied|gzip_static|gzip_types|gzip_vary|if|if_modified_since|ignore_invalid_headers|image_filter|image_filter_buffer|image_filter_jpeg_quality|image_filter_sharpen|image_filter_transparency|imap_capabilities|imap_client_buffer|include|index|internal|ip_hash|keepalive|keepalive_disable|keepalive_requests|keepalive_timeout|kqueue_changes|kqueue_events|large_client_header_buffers|limit_conn|limit_conn_log_level|limit_conn_zone|limit_except|limit_rate|limit_rate_after|limit_req|limit_req_log_level|limit_req_zone|limit_zone|lingering_close|lingering_time|lingering_timeout|listen|location|lock_file|log_format|log_format_combined|log_not_found|log_subrequest|map|map_hash_bucket_size|map_hash_max_size|master_process|max_ranges|memcached_buffer_size|memcached_connect_timeout|memcached_next_upstream|memcached_pass|memcached_read_timeout|memcached_send_timeout|merge_slashes|min_delete_depth|modern_browser|modern_browser_value|mp4|mp4_buffer_size|mp4_max_buffer_size|msie_padding|msie_refresh|multi_accept|open_file_cache|open_file_cache_errors|open_file_cache_min_uses|open_file_cache_valid|open_log_file_cache|optimize_server_names|override_charset|pcre_jit|perl|perl_modules|perl_require|perl_set|pid|pop3_auth|pop3_capabilities|port_in_redirect|post_action|postpone_output|protocol|proxy|proxy_buffer|proxy_buffer_size|proxy_buffering|proxy_buffers|proxy_busy_buffers_size|proxy_cache|proxy_cache_bypass|proxy_cache_key|proxy_cache_lock|proxy_cache_lock_timeout|proxy_cache_methods|proxy_cache_min_uses|proxy_cache_path|proxy_cache_use_stale|proxy_cache_valid|proxy_connect_timeout|proxy_cookie_domain|proxy_cookie_path|proxy_headers_hash_bucket_size|proxy_headers_hash_max_size|proxy_hide_header|proxy_http_version|proxy_ignore_client_abort|proxy_ignore_headers|proxy_intercept_errors|proxy_max_temp_file_size|proxy_method|proxy_next_upstream|proxy_no_cache|proxy_pass|proxy_pass_error_message|proxy_pass_header|proxy_pass_request_body|proxy_pass_request_headers|proxy_read_timeout|proxy_redirect|proxy_redirect_errors|proxy_send_lowat|proxy_send_timeout|proxy_set_body|proxy_set_header|proxy_ssl_session_reuse|proxy_store|proxy_store_access|proxy_temp_file_write_size|proxy_temp_path|proxy_timeout|proxy_upstream_fail_timeout|proxy_upstream_max_fails|random_index|read_ahead|real_ip_header|recursive_error_pages|request_pool_size|reset_timedout_connection|resolver|resolver_timeout|return|rewrite|root|rtsig_overflow_events|rtsig_overflow_test|rtsig_overflow_threshold|rtsig_signo|satisfy|satisfy_any|secure_link_secret|send_lowat|send_timeout|sendfile|sendfile_max_chunk|server|server_name|server_name_in_redirect|server_names_hash_bucket_size|server_names_hash_max_size|server_tokens|set|set_real_ip_from|smtp_auth|smtp_capabilities|so_keepalive|source_charset|split_clients|ssi|ssi_silent_errors|ssi_types|ssi_value_length|ssl|ssl_certificate|ssl_certificate_key|ssl_ciphers|ssl_client_certificate|ssl_crl|ssl_dhparam|ssl_engine|ssl_prefer_server_ciphers|ssl_protocols|ssl_session_cache|ssl_session_timeout|ssl_verify_client|ssl_verify_depth|starttls|stub_status|sub_filter|sub_filter_once|sub_filter_types|tcp_nodelay|tcp_nopush|timeout|timer_resolution|try_files|types|types_hash_bucket_size|types_hash_max_size|underscores_in_headers|uninitialized_variable_warn|upstream|use|user|userid|userid_domain|userid_expires|userid_name|userid_p3p|userid_path|userid_service|valid_referers|variables_hash_bucket_size|variables_hash_max_size|worker_connections|worker_cpu_affinity|worker_priority|worker_processes|worker_rlimit_core|worker_rlimit_nofile|worker_rlimit_sigpending|working_directory|xclient|xml_entities|xslt_entities|xslt_stylesheet|xslt_types)\b/i +}) + +Prism.languages.insertBefore('nginx', 'keyword', { + variable: /\$[a-z_]+/i +}) +Prism.languages.yaml = { + scalar: { + pattern: /([\-:]\s*(![^\s]+)?[ \t]*[|>])[ \t]*(?:((?:\r?\n|\r)[ \t]+)[^\r\n]+(?:\3[^\r\n]+)*)/, + lookbehind: true, + alias: 'string' + }, + comment: /#.*/, + key: { + pattern: /(\s*(?:^|[:\-,[{\r\n?])[ \t]*(![^\s]+)?[ \t]*)[^\r\n{[\]},#\s]+?(?=\s*:\s)/, + lookbehind: true, + alias: 'atrule' + }, + directive: { + pattern: /(^[ \t]*)%.+/m, + lookbehind: true, + alias: 'important' + }, + datetime: { + pattern: /([:\-,[{]\s*(![^\s]+)?[ \t]*)(\d{4}-\d\d?-\d\d?([tT]|[ \t]+)\d\d?:\d{2}:\d{2}(\.\d*)?[ \t]*(Z|[-+]\d\d?(:\d{2})?)?|\d{4}-\d{2}-\d{2}|\d\d?:\d{2}(:\d{2}(\.\d*)?)?)(?=[ \t]*($|,|]|}))/m, + lookbehind: true, + alias: 'number' + }, + boolean: { + pattern: /([:\-,[{]\s*(![^\s]+)?[ \t]*)(true|false)[ \t]*(?=$|,|]|})/im, + lookbehind: true, + alias: 'important' + }, + null: { + pattern: /([:\-,[{]\s*(![^\s]+)?[ \t]*)(null|~)[ \t]*(?=$|,|]|})/im, + lookbehind: true, + alias: 'important' + }, + string: { + pattern: /([:\-,[{]\s*(![^\s]+)?[ \t]*)("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')(?=[ \t]*($|,|]|}))/m, + lookbehind: true, + greedy: true + }, + number: { + pattern: /([:\-,[{]\s*(![^\s]+)?[ \t]*)[+\-]?(0x[\da-f]+|0o[0-7]+|(\d+\.?\d*|\.?\d+)(e[\+\-]?\d+)?|\.inf|\.nan)[ \t]*(?=$|,|]|})/im, + lookbehind: true + }, + tag: /![^\s]+/, + important: /[&*][\w]+/, + punctuation: /---|[:[\]{}\-,|>?]|\.\.\./ +} +Prism.languages.other = {} + +window.Prism = Prism +export default Prism diff --git a/src/js/prism/full.js b/src/js/prism/full.js deleted file mode 100644 index 9f5c80f..0000000 --- a/src/js/prism/full.js +++ /dev/null @@ -1,1889 +0,0 @@ -/** - * - * @authors yutent (yutent@doui.cc) - * @date 2017-08-02 21:50:34 - * @version $Id$ - */ - -define(['./base', 'css!./highlight'], function(Prism) { - - Prism.languages.actionscript = Prism.languages.extend('javascript', { - 'keyword': /\b(?:as|break|case|catch|class|const|default|delete|do|else|extends|finally|for|function|if|implements|import|in|instanceof|interface|internal|is|native|new|null|package|private|protected|public|return|super|switch|this|throw|try|typeof|use|var|void|while|with|dynamic|each|final|get|include|namespace|native|override|set|static)\b/, - 'operator': /\+\+|--|(?:[+\-*\/%^]|&&?|\|\|?|<>?>?|[!=]=?)=?|[~?@]/ - }); - Prism.languages.actionscript['class-name'].alias = 'function'; - - if (Prism.languages.markup) { - Prism.languages.insertBefore('actionscript', 'string', { - 'xml': { - pattern: /(^|[^.])<\/?\w+(?:\s+[^\s>\/=]+=("|')(?:\\\1|\\?(?!\1)[\s\S])*\2)*\s*\/?>/, - lookbehind: true, - inside: { - rest: Prism.languages.markup - } - } - }); - }; - - /*--------------------------------------------------------*/ - - Prism.languages.apacheconf = { - 'comment': /#.*/, - 'directive-inline': { - pattern: /^(\s*)\b(AcceptFilter|AcceptPathInfo|AccessFileName|Action|AddAlt|AddAltByEncoding|AddAltByType|AddCharset|AddDefaultCharset|AddDescription|AddEncoding|AddHandler|AddIcon|AddIconByEncoding|AddIconByType|AddInputFilter|AddLanguage|AddModuleInfo|AddOutputFilter|AddOutputFilterByType|AddType|Alias|AliasMatch|Allow|AllowCONNECT|AllowEncodedSlashes|AllowMethods|AllowOverride|AllowOverrideList|Anonymous|Anonymous_LogEmail|Anonymous_MustGiveEmail|Anonymous_NoUserID|Anonymous_VerifyEmail|AsyncRequestWorkerFactor|AuthBasicAuthoritative|AuthBasicFake|AuthBasicProvider|AuthBasicUseDigestAlgorithm|AuthDBDUserPWQuery|AuthDBDUserRealmQuery|AuthDBMGroupFile|AuthDBMType|AuthDBMUserFile|AuthDigestAlgorithm|AuthDigestDomain|AuthDigestNonceLifetime|AuthDigestProvider|AuthDigestQop|AuthDigestShmemSize|AuthFormAuthoritative|AuthFormBody|AuthFormDisableNoStore|AuthFormFakeBasicAuth|AuthFormLocation|AuthFormLoginRequiredLocation|AuthFormLoginSuccessLocation|AuthFormLogoutLocation|AuthFormMethod|AuthFormMimetype|AuthFormPassword|AuthFormProvider|AuthFormSitePassphrase|AuthFormSize|AuthFormUsername|AuthGroupFile|AuthLDAPAuthorizePrefix|AuthLDAPBindAuthoritative|AuthLDAPBindDN|AuthLDAPBindPassword|AuthLDAPCharsetConfig|AuthLDAPCompareAsUser|AuthLDAPCompareDNOnServer|AuthLDAPDereferenceAliases|AuthLDAPGroupAttribute|AuthLDAPGroupAttributeIsDN|AuthLDAPInitialBindAsUser|AuthLDAPInitialBindPattern|AuthLDAPMaxSubGroupDepth|AuthLDAPRemoteUserAttribute|AuthLDAPRemoteUserIsDN|AuthLDAPSearchAsUser|AuthLDAPSubGroupAttribute|AuthLDAPSubGroupClass|AuthLDAPUrl|AuthMerging|AuthName|AuthnCacheContext|AuthnCacheEnable|AuthnCacheProvideFor|AuthnCacheSOCache|AuthnCacheTimeout|AuthnzFcgiCheckAuthnProvider|AuthnzFcgiDefineProvider|AuthType|AuthUserFile|AuthzDBDLoginToReferer|AuthzDBDQuery|AuthzDBDRedirectQuery|AuthzDBMType|AuthzSendForbiddenOnFailure|BalancerGrowth|BalancerInherit|BalancerMember|BalancerPersist|BrowserMatch|BrowserMatchNoCase|BufferedLogs|BufferSize|CacheDefaultExpire|CacheDetailHeader|CacheDirLength|CacheDirLevels|CacheDisable|CacheEnable|CacheFile|CacheHeader|CacheIgnoreCacheControl|CacheIgnoreHeaders|CacheIgnoreNoLastMod|CacheIgnoreQueryString|CacheIgnoreURLSessionIdentifiers|CacheKeyBaseURL|CacheLastModifiedFactor|CacheLock|CacheLockMaxAge|CacheLockPath|CacheMaxExpire|CacheMaxFileSize|CacheMinExpire|CacheMinFileSize|CacheNegotiatedDocs|CacheQuickHandler|CacheReadSize|CacheReadTime|CacheRoot|CacheSocache|CacheSocacheMaxSize|CacheSocacheMaxTime|CacheSocacheMinTime|CacheSocacheReadSize|CacheSocacheReadTime|CacheStaleOnError|CacheStoreExpired|CacheStoreNoStore|CacheStorePrivate|CGIDScriptTimeout|CGIMapExtension|CharsetDefault|CharsetOptions|CharsetSourceEnc|CheckCaseOnly|CheckSpelling|ChrootDir|ContentDigest|CookieDomain|CookieExpires|CookieName|CookieStyle|CookieTracking|CoreDumpDirectory|CustomLog|Dav|DavDepthInfinity|DavGenericLockDB|DavLockDB|DavMinTimeout|DBDExptime|DBDInitSQL|DBDKeep|DBDMax|DBDMin|DBDParams|DBDPersist|DBDPrepareSQL|DBDriver|DefaultIcon|DefaultLanguage|DefaultRuntimeDir|DefaultType|Define|DeflateBufferSize|DeflateCompressionLevel|DeflateFilterNote|DeflateInflateLimitRequestBody|DeflateInflateRatioBurst|DeflateInflateRatioLimit|DeflateMemLevel|DeflateWindowSize|Deny|DirectoryCheckHandler|DirectoryIndex|DirectoryIndexRedirect|DirectorySlash|DocumentRoot|DTracePrivileges|DumpIOInput|DumpIOOutput|EnableExceptionHook|EnableMMAP|EnableSendfile|Error|ErrorDocument|ErrorLog|ErrorLogFormat|Example|ExpiresActive|ExpiresByType|ExpiresDefault|ExtendedStatus|ExtFilterDefine|ExtFilterOptions|FallbackResource|FileETag|FilterChain|FilterDeclare|FilterProtocol|FilterProvider|FilterTrace|ForceLanguagePriority|ForceType|ForensicLog|GprofDir|GracefulShutdownTimeout|Group|Header|HeaderName|HeartbeatAddress|HeartbeatListen|HeartbeatMaxServers|HeartbeatStorage|HeartbeatStorage|HostnameLookups|IdentityCheck|IdentityCheckTimeout|ImapBase|ImapDefault|ImapMenu|Include|IncludeOptional|IndexHeadInsert|IndexIgnore|IndexIgnoreReset|IndexOptions|IndexOrderDefault|IndexStyleSheet|InputSed|ISAPIAppendLogToErrors|ISAPIAppendLogToQuery|ISAPICacheFile|ISAPIFakeAsync|ISAPILogNotSupported|ISAPIReadAheadBuffer|KeepAlive|KeepAliveTimeout|KeptBodySize|LanguagePriority|LDAPCacheEntries|LDAPCacheTTL|LDAPConnectionPoolTTL|LDAPConnectionTimeout|LDAPLibraryDebug|LDAPOpCacheEntries|LDAPOpCacheTTL|LDAPReferralHopLimit|LDAPReferrals|LDAPRetries|LDAPRetryDelay|LDAPSharedCacheFile|LDAPSharedCacheSize|LDAPTimeout|LDAPTrustedClientCert|LDAPTrustedGlobalCert|LDAPTrustedMode|LDAPVerifyServerCert|LimitInternalRecursion|LimitRequestBody|LimitRequestFields|LimitRequestFieldSize|LimitRequestLine|LimitXMLRequestBody|Listen|ListenBackLog|LoadFile|LoadModule|LogFormat|LogLevel|LogMessage|LuaAuthzProvider|LuaCodeCache|LuaHookAccessChecker|LuaHookAuthChecker|LuaHookCheckUserID|LuaHookFixups|LuaHookInsertFilter|LuaHookLog|LuaHookMapToStorage|LuaHookTranslateName|LuaHookTypeChecker|LuaInherit|LuaInputFilter|LuaMapHandler|LuaOutputFilter|LuaPackageCPath|LuaPackagePath|LuaQuickHandler|LuaRoot|LuaScope|MaxConnectionsPerChild|MaxKeepAliveRequests|MaxMemFree|MaxRangeOverlaps|MaxRangeReversals|MaxRanges|MaxRequestWorkers|MaxSpareServers|MaxSpareThreads|MaxThreads|MergeTrailers|MetaDir|MetaFiles|MetaSuffix|MimeMagicFile|MinSpareServers|MinSpareThreads|MMapFile|ModemStandard|ModMimeUsePathInfo|MultiviewsMatch|Mutex|NameVirtualHost|NoProxy|NWSSLTrustedCerts|NWSSLUpgradeable|Options|Order|OutputSed|PassEnv|PidFile|PrivilegesMode|Protocol|ProtocolEcho|ProxyAddHeaders|ProxyBadHeader|ProxyBlock|ProxyDomain|ProxyErrorOverride|ProxyExpressDBMFile|ProxyExpressDBMType|ProxyExpressEnable|ProxyFtpDirCharset|ProxyFtpEscapeWildcards|ProxyFtpListOnWildcard|ProxyHTMLBufSize|ProxyHTMLCharsetOut|ProxyHTMLDocType|ProxyHTMLEnable|ProxyHTMLEvents|ProxyHTMLExtended|ProxyHTMLFixups|ProxyHTMLInterp|ProxyHTMLLinks|ProxyHTMLMeta|ProxyHTMLStripComments|ProxyHTMLURLMap|ProxyIOBufferSize|ProxyMaxForwards|ProxyPass|ProxyPassInherit|ProxyPassInterpolateEnv|ProxyPassMatch|ProxyPassReverse|ProxyPassReverseCookieDomain|ProxyPassReverseCookiePath|ProxyPreserveHost|ProxyReceiveBufferSize|ProxyRemote|ProxyRemoteMatch|ProxyRequests|ProxySCGIInternalRedirect|ProxySCGISendfile|ProxySet|ProxySourceAddress|ProxyStatus|ProxyTimeout|ProxyVia|ReadmeName|ReceiveBufferSize|Redirect|RedirectMatch|RedirectPermanent|RedirectTemp|ReflectorHeader|RemoteIPHeader|RemoteIPInternalProxy|RemoteIPInternalProxyList|RemoteIPProxiesHeader|RemoteIPTrustedProxy|RemoteIPTrustedProxyList|RemoveCharset|RemoveEncoding|RemoveHandler|RemoveInputFilter|RemoveLanguage|RemoveOutputFilter|RemoveType|RequestHeader|RequestReadTimeout|Require|RewriteBase|RewriteCond|RewriteEngine|RewriteMap|RewriteOptions|RewriteRule|RLimitCPU|RLimitMEM|RLimitNPROC|Satisfy|ScoreBoardFile|Script|ScriptAlias|ScriptAliasMatch|ScriptInterpreterSource|ScriptLog|ScriptLogBuffer|ScriptLogLength|ScriptSock|SecureListen|SeeRequestTail|SendBufferSize|ServerAdmin|ServerAlias|ServerLimit|ServerName|ServerPath|ServerRoot|ServerSignature|ServerTokens|Session|SessionCookieName|SessionCookieName2|SessionCookieRemove|SessionCryptoCipher|SessionCryptoDriver|SessionCryptoPassphrase|SessionCryptoPassphraseFile|SessionDBDCookieName|SessionDBDCookieName2|SessionDBDCookieRemove|SessionDBDDeleteLabel|SessionDBDInsertLabel|SessionDBDPerUser|SessionDBDSelectLabel|SessionDBDUpdateLabel|SessionEnv|SessionExclude|SessionHeader|SessionInclude|SessionMaxAge|SetEnv|SetEnvIf|SetEnvIfExpr|SetEnvIfNoCase|SetHandler|SetInputFilter|SetOutputFilter|SSIEndTag|SSIErrorMsg|SSIETag|SSILastModified|SSILegacyExprParser|SSIStartTag|SSITimeFormat|SSIUndefinedEcho|SSLCACertificateFile|SSLCACertificatePath|SSLCADNRequestFile|SSLCADNRequestPath|SSLCARevocationCheck|SSLCARevocationFile|SSLCARevocationPath|SSLCertificateChainFile|SSLCertificateFile|SSLCertificateKeyFile|SSLCipherSuite|SSLCompression|SSLCryptoDevice|SSLEngine|SSLFIPS|SSLHonorCipherOrder|SSLInsecureRenegotiation|SSLOCSPDefaultResponder|SSLOCSPEnable|SSLOCSPOverrideResponder|SSLOCSPResponderTimeout|SSLOCSPResponseMaxAge|SSLOCSPResponseTimeSkew|SSLOCSPUseRequestNonce|SSLOpenSSLConfCmd|SSLOptions|SSLPassPhraseDialog|SSLProtocol|SSLProxyCACertificateFile|SSLProxyCACertificatePath|SSLProxyCARevocationCheck|SSLProxyCARevocationFile|SSLProxyCARevocationPath|SSLProxyCheckPeerCN|SSLProxyCheckPeerExpire|SSLProxyCheckPeerName|SSLProxyCipherSuite|SSLProxyEngine|SSLProxyMachineCertificateChainFile|SSLProxyMachineCertificateFile|SSLProxyMachineCertificatePath|SSLProxyProtocol|SSLProxyVerify|SSLProxyVerifyDepth|SSLRandomSeed|SSLRenegBufferSize|SSLRequire|SSLRequireSSL|SSLSessionCache|SSLSessionCacheTimeout|SSLSessionTicketKeyFile|SSLSRPUnknownUserSeed|SSLSRPVerifierFile|SSLStaplingCache|SSLStaplingErrorCacheTimeout|SSLStaplingFakeTryLater|SSLStaplingForceURL|SSLStaplingResponderTimeout|SSLStaplingResponseMaxAge|SSLStaplingResponseTimeSkew|SSLStaplingReturnResponderErrors|SSLStaplingStandardCacheTimeout|SSLStrictSNIVHostCheck|SSLUserName|SSLUseStapling|SSLVerifyClient|SSLVerifyDepth|StartServers|StartThreads|Substitute|Suexec|SuexecUserGroup|ThreadLimit|ThreadsPerChild|ThreadStackSize|TimeOut|TraceEnable|TransferLog|TypesConfig|UnDefine|UndefMacro|UnsetEnv|Use|UseCanonicalName|UseCanonicalPhysicalPort|User|UserDir|VHostCGIMode|VHostCGIPrivs|VHostGroup|VHostPrivs|VHostSecure|VHostUser|VirtualDocumentRoot|VirtualDocumentRootIP|VirtualScriptAlias|VirtualScriptAliasIP|WatchdogInterval|XBitHack|xml2EncAlias|xml2EncDefault|xml2StartParse)\b/mi, - lookbehind: true, - alias: 'property' - }, - 'directive-block': { - pattern: /<\/?\b(AuthnProviderAlias|AuthzProviderAlias|Directory|DirectoryMatch|Else|ElseIf|Files|FilesMatch|If|IfDefine|IfModule|IfVersion|Limit|LimitExcept|Location|LocationMatch|Macro|Proxy|RequireAll|RequireAny|RequireNone|VirtualHost)\b *.*>/i, - inside: { - 'directive-block': { - pattern: /^<\/?\w+/, - inside: { - 'punctuation': /^<\/?/ - }, - alias: 'tag' - }, - 'directive-block-parameter': { - pattern: /.*[^>]/, - inside: { - 'punctuation': /:/, - 'string': { - pattern: /("|').*\1/, - inside: { - 'variable': /(\$|%)\{?(\w\.?(\+|\-|:)?)+\}?/ - } - } - }, - alias: 'attr-value' - }, - 'punctuation': />/ - }, - alias: 'tag' - }, - 'directive-flags': { - pattern: /\[(\w,?)+\]/, - alias: 'keyword' - }, - 'string': { - pattern: /("|').*\1/, - inside: { - 'variable': /(\$|%)\{?(\w\.?(\+|\-|:)?)+\}?/ - } - }, - 'variable': /(\$|%)\{?(\w\.?(\+|\-|:)?)+\}?/, - 'regex': /\^?.*\$|\^.*\$?/ - }; - - /*-------------------------------------------------------------*/ - - Prism.languages.aspnet = Prism.languages.extend('markup', { - 'page-directive tag': { - pattern: /<%\s*@.*%>/i, - inside: { - 'page-directive tag': /<%\s*@\s*(?:Assembly|Control|Implements|Import|Master(?:Type)?|OutputCache|Page|PreviousPageType|Reference|Register)?|%>/i, - rest: Prism.languages.markup.tag.inside - } - }, - 'directive tag': { - pattern: /<%.*%>/i, - inside: { - 'directive tag': /<%\s*?[$=%#:]{0,2}|%>/i, - rest: Prism.languages.csharp - } - } - }); - // Regexp copied from prism-markup, with a negative look-ahead added - Prism.languages.aspnet.tag.pattern = /<(?!%)\/?[^\s>\/]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\\1|\\?(?!\1)[\s\S])*\1|[^\s'">=]+))?)*\s*\/?>/i; - - // match directives of attribute value foo="<% Bar %>" - Prism.languages.insertBefore('inside', 'punctuation', { - 'directive tag': Prism.languages.aspnet['directive tag'] - }, Prism.languages.aspnet.tag.inside["attr-value"]); - - Prism.languages.insertBefore('aspnet', 'comment', { - 'asp comment': /<%--[\s\S]*?--%>/ - }); - - // script runat="server" contains csharp, not javascript - Prism.languages.insertBefore('aspnet', Prism.languages.javascript ? 'script' : 'tag', { - 'asp script': { - pattern: /()[\s\S]*?(?=<\/script>)/i, - lookbehind: true, - inside: Prism.languages.csharp || {} - } - }); - - /*-------------------------------------------------------------------*/ - - Prism.languages.basic = { - 'string': /"(?:""|[!#$%&'()*,\/:;<=>?^_ +\-.A-Z\d])*"/i, - 'comment': { - pattern: /(?:!|REM\b).+/i, - inside: { - 'keyword': /^REM/i - } - }, - 'number': /(?:\b|\B[.-])(?:\d+\.?\d*)(?:E[+-]?\d+)?/i, - 'keyword': /\b(?:AS|BEEP|BLOAD|BSAVE|CALL(?: ABSOLUTE)?|CASE|CHAIN|CHDIR|CLEAR|CLOSE|CLS|COM|COMMON|CONST|DATA|DECLARE|DEF(?: FN| SEG|DBL|INT|LNG|SNG|STR)|DIM|DO|DOUBLE|ELSE|ELSEIF|END|ENVIRON|ERASE|ERROR|EXIT|FIELD|FILES|FOR|FUNCTION|GET|GOSUB|GOTO|IF|INPUT|INTEGER|IOCTL|KEY|KILL|LINE INPUT|LOCATE|LOCK|LONG|LOOP|LSET|MKDIR|NAME|NEXT|OFF|ON(?: COM| ERROR| KEY| TIMER)?|OPEN|OPTION BASE|OUT|POKE|PUT|READ|REDIM|REM|RESTORE|RESUME|RETURN|RMDIR|RSET|RUN|SHARED|SINGLE|SELECT CASE|SHELL|SLEEP|STATIC|STEP|STOP|STRING|SUB|SWAP|SYSTEM|THEN|TIMER|TO|TROFF|TRON|TYPE|UNLOCK|UNTIL|USING|VIEW PRINT|WAIT|WEND|WHILE|WRITE)(?:\$|\b)/i, - 'function': /\b(?:ABS|ACCESS|ACOS|ANGLE|AREA|ARITHMETIC|ARRAY|ASIN|ASK|AT|ATN|BASE|BEGIN|BREAK|CAUSE|CEIL|CHR|CLIP|COLLATE|COLOR|CON|COS|COSH|COT|CSC|DATE|DATUM|DEBUG|DECIMAL|DEF|DEG|DEGREES|DELETE|DET|DEVICE|DISPLAY|DOT|ELAPSED|EPS|ERASABLE|EXLINE|EXP|EXTERNAL|EXTYPE|FILETYPE|FIXED|FP|GO|GRAPH|HANDLER|IDN|IMAGE|IN|INT|INTERNAL|IP|IS|KEYED|LBOUND|LCASE|LEFT|LEN|LENGTH|LET|LINE|LINES|LOG|LOG10|LOG2|LTRIM|MARGIN|MAT|MAX|MAXNUM|MID|MIN|MISSING|MOD|NATIVE|NUL|NUMERIC|OF|OPTION|ORD|ORGANIZATION|OUTIN|OUTPUT|PI|POINT|POINTER|POINTS|POS|PRINT|PROGRAM|PROMPT|RAD|RADIANS|RANDOMIZE|RECORD|RECSIZE|RECTYPE|RELATIVE|REMAINDER|REPEAT|REST|RETRY|REWRITE|RIGHT|RND|ROUND|RTRIM|SAME|SEC|SELECT|SEQUENTIAL|SET|SETTER|SGN|SIN|SINH|SIZE|SKIP|SQR|STANDARD|STATUS|STR|STREAM|STYLE|TAB|TAN|TANH|TEMPLATE|TEXT|THERE|TIME|TIMEOUT|TRACE|TRANSFORM|TRUNCATE|UBOUND|UCASE|USE|VAL|VARIABLE|VIEWPORT|WHEN|WINDOW|WITH|ZER|ZONEWIDTH)(?:\$|\b)/i, - 'operator': /<[=>]?|>=?|[+\-*\/^=&]|\b(?:AND|EQV|IMP|NOT|OR|XOR)\b/i, - 'punctuation': /[,;:()]/ - }; - - - /*----------------------------------------------------*/ - - Prism.languages.c = Prism.languages.extend('clike', { - 'keyword': /\b(asm|typeof|inline|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|void|volatile|while)\b/, - 'operator': /\-[>-]?|\+\+?|!=?|<>?=?|==?|&&?|\|?\||[~^%?*\/]/, - 'number': /\b-?(?:0x[\da-f]+|\d*\.?\d+(?:e[+-]?\d+)?)[ful]*\b/i - }); - - Prism.languages.insertBefore('c', 'string', { - 'macro': { - // allow for multiline macro definitions - // spaces after the # character compile fine with gcc - pattern: /(^\s*)#\s*[a-z]+([^\r\n\\]|\\.|\\(?:\r\n?|\n))*/im, - lookbehind: true, - alias: 'property', - inside: { - // highlight the path of the include statement as a string - 'string': { - pattern: /(#\s*include\s*)(<.+?>|("|')(\\?.)+?\3)/, - lookbehind: true - }, - // highlight macro directives as keywords - 'directive': { - pattern: /(#\s*)\b(define|elif|else|endif|error|ifdef|ifndef|if|import|include|line|pragma|undef|using)\b/, - lookbehind: true, - alias: 'keyword' - } - } - }, - // highlight predefined macros as constants - 'constant': /\b(__FILE__|__LINE__|__DATE__|__TIME__|__TIMESTAMP__|__func__|EOF|NULL|stdin|stdout|stderr)\b/ - }); - - delete Prism.languages.c['class-name']; - delete Prism.languages.c['boolean']; - - - /*---------------------------------------------------*/ - Prism.languages.csharp = Prism.languages.extend('clike', { - 'keyword': /\b(abstract|as|async|await|base|bool|break|byte|case|catch|char|checked|class|const|continue|decimal|default|delegate|do|double|else|enum|event|explicit|extern|false|finally|fixed|float|for|foreach|goto|if|implicit|in|int|interface|internal|is|lock|long|namespace|new|null|object|operator|out|override|params|private|protected|public|readonly|ref|return|sbyte|sealed|short|sizeof|stackalloc|static|string|struct|switch|this|throw|true|try|typeof|uint|ulong|unchecked|unsafe|ushort|using|virtual|void|volatile|while|add|alias|ascending|async|await|descending|dynamic|from|get|global|group|into|join|let|orderby|partial|remove|select|set|value|var|where|yield)\b/, - 'string': [ - { - pattern: /@("|')(\1\1|\\\1|\\?(?!\1)[\s\S])*\1/, - greedy: true - }, - { - pattern: /("|')(\\?.)*?\1/, - greedy: true - } - ], - 'number': /\b-?(0x[\da-f]+|\d*\.?\d+f?)\b/i - }); - - Prism.languages.insertBefore('csharp', 'keyword', { - 'generic-method': { - pattern: /[a-z0-9_]+\s*<[^>\r\n]+?>\s*(?=\()/i, - alias: 'function', - inside: { - keyword: Prism.languages.csharp.keyword, - punctuation: /[<>(),.:]/ - } - }, - 'preprocessor': { - pattern: /(^\s*)#.*/m, - lookbehind: true, - alias: 'property', - inside: { - // highlight preprocessor directives as keywords - 'directive': { - pattern: /(\s*#)\b(define|elif|else|endif|endregion|error|if|line|pragma|region|undef|warning)\b/, - lookbehind: true, - alias: 'keyword' - } - } - } - }); - - - /*-----------------------------------------------------------*/ - - Prism.languages.cpp = Prism.languages.extend('c', { - 'keyword': /\b(alignas|alignof|asm|auto|bool|break|case|catch|char|char16_t|char32_t|class|compl|const|constexpr|const_cast|continue|decltype|default|delete|do|double|dynamic_cast|else|enum|explicit|export|extern|float|for|friend|goto|if|inline|int|long|mutable|namespace|new|noexcept|nullptr|operator|private|protected|public|register|reinterpret_cast|return|short|signed|sizeof|static|static_assert|static_cast|struct|switch|template|this|thread_local|throw|try|typedef|typeid|typename|union|unsigned|using|virtual|void|volatile|wchar_t|while)\b/, - 'boolean': /\b(true|false)\b/, - 'operator': /[-+]{1,2}|!=?|<{1,2}=?|>{1,2}=?|\->|:{1,2}|={1,2}|\^|~|%|&{1,2}|\|?\||\?|\*|\/|\b(and|and_eq|bitand|bitor|not|not_eq|or|or_eq|xor|xor_eq)\b/ - }); - - Prism.languages.insertBefore('cpp', 'keyword', { - 'class-name': { - pattern: /(class\s+)[a-z0-9_]+/i, - lookbehind: true - } - }); - - /*-----------------------coffeescript-----------------------*/ - - ;(function(Prism) { - - // Ignore comments starting with { to privilege string interpolation highlighting - var comment = /#(?!\{).+/, - interpolation = { - pattern: /#\{[^}]+\}/, - alias: 'variable' - }; - - Prism.languages.coffeescript = Prism.languages.extend('javascript', { - 'comment': comment, - 'string': [ - - // Strings are multiline - { - pattern: /'(?:\\?[^\\])*?'/, - greedy: true - }, - - { - // Strings are multiline - pattern: /"(?:\\?[^\\])*?"/, - greedy: true, - inside: { - 'interpolation': interpolation - } - } - ], - 'keyword': /\b(and|break|by|catch|class|continue|debugger|delete|do|each|else|extend|extends|false|finally|for|if|in|instanceof|is|isnt|let|loop|namespace|new|no|not|null|of|off|on|or|own|return|super|switch|then|this|throw|true|try|typeof|undefined|unless|until|when|while|window|with|yes|yield)\b/, - 'class-member': { - pattern: /@(?!\d)\w+/, - alias: 'variable' - } - }); - - Prism.languages.insertBefore('coffeescript', 'comment', { - 'multiline-comment': { - pattern: /###[\s\S]+?###/, - alias: 'comment' - }, - - // Block regexp can contain comments and interpolation - 'block-regex': { - pattern: /\/{3}[\s\S]*?\/{3}/, - alias: 'regex', - inside: { - 'comment': comment, - 'interpolation': interpolation - } - } - }); - - Prism.languages.insertBefore('coffeescript', 'string', { - 'inline-javascript': { - pattern: /`(?:\\?[\s\S])*?`/, - inside: { - 'delimiter': { - pattern: /^`|`$/, - alias: 'punctuation' - }, - rest: Prism.languages.javascript - } - }, - - // Block strings - 'multiline-string': [ - { - pattern: /'''[\s\S]*?'''/, - greedy: true, - alias: 'string' - }, - { - pattern: /"""[\s\S]*?"""/, - greedy: true, - alias: 'string', - inside: { - interpolation: interpolation - } - } - ] - - }); - - Prism.languages.insertBefore('coffeescript', 'keyword', { - // Object property - 'property': /(?!\d)\w+(?=\s*:(?!:))/ - }); - - delete Prism.languages.coffeescript['template-string']; - - }(Prism)); - - - /*---------------------------ruby---------------------------*/ - - - (function(Prism) { - Prism.languages.ruby = Prism.languages.extend('clike', { - 'comment': [ - /#(?!\{[^\r\n]*?\}).*/, - /^=begin(?:\r?\n|\r)(?:.*(?:\r?\n|\r))*?=end/m - ], - 'keyword': /\b(alias|and|BEGIN|begin|break|case|class|def|define_method|defined|do|each|else|elsif|END|end|ensure|false|for|if|in|module|new|next|nil|not|or|raise|redo|require|rescue|retry|return|self|super|then|throw|true|undef|unless|until|when|while|yield)\b/ - }); - - var interpolation = { - pattern: /#\{[^}]+\}/, - inside: { - 'delimiter': { - pattern: /^#\{|\}$/, - alias: 'tag' - }, - rest: Prism.util.clone(Prism.languages.ruby) - } - }; - - Prism.languages.insertBefore('ruby', 'keyword', { - 'regex': [ - { - pattern: /%r([^a-zA-Z0-9\s\{\(\[<])(?:[^\\]|\\[\s\S])*?\1[gim]{0,3}/, - greedy: true, - inside: { - 'interpolation': interpolation - } - }, - { - pattern: /%r\((?:[^()\\]|\\[\s\S])*\)[gim]{0,3}/, - greedy: true, - inside: { - 'interpolation': interpolation - } - }, - { - // Here we need to specifically allow interpolation - pattern: /%r\{(?:[^#{}\\]|#(?:\{[^}]+\})?|\\[\s\S])*\}[gim]{0,3}/, - greedy: true, - inside: { - 'interpolation': interpolation - } - }, - { - pattern: /%r\[(?:[^\[\]\\]|\\[\s\S])*\][gim]{0,3}/, - greedy: true, - inside: { - 'interpolation': interpolation - } - }, - { - pattern: /%r<(?:[^<>\\]|\\[\s\S])*>[gim]{0,3}/, - greedy: true, - inside: { - 'interpolation': interpolation - } - }, - { - pattern: /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\\\r\n])+\/[gim]{0,3}(?=\s*($|[\r\n,.;})]))/, - lookbehind: true, - greedy: true - } - ], - 'variable': /[@$]+[a-zA-Z_][a-zA-Z_0-9]*(?:[?!]|\b)/, - 'symbol': /:[a-zA-Z_][a-zA-Z_0-9]*(?:[?!]|\b)/ - }); - - Prism.languages.insertBefore('ruby', 'number', { - 'builtin': /\b(Array|Bignum|Binding|Class|Continuation|Dir|Exception|FalseClass|File|Stat|File|Fixnum|Float|Hash|Integer|IO|MatchData|Method|Module|NilClass|Numeric|Object|Proc|Range|Regexp|String|Struct|TMS|Symbol|ThreadGroup|Thread|Time|TrueClass)\b/, - 'constant': /\b[A-Z][a-zA-Z_0-9]*(?:[?!]|\b)/ - }); - - Prism.languages.ruby.string = [ - { - pattern: /%[qQiIwWxs]?([^a-zA-Z0-9\s\{\(\[<])(?:[^\\]|\\[\s\S])*?\1/, - greedy: true, - inside: { - 'interpolation': interpolation - } - }, - { - pattern: /%[qQiIwWxs]?\((?:[^()\\]|\\[\s\S])*\)/, - greedy: true, - inside: { - 'interpolation': interpolation - } - }, - { - // Here we need to specifically allow interpolation - pattern: /%[qQiIwWxs]?\{(?:[^#{}\\]|#(?:\{[^}]+\})?|\\[\s\S])*\}/, - greedy: true, - inside: { - 'interpolation': interpolation - } - }, - { - pattern: /%[qQiIwWxs]?\[(?:[^\[\]\\]|\\[\s\S])*\]/, - greedy: true, - inside: { - 'interpolation': interpolation - } - }, - { - pattern: /%[qQiIwWxs]?<(?:[^<>\\]|\\[\s\S])*>/, - greedy: true, - inside: { - 'interpolation': interpolation - } - }, - { - pattern: /("|')(#\{[^}]+\}|\\(?:\r?\n|\r)|\\?.)*?\1/, - greedy: true, - inside: { - 'interpolation': interpolation - } - } - ]; - }(Prism)); - - - /*-------------------------------------------------------------*/ - - Prism.languages.d = Prism.languages.extend('clike', { - 'string': [ - // r"", x"" - /\b[rx]"(\\.|[^\\"])*"[cwd]?/, - // q"[]", q"()", q"<>", q"{}" - /\bq"(?:\[[\s\S]*?\]|\([\s\S]*?\)|<[\s\S]*?>|\{[\s\S]*?\})"/, - // q"IDENT - // ... - // IDENT" - /\bq"([_a-zA-Z][_a-zA-Z\d]*)(?:\r?\n|\r)[\s\S]*?(?:\r?\n|\r)\1"/, - // q"//", q"||", etc. - /\bq"(.)[\s\S]*?\1"/, - // Characters - /'(?:\\'|\\?[^']+)'/, - - /(["`])(\\.|(?!\1)[^\\])*\1[cwd]?/ - ], - - 'number': [ - // The lookbehind and the negative look-ahead try to prevent bad highlighting of the .. operator - // Hexadecimal numbers must be handled separately to avoid problems with exponent "e" - /\b0x\.?[a-f\d_]+(?:(?!\.\.)\.[a-f\d_]*)?(?:p[+-]?[a-f\d_]+)?[ulfi]*/i, - { - pattern: /((?:\.\.)?)(?:\b0b\.?|\b|\.)\d[\d_]*(?:(?!\.\.)\.[\d_]*)?(?:e[+-]?\d[\d_]*)?[ulfi]*/i, - lookbehind: true - } - ], - - // In order: $, keywords and special tokens, globally defined symbols - 'keyword': /\$|\b(?:abstract|alias|align|asm|assert|auto|body|bool|break|byte|case|cast|catch|cdouble|cent|cfloat|char|class|const|continue|creal|dchar|debug|default|delegate|delete|deprecated|do|double|else|enum|export|extern|false|final|finally|float|for|foreach|foreach_reverse|function|goto|idouble|if|ifloat|immutable|import|inout|int|interface|invariant|ireal|lazy|long|macro|mixin|module|new|nothrow|null|out|override|package|pragma|private|protected|public|pure|real|ref|return|scope|shared|short|static|struct|super|switch|synchronized|template|this|throw|true|try|typedef|typeid|typeof|ubyte|ucent|uint|ulong|union|unittest|ushort|version|void|volatile|wchar|while|with|__(?:(?:FILE|MODULE|LINE|FUNCTION|PRETTY_FUNCTION|DATE|EOF|TIME|TIMESTAMP|VENDOR|VERSION)__|gshared|traits|vector|parameters)|string|wstring|dstring|size_t|ptrdiff_t)\b/, - 'operator': /\|[|=]?|&[&=]?|\+[+=]?|-[-=]?|\.?\.\.|=[>=]?|!(?:i[ns]\b|<>?=?|>=?|=)?|\bi[ns]\b|(?:<[<>]?|>>?>?|\^\^|[*\/%^~])=?/ - }); - - - Prism.languages.d.comment = [ - // Shebang - /^\s*#!.+/, - // /+ +/ - { - // Allow one level of nesting - pattern: /(^|[^\\])\/\+(?:\/\+[\s\S]*?\+\/|[\s\S])*?\+\//, - lookbehind: true - } - ].concat(Prism.languages.d.comment); - - Prism.languages.insertBefore('d', 'comment', { - 'token-string': { - // Allow one level of nesting - pattern: /\bq\{(?:|\{[^}]*\}|[^}])*\}/, - alias: 'string' - } - }); - - Prism.languages.insertBefore('d', 'keyword', { - 'property': /\B@\w*/ - }); - - Prism.languages.insertBefore('d', 'function', { - 'register': { - // Iasm registers - pattern: /\b(?:[ABCD][LHX]|E[ABCD]X|E?(?:BP|SP|DI|SI)|[ECSDGF]S|CR[0234]|DR[012367]|TR[3-7]|X?MM[0-7]|R[ABCD]X|[BS]PL|R[BS]P|[DS]IL|R[DS]I|R(?:[89]|1[0-5])[BWD]?|XMM(?:[89]|1[0-5])|YMM(?:1[0-5]|\d))\b|\bST(?:\([0-7]\)|\b)/, - alias: 'variable' - } - }); - Prism.languages.dart = Prism.languages.extend('clike', { - 'string': [ - { - pattern: /r?("""|''')[\s\S]*?\1/, - greedy: true - }, - { - pattern: /r?("|')(\\?.)*?\1/, - greedy: true - } - ], - 'keyword': [ - /\b(?:async|sync|yield)\*/, - /\b(?:abstract|assert|async|await|break|case|catch|class|const|continue|default|deferred|do|dynamic|else|enum|export|external|extends|factory|final|finally|for|get|if|implements|import|in|library|new|null|operator|part|rethrow|return|set|static|super|switch|this|throw|try|typedef|var|void|while|with|yield)\b/ - ], - 'operator': /\bis!|\b(?:as|is)\b|\+\+|--|&&|\|\||<<=?|>>=?|~(?:\/=?)?|[+\-*\/%&^|=!<>]=?|\?/ - }); - - Prism.languages.insertBefore('dart','function',{ - 'metadata': { - pattern: /@\w+/, - alias: 'symbol' - } - }); - - - /*-----------------------------------------------------------*/ - - Prism.languages.docker = { - 'keyword': { - pattern: /(^\s*)(?:ONBUILD|FROM|MAINTAINER|RUN|EXPOSE|ENV|ADD|COPY|VOLUME|USER|WORKDIR|CMD|LABEL|ENTRYPOINT)(?=\s)/mi, - lookbehind: true - }, - 'string': /("|')(?:(?!\1)[^\\\r\n]|\\(?:\r\n|[\s\S]))*?\1/, - 'comment': /#.*/, - 'punctuation': /---|\.\.\.|[:[\]{}\-,|>?]/ - }; - Prism.languages.erlang = { - 'comment': /%.+/, - 'string': { - pattern: /"(?:\\?.)*?"/, - greedy: true - }, - 'quoted-function': { - pattern: /'(?:\\.|[^'\\])+'(?=\()/, - alias: 'function' - }, - 'quoted-atom': { - pattern: /'(?:\\.|[^'\\])+'/, - alias: 'atom' - }, - 'boolean': /\b(?:true|false)\b/, - 'keyword': /\b(?:fun|when|case|of|end|if|receive|after|try|catch)\b/, - 'number': [ - /\$\\?./, - /\d+#[a-z0-9]+/i, - /(?:\b|-)\d*\.?\d+([Ee][+-]?\d+)?\b/ - ], - 'function': /\b[a-z][\w@]*(?=\()/, - 'variable': { - // Look-behind is used to prevent wrong highlighting of atoms containing "@" - pattern: /(^|[^@])(?:\b|\?)[A-Z_][\w@]*/, - lookbehind: true - }, - 'operator': [ - /[=\/<>:]=|=[:\/]=|\+\+?|--?|[=*\/!]|\b(?:bnot|div|rem|band|bor|bxor|bsl|bsr|not|and|or|xor|orelse|andalso)\b/, - { - // We don't want to match << - pattern: /(^|[^<])<(?!<)/, - lookbehind: true - }, - { - // We don't want to match >> - pattern: /(^|[^>])>(?!>)/, - lookbehind: true - } - ], - 'atom': /\b[a-z][\w@]*/, - 'punctuation': /[()[\]{}:;,.#|]|<<|>>/ - - }; - - Prism.languages.git = { - 'comment': /^#.*/m, - 'deleted': /^[-–].*/m, - 'inserted': /^\+.*/m, - 'string': /("|')(\\?.)*?\1/m, - 'command': { - pattern: /^.*\$ git .*$/m, - inside: { - 'parameter': /\s(--|-)\w+/m - } - }, - 'coord': /^@@.*@@$/m, - 'commit_sha1': /^commit \w{40}$/m - }; - - - /*-----------------------------------------------------------*/ - Prism.languages.go = Prism.languages.extend('clike', { - 'keyword': /\b(break|case|chan|const|continue|default|defer|else|fallthrough|for|func|go(to)?|if|import|interface|map|package|range|return|select|struct|switch|type|var)\b/, - 'builtin': /\b(bool|byte|complex(64|128)|error|float(32|64)|rune|string|u?int(8|16|32|64|)|uintptr|append|cap|close|complex|copy|delete|imag|len|make|new|panic|print(ln)?|real|recover)\b/, - 'boolean': /\b(_|iota|nil|true|false)\b/, - 'operator': /[*\/%^!=]=?|\+[=+]?|-[=-]?|\|[=|]?|&(?:=|&|\^=?)?|>(?:>=?|=)?|<(?:<=?|=|-)?|:=|\.\.\./, - 'number': /\b(-?(0x[a-f\d]+|(\d+\.?\d*|\.\d+)(e[-+]?\d+)?)i?)\b/i, - 'string': { - pattern: /("|'|`)(\\?.|\r|\n)*?\1/, - greedy: true - } - }); - delete Prism.languages.go['class-name']; - - Prism.languages.haskell= { - 'comment': { - pattern: /(^|[^-!#$%*+=?&@|~.:<>^\\\/])(--[^-!#$%*+=?&@|~.:<>^\\\/].*|{-[\s\S]*?-})/m, - lookbehind: true - }, - 'char': /'([^\\']|\\([abfnrtv\\"'&]|\^[A-Z@[\]\^_]|NUL|SOH|STX|ETX|EOT|ENQ|ACK|BEL|BS|HT|LF|VT|FF|CR|SO|SI|DLE|DC1|DC2|DC3|DC4|NAK|SYN|ETB|CAN|EM|SUB|ESC|FS|GS|RS|US|SP|DEL|\d+|o[0-7]+|x[0-9a-fA-F]+))'/, - 'string': { - pattern: /"([^\\"]|\\([abfnrtv\\"'&]|\^[A-Z@[\]\^_]|NUL|SOH|STX|ETX|EOT|ENQ|ACK|BEL|BS|HT|LF|VT|FF|CR|SO|SI|DLE|DC1|DC2|DC3|DC4|NAK|SYN|ETB|CAN|EM|SUB|ESC|FS|GS|RS|US|SP|DEL|\d+|o[0-7]+|x[0-9a-fA-F]+)|\\\s+\\)*"/, - greedy: true - }, - 'keyword' : /\b(case|class|data|deriving|do|else|if|in|infixl|infixr|instance|let|module|newtype|of|primitive|then|type|where)\b/, - 'import_statement' : { - // The imported or hidden names are not included in this import - // statement. This is because we want to highlight those exactly like - // we do for the names in the program. - pattern: /(\r?\n|\r|^)\s*import\s+(qualified\s+)?([A-Z][_a-zA-Z0-9']*)(\.[A-Z][_a-zA-Z0-9']*)*(\s+as\s+([A-Z][_a-zA-Z0-9']*)(\.[A-Z][_a-zA-Z0-9']*)*)?(\s+hiding\b)?/m, - inside: { - 'keyword': /\b(import|qualified|as|hiding)\b/ - } - }, - // These are builtin variables only. Constructors are highlighted later as a constant. - 'builtin': /\b(abs|acos|acosh|all|and|any|appendFile|approxRational|asTypeOf|asin|asinh|atan|atan2|atanh|basicIORun|break|catch|ceiling|chr|compare|concat|concatMap|const|cos|cosh|curry|cycle|decodeFloat|denominator|digitToInt|div|divMod|drop|dropWhile|either|elem|encodeFloat|enumFrom|enumFromThen|enumFromThenTo|enumFromTo|error|even|exp|exponent|fail|filter|flip|floatDigits|floatRadix|floatRange|floor|fmap|foldl|foldl1|foldr|foldr1|fromDouble|fromEnum|fromInt|fromInteger|fromIntegral|fromRational|fst|gcd|getChar|getContents|getLine|group|head|id|inRange|index|init|intToDigit|interact|ioError|isAlpha|isAlphaNum|isAscii|isControl|isDenormalized|isDigit|isHexDigit|isIEEE|isInfinite|isLower|isNaN|isNegativeZero|isOctDigit|isPrint|isSpace|isUpper|iterate|last|lcm|length|lex|lexDigits|lexLitChar|lines|log|logBase|lookup|map|mapM|mapM_|max|maxBound|maximum|maybe|min|minBound|minimum|mod|negate|not|notElem|null|numerator|odd|or|ord|otherwise|pack|pi|pred|primExitWith|print|product|properFraction|putChar|putStr|putStrLn|quot|quotRem|range|rangeSize|read|readDec|readFile|readFloat|readHex|readIO|readInt|readList|readLitChar|readLn|readOct|readParen|readSigned|reads|readsPrec|realToFrac|recip|rem|repeat|replicate|return|reverse|round|scaleFloat|scanl|scanl1|scanr|scanr1|seq|sequence|sequence_|show|showChar|showInt|showList|showLitChar|showParen|showSigned|showString|shows|showsPrec|significand|signum|sin|sinh|snd|sort|span|splitAt|sqrt|subtract|succ|sum|tail|take|takeWhile|tan|tanh|threadToIOResult|toEnum|toInt|toInteger|toLower|toRational|toUpper|truncate|uncurry|undefined|unlines|until|unwords|unzip|unzip3|userError|words|writeFile|zip|zip3|zipWith|zipWith3)\b/, - // decimal integers and floating point numbers | octal integers | hexadecimal integers - 'number' : /\b(\d+(\.\d+)?(e[+-]?\d+)?|0o[0-7]+|0x[0-9a-f]+)\b/i, - // Most of this is needed because of the meaning of a single '.'. - // If it stands alone freely, it is the function composition. - // It may also be a separator between a module name and an identifier => no - // operator. If it comes together with other special characters it is an - // operator too. - 'operator' : /\s\.\s|[-!#$%*+=?&@|~.:<>^\\\/]*\.[-!#$%*+=?&@|~.:<>^\\\/]+|[-!#$%*+=?&@|~.:<>^\\\/]+\.[-!#$%*+=?&@|~.:<>^\\\/]*|[-!#$%*+=?&@|~:<>^\\\/]+|`([A-Z][_a-zA-Z0-9']*\.)*[_a-z][_a-zA-Z0-9']*`/, - // In Haskell, nearly everything is a variable, do not highlight these. - 'hvariable': /\b([A-Z][_a-zA-Z0-9']*\.)*[_a-z][_a-zA-Z0-9']*\b/, - 'constant': /\b([A-Z][_a-zA-Z0-9']*\.)*[A-Z][_a-zA-Z0-9']*\b/, - 'punctuation' : /[{}[\];(),.:]/ - }; - - /*---------------------------jade---------------------------*/ - - ;(function(Prism) { - - Prism.languages.jade = { - - 'comment': { - pattern: /(^([\t ]*))\/\/.*((?:\r?\n|\r)\2[\t ]+.+)*/m, - lookbehind: true - }, - 'multiline-script': { - pattern: /(^([\t ]*)script\b.*\.[\t ]*)((?:\r?\n|\r(?!\n))(?:\2[\t ]+.+|\s*?(?=\r?\n|\r)))+/m, - lookbehind: true, - inside: { - rest: Prism.languages.javascript - } - }, - 'filter': { - pattern: /(^([\t ]*)):.+((?:\r?\n|\r(?!\n))(?:\2[\t ]+.+|\s*?(?=\r?\n|\r)))+/m, - lookbehind: true, - inside: { - 'filter-name': { - pattern: /^:[\w-]+/, - alias: 'variable' - } - } - }, - 'multiline-plain-text': { - pattern: /(^([\t ]*)[\w\-#.]+\.[\t ]*)((?:\r?\n|\r(?!\n))(?:\2[\t ]+.+|\s*?(?=\r?\n|\r)))+/m, - lookbehind: true - }, - 'markup': { - pattern: /(^[\t ]*)<.+/m, - lookbehind: true, - inside: { - rest: Prism.languages.markup - } - }, - 'doctype': { - pattern: /((?:^|\n)[\t ]*)doctype(?: .+)?/, - lookbehind: true - }, - 'flow-control': { - pattern: /(^[\t ]*)(?:if|unless|else|case|when|default|each|while)\b(?: .+)?/m, - lookbehind: true, - inside: { - 'each': { - pattern: /^each .+? in\b/, - inside: { - 'keyword': /\b(?:each|in)\b/, - 'punctuation': /,/ - } - }, - 'branch': { - pattern: /^(?:if|unless|else|case|when|default|while)\b/, - alias: 'keyword' - }, - rest: Prism.languages.javascript - } - }, - 'keyword': { - pattern: /(^[\t ]*)(?:block|extends|include|append|prepend)\b.+/m, - lookbehind: true - }, - 'mixin': [ - { - pattern: /(^[\t ]*)mixin .+/m, - lookbehind: true, - inside: { - 'keyword': /^mixin/, - 'function': /\w+(?=\s*\(|\s*$)/, - 'punctuation': /[(),.]/ - } - }, - { - pattern: /(^[\t ]*)\+.+/m, - lookbehind: true, - inside: { - 'name': { - pattern: /^\+\w+/, - alias: 'function' - }, - 'rest': Prism.languages.javascript - } - } - ], - 'script': { - pattern: /(^[\t ]*script(?:(?:&[^(]+)?\([^)]+\))*[\t ]+).+/m, - lookbehind: true, - inside: { - rest: Prism.languages.javascript - } - }, - - 'plain-text': { - pattern: /(^[\t ]*(?!-)[\w\-#.]*[\w\-](?:(?:&[^(]+)?\([^)]+\))*\/?[\t ]+).+/m, - lookbehind: true - }, - 'tag': { - pattern: /(^[\t ]*)(?!-)[\w\-#.]*[\w\-](?:(?:&[^(]+)?\([^)]+\))*\/?:?/m, - lookbehind: true, - inside: { - 'attributes': [ - { - pattern: /&[^(]+\([^)]+\)/, - inside: { - rest: Prism.languages.javascript - } - }, - { - pattern: /\([^)]+\)/, - inside: { - 'attr-value': { - pattern: /(=\s*)(?:\{[^}]*\}|[^,)\r\n]+)/, - lookbehind: true, - inside: { - rest: Prism.languages.javascript - } - }, - 'attr-name': /[\w-]+(?=\s*!?=|\s*[,)])/, - 'punctuation': /[!=(),]+/ - } - } - ], - 'punctuation': /:/ - } - }, - 'code': [ - { - pattern: /(^[\t ]*(?:-|!?=)).+/m, - lookbehind: true, - inside: { - rest: Prism.languages.javascript - } - } - ], - 'punctuation': /[.\-!=|]+/ - }; - - var filter_pattern = '(^([\\t ]*)):{{filter_name}}((?:\\r?\\n|\\r(?!\\n))(?:\\2[\\t ]+.+|\\s*?(?=\\r?\\n|\\r)))+'; - - var filters = [ - {filter:'atpl',language:'twig'}, - {filter:'coffee',language:'coffeescript'}, - 'ejs', - 'handlebars', - 'hogan', - 'less', - 'livescript', - 'markdown', - 'mustache', - 'plates', - {filter:'sass',language:'scss'}, - 'stylus', - 'swig' - - ]; - var all_filters = {}; - for (var i = 0, l = filters.length; i < l; i++) { - var filter = filters[i]; - filter = typeof filter === 'string' ? {filter: filter, language: filter} : filter; - if (Prism.languages[filter.language]) { - all_filters['filter-' + filter.filter] = { - pattern: RegExp(filter_pattern.replace('{{filter_name}}', filter.filter), 'm'), - lookbehind: true, - inside: { - 'filter-name': { - pattern: /^:[\w-]+/, - alias: 'variable' - }, - rest: Prism.languages[filter.language] - } - } - } - } - - Prism.languages.insertBefore('jade', 'filter', all_filters); - - }(Prism)); - - /*-----------------------------------------------------------*/ - - Prism.languages.java = Prism.languages.extend('clike', { - 'keyword': /\b(abstract|continue|for|new|switch|assert|default|goto|package|synchronized|boolean|do|if|private|this|break|double|implements|protected|throw|byte|else|import|public|throws|case|enum|instanceof|return|transient|catch|extends|int|short|try|char|final|interface|static|void|class|finally|long|strictfp|volatile|const|float|native|super|while)\b/, - 'number': /\b0b[01]+\b|\b0x[\da-f]*\.?[\da-fp\-]+\b|\b\d*\.?\d+(?:e[+-]?\d+)?[df]?\b/i, - 'operator': { - pattern: /(^|[^.])(?:\+[+=]?|-[-=]?|!=?|<>?>?=?|==?|&[&=]?|\|[|=]?|\*=?|\/=?|%=?|\^=?|[?:~])/m, - lookbehind: true - } - }); - - Prism.languages.insertBefore('java','function', { - 'annotation': { - alias: 'punctuation', - pattern: /(^|[^.])@\w+/, - lookbehind: true - } - }); - - Prism.languages.json = { - 'property': /"(?:\\.|[^\\"])*"(?=\s*:)/ig, - 'string': /"(?!:)(?:\\.|[^\\"])*"(?!:)/g, - 'number': /\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee][+-]?\d+)?)\b/g, - 'punctuation': /[{}[\]);,]/g, - 'operator': /:/g, - 'boolean': /\b(true|false)\b/gi, - 'null': /\bnull\b/gi - }; - - Prism.languages.jsonp = Prism.languages.json; - - /*--------------------------kotlin----------------------------*/ - - ;(function (Prism) { - Prism.languages.kotlin = Prism.languages.extend('clike', { - 'keyword': { - // The lookbehind prevents wrong highlighting of e.g. kotlin.properties.get - pattern: /(^|[^.])\b(?:abstract|annotation|as|break|by|catch|class|companion|const|constructor|continue|crossinline|data|do|else|enum|final|finally|for|fun|get|if|import|in|init|inline|inner|interface|internal|is|lateinit|noinline|null|object|open|out|override|package|private|protected|public|reified|return|sealed|set|super|tailrec|this|throw|to|try|val|var|when|where|while)\b/, - lookbehind: true - }, - 'function': [ - /\w+(?=\s*\()/, - { - pattern: /(\.)\w+(?=\s*\{)/, - lookbehind: true - } - ], - 'number': /\b(?:0[bx][\da-fA-F]+|\d+(?:\.\d+)?(?:e[+-]?\d+)?[fFL]?)\b/, - 'operator': /\+[+=]?|-[-=>]?|==?=?|!(?:!|==?)?|[\/*%<>]=?|[?:]:?|\.\.|&&|\|\||\b(?:and|inv|or|shl|shr|ushr|xor)\b/ - }); - - delete Prism.languages.kotlin["class-name"]; - - Prism.languages.insertBefore('kotlin', 'string', { - 'raw-string': { - pattern: /(["'])\1\1[\s\S]*?\1{3}/, - alias: 'string' - // See interpolation below - } - }); - Prism.languages.insertBefore('kotlin', 'keyword', { - 'annotation': { - pattern: /\B@(?:\w+:)?(?:[A-Z]\w*|\[[^\]]+\])/, - alias: 'builtin' - } - }); - Prism.languages.insertBefore('kotlin', 'function', { - 'label': { - pattern: /\w+@|@\w+/, - alias: 'symbol' - } - }); - - var interpolation = [ - { - pattern: /\$\{[^}]+\}/, - inside: { - delimiter: { - pattern: /^\$\{|\}$/, - alias: 'variable' - }, - rest: Prism.util.clone(Prism.languages.kotlin) - } - }, - { - pattern: /\$\w+/, - alias: 'variable' - } - ]; - - Prism.languages.kotlin['string'].inside = Prism.languages.kotlin['raw-string'].inside = { - interpolation: interpolation - }; - - }(Prism)); - - - /*-----------------------------------------------------------*/ - - Prism.languages.less = Prism.languages.extend('css', { - 'comment': [ - /\/\*[\s\S]*?\*\//, - { - pattern: /(^|[^\\])\/\/.*/, - lookbehind: true - } - ], - 'atrule': { - pattern: /@[\w-]+?(?:\([^{}]+\)|[^(){};])*?(?=\s*\{)/i, - inside: { - 'punctuation': /[:()]/ - } - }, - // selectors and mixins are considered the same - 'selector': { - pattern: /(?:@\{[\w-]+\}|[^{};\s@])(?:@\{[\w-]+\}|\([^{}]*\)|[^{};@])*?(?=\s*\{)/, - inside: { - // mixin parameters - 'variable': /@+[\w-]+/ - } - }, - - 'property': /(?:@\{[\w-]+\}|[\w-])+(?:\+_?)?(?=\s*:)/i, - 'punctuation': /[{}();:,]/, - 'operator': /[+\-*\/]/ - }); - - // Invert function and punctuation positions - Prism.languages.insertBefore('less', 'punctuation', { - 'function': Prism.languages.less.function - }); - - Prism.languages.insertBefore('less', 'property', { - 'variable': [ - // Variable declaration (the colon must be consumed!) - { - pattern: /@[\w-]+\s*:/, - inside: { - "punctuation": /:/ - } - }, - - // Variable usage - /@@?[\w-]+/ - ], - 'mixin-usage': { - pattern: /([{;]\s*)[.#](?!\d)[\w-]+.*?(?=[(;])/, - lookbehind: true, - alias: 'function' - } - }); - - - - /*-----------------------------------------------------------*/ - - Prism.languages.lua = { - 'comment': /^#!.+|--(?:\[(=*)\[[\s\S]*?\]\1\]|.*)/m, - // \z may be used to skip the following space - 'string': { - pattern: /(["'])(?:(?!\1)[^\\\r\n]|\\z(?:\r\n|\s)|\\(?:\r\n|[\s\S]))*\1|\[(=*)\[[\s\S]*?\]\2\]/, - greedy: true - }, - 'number': /\b0x[a-f\d]+\.?[a-f\d]*(?:p[+-]?\d+)?\b|\b\d+(?:\.\B|\.?\d*(?:e[+-]?\d+)?\b)|\B\.\d+(?:e[+-]?\d+)?\b/i, - 'keyword': /\b(?:and|break|do|else|elseif|end|false|for|function|goto|if|in|local|nil|not|or|repeat|return|then|true|until|while)\b/, - 'function': /(?!\d)\w+(?=\s*(?:[({]))/, - 'operator': [ - /[-+*%^&|#]|\/\/?|<[<=]?|>[>=]?|[=~]=?/, - { - // Match ".." but don't break "..." - pattern: /(^|[^.])\.\.(?!\.)/, - lookbehind: true - } - ], - 'punctuation': /[\[\](){},;]|\.+|:+/ - }; - Prism.languages.matlab = { - // We put string before comment, because of printf() patterns that contain "%" - 'string': /\B'(?:''|[^'\n])*'/, - 'comment': [ - /%\{[\s\S]*?\}%/, - /%.+/ - ], - // FIXME We could handle imaginary numbers as a whole - 'number': /\b-?(?:\d*\.?\d+(?:[eE][+-]?\d+)?(?:[ij])?|[ij])\b/, - 'keyword': /\b(?:break|case|catch|continue|else|elseif|end|for|function|if|inf|NaN|otherwise|parfor|pause|pi|return|switch|try|while)\b/, - 'function': /(?!\d)\w+(?=\s*\()/, - 'operator': /\.?[*^\/\\']|[+\-:@]|[<>=~]=?|&&?|\|\|?/, - 'punctuation': /\.{3}|[.,;\[\](){}!]/ - }; - - Prism.languages.nim = { - 'comment': /#.*/, - // Double-quoted strings can be prefixed by an identifier (Generalized raw string literals) - // Character literals are handled specifically to prevent issues with numeric type suffixes - 'string': { - pattern: /(?:(?:\b(?!\d)(?:\w|\\x[8-9a-fA-F][0-9a-fA-F])+)?(?:"""[\s\S]*?"""(?!")|"(?:\\[\s\S]|""|[^"\\])*")|'(?:\\(?:\d+|x[\da-fA-F]{2}|.)|[^'])')/, - greedy: true - }, - // The negative look ahead prevents wrong highlighting of the .. operator - 'number': /\b(?:0[xXoObB][\da-fA-F_]+|\d[\d_]*(?:(?!\.\.)\.[\d_]*)?(?:[eE][+-]?\d[\d_]*)?)(?:'?[iuf]\d*)?/, - 'keyword': /\b(?:addr|as|asm|atomic|bind|block|break|case|cast|concept|const|continue|converter|defer|discard|distinct|do|elif|else|end|enum|except|export|finally|for|from|func|generic|if|import|include|interface|iterator|let|macro|method|mixin|nil|object|out|proc|ptr|raise|ref|return|static|template|try|tuple|type|using|var|when|while|with|without|yield)\b/, - 'function': { - pattern: /(?:(?!\d)(?:\w|\\x[8-9a-fA-F][0-9a-fA-F])+|`[^`\r\n]+`)\*?(?:\[[^\]]+\])?(?=\s*\()/, - inside: { - 'operator': /\*$/ - } - }, - // We don't want to highlight operators inside backticks - 'ignore': { - pattern: /`[^`\r\n]+`/, - inside: { - 'punctuation': /`/ - } - }, - 'operator': { - // Look behind and look ahead prevent wrong highlighting of punctuations [. .] {. .} (. .) - // but allow the slice operator .. to take precedence over them - // One can define his own operators in Nim so all combination of operators might be an operator. - pattern: /(^|[({\[](?=\.\.)|(?![({\[]\.).)(?:(?:[=+\-*\/<>@$~&%|!?^:\\]|\.\.|\.(?![)}\]]))+|\b(?:and|div|of|or|in|is|isnot|mod|not|notin|shl|shr|xor)\b)/m, - lookbehind: true - }, - 'punctuation': /[({\[]\.|\.[)}\]]|[`(){}\[\],:]/ - }; - Prism.languages.objectivec = Prism.languages.extend('c', { - 'keyword': /\b(asm|typeof|inline|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|void|volatile|while|in|self|super)\b|(@interface|@end|@implementation|@protocol|@class|@public|@protected|@private|@property|@try|@catch|@finally|@throw|@synthesize|@dynamic|@selector)\b/, - 'string': /("|')(\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1|@"(\\(?:\r\n|[\s\S])|[^"\\\r\n])*"/, - 'operator': /-[->]?|\+\+?|!=?|<>?=?|==?|&&?|\|\|?|[~^%?*\/@]/ - }); - - - /*-----------------------------------------------------------*/ - - - Prism.languages.perl = { - 'comment': [ - { - // POD - pattern: /(^\s*)=\w+[\s\S]*?=cut.*/m, - lookbehind: true - }, - { - pattern: /(^|[^\\$])#.*/, - lookbehind: true - } - ], - // TODO Could be nice to handle Heredoc too. - 'string': [ - // q/.../ - { - pattern: /\b(?:q|qq|qx|qw)\s*([^a-zA-Z0-9\s\{\(\[<])(?:[^\\]|\\[\s\S])*?\1/, - greedy: true - }, - - // q a...a - { - pattern: /\b(?:q|qq|qx|qw)\s+([a-zA-Z0-9])(?:[^\\]|\\[\s\S])*?\1/, - greedy: true - }, - - // q(...) - { - pattern: /\b(?:q|qq|qx|qw)\s*\((?:[^()\\]|\\[\s\S])*\)/, - greedy: true - }, - - // q{...} - { - pattern: /\b(?:q|qq|qx|qw)\s*\{(?:[^{}\\]|\\[\s\S])*\}/, - greedy: true - }, - - // q[...] - { - pattern: /\b(?:q|qq|qx|qw)\s*\[(?:[^[\]\\]|\\[\s\S])*\]/, - greedy: true - }, - - // q<...> - { - pattern: /\b(?:q|qq|qx|qw)\s*<(?:[^<>\\]|\\[\s\S])*>/, - greedy: true - }, - - // "...", `...` - { - pattern: /("|`)(?:[^\\]|\\[\s\S])*?\1/, - greedy: true - }, - - // '...' - // FIXME Multi-line single-quoted strings are not supported as they would break variables containing ' - { - pattern: /'(?:[^'\\\r\n]|\\.)*'/, - greedy: true - } - ], - 'regex': [ - // m/.../ - { - pattern: /\b(?:m|qr)\s*([^a-zA-Z0-9\s\{\(\[<])(?:[^\\]|\\[\s\S])*?\1[msixpodualngc]*/, - greedy: true - }, - - // m a...a - { - pattern: /\b(?:m|qr)\s+([a-zA-Z0-9])(?:[^\\]|\\.)*?\1[msixpodualngc]*/, - greedy: true - }, - - // m(...) - { - pattern: /\b(?:m|qr)\s*\((?:[^()\\]|\\[\s\S])*\)[msixpodualngc]*/, - greedy: true - }, - - // m{...} - { - pattern: /\b(?:m|qr)\s*\{(?:[^{}\\]|\\[\s\S])*\}[msixpodualngc]*/, - greedy: true - }, - - // m[...] - { - pattern: /\b(?:m|qr)\s*\[(?:[^[\]\\]|\\[\s\S])*\][msixpodualngc]*/, - greedy: true - }, - - // m<...> - { - pattern: /\b(?:m|qr)\s*<(?:[^<>\\]|\\[\s\S])*>[msixpodualngc]*/, - greedy: true - }, - - // The lookbehinds prevent -s from breaking - // FIXME We don't handle change of separator like s(...)[...] - // s/.../.../ - { - pattern: /(^|[^-]\b)(?:s|tr|y)\s*([^a-zA-Z0-9\s\{\(\[<])(?:[^\\]|\\[\s\S])*?\2(?:[^\\]|\\[\s\S])*?\2[msixpodualngcer]*/, - lookbehind: true, - greedy: true - }, - - // s a...a...a - { - pattern: /(^|[^-]\b)(?:s|tr|y)\s+([a-zA-Z0-9])(?:[^\\]|\\[\s\S])*?\2(?:[^\\]|\\[\s\S])*?\2[msixpodualngcer]*/, - lookbehind: true, - greedy: true - }, - - // s(...)(...) - { - pattern: /(^|[^-]\b)(?:s|tr|y)\s*\((?:[^()\\]|\\[\s\S])*\)\s*\((?:[^()\\]|\\[\s\S])*\)[msixpodualngcer]*/, - lookbehind: true, - greedy: true - }, - - // s{...}{...} - { - pattern: /(^|[^-]\b)(?:s|tr|y)\s*\{(?:[^{}\\]|\\[\s\S])*\}\s*\{(?:[^{}\\]|\\[\s\S])*\}[msixpodualngcer]*/, - lookbehind: true, - greedy: true - }, - - // s[...][...] - { - pattern: /(^|[^-]\b)(?:s|tr|y)\s*\[(?:[^[\]\\]|\\[\s\S])*\]\s*\[(?:[^[\]\\]|\\[\s\S])*\][msixpodualngcer]*/, - lookbehind: true, - greedy: true - }, - - // s<...><...> - { - pattern: /(^|[^-]\b)(?:s|tr|y)\s*<(?:[^<>\\]|\\[\s\S])*>\s*<(?:[^<>\\]|\\[\s\S])*>[msixpodualngcer]*/, - lookbehind: true, - greedy: true - }, - - // /.../ - // The look-ahead tries to prevent two divisions on - // the same line from being highlighted as regex. - // This does not support multi-line regex. - { - pattern: /\/(?:[^\/\\\r\n]|\\.)*\/[msixpodualngc]*(?=\s*(?:$|[\r\n,.;})&|\-+*~<>!?^]|(lt|gt|le|ge|eq|ne|cmp|not|and|or|xor|x)\b))/, - greedy: true - } - ], - - // FIXME Not sure about the handling of ::, ', and # - 'variable': [ - // ${^POSTMATCH} - /[&*$@%]\{\^[A-Z]+\}/, - // $^V - /[&*$@%]\^[A-Z_]/, - // ${...} - /[&*$@%]#?(?=\{)/, - // $foo - /[&*$@%]#?((::)*'?(?!\d)[\w$]+)+(::)*/i, - // $1 - /[&*$@%]\d+/, - // $_, @_, %! - // The negative lookahead prevents from breaking the %= operator - /(?!%=)[$@%][!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/ - ], - 'filehandle': { - // <>, , _ - pattern: /<(?![<=])\S*>|\b_\b/, - alias: 'symbol' - }, - 'vstring': { - // v1.2, 1.2.3 - pattern: /v\d+(\.\d+)*|\d+(\.\d+){2,}/, - alias: 'string' - }, - 'function': { - pattern: /sub [a-z0-9_]+/i, - inside: { - keyword: /sub/ - } - }, - 'keyword': /\b(any|break|continue|default|delete|die|do|else|elsif|eval|for|foreach|given|goto|if|last|local|my|next|our|package|print|redo|require|say|state|sub|switch|undef|unless|until|use|when|while)\b/, - 'number': /\b-?(0x[\dA-Fa-f](_?[\dA-Fa-f])*|0b[01](_?[01])*|(\d(_?\d)*)?\.?\d(_?\d)*([Ee][+-]?\d+)?)\b/, - 'operator': /-[rwxoRWXOezsfdlpSbctugkTBMAC]\b|\+[+=]?|-[-=>]?|\*\*?=?|\/\/?=?|=[=~>]?|~[~=]?|\|\|?=?|&&?=?|<(?:=>?|<=?)?|>>?=?|![~=]?|[%^]=?|\.(?:=|\.\.?)?|[\\?]|\bx(?:=|\b)|\b(lt|gt|le|ge|eq|ne|cmp|not|and|or|xor)\b/, - 'punctuation': /[{}[\];(),:]/ - }; - - /*-----------------------------------------------------------*/ - - Prism.languages.php = Prism.languages.extend('clike', { - 'keyword': /\b(and|or|xor|array|as|break|case|cfunction|class|const|continue|declare|default|die|do|else|elseif|enddeclare|endfor|endforeach|endif|endswitch|endwhile|extends|for|foreach|function|include|include_once|global|if|new|return|static|switch|use|require|require_once|var|while|abstract|interface|public|implements|private|protected|parent|throw|null|echo|print|trait|namespace|final|yield|goto|instanceof|finally|try|catch)\b/i, - 'constant': /\b[A-Z0-9_]{2,}\b/, - 'comment': { - pattern: /(^|[^\\])(?:\/\*[\s\S]*?\*\/|\/\/.*)/, - lookbehind: true - } - }); - - // Shell-like comments are matched after strings, because they are less - // common than strings containing hashes... - Prism.languages.insertBefore('php', 'class-name', { - 'shell-comment': { - pattern: /(^|[^\\])#.*/, - lookbehind: true, - alias: 'comment' - } - }); - - Prism.languages.insertBefore('php', 'keyword', { - 'delimiter': { - pattern: /\?>|<\?(?:php|=)?/i, - alias: 'important' - }, - 'variable': /\$\w+\b/i, - 'package': { - pattern: /(\\|namespace\s+|use\s+)[\w\\]+/, - lookbehind: true, - inside: { - punctuation: /\\/ - } - } - }); - - // Must be defined after the function pattern - Prism.languages.insertBefore('php', 'operator', { - 'property': { - pattern: /(->)[\w]+/, - lookbehind: true - } - }); - - // Add HTML support if the markup language exists - if (Prism.languages.markup) { - - // Tokenize all inline PHP blocks that are wrapped in - // This allows for easy PHP + markup highlighting - Prism.hooks.add('before-highlight', function(env) { - if (env.language !== 'php' || !/(?:<\?php|<\?)/ig.test(env.code)) { - return; - } - - env.tokenStack = []; - - env.backupCode = env.code; - env.code = env.code.replace(/(?:<\?php|<\?)[\s\S]*?(?:\?>|$)/ig, function(match) { - var i = env.tokenStack.length; - // Check for existing strings - while (env.backupCode.indexOf('___PHP' + i + '___') !== -1) - ++i; - - // Create a sparse array - env.tokenStack[i] = match; - - return '___PHP' + i + '___'; - }); - - // Switch the grammar to markup - env.grammar = Prism.languages.markup; - }); - - // Restore env.code for other plugins (e.g. line-numbers) - Prism.hooks.add('before-insert', function(env) { - if (env.language === 'php' && env.backupCode) { - env.code = env.backupCode; - delete env.backupCode; - } - }); - - // Re-insert the tokens after highlighting - Prism.hooks.add('after-highlight', function(env) { - if (env.language !== 'php' || !env.tokenStack) { - return; - } - - // Switch the grammar back - env.grammar = Prism.languages.php; - - for (var i = 0, keys = Object.keys(env.tokenStack); i < keys.length; ++i) { - var k = keys[i]; - var t = env.tokenStack[k]; - - // The replace prevents $$, $&, $`, $', $n, $nn from being interpreted as special patterns - env.highlightedCode = env.highlightedCode.replace('___PHP' + k + '___', - "" + - Prism.highlight(t, env.grammar, 'php').replace(/\$/g, '$$$$') + - ""); - } - - env.element.innerHTML = env.highlightedCode; - }); - }; - - - /*------------------------------------------------------------*/ - - Prism.languages.powershell = { - 'comment': [ - { - pattern: /(^|[^`])<#[\s\S]*?#>/, - lookbehind: true - }, - { - pattern: /(^|[^`])#.*/, - lookbehind: true - } - ], - 'string': [ - { - pattern: /"(`?[\s\S])*?"/, - greedy: true, - inside: { - 'function': { - pattern: /[^`]\$\(.*?\)/, - // Populated at end of file - inside: {} - } - } - }, - { - pattern: /'([^']|'')*'/, - greedy: true - } - ], - // Matches name spaces as well as casts, attribute decorators. Force starting with letter to avoid matching array indices - 'namespace': /\[[a-z][\s\S]*?\]/i, - 'boolean': /\$(true|false)\b/i, - 'variable': /\$\w+\b/i, - // Cmdlets and aliases. Aliases should come last, otherwise "write" gets preferred over "write-host" for example - // Get-Command | ?{ $_.ModuleName -match "Microsoft.PowerShell.(Util|Core|Management)" } - // Get-Alias | ?{ $_.ReferencedCommand.Module.Name -match "Microsoft.PowerShell.(Util|Core|Management)" } - 'function': [ - /\b(Add-(Computer|Content|History|Member|PSSnapin|Type)|Checkpoint-Computer|Clear-(Content|EventLog|History|Item|ItemProperty|Variable)|Compare-Object|Complete-Transaction|Connect-PSSession|ConvertFrom-(Csv|Json|StringData)|Convert-Path|ConvertTo-(Csv|Html|Json|Xml)|Copy-(Item|ItemProperty)|Debug-Process|Disable-(ComputerRestore|PSBreakpoint|PSRemoting|PSSessionConfiguration)|Disconnect-PSSession|Enable-(ComputerRestore|PSBreakpoint|PSRemoting|PSSessionConfiguration)|Enter-PSSession|Exit-PSSession|Export-(Alias|Clixml|Console|Csv|FormatData|ModuleMember|PSSession)|ForEach-Object|Format-(Custom|List|Table|Wide)|Get-(Alias|ChildItem|Command|ComputerRestorePoint|Content|ControlPanelItem|Culture|Date|Event|EventLog|EventSubscriber|FormatData|Help|History|Host|HotFix|Item|ItemProperty|Job|Location|Member|Module|Process|PSBreakpoint|PSCallStack|PSDrive|PSProvider|PSSession|PSSessionConfiguration|PSSnapin|Random|Service|TraceSource|Transaction|TypeData|UICulture|Unique|Variable|WmiObject)|Group-Object|Import-(Alias|Clixml|Csv|LocalizedData|Module|PSSession)|Invoke-(Command|Expression|History|Item|RestMethod|WebRequest|WmiMethod)|Join-Path|Limit-EventLog|Measure-(Command|Object)|Move-(Item|ItemProperty)|New-(Alias|Event|EventLog|Item|ItemProperty|Module|ModuleManifest|Object|PSDrive|PSSession|PSSessionConfigurationFile|PSSessionOption|PSTransportOption|Service|TimeSpan|Variable|WebServiceProxy)|Out-(Default|File|GridView|Host|Null|Printer|String)|Pop-Location|Push-Location|Read-Host|Receive-(Job|PSSession)|Register-(EngineEvent|ObjectEvent|PSSessionConfiguration|WmiEvent)|Remove-(Computer|Event|EventLog|Item|ItemProperty|Job|Module|PSBreakpoint|PSDrive|PSSession|PSSnapin|TypeData|Variable|WmiObject)|Rename-(Computer|Item|ItemProperty)|Reset-ComputerMachinePassword|Resolve-Path|Restart-(Computer|Service)|Restore-Computer|Resume-(Job|Service)|Save-Help|Select-(Object|String|Xml)|Send-MailMessage|Set-(Alias|Content|Date|Item|ItemProperty|Location|PSBreakpoint|PSDebug|PSSessionConfiguration|Service|StrictMode|TraceSource|Variable|WmiInstance)|Show-(Command|ControlPanelItem|EventLog)|Sort-Object|Split-Path|Start-(Job|Process|Service|Sleep|Transaction)|Stop-(Computer|Job|Process|Service)|Suspend-(Job|Service)|Tee-Object|Test-(ComputerSecureChannel|Connection|ModuleManifest|Path|PSSessionConfigurationFile)|Trace-Command|Unblock-File|Undo-Transaction|Unregister-(Event|PSSessionConfiguration)|Update-(FormatData|Help|List|TypeData)|Use-Transaction|Wait-(Event|Job|Process)|Where-Object|Write-(Debug|Error|EventLog|Host|Output|Progress|Verbose|Warning))\b/i, - /\b(ac|cat|chdir|clc|cli|clp|clv|compare|copy|cp|cpi|cpp|cvpa|dbp|del|diff|dir|ebp|echo|epal|epcsv|epsn|erase|fc|fl|ft|fw|gal|gbp|gc|gci|gcs|gdr|gi|gl|gm|gp|gps|group|gsv|gu|gv|gwmi|iex|ii|ipal|ipcsv|ipsn|irm|iwmi|iwr|kill|lp|ls|measure|mi|mount|move|mp|mv|nal|ndr|ni|nv|ogv|popd|ps|pushd|pwd|rbp|rd|rdr|ren|ri|rm|rmdir|rni|rnp|rp|rv|rvpa|rwmi|sal|saps|sasv|sbp|sc|select|set|shcm|si|sl|sleep|sls|sort|sp|spps|spsv|start|sv|swmi|tee|trcm|type|write)\b/i - ], - // per http://technet.microsoft.com/en-us/library/hh847744.aspx - 'keyword': /\b(Begin|Break|Catch|Class|Continue|Data|Define|Do|DynamicParam|Else|ElseIf|End|Exit|Filter|Finally|For|ForEach|From|Function|If|InlineScript|Parallel|Param|Process|Return|Sequence|Switch|Throw|Trap|Try|Until|Using|Var|While|Workflow)\b/i, - 'operator': { - pattern: /(\W?)(!|-(eq|ne|gt|ge|lt|le|sh[lr]|not|b?(and|x?or)|(Not)?(Like|Match|Contains|In)|Replace|Join|is(Not)?|as)\b|-[-=]?|\+[+=]?|[*\/%]=?)/i, - lookbehind: true - }, - 'punctuation': /[|{}[\];(),.]/ - }; - - // Variable interpolation inside strings, and nested expressions - Prism.languages.powershell.string[0].inside.boolean = Prism.languages.powershell.boolean; - Prism.languages.powershell.string[0].inside.variable = Prism.languages.powershell.variable; - Prism.languages.powershell.string[0].inside.function.inside = Prism.util.clone(Prism.languages.powershell); - - /*------------------------------------------------------------*/ - - - Prism.languages.python= { - 'triple-quoted-string': { - pattern: /"""[\s\S]+?"""|'''[\s\S]+?'''/, - alias: 'string' - }, - 'comment': { - pattern: /(^|[^\\])#.*/, - lookbehind: true - }, - 'string': { - pattern: /("|')(?:\\\\|\\?[^\\\r\n])*?\1/, - greedy: true - }, - 'function' : { - pattern: /((?:^|\s)def[ \t]+)[a-zA-Z_][a-zA-Z0-9_]*(?=\()/g, - lookbehind: true - }, - 'class-name': { - pattern: /(\bclass\s+)[a-z0-9_]+/i, - lookbehind: true - }, - 'keyword' : /\b(?:as|assert|async|await|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|pass|print|raise|return|try|while|with|yield)\b/, - 'boolean' : /\b(?:True|False)\b/, - 'number' : /\b-?(?:0[bo])?(?:(?:\d|0x[\da-f])[\da-f]*\.?\d*|\.\d+)(?:e[+-]?\d+)?j?\b/i, - 'operator' : /[-+%=]=?|!=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]|\b(?:or|and|not)\b/, - 'punctuation' : /[{}[\];(),.:]/ - }; - - Prism.languages.r = { - 'comment': /#.*/, - 'string': { - pattern: /(['"])(?:\\?.)*?\1/, - greedy: true - }, - 'percent-operator': { - // Includes user-defined operators - // and %%, %*%, %/%, %in%, %o%, %x% - pattern: /%[^%\s]*%/, - alias: 'operator' - }, - 'boolean': /\b(?:TRUE|FALSE)\b/, - 'ellipsis': /\.\.(?:\.|\d+)/, - 'number': [ - /\b(?:NaN|Inf)\b/, - /\b(?:0x[\dA-Fa-f]+(?:\.\d*)?|\d*\.?\d+)(?:[EePp][+-]?\d+)?[iL]?\b/ - ], - 'keyword': /\b(?:if|else|repeat|while|function|for|in|next|break|NULL|NA|NA_integer_|NA_real_|NA_complex_|NA_character_)\b/, - 'operator': /->?>?|<(?:=|=!]=?|::?|&&?|\|\|?|[+*\/^$@~]/, - 'punctuation': /[(){}\[\],;]/ - }; - - /*------------------------------------------------------------*/ - - Prism.languages.rust = { - 'comment': [ - { - pattern: /(^|[^\\])\/\*[\s\S]*?\*\//, - lookbehind: true - }, - { - pattern: /(^|[^\\:])\/\/.*/, - lookbehind: true - } - ], - 'string': [ - { - pattern: /b?r(#*)"(?:\\?.)*?"\1/, - greedy: true - }, - { - pattern: /b?("|')(?:\\?.)*?\1/, - greedy: true - } - ], - 'keyword': /\b(?:abstract|alignof|as|be|box|break|const|continue|crate|do|else|enum|extern|false|final|fn|for|if|impl|in|let|loop|match|mod|move|mut|offsetof|once|override|priv|pub|pure|ref|return|sizeof|static|self|struct|super|true|trait|type|typeof|unsafe|unsized|use|virtual|where|while|yield)\b/, - - 'attribute': { - pattern: /#!?\[.+?\]/, - greedy: true, - alias: 'attr-name' - }, - - 'function': [ - /[a-z0-9_]+(?=\s*\()/i, - // Macros can use parens or brackets - /[a-z0-9_]+!(?=\s*\(|\[)/i - ], - 'macro-rules': { - pattern: /[a-z0-9_]+!/i, - alias: 'function' - }, - - // Hex, oct, bin, dec numbers with visual separators and type suffix - 'number': /\b-?(?:0x[\dA-Fa-f](?:_?[\dA-Fa-f])*|0o[0-7](?:_?[0-7])*|0b[01](?:_?[01])*|(\d(_?\d)*)?\.?\d(_?\d)*([Ee][+-]?\d+)?)(?:_?(?:[iu](?:8|16|32|64)?|f32|f64))?\b/, - - // Closure params should not be confused with bitwise OR | - 'closure-params': { - pattern: /\|[^|]*\|(?=\s*[{-])/, - inside: { - 'punctuation': /[\|:,]/, - 'operator': /[&*]/ - } - }, - 'punctuation': /[{}[\];(),:]|\.+|->/, - 'operator': /[-+*\/%!^=]=?|@|&[&=]?|\|[|=]?|<>?=?/ - }; - - /*------------------------------------------------------------*/ - - ;(function(Prism) { - Prism.languages.sass = Prism.languages.extend('css', { - // Sass comments don't need to be closed, only indented - 'comment': { - pattern: /^([ \t]*)\/[\/*].*(?:(?:\r?\n|\r)\1[ \t]+.+)*/m, - lookbehind: true - } - }); - - Prism.languages.insertBefore('sass', 'atrule', { - // We want to consume the whole line - 'atrule-line': { - // Includes support for = and + shortcuts - pattern: /^(?:[ \t]*)[@+=].+/m, - inside: { - 'atrule': /(?:@[\w-]+|[+=])/m - } - } - }); - delete Prism.languages.sass.atrule; - - - var variable = /((\$[-_\w]+)|(#\{\$[-_\w]+\}))/i; - var operator = [ - /[+*\/%]|[=!]=|<=?|>=?|\b(?:and|or|not)\b/, - { - pattern: /(\s+)-(?=\s)/, - lookbehind: true - } - ]; - - Prism.languages.insertBefore('sass', 'property', { - // We want to consume the whole line - 'variable-line': { - pattern: /^[ \t]*\$.+/m, - inside: { - 'punctuation': /:/, - 'variable': variable, - 'operator': operator - } - }, - // We want to consume the whole line - 'property-line': { - pattern: /^[ \t]*(?:[^:\s]+ *:.*|:[^:\s]+.*)/m, - inside: { - 'property': [ - /[^:\s]+(?=\s*:)/, - { - pattern: /(:)[^:\s]+/, - lookbehind: true - } - ], - 'punctuation': /:/, - 'variable': variable, - 'operator': operator, - 'important': Prism.languages.sass.important - } - } - }); - delete Prism.languages.sass.property; - delete Prism.languages.sass.important; - - // Now that whole lines for other patterns are consumed, - // what's left should be selectors - delete Prism.languages.sass.selector; - Prism.languages.insertBefore('sass', 'punctuation', { - 'selector': { - pattern: /([ \t]*)\S(?:,?[^,\r\n]+)*(?:,(?:\r?\n|\r)\1[ \t]+\S(?:,?[^,\r\n]+)*)*/, - lookbehind: true - } - }); - - }(Prism)); - Prism.languages.scss = Prism.languages.extend('css', { - 'comment': { - pattern: /(^|[^\\])(?:\/\*[\s\S]*?\*\/|\/\/.*)/, - lookbehind: true - }, - 'atrule': { - pattern: /@[\w-]+(?:\([^()]+\)|[^(])*?(?=\s+[{;])/, - inside: { - 'rule': /@[\w-]+/ - // See rest below - } - }, - // url, compassified - 'url': /(?:[-a-z]+-)*url(?=\()/i, - // CSS selector regex is not appropriate for Sass - // since there can be lot more things (var, @ directive, nesting..) - // a selector must start at the end of a property or after a brace (end of other rules or nesting) - // it can contain some characters that aren't used for defining rules or end of selector, & (parent selector), or interpolated variable - // the end of a selector is found when there is no rules in it ( {} or {\s}) or if there is a property (because an interpolated var - // can "pass" as a selector- e.g: proper#{$erty}) - // this one was hard to do, so please be careful if you edit this one :) - 'selector': { - // Initial look-ahead is used to prevent matching of blank selectors - pattern: /(?=\S)[^@;\{\}\(\)]?([^@;\{\}\(\)]|&|#\{\$[-_\w]+\})+(?=\s*\{(\}|\s|[^\}]+(:|\{)[^\}]+))/m, - inside: { - 'parent': { - pattern: /&/, - alias: 'important' - }, - 'placeholder': /%[-_\w]+/, - 'variable': /\$[-_\w]+|#\{\$[-_\w]+\}/ - } - } - }); - - Prism.languages.insertBefore('scss', 'atrule', { - 'keyword': [ - /@(?:if|else(?: if)?|for|each|while|import|extend|debug|warn|mixin|include|function|return|content)/i, - { - pattern: /( +)(?:from|through)(?= )/, - lookbehind: true - } - ] - }); - - Prism.languages.scss.property = { - pattern: /(?:[\w-]|\$[-_\w]+|#\{\$[-_\w]+\})+(?=\s*:)/i, - inside: { - 'variable': /\$[-_\w]+|#\{\$[-_\w]+\}/ - } - }; - - Prism.languages.insertBefore('scss', 'important', { - // var and interpolated vars - 'variable': /\$[-_\w]+|#\{\$[-_\w]+\}/ - }); - - Prism.languages.insertBefore('scss', 'function', { - 'placeholder': { - pattern: /%[-_\w]+/, - alias: 'selector' - }, - 'statement': { - pattern: /\B!(?:default|optional)\b/i, - alias: 'keyword' - }, - 'boolean': /\b(?:true|false)\b/, - 'null': /\bnull\b/, - 'operator': { - pattern: /(\s)(?:[-+*\/%]|[=!]=|<=?|>=?|and|or|not)(?=\s)/, - lookbehind: true - } - }); - - Prism.languages.scss['atrule'].inside.rest = Prism.util.clone(Prism.languages.scss); - - /*-----------------------------smarty-------------------------*/ - - ;(function(Prism) { - - var smarty_pattern = /\{\*[\s\S]+?\*\}|\{[\s\S]+?\}/g; - var smarty_litteral_start = '{literal}'; - var smarty_litteral_end = '{/literal}'; - var smarty_litteral_mode = false; - - Prism.languages.smarty = Prism.languages.extend('markup', { - 'smarty': { - pattern: smarty_pattern, - inside: { - 'delimiter': { - pattern: /^\{|\}$/i, - alias: 'punctuation' - }, - 'string': /(["'])(?:\\?.)*?\1/, - 'number': /\b-?(?:0x[\dA-Fa-f]+|\d*\.?\d+(?:[Ee][-+]?\d+)?)\b/, - 'variable': [ - /\$(?!\d)\w+/, - /#(?!\d)\w+#/, - { - pattern: /(\.|->)(?!\d)\w+/, - lookbehind: true - }, - { - pattern: /(\[)(?!\d)\w+(?=\])/, - lookbehind: true - } - ], - 'function': [ - { - pattern: /(\|\s*)@?(?!\d)\w+/, - lookbehind: true - }, - /^\/?(?!\d)\w+/, - /(?!\d)\w+(?=\()/ - ], - 'attr-name': { - // Value is made optional because it may have already been tokenized - pattern: /\w+\s*=\s*(?:(?!\d)\w+)?/, - inside: { - "variable": { - pattern: /(=\s*)(?!\d)\w+/, - lookbehind: true - }, - "operator": /=/ - } - }, - 'punctuation': [ - /[\[\]().,:`]|\->/ - ], - 'operator': [ - /[+\-*\/%]|==?=?|[!<>]=?|&&|\|\|?/, - /\bis\s+(?:not\s+)?(?:div|even|odd)(?:\s+by)?\b/, - /\b(?:eq|neq?|gt|lt|gt?e|lt?e|not|mod|or|and)\b/ - ], - 'keyword': /\b(?:false|off|on|no|true|yes)\b/ - } - } - }); - - // Comments are inserted at top so that they can - // surround markup - Prism.languages.insertBefore('smarty', 'tag', { - 'smarty-comment': { - pattern: /\{\*[\s\S]*?\*\}/, - alias: ['smarty','comment'] - } - }); - - // Tokenize all inline Smarty expressions - Prism.hooks.add('before-highlight', function(env) { - if (env.language !== 'smarty') { - return; - } - - env.tokenStack = []; - - env.backupCode = env.code; - env.code = env.code.replace(smarty_pattern, function(match) { - - // Smarty tags inside {literal} block are ignored - if(match === smarty_litteral_end) { - smarty_litteral_mode = false; - } - - if(!smarty_litteral_mode) { - if(match === smarty_litteral_start) { - smarty_litteral_mode = true; - } - - var i = env.tokenStack.length; - // Check for existing strings - while (env.backupCode.indexOf('___SMARTY' + i + '___') !== -1) - ++i; - - // Create a sparse array - env.tokenStack[i] = match; - - return '___SMARTY' + i + '___'; - } - return match; - }); - }); - - // Restore env.code for other plugins (e.g. line-numbers) - Prism.hooks.add('before-insert', function(env) { - if (env.language === 'smarty') { - env.code = env.backupCode; - delete env.backupCode; - } - }); - - // Re-insert the tokens after highlighting - // and highlight them with defined grammar - Prism.hooks.add('after-highlight', function(env) { - if (env.language !== 'smarty') { - return; - } - - for (var i = 0, keys = Object.keys(env.tokenStack); i < keys.length; ++i) { - var k = keys[i]; - var t = env.tokenStack[k]; - - // The replace prevents $$, $&, $`, $', $n, $nn from being interpreted as special patterns - env.highlightedCode = env.highlightedCode.replace('___SMARTY' + k + '___', Prism.highlight(t, env.grammar, 'smarty').replace(/\$/g, '$$$$')); - } - - env.element.innerHTML = env.highlightedCode; - }); - - }(Prism)); - - /*-----------------------------------------------------------*/ - - Prism.languages.sql= { - 'comment': { - pattern: /(^|[^\\])(?:\/\*[\s\S]*?\*\/|(?:--|\/\/|#).*)/, - lookbehind: true - }, - 'string' : { - pattern: /(^|[^@\\])("|')(?:\\?[\s\S])*?\2/, - greedy: true, - lookbehind: true - }, - 'variable': /@[\w.$]+|@("|'|`)(?:\\?[\s\S])+?\1/, - 'function': /\b(?:COUNT|SUM|AVG|MIN|MAX|FIRST|LAST|UCASE|LCASE|MID|LEN|ROUND|NOW|FORMAT)(?=\s*\()/i, // Should we highlight user defined functions too? - 'keyword': /\b(?:ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR VARYING|CHARACTER (?:SET|VARYING)|CHARSET|CHECK|CHECKPOINT|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMN|COLUMNS|COMMENT|COMMIT|COMMITTED|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS|CONTAINSTABLE|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|DATA(?:BASES?)?|DATE(?:TIME)?|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITER(?:S)?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE(?: PRECISION)?|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE KEY|ELSE|ENABLE|ENCLOSED BY|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPE(?:D BY)?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|IDENTITY(?:_INSERT|COL)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTO|INVOKER|ISOLATION LEVEL|JOIN|KEYS?|KILL|LANGUAGE SQL|LAST|LEFT|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MODIFIES SQL DATA|MODIFY|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL(?: CHAR VARYING| CHARACTER(?: VARYING)?| VARCHAR)?|NATURAL|NCHAR(?: VARCHAR)?|NEXT|NO(?: SQL|CHECK|CYCLE)?|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READ(?:S SQL DATA|TEXT)?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEATABLE|REPLICATION|REQUIRE|RESTORE|RESTRICT|RETURNS?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE MODE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|START(?:ING BY)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED BY|TEXT(?:SIZE)?|THEN|TIMESTAMP|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNPIVOT|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?)\b/i, - 'boolean': /\b(?:TRUE|FALSE|NULL)\b/i, - 'number': /\b-?(?:0x)?\d*\.?[\da-f]+\b/, - 'operator': /[-+*\/=%^~]|&&?|\|?\||!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|IN|LIKE|NOT|OR|IS|DIV|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/i, - 'punctuation': /[;[\]()`,.]/ - }; - - /*-----------------------------------------------------------*/ - - Prism.languages.swift = Prism.languages.extend('clike', { - 'string': { - pattern: /("|')(\\(?:\((?:[^()]|\([^)]+\))+\)|\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/, - greedy: true, - inside: { - 'interpolation': { - pattern: /\\\((?:[^()]|\([^)]+\))+\)/, - inside: { - delimiter: { - pattern: /^\\\(|\)$/, - alias: 'variable' - } - // See rest below - } - } - } - }, - 'keyword': /\b(as|associativity|break|case|catch|class|continue|convenience|default|defer|deinit|didSet|do|dynamic(?:Type)?|else|enum|extension|fallthrough|final|for|func|get|guard|if|import|in|infix|init|inout|internal|is|lazy|left|let|mutating|new|none|nonmutating|operator|optional|override|postfix|precedence|prefix|private|Protocol|public|repeat|required|rethrows|return|right|safe|self|Self|set|static|struct|subscript|super|switch|throws?|try|Type|typealias|unowned|unsafe|var|weak|where|while|willSet|__(?:COLUMN__|FILE__|FUNCTION__|LINE__))\b/, - 'number': /\b([\d_]+(\.[\de_]+)?|0x[a-f0-9_]+(\.[a-f0-9p_]+)?|0b[01_]+|0o[0-7_]+)\b/i, - 'constant': /\b(nil|[A-Z_]{2,}|k[A-Z][A-Za-z_]+)\b/, - 'atrule': /@\b(IB(?:Outlet|Designable|Action|Inspectable)|class_protocol|exported|noreturn|NS(?:Copying|Managed)|objc|UIApplicationMain|auto_closure)\b/, - 'builtin': /\b([A-Z]\S+|abs|advance|alignof(?:Value)?|assert|contains|count(?:Elements)?|debugPrint(?:ln)?|distance|drop(?:First|Last)|dump|enumerate|equal|filter|find|first|getVaList|indices|isEmpty|join|last|lexicographicalCompare|map|max(?:Element)?|min(?:Element)?|numericCast|overlaps|partition|print(?:ln)?|reduce|reflect|reverse|sizeof(?:Value)?|sort(?:ed)?|split|startsWith|stride(?:of(?:Value)?)?|suffix|swap|toDebugString|toString|transcode|underestimateCount|unsafeBitCast|with(?:ExtendedLifetime|Unsafe(?:MutablePointers?|Pointers?)|VaList))\b/ - }); - Prism.languages.swift['string'].inside['interpolation'].inside.rest = Prism.util.clone(Prism.languages.swift); - Prism.languages.typescript = Prism.languages.extend('javascript', { - // From JavaScript Prism keyword list and TypeScript language spec: https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#221-reserved-words - 'keyword': /\b(as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|var|void|while|with|yield|false|true|module|declare|constructor|string|Function|any|number|boolean|Array|enum|symbol|namespace|abstract|require|type)\b/ - }); - - Prism.languages.ts = Prism.languages.typescript; - Prism.languages.vim = { - 'string': /"(?:[^"\\\r\n]|\\.)*"|'(?:[^'\r\n]|'')*'/, - 'comment': /".*/, - 'function': /\w+(?=\()/, - 'keyword': /\b(?:ab|abbreviate|abc|abclear|abo|aboveleft|al|all|arga|argadd|argd|argdelete|argdo|arge|argedit|argg|argglobal|argl|arglocal|ar|args|argu|argument|as|ascii|bad|badd|ba|ball|bd|bdelete|be|bel|belowright|bf|bfirst|bl|blast|bm|bmodified|bn|bnext|bN|bNext|bo|botright|bp|bprevious|brea|break|breaka|breakadd|breakd|breakdel|breakl|breaklist|br|brewind|bro|browse|bufdo|b|buffer|buffers|bun|bunload|bw|bwipeout|ca|cabbrev|cabc|cabclear|caddb|caddbuffer|cad|caddexpr|caddf|caddfile|cal|call|cat|catch|cb|cbuffer|cc|ccl|cclose|cd|ce|center|cex|cexpr|cf|cfile|cfir|cfirst|cgetb|cgetbuffer|cgete|cgetexpr|cg|cgetfile|c|change|changes|chd|chdir|che|checkpath|checkt|checktime|cla|clast|cl|clist|clo|close|cmapc|cmapclear|cnew|cnewer|cn|cnext|cN|cNext|cnf|cnfile|cNfcNfile|cnorea|cnoreabbrev|col|colder|colo|colorscheme|comc|comclear|comp|compiler|conf|confirm|con|continue|cope|copen|co|copy|cpf|cpfile|cp|cprevious|cq|cquit|cr|crewind|cuna|cunabbrev|cu|cunmap|cw|cwindow|debugg|debuggreedy|delc|delcommand|d|delete|delf|delfunction|delm|delmarks|diffg|diffget|diffoff|diffpatch|diffpu|diffput|diffsplit|diffthis|diffu|diffupdate|dig|digraphs|di|display|dj|djump|dl|dlist|dr|drop|ds|dsearch|dsp|dsplit|earlier|echoe|echoerr|echom|echomsg|echon|e|edit|el|else|elsei|elseif|em|emenu|endfo|endfor|endf|endfunction|endfun|en|endif|endt|endtry|endw|endwhile|ene|enew|ex|exi|exit|exu|exusage|f|file|files|filetype|fina|finally|fin|find|fini|finish|fir|first|fix|fixdel|fo|fold|foldc|foldclose|folddoc|folddoclosed|foldd|folddoopen|foldo|foldopen|for|fu|fun|function|go|goto|gr|grep|grepa|grepadd|ha|hardcopy|h|help|helpf|helpfind|helpg|helpgrep|helpt|helptags|hid|hide|his|history|ia|iabbrev|iabc|iabclear|if|ij|ijump|il|ilist|imapc|imapclear|in|inorea|inoreabbrev|isearch|isp|isplit|iuna|iunabbrev|iu|iunmap|j|join|ju|jumps|k|keepalt|keepj|keepjumps|kee|keepmarks|laddb|laddbuffer|lad|laddexpr|laddf|laddfile|lan|language|la|last|later|lb|lbuffer|lc|lcd|lch|lchdir|lcl|lclose|let|left|lefta|leftabove|lex|lexpr|lf|lfile|lfir|lfirst|lgetb|lgetbuffer|lgete|lgetexpr|lg|lgetfile|lgr|lgrep|lgrepa|lgrepadd|lh|lhelpgrep|l|list|ll|lla|llast|lli|llist|lmak|lmake|lm|lmap|lmapc|lmapclear|lnew|lnewer|lne|lnext|lN|lNext|lnf|lnfile|lNf|lNfile|ln|lnoremap|lo|loadview|loc|lockmarks|lockv|lockvar|lol|lolder|lop|lopen|lpf|lpfile|lp|lprevious|lr|lrewind|ls|lt|ltag|lu|lunmap|lv|lvimgrep|lvimgrepa|lvimgrepadd|lw|lwindow|mak|make|ma|mark|marks|mat|match|menut|menutranslate|mk|mkexrc|mks|mksession|mksp|mkspell|mkvie|mkview|mkv|mkvimrc|mod|mode|m|move|mzf|mzfile|mz|mzscheme|nbkey|new|n|next|N|Next|nmapc|nmapclear|noh|nohlsearch|norea|noreabbrev|nu|number|nun|nunmap|omapc|omapclear|on|only|o|open|opt|options|ou|ounmap|pc|pclose|ped|pedit|pe|perl|perld|perldo|po|pop|popu|popu|popup|pp|ppop|pre|preserve|prev|previous|p|print|P|Print|profd|profdel|prof|profile|promptf|promptfind|promptr|promptrepl|ps|psearch|pta|ptag|ptf|ptfirst|ptj|ptjump|ptl|ptlast|ptn|ptnext|ptN|ptNext|ptp|ptprevious|ptr|ptrewind|pts|ptselect|pu|put|pw|pwd|pyf|pyfile|py|python|qa|qall|q|quit|quita|quitall|r|read|rec|recover|redi|redir|red|redo|redr|redraw|redraws|redrawstatus|reg|registers|res|resize|ret|retab|retu|return|rew|rewind|ri|right|rightb|rightbelow|rub|ruby|rubyd|rubydo|rubyf|rubyfile|ru|runtime|rv|rviminfo|sal|sall|san|sandbox|sa|sargument|sav|saveas|sba|sball|sbf|sbfirst|sbl|sblast|sbm|sbmodified|sbn|sbnext|sbN|sbNext|sbp|sbprevious|sbr|sbrewind|sb|sbuffer|scripte|scriptencoding|scrip|scriptnames|se|set|setf|setfiletype|setg|setglobal|setl|setlocal|sf|sfind|sfir|sfirst|sh|shell|sign|sil|silent|sim|simalt|sla|slast|sl|sleep|sm|smagic|sm|smap|smapc|smapclear|sme|smenu|sn|snext|sN|sNext|sni|sniff|sno|snomagic|snor|snoremap|snoreme|snoremenu|sor|sort|so|source|spelld|spelldump|spe|spellgood|spelli|spellinfo|spellr|spellrepall|spellu|spellundo|spellw|spellwrong|sp|split|spr|sprevious|sre|srewind|sta|stag|startg|startgreplace|star|startinsert|startr|startreplace|stj|stjump|st|stop|stopi|stopinsert|sts|stselect|sun|sunhide|sunm|sunmap|sus|suspend|sv|sview|syncbind|t|tab|tabc|tabclose|tabd|tabdo|tabe|tabedit|tabf|tabfind|tabfir|tabfirst|tabl|tablast|tabm|tabmove|tabnew|tabn|tabnext|tabN|tabNext|tabo|tabonly|tabp|tabprevious|tabr|tabrewind|tabs|ta|tag|tags|tc|tcl|tcld|tcldo|tclf|tclfile|te|tearoff|tf|tfirst|th|throw|tj|tjump|tl|tlast|tm|tm|tmenu|tn|tnext|tN|tNext|to|topleft|tp|tprevious|tr|trewind|try|ts|tselect|tu|tu|tunmenu|una|unabbreviate|u|undo|undoj|undojoin|undol|undolist|unh|unhide|unlet|unlo|unlockvar|unm|unmap|up|update|verb|verbose|ve|version|vert|vertical|vie|view|vim|vimgrep|vimgrepa|vimgrepadd|vi|visual|viu|viusage|vmapc|vmapclear|vne|vnew|vs|vsplit|vu|vunmap|wa|wall|wh|while|winc|wincmd|windo|winp|winpos|win|winsize|wn|wnext|wN|wNext|wp|wprevious|wq|wqa|wqall|w|write|ws|wsverb|wv|wviminfo|X|xa|xall|x|xit|xm|xmap|xmapc|xmapclear|xme|xmenu|XMLent|XMLns|xn|xnoremap|xnoreme|xnoremenu|xu|xunmap|y|yank)\b/, - 'builtin': /\b(?:autocmd|acd|ai|akm|aleph|allowrevins|altkeymap|ambiwidth|ambw|anti|antialias|arab|arabic|arabicshape|ari|arshape|autochdir|autoindent|autoread|autowrite|autowriteall|aw|awa|background|backspace|backup|backupcopy|backupdir|backupext|backupskip|balloondelay|ballooneval|balloonexpr|bdir|bdlay|beval|bex|bexpr|bg|bh|bin|binary|biosk|bioskey|bk|bkc|bomb|breakat|brk|browsedir|bs|bsdir|bsk|bt|bufhidden|buflisted|buftype|casemap|ccv|cdpath|cedit|cfu|ch|charconvert|ci|cin|cindent|cink|cinkeys|cino|cinoptions|cinw|cinwords|clipboard|cmdheight|cmdwinheight|cmp|cms|columns|com|comments|commentstring|compatible|complete|completefunc|completeopt|consk|conskey|copyindent|cot|cpo|cpoptions|cpt|cscopepathcomp|cscopeprg|cscopequickfix|cscopetag|cscopetagorder|cscopeverbose|cspc|csprg|csqf|cst|csto|csverb|cuc|cul|cursorcolumn|cursorline|cwh|debug|deco|def|define|delcombine|dex|dg|dict|dictionary|diff|diffexpr|diffopt|digraph|dip|dir|directory|dy|ea|ead|eadirection|eb|ed|edcompatible|ef|efm|ei|ek|enc|encoding|endofline|eol|ep|equalalways|equalprg|errorbells|errorfile|errorformat|esckeys|et|eventignore|expandtab|exrc|fcl|fcs|fdc|fde|fdi|fdl|fdls|fdm|fdn|fdo|fdt|fen|fenc|fencs|fex|ff|ffs|fileencoding|fileencodings|fileformat|fileformats|fillchars|fk|fkmap|flp|fml|fmr|foldcolumn|foldenable|foldexpr|foldignore|foldlevel|foldlevelstart|foldmarker|foldmethod|foldminlines|foldnestmax|foldtext|formatexpr|formatlistpat|formatoptions|formatprg|fp|fs|fsync|ft|gcr|gd|gdefault|gfm|gfn|gfs|gfw|ghr|gp|grepformat|grepprg|gtl|gtt|guicursor|guifont|guifontset|guifontwide|guiheadroom|guioptions|guipty|guitablabel|guitabtooltip|helpfile|helpheight|helplang|hf|hh|hi|hidden|highlight|hk|hkmap|hkmapp|hkp|hl|hlg|hls|hlsearch|ic|icon|iconstring|ignorecase|im|imactivatekey|imak|imc|imcmdline|imd|imdisable|imi|iminsert|ims|imsearch|inc|include|includeexpr|incsearch|inde|indentexpr|indentkeys|indk|inex|inf|infercase|insertmode|isf|isfname|isi|isident|isk|iskeyword|isprint|joinspaces|js|key|keymap|keymodel|keywordprg|km|kmp|kp|langmap|langmenu|laststatus|lazyredraw|lbr|lcs|linebreak|lines|linespace|lisp|lispwords|listchars|loadplugins|lpl|lsp|lz|macatsui|magic|makeef|makeprg|matchpairs|matchtime|maxcombine|maxfuncdepth|maxmapdepth|maxmem|maxmempattern|maxmemtot|mco|mef|menuitems|mfd|mh|mis|mkspellmem|ml|mls|mm|mmd|mmp|mmt|modeline|modelines|modifiable|modified|more|mouse|mousef|mousefocus|mousehide|mousem|mousemodel|mouses|mouseshape|mouset|mousetime|mp|mps|msm|mzq|mzquantum|nf|nrformats|numberwidth|nuw|odev|oft|ofu|omnifunc|opendevice|operatorfunc|opfunc|osfiletype|pa|para|paragraphs|paste|pastetoggle|patchexpr|patchmode|path|pdev|penc|pex|pexpr|pfn|ph|pheader|pi|pm|pmbcs|pmbfn|popt|preserveindent|previewheight|previewwindow|printdevice|printencoding|printexpr|printfont|printheader|printmbcharset|printmbfont|printoptions|prompt|pt|pumheight|pvh|pvw|qe|quoteescape|readonly|remap|report|restorescreen|revins|rightleft|rightleftcmd|rl|rlc|ro|rs|rtp|ruf|ruler|rulerformat|runtimepath|sbo|sc|scb|scr|scroll|scrollbind|scrolljump|scrolloff|scrollopt|scs|sect|sections|secure|sel|selection|selectmode|sessionoptions|sft|shcf|shellcmdflag|shellpipe|shellquote|shellredir|shellslash|shelltemp|shelltype|shellxquote|shiftround|shiftwidth|shm|shortmess|shortname|showbreak|showcmd|showfulltag|showmatch|showmode|showtabline|shq|si|sidescroll|sidescrolloff|siso|sj|slm|smartcase|smartindent|smarttab|smc|smd|softtabstop|sol|spc|spell|spellcapcheck|spellfile|spelllang|spellsuggest|spf|spl|splitbelow|splitright|sps|sr|srr|ss|ssl|ssop|stal|startofline|statusline|stl|stmp|su|sua|suffixes|suffixesadd|sw|swapfile|swapsync|swb|swf|switchbuf|sws|sxq|syn|synmaxcol|syntax|tabline|tabpagemax|tabstop|tagbsearch|taglength|tagrelative|tagstack|tal|tb|tbi|tbidi|tbis|tbs|tenc|term|termbidi|termencoding|terse|textauto|textmode|textwidth|tgst|thesaurus|tildeop|timeout|timeoutlen|title|titlelen|titleold|titlestring|toolbar|toolbariconsize|top|tpm|tsl|tsr|ttimeout|ttimeoutlen|ttm|tty|ttybuiltin|ttyfast|ttym|ttymouse|ttyscroll|ttytype|tw|tx|uc|ul|undolevels|updatecount|updatetime|ut|vb|vbs|vdir|verbosefile|vfile|viewdir|viewoptions|viminfo|virtualedit|visualbell|vop|wak|warn|wb|wc|wcm|wd|weirdinvert|wfh|wfw|whichwrap|wi|wig|wildchar|wildcharm|wildignore|wildmenu|wildmode|wildoptions|wim|winaltkeys|window|winfixheight|winfixwidth|winheight|winminheight|winminwidth|winwidth|wiv|wiw|wm|wmh|wmnu|wmw|wop|wrap|wrapmargin|wrapscan|writeany|writebackup|writedelay|ww|noacd|noai|noakm|noallowrevins|noaltkeymap|noanti|noantialias|noar|noarab|noarabic|noarabicshape|noari|noarshape|noautochdir|noautoindent|noautoread|noautowrite|noautowriteall|noaw|noawa|nobackup|noballooneval|nobeval|nobin|nobinary|nobiosk|nobioskey|nobk|nobl|nobomb|nobuflisted|nocf|noci|nocin|nocindent|nocompatible|noconfirm|noconsk|noconskey|nocopyindent|nocp|nocscopetag|nocscopeverbose|nocst|nocsverb|nocuc|nocul|nocursorcolumn|nocursorline|nodeco|nodelcombine|nodg|nodiff|nodigraph|nodisable|noea|noeb|noed|noedcompatible|noek|noendofline|noeol|noequalalways|noerrorbells|noesckeys|noet|noex|noexpandtab|noexrc|nofen|nofk|nofkmap|nofoldenable|nogd|nogdefault|noguipty|nohid|nohidden|nohk|nohkmap|nohkmapp|nohkp|nohls|noic|noicon|noignorecase|noim|noimc|noimcmdline|noimd|noincsearch|noinf|noinfercase|noinsertmode|nois|nojoinspaces|nojs|nolazyredraw|nolbr|nolinebreak|nolisp|nolist|noloadplugins|nolpl|nolz|noma|nomacatsui|nomagic|nomh|noml|nomod|nomodeline|nomodifiable|nomodified|nomore|nomousef|nomousefocus|nomousehide|nonu|nonumber|noodev|noopendevice|nopaste|nopi|nopreserveindent|nopreviewwindow|noprompt|nopvw|noreadonly|noremap|norestorescreen|norevins|nori|norightleft|norightleftcmd|norl|norlc|noro|nors|noru|noruler|nosb|nosc|noscb|noscrollbind|noscs|nosecure|nosft|noshellslash|noshelltemp|noshiftround|noshortname|noshowcmd|noshowfulltag|noshowmatch|noshowmode|nosi|nosm|nosmartcase|nosmartindent|nosmarttab|nosmd|nosn|nosol|nospell|nosplitbelow|nosplitright|nospr|nosr|nossl|nosta|nostartofline|nostmp|noswapfile|noswf|nota|notagbsearch|notagrelative|notagstack|notbi|notbidi|notbs|notermbidi|noterse|notextauto|notextmode|notf|notgst|notildeop|notimeout|notitle|noto|notop|notr|nottimeout|nottybuiltin|nottyfast|notx|novb|novisualbell|nowa|nowarn|nowb|noweirdinvert|nowfh|nowfw|nowildmenu|nowinfixheight|nowinfixwidth|nowiv|nowmnu|nowrap|nowrapscan|nowrite|nowriteany|nowritebackup|nows|invacd|invai|invakm|invallowrevins|invaltkeymap|invanti|invantialias|invar|invarab|invarabic|invarabicshape|invari|invarshape|invautochdir|invautoindent|invautoread|invautowrite|invautowriteall|invaw|invawa|invbackup|invballooneval|invbeval|invbin|invbinary|invbiosk|invbioskey|invbk|invbl|invbomb|invbuflisted|invcf|invci|invcin|invcindent|invcompatible|invconfirm|invconsk|invconskey|invcopyindent|invcp|invcscopetag|invcscopeverbose|invcst|invcsverb|invcuc|invcul|invcursorcolumn|invcursorline|invdeco|invdelcombine|invdg|invdiff|invdigraph|invdisable|invea|inveb|inved|invedcompatible|invek|invendofline|inveol|invequalalways|inverrorbells|invesckeys|invet|invex|invexpandtab|invexrc|invfen|invfk|invfkmap|invfoldenable|invgd|invgdefault|invguipty|invhid|invhidden|invhk|invhkmap|invhkmapp|invhkp|invhls|invhlsearch|invic|invicon|invignorecase|invim|invimc|invimcmdline|invimd|invincsearch|invinf|invinfercase|invinsertmode|invis|invjoinspaces|invjs|invlazyredraw|invlbr|invlinebreak|invlisp|invlist|invloadplugins|invlpl|invlz|invma|invmacatsui|invmagic|invmh|invml|invmod|invmodeline|invmodifiable|invmodified|invmore|invmousef|invmousefocus|invmousehide|invnu|invnumber|invodev|invopendevice|invpaste|invpi|invpreserveindent|invpreviewwindow|invprompt|invpvw|invreadonly|invremap|invrestorescreen|invrevins|invri|invrightleft|invrightleftcmd|invrl|invrlc|invro|invrs|invru|invruler|invsb|invsc|invscb|invscrollbind|invscs|invsecure|invsft|invshellslash|invshelltemp|invshiftround|invshortname|invshowcmd|invshowfulltag|invshowmatch|invshowmode|invsi|invsm|invsmartcase|invsmartindent|invsmarttab|invsmd|invsn|invsol|invspell|invsplitbelow|invsplitright|invspr|invsr|invssl|invsta|invstartofline|invstmp|invswapfile|invswf|invta|invtagbsearch|invtagrelative|invtagstack|invtbi|invtbidi|invtbs|invtermbidi|invterse|invtextauto|invtextmode|invtf|invtgst|invtildeop|invtimeout|invtitle|invto|invtop|invtr|invttimeout|invttybuiltin|invttyfast|invtx|invvb|invvisualbell|invwa|invwarn|invwb|invweirdinvert|invwfh|invwfw|invwildmenu|invwinfixheight|invwinfixwidth|invwiv|invwmnu|invwrap|invwrapscan|invwrite|invwriteany|invwritebackup|invws|t_AB|t_AF|t_al|t_AL|t_bc|t_cd|t_ce|t_Ce|t_cl|t_cm|t_Co|t_cs|t_Cs|t_CS|t_CV|t_da|t_db|t_dl|t_DL|t_EI|t_F1|t_F2|t_F3|t_F4|t_F5|t_F6|t_F7|t_F8|t_F9|t_fs|t_IE|t_IS|t_k1|t_K1|t_k2|t_k3|t_K3|t_k4|t_K4|t_k5|t_K5|t_k6|t_K6|t_k7|t_K7|t_k8|t_K8|t_k9|t_K9|t_KA|t_kb|t_kB|t_KB|t_KC|t_kd|t_kD|t_KD|t_ke|t_KE|t_KF|t_KG|t_kh|t_KH|t_kI|t_KI|t_KJ|t_KK|t_kl|t_KL|t_kN|t_kP|t_kr|t_ks|t_ku|t_le|t_mb|t_md|t_me|t_mr|t_ms|t_nd|t_op|t_RI|t_RV|t_Sb|t_se|t_Sf|t_SI|t_so|t_sr|t_te|t_ti|t_ts|t_ue|t_us|t_ut|t_vb|t_ve|t_vi|t_vs|t_WP|t_WS|t_xs|t_ZH|t_ZR)\b/, - 'number': /\b(?:0x[\da-f]+|\d+(?:\.\d+)?)\b/i, - 'operator': /\|\||&&|[-+.]=?|[=!](?:[=~][#?]?)?|[<>]=?[#?]?|[*\/%?]|\b(?:is(?:not)?)\b/, - 'punctuation': /[{}[\](),;:]/ - }; - - return Prism -}) \ No newline at end of file diff --git a/src/js/prism/index.js b/src/js/prism/index.js new file mode 100644 index 0000000..f59a69a --- /dev/null +++ b/src/js/prism/index.js @@ -0,0 +1,1876 @@ +/** + * + * @authors yutent (yutent@doui.cc) + * @date 2017-08-02 21:50:34 + * @version $Id$ + */ + +import './base' + +Prism.languages.actionscript = Prism.languages.extend('javascript', { + keyword: /\b(?:as|break|case|catch|class|const|default|delete|do|else|extends|finally|for|function|if|implements|import|in|instanceof|interface|internal|is|native|new|null|package|private|protected|public|return|super|switch|this|throw|try|typeof|use|var|void|while|with|dynamic|each|final|get|include|namespace|native|override|set|static)\b/, + operator: /\+\+|--|(?:[+\-*\/%^]|&&?|\|\|?|<>?>?|[!=]=?)=?|[~?@]/ +}) +Prism.languages.actionscript['class-name'].alias = 'function' + +if (Prism.languages.markup) { + Prism.languages.insertBefore('actionscript', 'string', { + xml: { + pattern: /(^|[^.])<\/?\w+(?:\s+[^\s>\/=]+=("|')(?:\\\1|\\?(?!\1)[\s\S])*\2)*\s*\/?>/, + lookbehind: true, + inside: { + rest: Prism.languages.markup + } + } + }) +} + +/*--------------------------------------------------------*/ + +Prism.languages.apacheconf = { + comment: /#.*/, + 'directive-inline': { + pattern: /^(\s*)\b(AcceptFilter|AcceptPathInfo|AccessFileName|Action|AddAlt|AddAltByEncoding|AddAltByType|AddCharset|AddDefaultCharset|AddDescription|AddEncoding|AddHandler|AddIcon|AddIconByEncoding|AddIconByType|AddInputFilter|AddLanguage|AddModuleInfo|AddOutputFilter|AddOutputFilterByType|AddType|Alias|AliasMatch|Allow|AllowCONNECT|AllowEncodedSlashes|AllowMethods|AllowOverride|AllowOverrideList|Anonymous|Anonymous_LogEmail|Anonymous_MustGiveEmail|Anonymous_NoUserID|Anonymous_VerifyEmail|AsyncRequestWorkerFactor|AuthBasicAuthoritative|AuthBasicFake|AuthBasicProvider|AuthBasicUseDigestAlgorithm|AuthDBDUserPWQuery|AuthDBDUserRealmQuery|AuthDBMGroupFile|AuthDBMType|AuthDBMUserFile|AuthDigestAlgorithm|AuthDigestDomain|AuthDigestNonceLifetime|AuthDigestProvider|AuthDigestQop|AuthDigestShmemSize|AuthFormAuthoritative|AuthFormBody|AuthFormDisableNoStore|AuthFormFakeBasicAuth|AuthFormLocation|AuthFormLoginRequiredLocation|AuthFormLoginSuccessLocation|AuthFormLogoutLocation|AuthFormMethod|AuthFormMimetype|AuthFormPassword|AuthFormProvider|AuthFormSitePassphrase|AuthFormSize|AuthFormUsername|AuthGroupFile|AuthLDAPAuthorizePrefix|AuthLDAPBindAuthoritative|AuthLDAPBindDN|AuthLDAPBindPassword|AuthLDAPCharsetConfig|AuthLDAPCompareAsUser|AuthLDAPCompareDNOnServer|AuthLDAPDereferenceAliases|AuthLDAPGroupAttribute|AuthLDAPGroupAttributeIsDN|AuthLDAPInitialBindAsUser|AuthLDAPInitialBindPattern|AuthLDAPMaxSubGroupDepth|AuthLDAPRemoteUserAttribute|AuthLDAPRemoteUserIsDN|AuthLDAPSearchAsUser|AuthLDAPSubGroupAttribute|AuthLDAPSubGroupClass|AuthLDAPUrl|AuthMerging|AuthName|AuthnCacheContext|AuthnCacheEnable|AuthnCacheProvideFor|AuthnCacheSOCache|AuthnCacheTimeout|AuthnzFcgiCheckAuthnProvider|AuthnzFcgiDefineProvider|AuthType|AuthUserFile|AuthzDBDLoginToReferer|AuthzDBDQuery|AuthzDBDRedirectQuery|AuthzDBMType|AuthzSendForbiddenOnFailure|BalancerGrowth|BalancerInherit|BalancerMember|BalancerPersist|BrowserMatch|BrowserMatchNoCase|BufferedLogs|BufferSize|CacheDefaultExpire|CacheDetailHeader|CacheDirLength|CacheDirLevels|CacheDisable|CacheEnable|CacheFile|CacheHeader|CacheIgnoreCacheControl|CacheIgnoreHeaders|CacheIgnoreNoLastMod|CacheIgnoreQueryString|CacheIgnoreURLSessionIdentifiers|CacheKeyBaseURL|CacheLastModifiedFactor|CacheLock|CacheLockMaxAge|CacheLockPath|CacheMaxExpire|CacheMaxFileSize|CacheMinExpire|CacheMinFileSize|CacheNegotiatedDocs|CacheQuickHandler|CacheReadSize|CacheReadTime|CacheRoot|CacheSocache|CacheSocacheMaxSize|CacheSocacheMaxTime|CacheSocacheMinTime|CacheSocacheReadSize|CacheSocacheReadTime|CacheStaleOnError|CacheStoreExpired|CacheStoreNoStore|CacheStorePrivate|CGIDScriptTimeout|CGIMapExtension|CharsetDefault|CharsetOptions|CharsetSourceEnc|CheckCaseOnly|CheckSpelling|ChrootDir|ContentDigest|CookieDomain|CookieExpires|CookieName|CookieStyle|CookieTracking|CoreDumpDirectory|CustomLog|Dav|DavDepthInfinity|DavGenericLockDB|DavLockDB|DavMinTimeout|DBDExptime|DBDInitSQL|DBDKeep|DBDMax|DBDMin|DBDParams|DBDPersist|DBDPrepareSQL|DBDriver|DefaultIcon|DefaultLanguage|DefaultRuntimeDir|DefaultType|Define|DeflateBufferSize|DeflateCompressionLevel|DeflateFilterNote|DeflateInflateLimitRequestBody|DeflateInflateRatioBurst|DeflateInflateRatioLimit|DeflateMemLevel|DeflateWindowSize|Deny|DirectoryCheckHandler|DirectoryIndex|DirectoryIndexRedirect|DirectorySlash|DocumentRoot|DTracePrivileges|DumpIOInput|DumpIOOutput|EnableExceptionHook|EnableMMAP|EnableSendfile|Error|ErrorDocument|ErrorLog|ErrorLogFormat|Example|ExpiresActive|ExpiresByType|ExpiresDefault|ExtendedStatus|ExtFilterDefine|ExtFilterOptions|FallbackResource|FileETag|FilterChain|FilterDeclare|FilterProtocol|FilterProvider|FilterTrace|ForceLanguagePriority|ForceType|ForensicLog|GprofDir|GracefulShutdownTimeout|Group|Header|HeaderName|HeartbeatAddress|HeartbeatListen|HeartbeatMaxServers|HeartbeatStorage|HeartbeatStorage|HostnameLookups|IdentityCheck|IdentityCheckTimeout|ImapBase|ImapDefault|ImapMenu|Include|IncludeOptional|IndexHeadInsert|IndexIgnore|IndexIgnoreReset|IndexOptions|IndexOrderDefault|IndexStyleSheet|InputSed|ISAPIAppendLogToErrors|ISAPIAppendLogToQuery|ISAPICacheFile|ISAPIFakeAsync|ISAPILogNotSupported|ISAPIReadAheadBuffer|KeepAlive|KeepAliveTimeout|KeptBodySize|LanguagePriority|LDAPCacheEntries|LDAPCacheTTL|LDAPConnectionPoolTTL|LDAPConnectionTimeout|LDAPLibraryDebug|LDAPOpCacheEntries|LDAPOpCacheTTL|LDAPReferralHopLimit|LDAPReferrals|LDAPRetries|LDAPRetryDelay|LDAPSharedCacheFile|LDAPSharedCacheSize|LDAPTimeout|LDAPTrustedClientCert|LDAPTrustedGlobalCert|LDAPTrustedMode|LDAPVerifyServerCert|LimitInternalRecursion|LimitRequestBody|LimitRequestFields|LimitRequestFieldSize|LimitRequestLine|LimitXMLRequestBody|Listen|ListenBackLog|LoadFile|LoadModule|LogFormat|LogLevel|LogMessage|LuaAuthzProvider|LuaCodeCache|LuaHookAccessChecker|LuaHookAuthChecker|LuaHookCheckUserID|LuaHookFixups|LuaHookInsertFilter|LuaHookLog|LuaHookMapToStorage|LuaHookTranslateName|LuaHookTypeChecker|LuaInherit|LuaInputFilter|LuaMapHandler|LuaOutputFilter|LuaPackageCPath|LuaPackagePath|LuaQuickHandler|LuaRoot|LuaScope|MaxConnectionsPerChild|MaxKeepAliveRequests|MaxMemFree|MaxRangeOverlaps|MaxRangeReversals|MaxRanges|MaxRequestWorkers|MaxSpareServers|MaxSpareThreads|MaxThreads|MergeTrailers|MetaDir|MetaFiles|MetaSuffix|MimeMagicFile|MinSpareServers|MinSpareThreads|MMapFile|ModemStandard|ModMimeUsePathInfo|MultiviewsMatch|Mutex|NameVirtualHost|NoProxy|NWSSLTrustedCerts|NWSSLUpgradeable|Options|Order|OutputSed|PassEnv|PidFile|PrivilegesMode|Protocol|ProtocolEcho|ProxyAddHeaders|ProxyBadHeader|ProxyBlock|ProxyDomain|ProxyErrorOverride|ProxyExpressDBMFile|ProxyExpressDBMType|ProxyExpressEnable|ProxyFtpDirCharset|ProxyFtpEscapeWildcards|ProxyFtpListOnWildcard|ProxyHTMLBufSize|ProxyHTMLCharsetOut|ProxyHTMLDocType|ProxyHTMLEnable|ProxyHTMLEvents|ProxyHTMLExtended|ProxyHTMLFixups|ProxyHTMLInterp|ProxyHTMLLinks|ProxyHTMLMeta|ProxyHTMLStripComments|ProxyHTMLURLMap|ProxyIOBufferSize|ProxyMaxForwards|ProxyPass|ProxyPassInherit|ProxyPassInterpolateEnv|ProxyPassMatch|ProxyPassReverse|ProxyPassReverseCookieDomain|ProxyPassReverseCookiePath|ProxyPreserveHost|ProxyReceiveBufferSize|ProxyRemote|ProxyRemoteMatch|ProxyRequests|ProxySCGIInternalRedirect|ProxySCGISendfile|ProxySet|ProxySourceAddress|ProxyStatus|ProxyTimeout|ProxyVia|ReadmeName|ReceiveBufferSize|Redirect|RedirectMatch|RedirectPermanent|RedirectTemp|ReflectorHeader|RemoteIPHeader|RemoteIPInternalProxy|RemoteIPInternalProxyList|RemoteIPProxiesHeader|RemoteIPTrustedProxy|RemoteIPTrustedProxyList|RemoveCharset|RemoveEncoding|RemoveHandler|RemoveInputFilter|RemoveLanguage|RemoveOutputFilter|RemoveType|RequestHeader|RequestReadTimeout|Require|RewriteBase|RewriteCond|RewriteEngine|RewriteMap|RewriteOptions|RewriteRule|RLimitCPU|RLimitMEM|RLimitNPROC|Satisfy|ScoreBoardFile|Script|ScriptAlias|ScriptAliasMatch|ScriptInterpreterSource|ScriptLog|ScriptLogBuffer|ScriptLogLength|ScriptSock|SecureListen|SeeRequestTail|SendBufferSize|ServerAdmin|ServerAlias|ServerLimit|ServerName|ServerPath|ServerRoot|ServerSignature|ServerTokens|Session|SessionCookieName|SessionCookieName2|SessionCookieRemove|SessionCryptoCipher|SessionCryptoDriver|SessionCryptoPassphrase|SessionCryptoPassphraseFile|SessionDBDCookieName|SessionDBDCookieName2|SessionDBDCookieRemove|SessionDBDDeleteLabel|SessionDBDInsertLabel|SessionDBDPerUser|SessionDBDSelectLabel|SessionDBDUpdateLabel|SessionEnv|SessionExclude|SessionHeader|SessionInclude|SessionMaxAge|SetEnv|SetEnvIf|SetEnvIfExpr|SetEnvIfNoCase|SetHandler|SetInputFilter|SetOutputFilter|SSIEndTag|SSIErrorMsg|SSIETag|SSILastModified|SSILegacyExprParser|SSIStartTag|SSITimeFormat|SSIUndefinedEcho|SSLCACertificateFile|SSLCACertificatePath|SSLCADNRequestFile|SSLCADNRequestPath|SSLCARevocationCheck|SSLCARevocationFile|SSLCARevocationPath|SSLCertificateChainFile|SSLCertificateFile|SSLCertificateKeyFile|SSLCipherSuite|SSLCompression|SSLCryptoDevice|SSLEngine|SSLFIPS|SSLHonorCipherOrder|SSLInsecureRenegotiation|SSLOCSPDefaultResponder|SSLOCSPEnable|SSLOCSPOverrideResponder|SSLOCSPResponderTimeout|SSLOCSPResponseMaxAge|SSLOCSPResponseTimeSkew|SSLOCSPUseRequestNonce|SSLOpenSSLConfCmd|SSLOptions|SSLPassPhraseDialog|SSLProtocol|SSLProxyCACertificateFile|SSLProxyCACertificatePath|SSLProxyCARevocationCheck|SSLProxyCARevocationFile|SSLProxyCARevocationPath|SSLProxyCheckPeerCN|SSLProxyCheckPeerExpire|SSLProxyCheckPeerName|SSLProxyCipherSuite|SSLProxyEngine|SSLProxyMachineCertificateChainFile|SSLProxyMachineCertificateFile|SSLProxyMachineCertificatePath|SSLProxyProtocol|SSLProxyVerify|SSLProxyVerifyDepth|SSLRandomSeed|SSLRenegBufferSize|SSLRequire|SSLRequireSSL|SSLSessionCache|SSLSessionCacheTimeout|SSLSessionTicketKeyFile|SSLSRPUnknownUserSeed|SSLSRPVerifierFile|SSLStaplingCache|SSLStaplingErrorCacheTimeout|SSLStaplingFakeTryLater|SSLStaplingForceURL|SSLStaplingResponderTimeout|SSLStaplingResponseMaxAge|SSLStaplingResponseTimeSkew|SSLStaplingReturnResponderErrors|SSLStaplingStandardCacheTimeout|SSLStrictSNIVHostCheck|SSLUserName|SSLUseStapling|SSLVerifyClient|SSLVerifyDepth|StartServers|StartThreads|Substitute|Suexec|SuexecUserGroup|ThreadLimit|ThreadsPerChild|ThreadStackSize|TimeOut|TraceEnable|TransferLog|TypesConfig|UnDefine|UndefMacro|UnsetEnv|Use|UseCanonicalName|UseCanonicalPhysicalPort|User|UserDir|VHostCGIMode|VHostCGIPrivs|VHostGroup|VHostPrivs|VHostSecure|VHostUser|VirtualDocumentRoot|VirtualDocumentRootIP|VirtualScriptAlias|VirtualScriptAliasIP|WatchdogInterval|XBitHack|xml2EncAlias|xml2EncDefault|xml2StartParse)\b/im, + lookbehind: true, + alias: 'property' + }, + 'directive-block': { + pattern: /<\/?\b(AuthnProviderAlias|AuthzProviderAlias|Directory|DirectoryMatch|Else|ElseIf|Files|FilesMatch|If|IfDefine|IfModule|IfVersion|Limit|LimitExcept|Location|LocationMatch|Macro|Proxy|RequireAll|RequireAny|RequireNone|VirtualHost)\b *.*>/i, + inside: { + 'directive-block': { + pattern: /^<\/?\w+/, + inside: { + punctuation: /^<\/?/ + }, + alias: 'tag' + }, + 'directive-block-parameter': { + pattern: /.*[^>]/, + inside: { + punctuation: /:/, + string: { + pattern: /("|').*\1/, + inside: { + variable: /(\$|%)\{?(\w\.?(\+|\-|:)?)+\}?/ + } + } + }, + alias: 'attr-value' + }, + punctuation: />/ + }, + alias: 'tag' + }, + 'directive-flags': { + pattern: /\[(\w,?)+\]/, + alias: 'keyword' + }, + string: { + pattern: /("|').*\1/, + inside: { + variable: /(\$|%)\{?(\w\.?(\+|\-|:)?)+\}?/ + } + }, + variable: /(\$|%)\{?(\w\.?(\+|\-|:)?)+\}?/, + regex: /\^?.*\$|\^.*\$?/ +} + +/*-------------------------------------------------------------*/ + +Prism.languages.aspnet = Prism.languages.extend('markup', { + 'page-directive tag': { + pattern: /<%\s*@.*%>/i, + inside: { + 'page-directive tag': /<%\s*@\s*(?:Assembly|Control|Implements|Import|Master(?:Type)?|OutputCache|Page|PreviousPageType|Reference|Register)?|%>/i, + rest: Prism.languages.markup.tag.inside + } + }, + 'directive tag': { + pattern: /<%.*%>/i, + inside: { + 'directive tag': /<%\s*?[$=%#:]{0,2}|%>/i, + rest: Prism.languages.csharp + } + } +}) +// Regexp copied from prism-markup, with a negative look-ahead added +Prism.languages.aspnet.tag.pattern = /<(?!%)\/?[^\s>\/]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\\1|\\?(?!\1)[\s\S])*\1|[^\s'">=]+))?)*\s*\/?>/i + +// match directives of attribute value foo="<% Bar %>" +Prism.languages.insertBefore( + 'inside', + 'punctuation', + { + 'directive tag': Prism.languages.aspnet['directive tag'] + }, + Prism.languages.aspnet.tag.inside['attr-value'] +) + +Prism.languages.insertBefore('aspnet', 'comment', { + 'asp comment': /<%--[\s\S]*?--%>/ +}) + +// script runat="server" contains csharp, not javascript +Prism.languages.insertBefore( + 'aspnet', + Prism.languages.javascript ? 'script' : 'tag', + { + 'asp script': { + pattern: /()[\s\S]*?(?=<\/script>)/i, + lookbehind: true, + inside: Prism.languages.csharp || {} + } + } +) + +/*-------------------------------------------------------------------*/ + +Prism.languages.basic = { + string: /"(?:""|[!#$%&'()*,\/:;<=>?^_ +\-.A-Z\d])*"/i, + comment: { + pattern: /(?:!|REM\b).+/i, + inside: { + keyword: /^REM/i + } + }, + number: /(?:\b|\B[.-])(?:\d+\.?\d*)(?:E[+-]?\d+)?/i, + keyword: /\b(?:AS|BEEP|BLOAD|BSAVE|CALL(?: ABSOLUTE)?|CASE|CHAIN|CHDIR|CLEAR|CLOSE|CLS|COM|COMMON|CONST|DATA|DECLARE|DEF(?: FN| SEG|DBL|INT|LNG|SNG|STR)|DIM|DO|DOUBLE|ELSE|ELSEIF|END|ENVIRON|ERASE|ERROR|EXIT|FIELD|FILES|FOR|FUNCTION|GET|GOSUB|GOTO|IF|INPUT|INTEGER|IOCTL|KEY|KILL|LINE INPUT|LOCATE|LOCK|LONG|LOOP|LSET|MKDIR|NAME|NEXT|OFF|ON(?: COM| ERROR| KEY| TIMER)?|OPEN|OPTION BASE|OUT|POKE|PUT|READ|REDIM|REM|RESTORE|RESUME|RETURN|RMDIR|RSET|RUN|SHARED|SINGLE|SELECT CASE|SHELL|SLEEP|STATIC|STEP|STOP|STRING|SUB|SWAP|SYSTEM|THEN|TIMER|TO|TROFF|TRON|TYPE|UNLOCK|UNTIL|USING|VIEW PRINT|WAIT|WEND|WHILE|WRITE)(?:\$|\b)/i, + function: /\b(?:ABS|ACCESS|ACOS|ANGLE|AREA|ARITHMETIC|ARRAY|ASIN|ASK|AT|ATN|BASE|BEGIN|BREAK|CAUSE|CEIL|CHR|CLIP|COLLATE|COLOR|CON|COS|COSH|COT|CSC|DATE|DATUM|DEBUG|DECIMAL|DEF|DEG|DEGREES|DELETE|DET|DEVICE|DISPLAY|DOT|ELAPSED|EPS|ERASABLE|EXLINE|EXP|EXTERNAL|EXTYPE|FILETYPE|FIXED|FP|GO|GRAPH|HANDLER|IDN|IMAGE|IN|INT|INTERNAL|IP|IS|KEYED|LBOUND|LCASE|LEFT|LEN|LENGTH|LET|LINE|LINES|LOG|LOG10|LOG2|LTRIM|MARGIN|MAT|MAX|MAXNUM|MID|MIN|MISSING|MOD|NATIVE|NUL|NUMERIC|OF|OPTION|ORD|ORGANIZATION|OUTIN|OUTPUT|PI|POINT|POINTER|POINTS|POS|PRINT|PROGRAM|PROMPT|RAD|RADIANS|RANDOMIZE|RECORD|RECSIZE|RECTYPE|RELATIVE|REMAINDER|REPEAT|REST|RETRY|REWRITE|RIGHT|RND|ROUND|RTRIM|SAME|SEC|SELECT|SEQUENTIAL|SET|SETTER|SGN|SIN|SINH|SIZE|SKIP|SQR|STANDARD|STATUS|STR|STREAM|STYLE|TAB|TAN|TANH|TEMPLATE|TEXT|THERE|TIME|TIMEOUT|TRACE|TRANSFORM|TRUNCATE|UBOUND|UCASE|USE|VAL|VARIABLE|VIEWPORT|WHEN|WINDOW|WITH|ZER|ZONEWIDTH)(?:\$|\b)/i, + operator: /<[=>]?|>=?|[+\-*\/^=&]|\b(?:AND|EQV|IMP|NOT|OR|XOR)\b/i, + punctuation: /[,;:()]/ +} + +/*----------------------------------------------------*/ + +Prism.languages.c = Prism.languages.extend('clike', { + keyword: /\b(asm|typeof|inline|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|void|volatile|while)\b/, + operator: /\-[>-]?|\+\+?|!=?|<>?=?|==?|&&?|\|?\||[~^%?*\/]/, + number: /\b-?(?:0x[\da-f]+|\d*\.?\d+(?:e[+-]?\d+)?)[ful]*\b/i +}) + +Prism.languages.insertBefore('c', 'string', { + macro: { + // allow for multiline macro definitions + // spaces after the # character compile fine with gcc + pattern: /(^\s*)#\s*[a-z]+([^\r\n\\]|\\.|\\(?:\r\n?|\n))*/im, + lookbehind: true, + alias: 'property', + inside: { + // highlight the path of the include statement as a string + string: { + pattern: /(#\s*include\s*)(<.+?>|("|')(\\?.)+?\3)/, + lookbehind: true + }, + // highlight macro directives as keywords + directive: { + pattern: /(#\s*)\b(define|elif|else|endif|error|ifdef|ifndef|if|import|include|line|pragma|undef|using)\b/, + lookbehind: true, + alias: 'keyword' + } + } + }, + // highlight predefined macros as constants + constant: /\b(__FILE__|__LINE__|__DATE__|__TIME__|__TIMESTAMP__|__func__|EOF|NULL|stdin|stdout|stderr)\b/ +}) + +delete Prism.languages.c['class-name'] +delete Prism.languages.c['boolean'] + +/*---------------------------------------------------*/ +Prism.languages.csharp = Prism.languages.extend('clike', { + keyword: /\b(abstract|as|async|await|base|bool|break|byte|case|catch|char|checked|class|const|continue|decimal|default|delegate|do|double|else|enum|event|explicit|extern|false|finally|fixed|float|for|foreach|goto|if|implicit|in|int|interface|internal|is|lock|long|namespace|new|null|object|operator|out|override|params|private|protected|public|readonly|ref|return|sbyte|sealed|short|sizeof|stackalloc|static|string|struct|switch|this|throw|true|try|typeof|uint|ulong|unchecked|unsafe|ushort|using|virtual|void|volatile|while|add|alias|ascending|async|await|descending|dynamic|from|get|global|group|into|join|let|orderby|partial|remove|select|set|value|var|where|yield)\b/, + string: [ + { + pattern: /@("|')(\1\1|\\\1|\\?(?!\1)[\s\S])*\1/, + greedy: true + }, + { + pattern: /("|')(\\?.)*?\1/, + greedy: true + } + ], + number: /\b-?(0x[\da-f]+|\d*\.?\d+f?)\b/i +}) + +Prism.languages.insertBefore('csharp', 'keyword', { + 'generic-method': { + pattern: /[a-z0-9_]+\s*<[^>\r\n]+?>\s*(?=\()/i, + alias: 'function', + inside: { + keyword: Prism.languages.csharp.keyword, + punctuation: /[<>(),.:]/ + } + }, + preprocessor: { + pattern: /(^\s*)#.*/m, + lookbehind: true, + alias: 'property', + inside: { + // highlight preprocessor directives as keywords + directive: { + pattern: /(\s*#)\b(define|elif|else|endif|endregion|error|if|line|pragma|region|undef|warning)\b/, + lookbehind: true, + alias: 'keyword' + } + } + } +}) + +/*-----------------------------------------------------------*/ + +Prism.languages.cpp = Prism.languages.extend('c', { + keyword: /\b(alignas|alignof|asm|auto|bool|break|case|catch|char|char16_t|char32_t|class|compl|const|constexpr|const_cast|continue|decltype|default|delete|do|double|dynamic_cast|else|enum|explicit|export|extern|float|for|friend|goto|if|inline|int|long|mutable|namespace|new|noexcept|nullptr|operator|private|protected|public|register|reinterpret_cast|return|short|signed|sizeof|static|static_assert|static_cast|struct|switch|template|this|thread_local|throw|try|typedef|typeid|typename|union|unsigned|using|virtual|void|volatile|wchar_t|while)\b/, + boolean: /\b(true|false)\b/, + operator: /[-+]{1,2}|!=?|<{1,2}=?|>{1,2}=?|\->|:{1,2}|={1,2}|\^|~|%|&{1,2}|\|?\||\?|\*|\/|\b(and|and_eq|bitand|bitor|not|not_eq|or|or_eq|xor|xor_eq)\b/ +}) + +Prism.languages.insertBefore('cpp', 'keyword', { + 'class-name': { + pattern: /(class\s+)[a-z0-9_]+/i, + lookbehind: true + } +}) + +/*-----------------------coffeescript-----------------------*/ + +;(function(Prism) { + // Ignore comments starting with { to privilege string interpolation highlighting + var comment = /#(?!\{).+/, + interpolation = { + pattern: /#\{[^}]+\}/, + alias: 'variable' + } + + Prism.languages.coffeescript = Prism.languages.extend('javascript', { + comment: comment, + string: [ + // Strings are multiline + { + pattern: /'(?:\\?[^\\])*?'/, + greedy: true + }, + + { + // Strings are multiline + pattern: /"(?:\\?[^\\])*?"/, + greedy: true, + inside: { + interpolation: interpolation + } + } + ], + keyword: /\b(and|break|by|catch|class|continue|debugger|delete|do|each|else|extend|extends|false|finally|for|if|in|instanceof|is|isnt|let|loop|namespace|new|no|not|null|of|off|on|or|own|return|super|switch|then|this|throw|true|try|typeof|undefined|unless|until|when|while|window|with|yes|yield)\b/, + 'class-member': { + pattern: /@(?!\d)\w+/, + alias: 'variable' + } + }) + + Prism.languages.insertBefore('coffeescript', 'comment', { + 'multiline-comment': { + pattern: /###[\s\S]+?###/, + alias: 'comment' + }, + + // Block regexp can contain comments and interpolation + 'block-regex': { + pattern: /\/{3}[\s\S]*?\/{3}/, + alias: 'regex', + inside: { + comment: comment, + interpolation: interpolation + } + } + }) + + Prism.languages.insertBefore('coffeescript', 'string', { + 'inline-javascript': { + pattern: /`(?:\\?[\s\S])*?`/, + inside: { + delimiter: { + pattern: /^`|`$/, + alias: 'punctuation' + }, + rest: Prism.languages.javascript + } + }, + + // Block strings + 'multiline-string': [ + { + pattern: /'''[\s\S]*?'''/, + greedy: true, + alias: 'string' + }, + { + pattern: /"""[\s\S]*?"""/, + greedy: true, + alias: 'string', + inside: { + interpolation: interpolation + } + } + ] + }) + + Prism.languages.insertBefore('coffeescript', 'keyword', { + // Object property + property: /(?!\d)\w+(?=\s*:(?!:))/ + }) + + delete Prism.languages.coffeescript['template-string'] +})(Prism) + +/*---------------------------ruby---------------------------*/ + +;(function(Prism) { + Prism.languages.ruby = Prism.languages.extend('clike', { + comment: [ + /#(?!\{[^\r\n]*?\}).*/, + /^=begin(?:\r?\n|\r)(?:.*(?:\r?\n|\r))*?=end/m + ], + keyword: /\b(alias|and|BEGIN|begin|break|case|class|def|define_method|defined|do|each|else|elsif|END|end|ensure|false|for|if|in|module|new|next|nil|not|or|raise|redo|require|rescue|retry|return|self|super|then|throw|true|undef|unless|until|when|while|yield)\b/ + }) + + var interpolation = { + pattern: /#\{[^}]+\}/, + inside: { + delimiter: { + pattern: /^#\{|\}$/, + alias: 'tag' + }, + rest: Prism.util.clone(Prism.languages.ruby) + } + } + + Prism.languages.insertBefore('ruby', 'keyword', { + regex: [ + { + pattern: /%r([^a-zA-Z0-9\s\{\(\[<])(?:[^\\]|\\[\s\S])*?\1[gim]{0,3}/, + greedy: true, + inside: { + interpolation: interpolation + } + }, + { + pattern: /%r\((?:[^()\\]|\\[\s\S])*\)[gim]{0,3}/, + greedy: true, + inside: { + interpolation: interpolation + } + }, + { + // Here we need to specifically allow interpolation + pattern: /%r\{(?:[^#{}\\]|#(?:\{[^}]+\})?|\\[\s\S])*\}[gim]{0,3}/, + greedy: true, + inside: { + interpolation: interpolation + } + }, + { + pattern: /%r\[(?:[^\[\]\\]|\\[\s\S])*\][gim]{0,3}/, + greedy: true, + inside: { + interpolation: interpolation + } + }, + { + pattern: /%r<(?:[^<>\\]|\\[\s\S])*>[gim]{0,3}/, + greedy: true, + inside: { + interpolation: interpolation + } + }, + { + pattern: /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\\\r\n])+\/[gim]{0,3}(?=\s*($|[\r\n,.;})]))/, + lookbehind: true, + greedy: true + } + ], + variable: /[@$]+[a-zA-Z_][a-zA-Z_0-9]*(?:[?!]|\b)/, + symbol: /:[a-zA-Z_][a-zA-Z_0-9]*(?:[?!]|\b)/ + }) + + Prism.languages.insertBefore('ruby', 'number', { + builtin: /\b(Array|Bignum|Binding|Class|Continuation|Dir|Exception|FalseClass|File|Stat|File|Fixnum|Float|Hash|Integer|IO|MatchData|Method|Module|NilClass|Numeric|Object|Proc|Range|Regexp|String|Struct|TMS|Symbol|ThreadGroup|Thread|Time|TrueClass)\b/, + constant: /\b[A-Z][a-zA-Z_0-9]*(?:[?!]|\b)/ + }) + + Prism.languages.ruby.string = [ + { + pattern: /%[qQiIwWxs]?([^a-zA-Z0-9\s\{\(\[<])(?:[^\\]|\\[\s\S])*?\1/, + greedy: true, + inside: { + interpolation: interpolation + } + }, + { + pattern: /%[qQiIwWxs]?\((?:[^()\\]|\\[\s\S])*\)/, + greedy: true, + inside: { + interpolation: interpolation + } + }, + { + // Here we need to specifically allow interpolation + pattern: /%[qQiIwWxs]?\{(?:[^#{}\\]|#(?:\{[^}]+\})?|\\[\s\S])*\}/, + greedy: true, + inside: { + interpolation: interpolation + } + }, + { + pattern: /%[qQiIwWxs]?\[(?:[^\[\]\\]|\\[\s\S])*\]/, + greedy: true, + inside: { + interpolation: interpolation + } + }, + { + pattern: /%[qQiIwWxs]?<(?:[^<>\\]|\\[\s\S])*>/, + greedy: true, + inside: { + interpolation: interpolation + } + }, + { + pattern: /("|')(#\{[^}]+\}|\\(?:\r?\n|\r)|\\?.)*?\1/, + greedy: true, + inside: { + interpolation: interpolation + } + } + ] +})(Prism) + +/*-------------------------------------------------------------*/ + +Prism.languages.d = Prism.languages.extend('clike', { + string: [ + // r"", x"" + /\b[rx]"(\\.|[^\\"])*"[cwd]?/, + // q"[]", q"()", q"<>", q"{}" + /\bq"(?:\[[\s\S]*?\]|\([\s\S]*?\)|<[\s\S]*?>|\{[\s\S]*?\})"/, + // q"IDENT + // ... + // IDENT" + /\bq"([_a-zA-Z][_a-zA-Z\d]*)(?:\r?\n|\r)[\s\S]*?(?:\r?\n|\r)\1"/, + // q"//", q"||", etc. + /\bq"(.)[\s\S]*?\1"/, + // Characters + /'(?:\\'|\\?[^']+)'/, + + /(["`])(\\.|(?!\1)[^\\])*\1[cwd]?/ + ], + + number: [ + // The lookbehind and the negative look-ahead try to prevent bad highlighting of the .. operator + // Hexadecimal numbers must be handled separately to avoid problems with exponent "e" + /\b0x\.?[a-f\d_]+(?:(?!\.\.)\.[a-f\d_]*)?(?:p[+-]?[a-f\d_]+)?[ulfi]*/i, + { + pattern: /((?:\.\.)?)(?:\b0b\.?|\b|\.)\d[\d_]*(?:(?!\.\.)\.[\d_]*)?(?:e[+-]?\d[\d_]*)?[ulfi]*/i, + lookbehind: true + } + ], + + // In order: $, keywords and special tokens, globally defined symbols + keyword: /\$|\b(?:abstract|alias|align|asm|assert|auto|body|bool|break|byte|case|cast|catch|cdouble|cent|cfloat|char|class|const|continue|creal|dchar|debug|default|delegate|delete|deprecated|do|double|else|enum|export|extern|false|final|finally|float|for|foreach|foreach_reverse|function|goto|idouble|if|ifloat|immutable|import|inout|int|interface|invariant|ireal|lazy|long|macro|mixin|module|new|nothrow|null|out|override|package|pragma|private|protected|public|pure|real|ref|return|scope|shared|short|static|struct|super|switch|synchronized|template|this|throw|true|try|typedef|typeid|typeof|ubyte|ucent|uint|ulong|union|unittest|ushort|version|void|volatile|wchar|while|with|__(?:(?:FILE|MODULE|LINE|FUNCTION|PRETTY_FUNCTION|DATE|EOF|TIME|TIMESTAMP|VENDOR|VERSION)__|gshared|traits|vector|parameters)|string|wstring|dstring|size_t|ptrdiff_t)\b/, + operator: /\|[|=]?|&[&=]?|\+[+=]?|-[-=]?|\.?\.\.|=[>=]?|!(?:i[ns]\b|<>?=?|>=?|=)?|\bi[ns]\b|(?:<[<>]?|>>?>?|\^\^|[*\/%^~])=?/ +}) + +Prism.languages.d.comment = [ + // Shebang + /^\s*#!.+/, + // /+ +/ + { + // Allow one level of nesting + pattern: /(^|[^\\])\/\+(?:\/\+[\s\S]*?\+\/|[\s\S])*?\+\//, + lookbehind: true + } +].concat(Prism.languages.d.comment) + +Prism.languages.insertBefore('d', 'comment', { + 'token-string': { + // Allow one level of nesting + pattern: /\bq\{(?:|\{[^}]*\}|[^}])*\}/, + alias: 'string' + } +}) + +Prism.languages.insertBefore('d', 'keyword', { + property: /\B@\w*/ +}) + +Prism.languages.insertBefore('d', 'function', { + register: { + // Iasm registers + pattern: /\b(?:[ABCD][LHX]|E[ABCD]X|E?(?:BP|SP|DI|SI)|[ECSDGF]S|CR[0234]|DR[012367]|TR[3-7]|X?MM[0-7]|R[ABCD]X|[BS]PL|R[BS]P|[DS]IL|R[DS]I|R(?:[89]|1[0-5])[BWD]?|XMM(?:[89]|1[0-5])|YMM(?:1[0-5]|\d))\b|\bST(?:\([0-7]\)|\b)/, + alias: 'variable' + } +}) +Prism.languages.dart = Prism.languages.extend('clike', { + string: [ + { + pattern: /r?("""|''')[\s\S]*?\1/, + greedy: true + }, + { + pattern: /r?("|')(\\?.)*?\1/, + greedy: true + } + ], + keyword: [ + /\b(?:async|sync|yield)\*/, + /\b(?:abstract|assert|async|await|break|case|catch|class|const|continue|default|deferred|do|dynamic|else|enum|export|external|extends|factory|final|finally|for|get|if|implements|import|in|library|new|null|operator|part|rethrow|return|set|static|super|switch|this|throw|try|typedef|var|void|while|with|yield)\b/ + ], + operator: /\bis!|\b(?:as|is)\b|\+\+|--|&&|\|\||<<=?|>>=?|~(?:\/=?)?|[+\-*\/%&^|=!<>]=?|\?/ +}) + +Prism.languages.insertBefore('dart', 'function', { + metadata: { + pattern: /@\w+/, + alias: 'symbol' + } +}) + +/*-----------------------------------------------------------*/ + +Prism.languages.docker = { + keyword: { + pattern: /(^\s*)(?:ONBUILD|FROM|MAINTAINER|RUN|EXPOSE|ENV|ADD|COPY|VOLUME|USER|WORKDIR|CMD|LABEL|ENTRYPOINT)(?=\s)/im, + lookbehind: true + }, + string: /("|')(?:(?!\1)[^\\\r\n]|\\(?:\r\n|[\s\S]))*?\1/, + comment: /#.*/, + punctuation: /---|\.\.\.|[:[\]{}\-,|>?]/ +} +Prism.languages.erlang = { + comment: /%.+/, + string: { + pattern: /"(?:\\?.)*?"/, + greedy: true + }, + 'quoted-function': { + pattern: /'(?:\\.|[^'\\])+'(?=\()/, + alias: 'function' + }, + 'quoted-atom': { + pattern: /'(?:\\.|[^'\\])+'/, + alias: 'atom' + }, + boolean: /\b(?:true|false)\b/, + keyword: /\b(?:fun|when|case|of|end|if|receive|after|try|catch)\b/, + number: [/\$\\?./, /\d+#[a-z0-9]+/i, /(?:\b|-)\d*\.?\d+([Ee][+-]?\d+)?\b/], + function: /\b[a-z][\w@]*(?=\()/, + variable: { + // Look-behind is used to prevent wrong highlighting of atoms containing "@" + pattern: /(^|[^@])(?:\b|\?)[A-Z_][\w@]*/, + lookbehind: true + }, + operator: [ + /[=\/<>:]=|=[:\/]=|\+\+?|--?|[=*\/!]|\b(?:bnot|div|rem|band|bor|bxor|bsl|bsr|not|and|or|xor|orelse|andalso)\b/, + { + // We don't want to match << + pattern: /(^|[^<])<(?!<)/, + lookbehind: true + }, + { + // We don't want to match >> + pattern: /(^|[^>])>(?!>)/, + lookbehind: true + } + ], + atom: /\b[a-z][\w@]*/, + punctuation: /[()[\]{}:;,.#|]|<<|>>/ +} + +Prism.languages.git = { + comment: /^#.*/m, + deleted: /^[-–].*/m, + inserted: /^\+.*/m, + string: /("|')(\\?.)*?\1/m, + command: { + pattern: /^.*\$ git .*$/m, + inside: { + parameter: /\s(--|-)\w+/m + } + }, + coord: /^@@.*@@$/m, + commit_sha1: /^commit \w{40}$/m +} + +/*-----------------------------------------------------------*/ +Prism.languages.go = Prism.languages.extend('clike', { + keyword: /\b(break|case|chan|const|continue|default|defer|else|fallthrough|for|func|go(to)?|if|import|interface|map|package|range|return|select|struct|switch|type|var)\b/, + builtin: /\b(bool|byte|complex(64|128)|error|float(32|64)|rune|string|u?int(8|16|32|64|)|uintptr|append|cap|close|complex|copy|delete|imag|len|make|new|panic|print(ln)?|real|recover)\b/, + boolean: /\b(_|iota|nil|true|false)\b/, + operator: /[*\/%^!=]=?|\+[=+]?|-[=-]?|\|[=|]?|&(?:=|&|\^=?)?|>(?:>=?|=)?|<(?:<=?|=|-)?|:=|\.\.\./, + number: /\b(-?(0x[a-f\d]+|(\d+\.?\d*|\.\d+)(e[-+]?\d+)?)i?)\b/i, + string: { + pattern: /("|'|`)(\\?.|\r|\n)*?\1/, + greedy: true + } +}) +delete Prism.languages.go['class-name'] + +Prism.languages.haskell = { + comment: { + pattern: /(^|[^-!#$%*+=?&@|~.:<>^\\\/])(--[^-!#$%*+=?&@|~.:<>^\\\/].*|{-[\s\S]*?-})/m, + lookbehind: true + }, + char: /'([^\\']|\\([abfnrtv\\"'&]|\^[A-Z@[\]\^_]|NUL|SOH|STX|ETX|EOT|ENQ|ACK|BEL|BS|HT|LF|VT|FF|CR|SO|SI|DLE|DC1|DC2|DC3|DC4|NAK|SYN|ETB|CAN|EM|SUB|ESC|FS|GS|RS|US|SP|DEL|\d+|o[0-7]+|x[0-9a-fA-F]+))'/, + string: { + pattern: /"([^\\"]|\\([abfnrtv\\"'&]|\^[A-Z@[\]\^_]|NUL|SOH|STX|ETX|EOT|ENQ|ACK|BEL|BS|HT|LF|VT|FF|CR|SO|SI|DLE|DC1|DC2|DC3|DC4|NAK|SYN|ETB|CAN|EM|SUB|ESC|FS|GS|RS|US|SP|DEL|\d+|o[0-7]+|x[0-9a-fA-F]+)|\\\s+\\)*"/, + greedy: true + }, + keyword: /\b(case|class|data|deriving|do|else|if|in|infixl|infixr|instance|let|module|newtype|of|primitive|then|type|where)\b/, + import_statement: { + // The imported or hidden names are not included in this import + // statement. This is because we want to highlight those exactly like + // we do for the names in the program. + pattern: /(\r?\n|\r|^)\s*import\s+(qualified\s+)?([A-Z][_a-zA-Z0-9']*)(\.[A-Z][_a-zA-Z0-9']*)*(\s+as\s+([A-Z][_a-zA-Z0-9']*)(\.[A-Z][_a-zA-Z0-9']*)*)?(\s+hiding\b)?/m, + inside: { + keyword: /\b(import|qualified|as|hiding)\b/ + } + }, + // These are builtin variables only. Constructors are highlighted later as a constant. + builtin: /\b(abs|acos|acosh|all|and|any|appendFile|approxRational|asTypeOf|asin|asinh|atan|atan2|atanh|basicIORun|break|catch|ceiling|chr|compare|concat|concatMap|const|cos|cosh|curry|cycle|decodeFloat|denominator|digitToInt|div|divMod|drop|dropWhile|either|elem|encodeFloat|enumFrom|enumFromThen|enumFromThenTo|enumFromTo|error|even|exp|exponent|fail|filter|flip|floatDigits|floatRadix|floatRange|floor|fmap|foldl|foldl1|foldr|foldr1|fromDouble|fromEnum|fromInt|fromInteger|fromIntegral|fromRational|fst|gcd|getChar|getContents|getLine|group|head|id|inRange|index|init|intToDigit|interact|ioError|isAlpha|isAlphaNum|isAscii|isControl|isDenormalized|isDigit|isHexDigit|isIEEE|isInfinite|isLower|isNaN|isNegativeZero|isOctDigit|isPrint|isSpace|isUpper|iterate|last|lcm|length|lex|lexDigits|lexLitChar|lines|log|logBase|lookup|map|mapM|mapM_|max|maxBound|maximum|maybe|min|minBound|minimum|mod|negate|not|notElem|null|numerator|odd|or|ord|otherwise|pack|pi|pred|primExitWith|print|product|properFraction|putChar|putStr|putStrLn|quot|quotRem|range|rangeSize|read|readDec|readFile|readFloat|readHex|readIO|readInt|readList|readLitChar|readLn|readOct|readParen|readSigned|reads|readsPrec|realToFrac|recip|rem|repeat|replicate|return|reverse|round|scaleFloat|scanl|scanl1|scanr|scanr1|seq|sequence|sequence_|show|showChar|showInt|showList|showLitChar|showParen|showSigned|showString|shows|showsPrec|significand|signum|sin|sinh|snd|sort|span|splitAt|sqrt|subtract|succ|sum|tail|take|takeWhile|tan|tanh|threadToIOResult|toEnum|toInt|toInteger|toLower|toRational|toUpper|truncate|uncurry|undefined|unlines|until|unwords|unzip|unzip3|userError|words|writeFile|zip|zip3|zipWith|zipWith3)\b/, + // decimal integers and floating point numbers | octal integers | hexadecimal integers + number: /\b(\d+(\.\d+)?(e[+-]?\d+)?|0o[0-7]+|0x[0-9a-f]+)\b/i, + // Most of this is needed because of the meaning of a single '.'. + // If it stands alone freely, it is the function composition. + // It may also be a separator between a module name and an identifier => no + // operator. If it comes together with other special characters it is an + // operator too. + operator: /\s\.\s|[-!#$%*+=?&@|~.:<>^\\\/]*\.[-!#$%*+=?&@|~.:<>^\\\/]+|[-!#$%*+=?&@|~.:<>^\\\/]+\.[-!#$%*+=?&@|~.:<>^\\\/]*|[-!#$%*+=?&@|~:<>^\\\/]+|`([A-Z][_a-zA-Z0-9']*\.)*[_a-z][_a-zA-Z0-9']*`/, + // In Haskell, nearly everything is a variable, do not highlight these. + hvariable: /\b([A-Z][_a-zA-Z0-9']*\.)*[_a-z][_a-zA-Z0-9']*\b/, + constant: /\b([A-Z][_a-zA-Z0-9']*\.)*[A-Z][_a-zA-Z0-9']*\b/, + punctuation: /[{}[\];(),.:]/ +} + +/*---------------------------jade---------------------------*/ + +;(function(Prism) { + Prism.languages.jade = { + comment: { + pattern: /(^([\t ]*))\/\/.*((?:\r?\n|\r)\2[\t ]+.+)*/m, + lookbehind: true + }, + 'multiline-script': { + pattern: /(^([\t ]*)script\b.*\.[\t ]*)((?:\r?\n|\r(?!\n))(?:\2[\t ]+.+|\s*?(?=\r?\n|\r)))+/m, + lookbehind: true, + inside: { + rest: Prism.languages.javascript + } + }, + filter: { + pattern: /(^([\t ]*)):.+((?:\r?\n|\r(?!\n))(?:\2[\t ]+.+|\s*?(?=\r?\n|\r)))+/m, + lookbehind: true, + inside: { + 'filter-name': { + pattern: /^:[\w-]+/, + alias: 'variable' + } + } + }, + 'multiline-plain-text': { + pattern: /(^([\t ]*)[\w\-#.]+\.[\t ]*)((?:\r?\n|\r(?!\n))(?:\2[\t ]+.+|\s*?(?=\r?\n|\r)))+/m, + lookbehind: true + }, + markup: { + pattern: /(^[\t ]*)<.+/m, + lookbehind: true, + inside: { + rest: Prism.languages.markup + } + }, + doctype: { + pattern: /((?:^|\n)[\t ]*)doctype(?: .+)?/, + lookbehind: true + }, + 'flow-control': { + pattern: /(^[\t ]*)(?:if|unless|else|case|when|default|each|while)\b(?: .+)?/m, + lookbehind: true, + inside: { + each: { + pattern: /^each .+? in\b/, + inside: { + keyword: /\b(?:each|in)\b/, + punctuation: /,/ + } + }, + branch: { + pattern: /^(?:if|unless|else|case|when|default|while)\b/, + alias: 'keyword' + }, + rest: Prism.languages.javascript + } + }, + keyword: { + pattern: /(^[\t ]*)(?:block|extends|include|append|prepend)\b.+/m, + lookbehind: true + }, + mixin: [ + { + pattern: /(^[\t ]*)mixin .+/m, + lookbehind: true, + inside: { + keyword: /^mixin/, + function: /\w+(?=\s*\(|\s*$)/, + punctuation: /[(),.]/ + } + }, + { + pattern: /(^[\t ]*)\+.+/m, + lookbehind: true, + inside: { + name: { + pattern: /^\+\w+/, + alias: 'function' + }, + rest: Prism.languages.javascript + } + } + ], + script: { + pattern: /(^[\t ]*script(?:(?:&[^(]+)?\([^)]+\))*[\t ]+).+/m, + lookbehind: true, + inside: { + rest: Prism.languages.javascript + } + }, + + 'plain-text': { + pattern: /(^[\t ]*(?!-)[\w\-#.]*[\w\-](?:(?:&[^(]+)?\([^)]+\))*\/?[\t ]+).+/m, + lookbehind: true + }, + tag: { + pattern: /(^[\t ]*)(?!-)[\w\-#.]*[\w\-](?:(?:&[^(]+)?\([^)]+\))*\/?:?/m, + lookbehind: true, + inside: { + attributes: [ + { + pattern: /&[^(]+\([^)]+\)/, + inside: { + rest: Prism.languages.javascript + } + }, + { + pattern: /\([^)]+\)/, + inside: { + 'attr-value': { + pattern: /(=\s*)(?:\{[^}]*\}|[^,)\r\n]+)/, + lookbehind: true, + inside: { + rest: Prism.languages.javascript + } + }, + 'attr-name': /[\w-]+(?=\s*!?=|\s*[,)])/, + punctuation: /[!=(),]+/ + } + } + ], + punctuation: /:/ + } + }, + code: [ + { + pattern: /(^[\t ]*(?:-|!?=)).+/m, + lookbehind: true, + inside: { + rest: Prism.languages.javascript + } + } + ], + punctuation: /[.\-!=|]+/ + } + + var filter_pattern = + '(^([\\t ]*)):{{filter_name}}((?:\\r?\\n|\\r(?!\\n))(?:\\2[\\t ]+.+|\\s*?(?=\\r?\\n|\\r)))+' + + var filters = [ + { filter: 'atpl', language: 'twig' }, + { filter: 'coffee', language: 'coffeescript' }, + 'ejs', + 'handlebars', + 'hogan', + 'less', + 'livescript', + 'markdown', + 'mustache', + 'plates', + { filter: 'sass', language: 'scss' }, + 'stylus', + 'swig' + ] + var all_filters = {} + for (var i = 0, l = filters.length; i < l; i++) { + var filter = filters[i] + filter = + typeof filter === 'string' ? { filter: filter, language: filter } : filter + if (Prism.languages[filter.language]) { + all_filters['filter-' + filter.filter] = { + pattern: RegExp( + filter_pattern.replace('{{filter_name}}', filter.filter), + 'm' + ), + lookbehind: true, + inside: { + 'filter-name': { + pattern: /^:[\w-]+/, + alias: 'variable' + }, + rest: Prism.languages[filter.language] + } + } + } + } + + Prism.languages.insertBefore('jade', 'filter', all_filters) +})(Prism) + +/*-----------------------------------------------------------*/ + +Prism.languages.java = Prism.languages.extend('clike', { + keyword: /\b(abstract|continue|for|new|switch|assert|default|goto|package|synchronized|boolean|do|if|private|this|break|double|implements|protected|throw|byte|else|import|public|throws|case|enum|instanceof|return|transient|catch|extends|int|short|try|char|final|interface|static|void|class|finally|long|strictfp|volatile|const|float|native|super|while)\b/, + number: /\b0b[01]+\b|\b0x[\da-f]*\.?[\da-fp\-]+\b|\b\d*\.?\d+(?:e[+-]?\d+)?[df]?\b/i, + operator: { + pattern: /(^|[^.])(?:\+[+=]?|-[-=]?|!=?|<>?>?=?|==?|&[&=]?|\|[|=]?|\*=?|\/=?|%=?|\^=?|[?:~])/m, + lookbehind: true + } +}) + +Prism.languages.insertBefore('java', 'function', { + annotation: { + alias: 'punctuation', + pattern: /(^|[^.])@\w+/, + lookbehind: true + } +}) + +Prism.languages.json = { + property: /"(?:\\.|[^\\"])*"(?=\s*:)/gi, + string: /"(?!:)(?:\\.|[^\\"])*"(?!:)/g, + number: /\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee][+-]?\d+)?)\b/g, + punctuation: /[{}[\]);,]/g, + operator: /:/g, + boolean: /\b(true|false)\b/gi, + null: /\bnull\b/gi +} + +Prism.languages.jsonp = Prism.languages.json + +/*--------------------------kotlin----------------------------*/ + +;(function(Prism) { + Prism.languages.kotlin = Prism.languages.extend('clike', { + keyword: { + // The lookbehind prevents wrong highlighting of e.g. kotlin.properties.get + pattern: /(^|[^.])\b(?:abstract|annotation|as|break|by|catch|class|companion|const|constructor|continue|crossinline|data|do|else|enum|final|finally|for|fun|get|if|import|in|init|inline|inner|interface|internal|is|lateinit|noinline|null|object|open|out|override|package|private|protected|public|reified|return|sealed|set|super|tailrec|this|throw|to|try|val|var|when|where|while)\b/, + lookbehind: true + }, + function: [ + /\w+(?=\s*\()/, + { + pattern: /(\.)\w+(?=\s*\{)/, + lookbehind: true + } + ], + number: /\b(?:0[bx][\da-fA-F]+|\d+(?:\.\d+)?(?:e[+-]?\d+)?[fFL]?)\b/, + operator: /\+[+=]?|-[-=>]?|==?=?|!(?:!|==?)?|[\/*%<>]=?|[?:]:?|\.\.|&&|\|\||\b(?:and|inv|or|shl|shr|ushr|xor)\b/ + }) + + delete Prism.languages.kotlin['class-name'] + + Prism.languages.insertBefore('kotlin', 'string', { + 'raw-string': { + pattern: /(["'])\1\1[\s\S]*?\1{3}/, + alias: 'string' + // See interpolation below + } + }) + Prism.languages.insertBefore('kotlin', 'keyword', { + annotation: { + pattern: /\B@(?:\w+:)?(?:[A-Z]\w*|\[[^\]]+\])/, + alias: 'builtin' + } + }) + Prism.languages.insertBefore('kotlin', 'function', { + label: { + pattern: /\w+@|@\w+/, + alias: 'symbol' + } + }) + + var interpolation = [ + { + pattern: /\$\{[^}]+\}/, + inside: { + delimiter: { + pattern: /^\$\{|\}$/, + alias: 'variable' + }, + rest: Prism.util.clone(Prism.languages.kotlin) + } + }, + { + pattern: /\$\w+/, + alias: 'variable' + } + ] + + Prism.languages.kotlin['string'].inside = Prism.languages.kotlin[ + 'raw-string' + ].inside = { + interpolation: interpolation + } +})(Prism) + +/*-----------------------------------------------------------*/ + +Prism.languages.less = Prism.languages.extend('css', { + comment: [ + /\/\*[\s\S]*?\*\//, + { + pattern: /(^|[^\\])\/\/.*/, + lookbehind: true + } + ], + atrule: { + pattern: /@[\w-]+?(?:\([^{}]+\)|[^(){};])*?(?=\s*\{)/i, + inside: { + punctuation: /[:()]/ + } + }, + // selectors and mixins are considered the same + selector: { + pattern: /(?:@\{[\w-]+\}|[^{};\s@])(?:@\{[\w-]+\}|\([^{}]*\)|[^{};@])*?(?=\s*\{)/, + inside: { + // mixin parameters + variable: /@+[\w-]+/ + } + }, + + property: /(?:@\{[\w-]+\}|[\w-])+(?:\+_?)?(?=\s*:)/i, + punctuation: /[{}();:,]/, + operator: /[+\-*\/]/ +}) + +// Invert function and punctuation positions +Prism.languages.insertBefore('less', 'punctuation', { + function: Prism.languages.less.function +}) + +Prism.languages.insertBefore('less', 'property', { + variable: [ + // Variable declaration (the colon must be consumed!) + { + pattern: /@[\w-]+\s*:/, + inside: { + punctuation: /:/ + } + }, + + // Variable usage + /@@?[\w-]+/ + ], + 'mixin-usage': { + pattern: /([{;]\s*)[.#](?!\d)[\w-]+.*?(?=[(;])/, + lookbehind: true, + alias: 'function' + } +}) + +/*-----------------------------------------------------------*/ + +Prism.languages.lua = { + comment: /^#!.+|--(?:\[(=*)\[[\s\S]*?\]\1\]|.*)/m, + // \z may be used to skip the following space + string: { + pattern: /(["'])(?:(?!\1)[^\\\r\n]|\\z(?:\r\n|\s)|\\(?:\r\n|[\s\S]))*\1|\[(=*)\[[\s\S]*?\]\2\]/, + greedy: true + }, + number: /\b0x[a-f\d]+\.?[a-f\d]*(?:p[+-]?\d+)?\b|\b\d+(?:\.\B|\.?\d*(?:e[+-]?\d+)?\b)|\B\.\d+(?:e[+-]?\d+)?\b/i, + keyword: /\b(?:and|break|do|else|elseif|end|false|for|function|goto|if|in|local|nil|not|or|repeat|return|then|true|until|while)\b/, + function: /(?!\d)\w+(?=\s*(?:[({]))/, + operator: [ + /[-+*%^&|#]|\/\/?|<[<=]?|>[>=]?|[=~]=?/, + { + // Match ".." but don't break "..." + pattern: /(^|[^.])\.\.(?!\.)/, + lookbehind: true + } + ], + punctuation: /[\[\](){},;]|\.+|:+/ +} +Prism.languages.matlab = { + // We put string before comment, because of printf() patterns that contain "%" + string: /\B'(?:''|[^'\n])*'/, + comment: [/%\{[\s\S]*?\}%/, /%.+/], + // FIXME We could handle imaginary numbers as a whole + number: /\b-?(?:\d*\.?\d+(?:[eE][+-]?\d+)?(?:[ij])?|[ij])\b/, + keyword: /\b(?:break|case|catch|continue|else|elseif|end|for|function|if|inf|NaN|otherwise|parfor|pause|pi|return|switch|try|while)\b/, + function: /(?!\d)\w+(?=\s*\()/, + operator: /\.?[*^\/\\']|[+\-:@]|[<>=~]=?|&&?|\|\|?/, + punctuation: /\.{3}|[.,;\[\](){}!]/ +} + +Prism.languages.nim = { + comment: /#.*/, + // Double-quoted strings can be prefixed by an identifier (Generalized raw string literals) + // Character literals are handled specifically to prevent issues with numeric type suffixes + string: { + pattern: /(?:(?:\b(?!\d)(?:\w|\\x[8-9a-fA-F][0-9a-fA-F])+)?(?:"""[\s\S]*?"""(?!")|"(?:\\[\s\S]|""|[^"\\])*")|'(?:\\(?:\d+|x[\da-fA-F]{2}|.)|[^'])')/, + greedy: true + }, + // The negative look ahead prevents wrong highlighting of the .. operator + number: /\b(?:0[xXoObB][\da-fA-F_]+|\d[\d_]*(?:(?!\.\.)\.[\d_]*)?(?:[eE][+-]?\d[\d_]*)?)(?:'?[iuf]\d*)?/, + keyword: /\b(?:addr|as|asm|atomic|bind|block|break|case|cast|concept|const|continue|converter|defer|discard|distinct|do|elif|else|end|enum|except|export|finally|for|from|func|generic|if|import|include|interface|iterator|let|macro|method|mixin|nil|object|out|proc|ptr|raise|ref|return|static|template|try|tuple|type|using|var|when|while|with|without|yield)\b/, + function: { + pattern: /(?:(?!\d)(?:\w|\\x[8-9a-fA-F][0-9a-fA-F])+|`[^`\r\n]+`)\*?(?:\[[^\]]+\])?(?=\s*\()/, + inside: { + operator: /\*$/ + } + }, + // We don't want to highlight operators inside backticks + ignore: { + pattern: /`[^`\r\n]+`/, + inside: { + punctuation: /`/ + } + }, + operator: { + // Look behind and look ahead prevent wrong highlighting of punctuations [. .] {. .} (. .) + // but allow the slice operator .. to take precedence over them + // One can define his own operators in Nim so all combination of operators might be an operator. + pattern: /(^|[({\[](?=\.\.)|(?![({\[]\.).)(?:(?:[=+\-*\/<>@$~&%|!?^:\\]|\.\.|\.(?![)}\]]))+|\b(?:and|div|of|or|in|is|isnot|mod|not|notin|shl|shr|xor)\b)/m, + lookbehind: true + }, + punctuation: /[({\[]\.|\.[)}\]]|[`(){}\[\],:]/ +} +Prism.languages.objectivec = Prism.languages.extend('c', { + keyword: /\b(asm|typeof|inline|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|void|volatile|while|in|self|super)\b|(@interface|@end|@implementation|@protocol|@class|@public|@protected|@private|@property|@try|@catch|@finally|@throw|@synthesize|@dynamic|@selector)\b/, + string: /("|')(\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1|@"(\\(?:\r\n|[\s\S])|[^"\\\r\n])*"/, + operator: /-[->]?|\+\+?|!=?|<>?=?|==?|&&?|\|\|?|[~^%?*\/@]/ +}) + +/*-----------------------------------------------------------*/ + +Prism.languages.perl = { + comment: [ + { + // POD + pattern: /(^\s*)=\w+[\s\S]*?=cut.*/m, + lookbehind: true + }, + { + pattern: /(^|[^\\$])#.*/, + lookbehind: true + } + ], + // TODO Could be nice to handle Heredoc too. + string: [ + // q/.../ + { + pattern: /\b(?:q|qq|qx|qw)\s*([^a-zA-Z0-9\s\{\(\[<])(?:[^\\]|\\[\s\S])*?\1/, + greedy: true + }, + + // q a...a + { + pattern: /\b(?:q|qq|qx|qw)\s+([a-zA-Z0-9])(?:[^\\]|\\[\s\S])*?\1/, + greedy: true + }, + + // q(...) + { + pattern: /\b(?:q|qq|qx|qw)\s*\((?:[^()\\]|\\[\s\S])*\)/, + greedy: true + }, + + // q{...} + { + pattern: /\b(?:q|qq|qx|qw)\s*\{(?:[^{}\\]|\\[\s\S])*\}/, + greedy: true + }, + + // q[...] + { + pattern: /\b(?:q|qq|qx|qw)\s*\[(?:[^[\]\\]|\\[\s\S])*\]/, + greedy: true + }, + + // q<...> + { + pattern: /\b(?:q|qq|qx|qw)\s*<(?:[^<>\\]|\\[\s\S])*>/, + greedy: true + }, + + // "...", `...` + { + pattern: /("|`)(?:[^\\]|\\[\s\S])*?\1/, + greedy: true + }, + + // '...' + // FIXME Multi-line single-quoted strings are not supported as they would break variables containing ' + { + pattern: /'(?:[^'\\\r\n]|\\.)*'/, + greedy: true + } + ], + regex: [ + // m/.../ + { + pattern: /\b(?:m|qr)\s*([^a-zA-Z0-9\s\{\(\[<])(?:[^\\]|\\[\s\S])*?\1[msixpodualngc]*/, + greedy: true + }, + + // m a...a + { + pattern: /\b(?:m|qr)\s+([a-zA-Z0-9])(?:[^\\]|\\.)*?\1[msixpodualngc]*/, + greedy: true + }, + + // m(...) + { + pattern: /\b(?:m|qr)\s*\((?:[^()\\]|\\[\s\S])*\)[msixpodualngc]*/, + greedy: true + }, + + // m{...} + { + pattern: /\b(?:m|qr)\s*\{(?:[^{}\\]|\\[\s\S])*\}[msixpodualngc]*/, + greedy: true + }, + + // m[...] + { + pattern: /\b(?:m|qr)\s*\[(?:[^[\]\\]|\\[\s\S])*\][msixpodualngc]*/, + greedy: true + }, + + // m<...> + { + pattern: /\b(?:m|qr)\s*<(?:[^<>\\]|\\[\s\S])*>[msixpodualngc]*/, + greedy: true + }, + + // The lookbehinds prevent -s from breaking + // FIXME We don't handle change of separator like s(...)[...] + // s/.../.../ + { + pattern: /(^|[^-]\b)(?:s|tr|y)\s*([^a-zA-Z0-9\s\{\(\[<])(?:[^\\]|\\[\s\S])*?\2(?:[^\\]|\\[\s\S])*?\2[msixpodualngcer]*/, + lookbehind: true, + greedy: true + }, + + // s a...a...a + { + pattern: /(^|[^-]\b)(?:s|tr|y)\s+([a-zA-Z0-9])(?:[^\\]|\\[\s\S])*?\2(?:[^\\]|\\[\s\S])*?\2[msixpodualngcer]*/, + lookbehind: true, + greedy: true + }, + + // s(...)(...) + { + pattern: /(^|[^-]\b)(?:s|tr|y)\s*\((?:[^()\\]|\\[\s\S])*\)\s*\((?:[^()\\]|\\[\s\S])*\)[msixpodualngcer]*/, + lookbehind: true, + greedy: true + }, + + // s{...}{...} + { + pattern: /(^|[^-]\b)(?:s|tr|y)\s*\{(?:[^{}\\]|\\[\s\S])*\}\s*\{(?:[^{}\\]|\\[\s\S])*\}[msixpodualngcer]*/, + lookbehind: true, + greedy: true + }, + + // s[...][...] + { + pattern: /(^|[^-]\b)(?:s|tr|y)\s*\[(?:[^[\]\\]|\\[\s\S])*\]\s*\[(?:[^[\]\\]|\\[\s\S])*\][msixpodualngcer]*/, + lookbehind: true, + greedy: true + }, + + // s<...><...> + { + pattern: /(^|[^-]\b)(?:s|tr|y)\s*<(?:[^<>\\]|\\[\s\S])*>\s*<(?:[^<>\\]|\\[\s\S])*>[msixpodualngcer]*/, + lookbehind: true, + greedy: true + }, + + // /.../ + // The look-ahead tries to prevent two divisions on + // the same line from being highlighted as regex. + // This does not support multi-line regex. + { + pattern: /\/(?:[^\/\\\r\n]|\\.)*\/[msixpodualngc]*(?=\s*(?:$|[\r\n,.;})&|\-+*~<>!?^]|(lt|gt|le|ge|eq|ne|cmp|not|and|or|xor|x)\b))/, + greedy: true + } + ], + + // FIXME Not sure about the handling of ::, ', and # + variable: [ + // ${^POSTMATCH} + /[&*$@%]\{\^[A-Z]+\}/, + // $^V + /[&*$@%]\^[A-Z_]/, + // ${...} + /[&*$@%]#?(?=\{)/, + // $foo + /[&*$@%]#?((::)*'?(?!\d)[\w$]+)+(::)*/i, + // $1 + /[&*$@%]\d+/, + // $_, @_, %! + // The negative lookahead prevents from breaking the %= operator + /(?!%=)[$@%][!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/ + ], + filehandle: { + // <>, , _ + pattern: /<(?![<=])\S*>|\b_\b/, + alias: 'symbol' + }, + vstring: { + // v1.2, 1.2.3 + pattern: /v\d+(\.\d+)*|\d+(\.\d+){2,}/, + alias: 'string' + }, + function: { + pattern: /sub [a-z0-9_]+/i, + inside: { + keyword: /sub/ + } + }, + keyword: /\b(any|break|continue|default|delete|die|do|else|elsif|eval|for|foreach|given|goto|if|last|local|my|next|our|package|print|redo|require|say|state|sub|switch|undef|unless|until|use|when|while)\b/, + number: /\b-?(0x[\dA-Fa-f](_?[\dA-Fa-f])*|0b[01](_?[01])*|(\d(_?\d)*)?\.?\d(_?\d)*([Ee][+-]?\d+)?)\b/, + operator: /-[rwxoRWXOezsfdlpSbctugkTBMAC]\b|\+[+=]?|-[-=>]?|\*\*?=?|\/\/?=?|=[=~>]?|~[~=]?|\|\|?=?|&&?=?|<(?:=>?|<=?)?|>>?=?|![~=]?|[%^]=?|\.(?:=|\.\.?)?|[\\?]|\bx(?:=|\b)|\b(lt|gt|le|ge|eq|ne|cmp|not|and|or|xor)\b/, + punctuation: /[{}[\];(),:]/ +} + +/*-----------------------------------------------------------*/ + +Prism.languages.php = Prism.languages.extend('clike', { + keyword: /\b(and|or|xor|array|as|break|case|cfunction|class|const|continue|declare|default|die|do|else|elseif|enddeclare|endfor|endforeach|endif|endswitch|endwhile|extends|for|foreach|function|include|include_once|global|if|new|return|static|switch|use|require|require_once|var|while|abstract|interface|public|implements|private|protected|parent|throw|null|echo|print|trait|namespace|final|yield|goto|instanceof|finally|try|catch)\b/i, + constant: /\b[A-Z0-9_]{2,}\b/, + comment: { + pattern: /(^|[^\\])(?:\/\*[\s\S]*?\*\/|\/\/.*)/, + lookbehind: true + } +}) + +// Shell-like comments are matched after strings, because they are less +// common than strings containing hashes... +Prism.languages.insertBefore('php', 'class-name', { + 'shell-comment': { + pattern: /(^|[^\\])#.*/, + lookbehind: true, + alias: 'comment' + } +}) + +Prism.languages.insertBefore('php', 'keyword', { + delimiter: { + pattern: /\?>|<\?(?:php|=)?/i, + alias: 'important' + }, + variable: /\$\w+\b/i, + package: { + pattern: /(\\|namespace\s+|use\s+)[\w\\]+/, + lookbehind: true, + inside: { + punctuation: /\\/ + } + } +}) + +// Must be defined after the function pattern +Prism.languages.insertBefore('php', 'operator', { + property: { + pattern: /(->)[\w]+/, + lookbehind: true + } +}) + +// Add HTML support if the markup language exists +if (Prism.languages.markup) { + // Tokenize all inline PHP blocks that are wrapped in + // This allows for easy PHP + markup highlighting + Prism.hooks.add('before-highlight', function(env) { + if (env.language !== 'php' || !/(?:<\?php|<\?)/gi.test(env.code)) { + return + } + + env.tokenStack = [] + + env.backupCode = env.code + env.code = env.code.replace(/(?:<\?php|<\?)[\s\S]*?(?:\?>|$)/gi, function( + match + ) { + var i = env.tokenStack.length + // Check for existing strings + while (env.backupCode.indexOf('___PHP' + i + '___') !== -1) ++i + + // Create a sparse array + env.tokenStack[i] = match + + return '___PHP' + i + '___' + }) + + // Switch the grammar to markup + env.grammar = Prism.languages.markup + }) + + // Restore env.code for other plugins (e.g. line-numbers) + Prism.hooks.add('before-insert', function(env) { + if (env.language === 'php' && env.backupCode) { + env.code = env.backupCode + delete env.backupCode + } + }) + + // Re-insert the tokens after highlighting + Prism.hooks.add('after-highlight', function(env) { + if (env.language !== 'php' || !env.tokenStack) { + return + } + + // Switch the grammar back + env.grammar = Prism.languages.php + + for (var i = 0, keys = Object.keys(env.tokenStack); i < keys.length; ++i) { + var k = keys[i] + var t = env.tokenStack[k] + + // The replace prevents $$, $&, $`, $', $n, $nn from being interpreted as special patterns + env.highlightedCode = env.highlightedCode.replace( + '___PHP' + k + '___', + '' + + Prism.highlight(t, env.grammar, 'php').replace(/\$/g, '$$$$') + + '' + ) + } + + env.element.innerHTML = env.highlightedCode + }) +} + +/*------------------------------------------------------------*/ + +Prism.languages.powershell = { + comment: [ + { + pattern: /(^|[^`])<#[\s\S]*?#>/, + lookbehind: true + }, + { + pattern: /(^|[^`])#.*/, + lookbehind: true + } + ], + string: [ + { + pattern: /"(`?[\s\S])*?"/, + greedy: true, + inside: { + function: { + pattern: /[^`]\$\(.*?\)/, + // Populated at end of file + inside: {} + } + } + }, + { + pattern: /'([^']|'')*'/, + greedy: true + } + ], + // Matches name spaces as well as casts, attribute decorators. Force starting with letter to avoid matching array indices + namespace: /\[[a-z][\s\S]*?\]/i, + boolean: /\$(true|false)\b/i, + variable: /\$\w+\b/i, + // Cmdlets and aliases. Aliases should come last, otherwise "write" gets preferred over "write-host" for example + // Get-Command | ?{ $_.ModuleName -match "Microsoft.PowerShell.(Util|Core|Management)" } + // Get-Alias | ?{ $_.ReferencedCommand.Module.Name -match "Microsoft.PowerShell.(Util|Core|Management)" } + function: [ + /\b(Add-(Computer|Content|History|Member|PSSnapin|Type)|Checkpoint-Computer|Clear-(Content|EventLog|History|Item|ItemProperty|Variable)|Compare-Object|Complete-Transaction|Connect-PSSession|ConvertFrom-(Csv|Json|StringData)|Convert-Path|ConvertTo-(Csv|Html|Json|Xml)|Copy-(Item|ItemProperty)|Debug-Process|Disable-(ComputerRestore|PSBreakpoint|PSRemoting|PSSessionConfiguration)|Disconnect-PSSession|Enable-(ComputerRestore|PSBreakpoint|PSRemoting|PSSessionConfiguration)|Enter-PSSession|Exit-PSSession|Export-(Alias|Clixml|Console|Csv|FormatData|ModuleMember|PSSession)|ForEach-Object|Format-(Custom|List|Table|Wide)|Get-(Alias|ChildItem|Command|ComputerRestorePoint|Content|ControlPanelItem|Culture|Date|Event|EventLog|EventSubscriber|FormatData|Help|History|Host|HotFix|Item|ItemProperty|Job|Location|Member|Module|Process|PSBreakpoint|PSCallStack|PSDrive|PSProvider|PSSession|PSSessionConfiguration|PSSnapin|Random|Service|TraceSource|Transaction|TypeData|UICulture|Unique|Variable|WmiObject)|Group-Object|Import-(Alias|Clixml|Csv|LocalizedData|Module|PSSession)|Invoke-(Command|Expression|History|Item|RestMethod|WebRequest|WmiMethod)|Join-Path|Limit-EventLog|Measure-(Command|Object)|Move-(Item|ItemProperty)|New-(Alias|Event|EventLog|Item|ItemProperty|Module|ModuleManifest|Object|PSDrive|PSSession|PSSessionConfigurationFile|PSSessionOption|PSTransportOption|Service|TimeSpan|Variable|WebServiceProxy)|Out-(Default|File|GridView|Host|Null|Printer|String)|Pop-Location|Push-Location|Read-Host|Receive-(Job|PSSession)|Register-(EngineEvent|ObjectEvent|PSSessionConfiguration|WmiEvent)|Remove-(Computer|Event|EventLog|Item|ItemProperty|Job|Module|PSBreakpoint|PSDrive|PSSession|PSSnapin|TypeData|Variable|WmiObject)|Rename-(Computer|Item|ItemProperty)|Reset-ComputerMachinePassword|Resolve-Path|Restart-(Computer|Service)|Restore-Computer|Resume-(Job|Service)|Save-Help|Select-(Object|String|Xml)|Send-MailMessage|Set-(Alias|Content|Date|Item|ItemProperty|Location|PSBreakpoint|PSDebug|PSSessionConfiguration|Service|StrictMode|TraceSource|Variable|WmiInstance)|Show-(Command|ControlPanelItem|EventLog)|Sort-Object|Split-Path|Start-(Job|Process|Service|Sleep|Transaction)|Stop-(Computer|Job|Process|Service)|Suspend-(Job|Service)|Tee-Object|Test-(ComputerSecureChannel|Connection|ModuleManifest|Path|PSSessionConfigurationFile)|Trace-Command|Unblock-File|Undo-Transaction|Unregister-(Event|PSSessionConfiguration)|Update-(FormatData|Help|List|TypeData)|Use-Transaction|Wait-(Event|Job|Process)|Where-Object|Write-(Debug|Error|EventLog|Host|Output|Progress|Verbose|Warning))\b/i, + /\b(ac|cat|chdir|clc|cli|clp|clv|compare|copy|cp|cpi|cpp|cvpa|dbp|del|diff|dir|ebp|echo|epal|epcsv|epsn|erase|fc|fl|ft|fw|gal|gbp|gc|gci|gcs|gdr|gi|gl|gm|gp|gps|group|gsv|gu|gv|gwmi|iex|ii|ipal|ipcsv|ipsn|irm|iwmi|iwr|kill|lp|ls|measure|mi|mount|move|mp|mv|nal|ndr|ni|nv|ogv|popd|ps|pushd|pwd|rbp|rd|rdr|ren|ri|rm|rmdir|rni|rnp|rp|rv|rvpa|rwmi|sal|saps|sasv|sbp|sc|select|set|shcm|si|sl|sleep|sls|sort|sp|spps|spsv|start|sv|swmi|tee|trcm|type|write)\b/i + ], + // per http://technet.microsoft.com/en-us/library/hh847744.aspx + keyword: /\b(Begin|Break|Catch|Class|Continue|Data|Define|Do|DynamicParam|Else|ElseIf|End|Exit|Filter|Finally|For|ForEach|From|Function|If|InlineScript|Parallel|Param|Process|Return|Sequence|Switch|Throw|Trap|Try|Until|Using|Var|While|Workflow)\b/i, + operator: { + pattern: /(\W?)(!|-(eq|ne|gt|ge|lt|le|sh[lr]|not|b?(and|x?or)|(Not)?(Like|Match|Contains|In)|Replace|Join|is(Not)?|as)\b|-[-=]?|\+[+=]?|[*\/%]=?)/i, + lookbehind: true + }, + punctuation: /[|{}[\];(),.]/ +} + +// Variable interpolation inside strings, and nested expressions +Prism.languages.powershell.string[0].inside.boolean = + Prism.languages.powershell.boolean +Prism.languages.powershell.string[0].inside.variable = + Prism.languages.powershell.variable +Prism.languages.powershell.string[0].inside.function.inside = Prism.util.clone( + Prism.languages.powershell +) + +/*------------------------------------------------------------*/ + +Prism.languages.python = { + 'triple-quoted-string': { + pattern: /"""[\s\S]+?"""|'''[\s\S]+?'''/, + alias: 'string' + }, + comment: { + pattern: /(^|[^\\])#.*/, + lookbehind: true + }, + string: { + pattern: /("|')(?:\\\\|\\?[^\\\r\n])*?\1/, + greedy: true + }, + function: { + pattern: /((?:^|\s)def[ \t]+)[a-zA-Z_][a-zA-Z0-9_]*(?=\()/g, + lookbehind: true + }, + 'class-name': { + pattern: /(\bclass\s+)[a-z0-9_]+/i, + lookbehind: true + }, + keyword: /\b(?:as|assert|async|await|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|pass|print|raise|return|try|while|with|yield)\b/, + boolean: /\b(?:True|False)\b/, + number: /\b-?(?:0[bo])?(?:(?:\d|0x[\da-f])[\da-f]*\.?\d*|\.\d+)(?:e[+-]?\d+)?j?\b/i, + operator: /[-+%=]=?|!=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]|\b(?:or|and|not)\b/, + punctuation: /[{}[\];(),.:]/ +} + +Prism.languages.r = { + comment: /#.*/, + string: { + pattern: /(['"])(?:\\?.)*?\1/, + greedy: true + }, + 'percent-operator': { + // Includes user-defined operators + // and %%, %*%, %/%, %in%, %o%, %x% + pattern: /%[^%\s]*%/, + alias: 'operator' + }, + boolean: /\b(?:TRUE|FALSE)\b/, + ellipsis: /\.\.(?:\.|\d+)/, + number: [ + /\b(?:NaN|Inf)\b/, + /\b(?:0x[\dA-Fa-f]+(?:\.\d*)?|\d*\.?\d+)(?:[EePp][+-]?\d+)?[iL]?\b/ + ], + keyword: /\b(?:if|else|repeat|while|function|for|in|next|break|NULL|NA|NA_integer_|NA_real_|NA_complex_|NA_character_)\b/, + operator: /->?>?|<(?:=|=!]=?|::?|&&?|\|\|?|[+*\/^$@~]/, + punctuation: /[(){}\[\],;]/ +} + +/*------------------------------------------------------------*/ + +Prism.languages.rust = { + comment: [ + { + pattern: /(^|[^\\])\/\*[\s\S]*?\*\//, + lookbehind: true + }, + { + pattern: /(^|[^\\:])\/\/.*/, + lookbehind: true + } + ], + string: [ + { + pattern: /b?r(#*)"(?:\\?.)*?"\1/, + greedy: true + }, + { + pattern: /b?("|')(?:\\?.)*?\1/, + greedy: true + } + ], + keyword: /\b(?:abstract|alignof|as|be|box|break|const|continue|crate|do|else|enum|extern|false|final|fn|for|if|impl|in|let|loop|match|mod|move|mut|offsetof|once|override|priv|pub|pure|ref|return|sizeof|static|self|struct|super|true|trait|type|typeof|unsafe|unsized|use|virtual|where|while|yield)\b/, + + attribute: { + pattern: /#!?\[.+?\]/, + greedy: true, + alias: 'attr-name' + }, + + function: [ + /[a-z0-9_]+(?=\s*\()/i, + // Macros can use parens or brackets + /[a-z0-9_]+!(?=\s*\(|\[)/i + ], + 'macro-rules': { + pattern: /[a-z0-9_]+!/i, + alias: 'function' + }, + + // Hex, oct, bin, dec numbers with visual separators and type suffix + number: /\b-?(?:0x[\dA-Fa-f](?:_?[\dA-Fa-f])*|0o[0-7](?:_?[0-7])*|0b[01](?:_?[01])*|(\d(_?\d)*)?\.?\d(_?\d)*([Ee][+-]?\d+)?)(?:_?(?:[iu](?:8|16|32|64)?|f32|f64))?\b/, + + // Closure params should not be confused with bitwise OR | + 'closure-params': { + pattern: /\|[^|]*\|(?=\s*[{-])/, + inside: { + punctuation: /[\|:,]/, + operator: /[&*]/ + } + }, + punctuation: /[{}[\];(),:]|\.+|->/, + operator: /[-+*\/%!^=]=?|@|&[&=]?|\|[|=]?|<>?=?/ +} + +/*------------------------------------------------------------*/ + +;(function(Prism) { + Prism.languages.sass = Prism.languages.extend('css', { + // Sass comments don't need to be closed, only indented + comment: { + pattern: /^([ \t]*)\/[\/*].*(?:(?:\r?\n|\r)\1[ \t]+.+)*/m, + lookbehind: true + } + }) + + Prism.languages.insertBefore('sass', 'atrule', { + // We want to consume the whole line + 'atrule-line': { + // Includes support for = and + shortcuts + pattern: /^(?:[ \t]*)[@+=].+/m, + inside: { + atrule: /(?:@[\w-]+|[+=])/m + } + } + }) + delete Prism.languages.sass.atrule + + var variable = /((\$[-_\w]+)|(#\{\$[-_\w]+\}))/i + var operator = [ + /[+*\/%]|[=!]=|<=?|>=?|\b(?:and|or|not)\b/, + { + pattern: /(\s+)-(?=\s)/, + lookbehind: true + } + ] + + Prism.languages.insertBefore('sass', 'property', { + // We want to consume the whole line + 'variable-line': { + pattern: /^[ \t]*\$.+/m, + inside: { + punctuation: /:/, + variable: variable, + operator: operator + } + }, + // We want to consume the whole line + 'property-line': { + pattern: /^[ \t]*(?:[^:\s]+ *:.*|:[^:\s]+.*)/m, + inside: { + property: [ + /[^:\s]+(?=\s*:)/, + { + pattern: /(:)[^:\s]+/, + lookbehind: true + } + ], + punctuation: /:/, + variable: variable, + operator: operator, + important: Prism.languages.sass.important + } + } + }) + delete Prism.languages.sass.property + delete Prism.languages.sass.important + + // Now that whole lines for other patterns are consumed, + // what's left should be selectors + delete Prism.languages.sass.selector + Prism.languages.insertBefore('sass', 'punctuation', { + selector: { + pattern: /([ \t]*)\S(?:,?[^,\r\n]+)*(?:,(?:\r?\n|\r)\1[ \t]+\S(?:,?[^,\r\n]+)*)*/, + lookbehind: true + } + }) +})(Prism) +Prism.languages.scss = Prism.languages.extend('css', { + comment: { + pattern: /(^|[^\\])(?:\/\*[\s\S]*?\*\/|\/\/.*)/, + lookbehind: true + }, + atrule: { + pattern: /@[\w-]+(?:\([^()]+\)|[^(])*?(?=\s+[{;])/, + inside: { + rule: /@[\w-]+/ + // See rest below + } + }, + // url, compassified + url: /(?:[-a-z]+-)*url(?=\()/i, + // CSS selector regex is not appropriate for Sass + // since there can be lot more things (var, @ directive, nesting..) + // a selector must start at the end of a property or after a brace (end of other rules or nesting) + // it can contain some characters that aren't used for defining rules or end of selector, & (parent selector), or interpolated variable + // the end of a selector is found when there is no rules in it ( {} or {\s}) or if there is a property (because an interpolated var + // can "pass" as a selector- e.g: proper#{$erty}) + // this one was hard to do, so please be careful if you edit this one :) + selector: { + // Initial look-ahead is used to prevent matching of blank selectors + pattern: /(?=\S)[^@;\{\}\(\)]?([^@;\{\}\(\)]|&|#\{\$[-_\w]+\})+(?=\s*\{(\}|\s|[^\}]+(:|\{)[^\}]+))/m, + inside: { + parent: { + pattern: /&/, + alias: 'important' + }, + placeholder: /%[-_\w]+/, + variable: /\$[-_\w]+|#\{\$[-_\w]+\}/ + } + } +}) + +Prism.languages.insertBefore('scss', 'atrule', { + keyword: [ + /@(?:if|else(?: if)?|for|each|while|import|extend|debug|warn|mixin|include|function|return|content)/i, + { + pattern: /( +)(?:from|through)(?= )/, + lookbehind: true + } + ] +}) + +Prism.languages.scss.property = { + pattern: /(?:[\w-]|\$[-_\w]+|#\{\$[-_\w]+\})+(?=\s*:)/i, + inside: { + variable: /\$[-_\w]+|#\{\$[-_\w]+\}/ + } +} + +Prism.languages.insertBefore('scss', 'important', { + // var and interpolated vars + variable: /\$[-_\w]+|#\{\$[-_\w]+\}/ +}) + +Prism.languages.insertBefore('scss', 'function', { + placeholder: { + pattern: /%[-_\w]+/, + alias: 'selector' + }, + statement: { + pattern: /\B!(?:default|optional)\b/i, + alias: 'keyword' + }, + boolean: /\b(?:true|false)\b/, + null: /\bnull\b/, + operator: { + pattern: /(\s)(?:[-+*\/%]|[=!]=|<=?|>=?|and|or|not)(?=\s)/, + lookbehind: true + } +}) + +Prism.languages.scss['atrule'].inside.rest = Prism.util.clone( + Prism.languages.scss +) + +/*-----------------------------smarty-------------------------*/ + +;(function(Prism) { + var smarty_pattern = /\{\*[\s\S]+?\*\}|\{[\s\S]+?\}/g + var smarty_litteral_start = '{literal}' + var smarty_litteral_end = '{/literal}' + var smarty_litteral_mode = false + + Prism.languages.smarty = Prism.languages.extend('markup', { + smarty: { + pattern: smarty_pattern, + inside: { + delimiter: { + pattern: /^\{|\}$/i, + alias: 'punctuation' + }, + string: /(["'])(?:\\?.)*?\1/, + number: /\b-?(?:0x[\dA-Fa-f]+|\d*\.?\d+(?:[Ee][-+]?\d+)?)\b/, + variable: [ + /\$(?!\d)\w+/, + /#(?!\d)\w+#/, + { + pattern: /(\.|->)(?!\d)\w+/, + lookbehind: true + }, + { + pattern: /(\[)(?!\d)\w+(?=\])/, + lookbehind: true + } + ], + function: [ + { + pattern: /(\|\s*)@?(?!\d)\w+/, + lookbehind: true + }, + /^\/?(?!\d)\w+/, + /(?!\d)\w+(?=\()/ + ], + 'attr-name': { + // Value is made optional because it may have already been tokenized + pattern: /\w+\s*=\s*(?:(?!\d)\w+)?/, + inside: { + variable: { + pattern: /(=\s*)(?!\d)\w+/, + lookbehind: true + }, + operator: /=/ + } + }, + punctuation: [/[\[\]().,:`]|\->/], + operator: [ + /[+\-*\/%]|==?=?|[!<>]=?|&&|\|\|?/, + /\bis\s+(?:not\s+)?(?:div|even|odd)(?:\s+by)?\b/, + /\b(?:eq|neq?|gt|lt|gt?e|lt?e|not|mod|or|and)\b/ + ], + keyword: /\b(?:false|off|on|no|true|yes)\b/ + } + } + }) + + // Comments are inserted at top so that they can + // surround markup + Prism.languages.insertBefore('smarty', 'tag', { + 'smarty-comment': { + pattern: /\{\*[\s\S]*?\*\}/, + alias: ['smarty', 'comment'] + } + }) + + // Tokenize all inline Smarty expressions + Prism.hooks.add('before-highlight', function(env) { + if (env.language !== 'smarty') { + return + } + + env.tokenStack = [] + + env.backupCode = env.code + env.code = env.code.replace(smarty_pattern, function(match) { + // Smarty tags inside {literal} block are ignored + if (match === smarty_litteral_end) { + smarty_litteral_mode = false + } + + if (!smarty_litteral_mode) { + if (match === smarty_litteral_start) { + smarty_litteral_mode = true + } + + var i = env.tokenStack.length + // Check for existing strings + while (env.backupCode.indexOf('___SMARTY' + i + '___') !== -1) ++i + + // Create a sparse array + env.tokenStack[i] = match + + return '___SMARTY' + i + '___' + } + return match + }) + }) + + // Restore env.code for other plugins (e.g. line-numbers) + Prism.hooks.add('before-insert', function(env) { + if (env.language === 'smarty') { + env.code = env.backupCode + delete env.backupCode + } + }) + + // Re-insert the tokens after highlighting + // and highlight them with defined grammar + Prism.hooks.add('after-highlight', function(env) { + if (env.language !== 'smarty') { + return + } + + for (var i = 0, keys = Object.keys(env.tokenStack); i < keys.length; ++i) { + var k = keys[i] + var t = env.tokenStack[k] + + // The replace prevents $$, $&, $`, $', $n, $nn from being interpreted as special patterns + env.highlightedCode = env.highlightedCode.replace( + '___SMARTY' + k + '___', + Prism.highlight(t, env.grammar, 'smarty').replace(/\$/g, '$$$$') + ) + } + + env.element.innerHTML = env.highlightedCode + }) +})(Prism) + +/*-----------------------------------------------------------*/ + +Prism.languages.sql = { + comment: { + pattern: /(^|[^\\])(?:\/\*[\s\S]*?\*\/|(?:--|\/\/|#).*)/, + lookbehind: true + }, + string: { + pattern: /(^|[^@\\])("|')(?:\\?[\s\S])*?\2/, + greedy: true, + lookbehind: true + }, + variable: /@[\w.$]+|@("|'|`)(?:\\?[\s\S])+?\1/, + function: /\b(?:COUNT|SUM|AVG|MIN|MAX|FIRST|LAST|UCASE|LCASE|MID|LEN|ROUND|NOW|FORMAT)(?=\s*\()/i, // Should we highlight user defined functions too? + keyword: /\b(?:ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR VARYING|CHARACTER (?:SET|VARYING)|CHARSET|CHECK|CHECKPOINT|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMN|COLUMNS|COMMENT|COMMIT|COMMITTED|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS|CONTAINSTABLE|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|DATA(?:BASES?)?|DATE(?:TIME)?|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITER(?:S)?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE(?: PRECISION)?|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE KEY|ELSE|ENABLE|ENCLOSED BY|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPE(?:D BY)?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|IDENTITY(?:_INSERT|COL)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTO|INVOKER|ISOLATION LEVEL|JOIN|KEYS?|KILL|LANGUAGE SQL|LAST|LEFT|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MODIFIES SQL DATA|MODIFY|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL(?: CHAR VARYING| CHARACTER(?: VARYING)?| VARCHAR)?|NATURAL|NCHAR(?: VARCHAR)?|NEXT|NO(?: SQL|CHECK|CYCLE)?|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READ(?:S SQL DATA|TEXT)?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEATABLE|REPLICATION|REQUIRE|RESTORE|RESTRICT|RETURNS?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE MODE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|START(?:ING BY)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED BY|TEXT(?:SIZE)?|THEN|TIMESTAMP|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNPIVOT|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?)\b/i, + boolean: /\b(?:TRUE|FALSE|NULL)\b/i, + number: /\b-?(?:0x)?\d*\.?[\da-f]+\b/, + operator: /[-+*\/=%^~]|&&?|\|?\||!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|IN|LIKE|NOT|OR|IS|DIV|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/i, + punctuation: /[;[\]()`,.]/ +} + +/*-----------------------------------------------------------*/ + +Prism.languages.swift = Prism.languages.extend('clike', { + string: { + pattern: /("|')(\\(?:\((?:[^()]|\([^)]+\))+\)|\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/, + greedy: true, + inside: { + interpolation: { + pattern: /\\\((?:[^()]|\([^)]+\))+\)/, + inside: { + delimiter: { + pattern: /^\\\(|\)$/, + alias: 'variable' + } + // See rest below + } + } + } + }, + keyword: /\b(as|associativity|break|case|catch|class|continue|convenience|default|defer|deinit|didSet|do|dynamic(?:Type)?|else|enum|extension|fallthrough|final|for|func|get|guard|if|import|in|infix|init|inout|internal|is|lazy|left|let|mutating|new|none|nonmutating|operator|optional|override|postfix|precedence|prefix|private|Protocol|public|repeat|required|rethrows|return|right|safe|self|Self|set|static|struct|subscript|super|switch|throws?|try|Type|typealias|unowned|unsafe|var|weak|where|while|willSet|__(?:COLUMN__|FILE__|FUNCTION__|LINE__))\b/, + number: /\b([\d_]+(\.[\de_]+)?|0x[a-f0-9_]+(\.[a-f0-9p_]+)?|0b[01_]+|0o[0-7_]+)\b/i, + constant: /\b(nil|[A-Z_]{2,}|k[A-Z][A-Za-z_]+)\b/, + atrule: /@\b(IB(?:Outlet|Designable|Action|Inspectable)|class_protocol|exported|noreturn|NS(?:Copying|Managed)|objc|UIApplicationMain|auto_closure)\b/, + builtin: /\b([A-Z]\S+|abs|advance|alignof(?:Value)?|assert|contains|count(?:Elements)?|debugPrint(?:ln)?|distance|drop(?:First|Last)|dump|enumerate|equal|filter|find|first|getVaList|indices|isEmpty|join|last|lexicographicalCompare|map|max(?:Element)?|min(?:Element)?|numericCast|overlaps|partition|print(?:ln)?|reduce|reflect|reverse|sizeof(?:Value)?|sort(?:ed)?|split|startsWith|stride(?:of(?:Value)?)?|suffix|swap|toDebugString|toString|transcode|underestimateCount|unsafeBitCast|with(?:ExtendedLifetime|Unsafe(?:MutablePointers?|Pointers?)|VaList))\b/ +}) +Prism.languages.swift['string'].inside[ + 'interpolation' +].inside.rest = Prism.util.clone(Prism.languages.swift) +Prism.languages.typescript = Prism.languages.extend('javascript', { + // From JavaScript Prism keyword list and TypeScript language spec: https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#221-reserved-words + keyword: /\b(as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|var|void|while|with|yield|false|true|module|declare|constructor|string|Function|any|number|boolean|Array|enum|symbol|namespace|abstract|require|type)\b/ +}) + +Prism.languages.ts = Prism.languages.typescript +Prism.languages.vim = { + string: /"(?:[^"\\\r\n]|\\.)*"|'(?:[^'\r\n]|'')*'/, + comment: /".*/, + function: /\w+(?=\()/, + keyword: /\b(?:ab|abbreviate|abc|abclear|abo|aboveleft|al|all|arga|argadd|argd|argdelete|argdo|arge|argedit|argg|argglobal|argl|arglocal|ar|args|argu|argument|as|ascii|bad|badd|ba|ball|bd|bdelete|be|bel|belowright|bf|bfirst|bl|blast|bm|bmodified|bn|bnext|bN|bNext|bo|botright|bp|bprevious|brea|break|breaka|breakadd|breakd|breakdel|breakl|breaklist|br|brewind|bro|browse|bufdo|b|buffer|buffers|bun|bunload|bw|bwipeout|ca|cabbrev|cabc|cabclear|caddb|caddbuffer|cad|caddexpr|caddf|caddfile|cal|call|cat|catch|cb|cbuffer|cc|ccl|cclose|cd|ce|center|cex|cexpr|cf|cfile|cfir|cfirst|cgetb|cgetbuffer|cgete|cgetexpr|cg|cgetfile|c|change|changes|chd|chdir|che|checkpath|checkt|checktime|cla|clast|cl|clist|clo|close|cmapc|cmapclear|cnew|cnewer|cn|cnext|cN|cNext|cnf|cnfile|cNfcNfile|cnorea|cnoreabbrev|col|colder|colo|colorscheme|comc|comclear|comp|compiler|conf|confirm|con|continue|cope|copen|co|copy|cpf|cpfile|cp|cprevious|cq|cquit|cr|crewind|cuna|cunabbrev|cu|cunmap|cw|cwindow|debugg|debuggreedy|delc|delcommand|d|delete|delf|delfunction|delm|delmarks|diffg|diffget|diffoff|diffpatch|diffpu|diffput|diffsplit|diffthis|diffu|diffupdate|dig|digraphs|di|display|dj|djump|dl|dlist|dr|drop|ds|dsearch|dsp|dsplit|earlier|echoe|echoerr|echom|echomsg|echon|e|edit|el|else|elsei|elseif|em|emenu|endfo|endfor|endf|endfunction|endfun|en|endif|endt|endtry|endw|endwhile|ene|enew|ex|exi|exit|exu|exusage|f|file|files|filetype|fina|finally|fin|find|fini|finish|fir|first|fix|fixdel|fo|fold|foldc|foldclose|folddoc|folddoclosed|foldd|folddoopen|foldo|foldopen|for|fu|fun|function|go|goto|gr|grep|grepa|grepadd|ha|hardcopy|h|help|helpf|helpfind|helpg|helpgrep|helpt|helptags|hid|hide|his|history|ia|iabbrev|iabc|iabclear|if|ij|ijump|il|ilist|imapc|imapclear|in|inorea|inoreabbrev|isearch|isp|isplit|iuna|iunabbrev|iu|iunmap|j|join|ju|jumps|k|keepalt|keepj|keepjumps|kee|keepmarks|laddb|laddbuffer|lad|laddexpr|laddf|laddfile|lan|language|la|last|later|lb|lbuffer|lc|lcd|lch|lchdir|lcl|lclose|let|left|lefta|leftabove|lex|lexpr|lf|lfile|lfir|lfirst|lgetb|lgetbuffer|lgete|lgetexpr|lg|lgetfile|lgr|lgrep|lgrepa|lgrepadd|lh|lhelpgrep|l|list|ll|lla|llast|lli|llist|lmak|lmake|lm|lmap|lmapc|lmapclear|lnew|lnewer|lne|lnext|lN|lNext|lnf|lnfile|lNf|lNfile|ln|lnoremap|lo|loadview|loc|lockmarks|lockv|lockvar|lol|lolder|lop|lopen|lpf|lpfile|lp|lprevious|lr|lrewind|ls|lt|ltag|lu|lunmap|lv|lvimgrep|lvimgrepa|lvimgrepadd|lw|lwindow|mak|make|ma|mark|marks|mat|match|menut|menutranslate|mk|mkexrc|mks|mksession|mksp|mkspell|mkvie|mkview|mkv|mkvimrc|mod|mode|m|move|mzf|mzfile|mz|mzscheme|nbkey|new|n|next|N|Next|nmapc|nmapclear|noh|nohlsearch|norea|noreabbrev|nu|number|nun|nunmap|omapc|omapclear|on|only|o|open|opt|options|ou|ounmap|pc|pclose|ped|pedit|pe|perl|perld|perldo|po|pop|popu|popu|popup|pp|ppop|pre|preserve|prev|previous|p|print|P|Print|profd|profdel|prof|profile|promptf|promptfind|promptr|promptrepl|ps|psearch|pta|ptag|ptf|ptfirst|ptj|ptjump|ptl|ptlast|ptn|ptnext|ptN|ptNext|ptp|ptprevious|ptr|ptrewind|pts|ptselect|pu|put|pw|pwd|pyf|pyfile|py|python|qa|qall|q|quit|quita|quitall|r|read|rec|recover|redi|redir|red|redo|redr|redraw|redraws|redrawstatus|reg|registers|res|resize|ret|retab|retu|return|rew|rewind|ri|right|rightb|rightbelow|rub|ruby|rubyd|rubydo|rubyf|rubyfile|ru|runtime|rv|rviminfo|sal|sall|san|sandbox|sa|sargument|sav|saveas|sba|sball|sbf|sbfirst|sbl|sblast|sbm|sbmodified|sbn|sbnext|sbN|sbNext|sbp|sbprevious|sbr|sbrewind|sb|sbuffer|scripte|scriptencoding|scrip|scriptnames|se|set|setf|setfiletype|setg|setglobal|setl|setlocal|sf|sfind|sfir|sfirst|sh|shell|sign|sil|silent|sim|simalt|sla|slast|sl|sleep|sm|smagic|sm|smap|smapc|smapclear|sme|smenu|sn|snext|sN|sNext|sni|sniff|sno|snomagic|snor|snoremap|snoreme|snoremenu|sor|sort|so|source|spelld|spelldump|spe|spellgood|spelli|spellinfo|spellr|spellrepall|spellu|spellundo|spellw|spellwrong|sp|split|spr|sprevious|sre|srewind|sta|stag|startg|startgreplace|star|startinsert|startr|startreplace|stj|stjump|st|stop|stopi|stopinsert|sts|stselect|sun|sunhide|sunm|sunmap|sus|suspend|sv|sview|syncbind|t|tab|tabc|tabclose|tabd|tabdo|tabe|tabedit|tabf|tabfind|tabfir|tabfirst|tabl|tablast|tabm|tabmove|tabnew|tabn|tabnext|tabN|tabNext|tabo|tabonly|tabp|tabprevious|tabr|tabrewind|tabs|ta|tag|tags|tc|tcl|tcld|tcldo|tclf|tclfile|te|tearoff|tf|tfirst|th|throw|tj|tjump|tl|tlast|tm|tm|tmenu|tn|tnext|tN|tNext|to|topleft|tp|tprevious|tr|trewind|try|ts|tselect|tu|tu|tunmenu|una|unabbreviate|u|undo|undoj|undojoin|undol|undolist|unh|unhide|unlet|unlo|unlockvar|unm|unmap|up|update|verb|verbose|ve|version|vert|vertical|vie|view|vim|vimgrep|vimgrepa|vimgrepadd|vi|visual|viu|viusage|vmapc|vmapclear|vne|vnew|vs|vsplit|vu|vunmap|wa|wall|wh|while|winc|wincmd|windo|winp|winpos|win|winsize|wn|wnext|wN|wNext|wp|wprevious|wq|wqa|wqall|w|write|ws|wsverb|wv|wviminfo|X|xa|xall|x|xit|xm|xmap|xmapc|xmapclear|xme|xmenu|XMLent|XMLns|xn|xnoremap|xnoreme|xnoremenu|xu|xunmap|y|yank)\b/, + builtin: /\b(?:autocmd|acd|ai|akm|aleph|allowrevins|altkeymap|ambiwidth|ambw|anti|antialias|arab|arabic|arabicshape|ari|arshape|autochdir|autoindent|autoread|autowrite|autowriteall|aw|awa|background|backspace|backup|backupcopy|backupdir|backupext|backupskip|balloondelay|ballooneval|balloonexpr|bdir|bdlay|beval|bex|bexpr|bg|bh|bin|binary|biosk|bioskey|bk|bkc|bomb|breakat|brk|browsedir|bs|bsdir|bsk|bt|bufhidden|buflisted|buftype|casemap|ccv|cdpath|cedit|cfu|ch|charconvert|ci|cin|cindent|cink|cinkeys|cino|cinoptions|cinw|cinwords|clipboard|cmdheight|cmdwinheight|cmp|cms|columns|com|comments|commentstring|compatible|complete|completefunc|completeopt|consk|conskey|copyindent|cot|cpo|cpoptions|cpt|cscopepathcomp|cscopeprg|cscopequickfix|cscopetag|cscopetagorder|cscopeverbose|cspc|csprg|csqf|cst|csto|csverb|cuc|cul|cursorcolumn|cursorline|cwh|debug|deco|def|define|delcombine|dex|dg|dict|dictionary|diff|diffexpr|diffopt|digraph|dip|dir|directory|dy|ea|ead|eadirection|eb|ed|edcompatible|ef|efm|ei|ek|enc|encoding|endofline|eol|ep|equalalways|equalprg|errorbells|errorfile|errorformat|esckeys|et|eventignore|expandtab|exrc|fcl|fcs|fdc|fde|fdi|fdl|fdls|fdm|fdn|fdo|fdt|fen|fenc|fencs|fex|ff|ffs|fileencoding|fileencodings|fileformat|fileformats|fillchars|fk|fkmap|flp|fml|fmr|foldcolumn|foldenable|foldexpr|foldignore|foldlevel|foldlevelstart|foldmarker|foldmethod|foldminlines|foldnestmax|foldtext|formatexpr|formatlistpat|formatoptions|formatprg|fp|fs|fsync|ft|gcr|gd|gdefault|gfm|gfn|gfs|gfw|ghr|gp|grepformat|grepprg|gtl|gtt|guicursor|guifont|guifontset|guifontwide|guiheadroom|guioptions|guipty|guitablabel|guitabtooltip|helpfile|helpheight|helplang|hf|hh|hi|hidden|highlight|hk|hkmap|hkmapp|hkp|hl|hlg|hls|hlsearch|ic|icon|iconstring|ignorecase|im|imactivatekey|imak|imc|imcmdline|imd|imdisable|imi|iminsert|ims|imsearch|inc|include|includeexpr|incsearch|inde|indentexpr|indentkeys|indk|inex|inf|infercase|insertmode|isf|isfname|isi|isident|isk|iskeyword|isprint|joinspaces|js|key|keymap|keymodel|keywordprg|km|kmp|kp|langmap|langmenu|laststatus|lazyredraw|lbr|lcs|linebreak|lines|linespace|lisp|lispwords|listchars|loadplugins|lpl|lsp|lz|macatsui|magic|makeef|makeprg|matchpairs|matchtime|maxcombine|maxfuncdepth|maxmapdepth|maxmem|maxmempattern|maxmemtot|mco|mef|menuitems|mfd|mh|mis|mkspellmem|ml|mls|mm|mmd|mmp|mmt|modeline|modelines|modifiable|modified|more|mouse|mousef|mousefocus|mousehide|mousem|mousemodel|mouses|mouseshape|mouset|mousetime|mp|mps|msm|mzq|mzquantum|nf|nrformats|numberwidth|nuw|odev|oft|ofu|omnifunc|opendevice|operatorfunc|opfunc|osfiletype|pa|para|paragraphs|paste|pastetoggle|patchexpr|patchmode|path|pdev|penc|pex|pexpr|pfn|ph|pheader|pi|pm|pmbcs|pmbfn|popt|preserveindent|previewheight|previewwindow|printdevice|printencoding|printexpr|printfont|printheader|printmbcharset|printmbfont|printoptions|prompt|pt|pumheight|pvh|pvw|qe|quoteescape|readonly|remap|report|restorescreen|revins|rightleft|rightleftcmd|rl|rlc|ro|rs|rtp|ruf|ruler|rulerformat|runtimepath|sbo|sc|scb|scr|scroll|scrollbind|scrolljump|scrolloff|scrollopt|scs|sect|sections|secure|sel|selection|selectmode|sessionoptions|sft|shcf|shellcmdflag|shellpipe|shellquote|shellredir|shellslash|shelltemp|shelltype|shellxquote|shiftround|shiftwidth|shm|shortmess|shortname|showbreak|showcmd|showfulltag|showmatch|showmode|showtabline|shq|si|sidescroll|sidescrolloff|siso|sj|slm|smartcase|smartindent|smarttab|smc|smd|softtabstop|sol|spc|spell|spellcapcheck|spellfile|spelllang|spellsuggest|spf|spl|splitbelow|splitright|sps|sr|srr|ss|ssl|ssop|stal|startofline|statusline|stl|stmp|su|sua|suffixes|suffixesadd|sw|swapfile|swapsync|swb|swf|switchbuf|sws|sxq|syn|synmaxcol|syntax|tabline|tabpagemax|tabstop|tagbsearch|taglength|tagrelative|tagstack|tal|tb|tbi|tbidi|tbis|tbs|tenc|term|termbidi|termencoding|terse|textauto|textmode|textwidth|tgst|thesaurus|tildeop|timeout|timeoutlen|title|titlelen|titleold|titlestring|toolbar|toolbariconsize|top|tpm|tsl|tsr|ttimeout|ttimeoutlen|ttm|tty|ttybuiltin|ttyfast|ttym|ttymouse|ttyscroll|ttytype|tw|tx|uc|ul|undolevels|updatecount|updatetime|ut|vb|vbs|vdir|verbosefile|vfile|viewdir|viewoptions|viminfo|virtualedit|visualbell|vop|wak|warn|wb|wc|wcm|wd|weirdinvert|wfh|wfw|whichwrap|wi|wig|wildchar|wildcharm|wildignore|wildmenu|wildmode|wildoptions|wim|winaltkeys|window|winfixheight|winfixwidth|winheight|winminheight|winminwidth|winwidth|wiv|wiw|wm|wmh|wmnu|wmw|wop|wrap|wrapmargin|wrapscan|writeany|writebackup|writedelay|ww|noacd|noai|noakm|noallowrevins|noaltkeymap|noanti|noantialias|noar|noarab|noarabic|noarabicshape|noari|noarshape|noautochdir|noautoindent|noautoread|noautowrite|noautowriteall|noaw|noawa|nobackup|noballooneval|nobeval|nobin|nobinary|nobiosk|nobioskey|nobk|nobl|nobomb|nobuflisted|nocf|noci|nocin|nocindent|nocompatible|noconfirm|noconsk|noconskey|nocopyindent|nocp|nocscopetag|nocscopeverbose|nocst|nocsverb|nocuc|nocul|nocursorcolumn|nocursorline|nodeco|nodelcombine|nodg|nodiff|nodigraph|nodisable|noea|noeb|noed|noedcompatible|noek|noendofline|noeol|noequalalways|noerrorbells|noesckeys|noet|noex|noexpandtab|noexrc|nofen|nofk|nofkmap|nofoldenable|nogd|nogdefault|noguipty|nohid|nohidden|nohk|nohkmap|nohkmapp|nohkp|nohls|noic|noicon|noignorecase|noim|noimc|noimcmdline|noimd|noincsearch|noinf|noinfercase|noinsertmode|nois|nojoinspaces|nojs|nolazyredraw|nolbr|nolinebreak|nolisp|nolist|noloadplugins|nolpl|nolz|noma|nomacatsui|nomagic|nomh|noml|nomod|nomodeline|nomodifiable|nomodified|nomore|nomousef|nomousefocus|nomousehide|nonu|nonumber|noodev|noopendevice|nopaste|nopi|nopreserveindent|nopreviewwindow|noprompt|nopvw|noreadonly|noremap|norestorescreen|norevins|nori|norightleft|norightleftcmd|norl|norlc|noro|nors|noru|noruler|nosb|nosc|noscb|noscrollbind|noscs|nosecure|nosft|noshellslash|noshelltemp|noshiftround|noshortname|noshowcmd|noshowfulltag|noshowmatch|noshowmode|nosi|nosm|nosmartcase|nosmartindent|nosmarttab|nosmd|nosn|nosol|nospell|nosplitbelow|nosplitright|nospr|nosr|nossl|nosta|nostartofline|nostmp|noswapfile|noswf|nota|notagbsearch|notagrelative|notagstack|notbi|notbidi|notbs|notermbidi|noterse|notextauto|notextmode|notf|notgst|notildeop|notimeout|notitle|noto|notop|notr|nottimeout|nottybuiltin|nottyfast|notx|novb|novisualbell|nowa|nowarn|nowb|noweirdinvert|nowfh|nowfw|nowildmenu|nowinfixheight|nowinfixwidth|nowiv|nowmnu|nowrap|nowrapscan|nowrite|nowriteany|nowritebackup|nows|invacd|invai|invakm|invallowrevins|invaltkeymap|invanti|invantialias|invar|invarab|invarabic|invarabicshape|invari|invarshape|invautochdir|invautoindent|invautoread|invautowrite|invautowriteall|invaw|invawa|invbackup|invballooneval|invbeval|invbin|invbinary|invbiosk|invbioskey|invbk|invbl|invbomb|invbuflisted|invcf|invci|invcin|invcindent|invcompatible|invconfirm|invconsk|invconskey|invcopyindent|invcp|invcscopetag|invcscopeverbose|invcst|invcsverb|invcuc|invcul|invcursorcolumn|invcursorline|invdeco|invdelcombine|invdg|invdiff|invdigraph|invdisable|invea|inveb|inved|invedcompatible|invek|invendofline|inveol|invequalalways|inverrorbells|invesckeys|invet|invex|invexpandtab|invexrc|invfen|invfk|invfkmap|invfoldenable|invgd|invgdefault|invguipty|invhid|invhidden|invhk|invhkmap|invhkmapp|invhkp|invhls|invhlsearch|invic|invicon|invignorecase|invim|invimc|invimcmdline|invimd|invincsearch|invinf|invinfercase|invinsertmode|invis|invjoinspaces|invjs|invlazyredraw|invlbr|invlinebreak|invlisp|invlist|invloadplugins|invlpl|invlz|invma|invmacatsui|invmagic|invmh|invml|invmod|invmodeline|invmodifiable|invmodified|invmore|invmousef|invmousefocus|invmousehide|invnu|invnumber|invodev|invopendevice|invpaste|invpi|invpreserveindent|invpreviewwindow|invprompt|invpvw|invreadonly|invremap|invrestorescreen|invrevins|invri|invrightleft|invrightleftcmd|invrl|invrlc|invro|invrs|invru|invruler|invsb|invsc|invscb|invscrollbind|invscs|invsecure|invsft|invshellslash|invshelltemp|invshiftround|invshortname|invshowcmd|invshowfulltag|invshowmatch|invshowmode|invsi|invsm|invsmartcase|invsmartindent|invsmarttab|invsmd|invsn|invsol|invspell|invsplitbelow|invsplitright|invspr|invsr|invssl|invsta|invstartofline|invstmp|invswapfile|invswf|invta|invtagbsearch|invtagrelative|invtagstack|invtbi|invtbidi|invtbs|invtermbidi|invterse|invtextauto|invtextmode|invtf|invtgst|invtildeop|invtimeout|invtitle|invto|invtop|invtr|invttimeout|invttybuiltin|invttyfast|invtx|invvb|invvisualbell|invwa|invwarn|invwb|invweirdinvert|invwfh|invwfw|invwildmenu|invwinfixheight|invwinfixwidth|invwiv|invwmnu|invwrap|invwrapscan|invwrite|invwriteany|invwritebackup|invws|t_AB|t_AF|t_al|t_AL|t_bc|t_cd|t_ce|t_Ce|t_cl|t_cm|t_Co|t_cs|t_Cs|t_CS|t_CV|t_da|t_db|t_dl|t_DL|t_EI|t_F1|t_F2|t_F3|t_F4|t_F5|t_F6|t_F7|t_F8|t_F9|t_fs|t_IE|t_IS|t_k1|t_K1|t_k2|t_k3|t_K3|t_k4|t_K4|t_k5|t_K5|t_k6|t_K6|t_k7|t_K7|t_k8|t_K8|t_k9|t_K9|t_KA|t_kb|t_kB|t_KB|t_KC|t_kd|t_kD|t_KD|t_ke|t_KE|t_KF|t_KG|t_kh|t_KH|t_kI|t_KI|t_KJ|t_KK|t_kl|t_KL|t_kN|t_kP|t_kr|t_ks|t_ku|t_le|t_mb|t_md|t_me|t_mr|t_ms|t_nd|t_op|t_RI|t_RV|t_Sb|t_se|t_Sf|t_SI|t_so|t_sr|t_te|t_ti|t_ts|t_ue|t_us|t_ut|t_vb|t_ve|t_vi|t_vs|t_WP|t_WS|t_xs|t_ZH|t_ZR)\b/, + number: /\b(?:0x[\da-f]+|\d+(?:\.\d+)?)\b/i, + operator: /\|\||&&|[-+.]=?|[=!](?:[=~][#?]?)?|[<>]=?[#?]?|[*\/%?]|\b(?:is(?:not)?)\b/, + punctuation: /[{}[\](),;:]/ +} + +export default Prism